2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
50 #include <asm/irq_regs.h>
52 static struct workqueue_struct *perf_wq;
54 typedef int (*remote_function_f)(void *);
56 struct remote_function_call {
57 struct task_struct *p;
58 remote_function_f func;
63 static void remote_function(void *data)
65 struct remote_function_call *tfc = data;
66 struct task_struct *p = tfc->p;
70 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
74 tfc->ret = tfc->func(tfc->info);
78 * task_function_call - call a function on the cpu on which a task runs
79 * @p: the task to evaluate
80 * @func: the function to be called
81 * @info: the function call argument
83 * Calls the function @func when the task is currently running. This might
84 * be on the current CPU, which just calls the function directly
86 * returns: @func return value, or
87 * -ESRCH - when the process isn't running
88 * -EAGAIN - when the process moved away
91 task_function_call(struct task_struct *p, remote_function_f func, void *info)
93 struct remote_function_call data = {
97 .ret = -ESRCH, /* No such (running) process */
101 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
107 * cpu_function_call - call a function on the cpu
108 * @func: the function to be called
109 * @info: the function call argument
111 * Calls the function @func on the remote cpu.
113 * returns: @func return value or -ENXIO when the cpu is offline
115 static int cpu_function_call(int cpu, remote_function_f func, void *info)
117 struct remote_function_call data = {
121 .ret = -ENXIO, /* No such CPU */
124 smp_call_function_single(cpu, remote_function, &data, 1);
129 #define EVENT_OWNER_KERNEL ((void *) -1)
131 static bool is_kernel_event(struct perf_event *event)
133 return event->owner == EVENT_OWNER_KERNEL;
136 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
137 PERF_FLAG_FD_OUTPUT |\
138 PERF_FLAG_PID_CGROUP |\
139 PERF_FLAG_FD_CLOEXEC)
142 * branch priv levels that need permission checks
144 #define PERF_SAMPLE_BRANCH_PERM_PLM \
145 (PERF_SAMPLE_BRANCH_KERNEL |\
146 PERF_SAMPLE_BRANCH_HV)
149 EVENT_FLEXIBLE = 0x1,
151 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
155 * perf_sched_events : >0 events exist
156 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
158 struct static_key_deferred perf_sched_events __read_mostly;
159 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
160 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
161 static DEFINE_PER_CPU(bool, is_idle);
163 static atomic_t nr_mmap_events __read_mostly;
164 static atomic_t nr_comm_events __read_mostly;
165 static atomic_t nr_task_events __read_mostly;
166 static atomic_t nr_freq_events __read_mostly;
167 static atomic_t nr_switch_events __read_mostly;
169 static LIST_HEAD(pmus);
170 static DEFINE_MUTEX(pmus_lock);
171 static struct srcu_struct pmus_srcu;
174 * perf event paranoia level:
175 * -1 - not paranoid at all
176 * 0 - disallow raw tracepoint access for unpriv
177 * 1 - disallow cpu events for unpriv
178 * 2 - disallow kernel profiling for unpriv
179 * 3 - disallow all unpriv perf event use
181 #ifdef CONFIG_PERF_EVENTS_USERMODE
182 int sysctl_perf_event_paranoid __read_mostly = -1;
183 #elif defined CONFIG_SECURITY_PERF_EVENTS_RESTRICT
184 int sysctl_perf_event_paranoid __read_mostly = 3;
186 int sysctl_perf_event_paranoid __read_mostly = 1;
189 /* Minimum for 512 kiB + 1 user control page */
190 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
193 * max perf event sample rate
195 #define DEFAULT_MAX_SAMPLE_RATE 100000
196 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
197 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
199 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
201 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
202 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
204 static int perf_sample_allowed_ns __read_mostly =
205 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
207 static void update_perf_cpu_limits(void)
209 u64 tmp = perf_sample_period_ns;
211 tmp *= sysctl_perf_cpu_time_max_percent;
213 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
216 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
218 int perf_proc_update_handler(struct ctl_table *table, int write,
219 void __user *buffer, size_t *lenp,
222 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
227 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
228 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
229 update_perf_cpu_limits();
234 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
236 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
237 void __user *buffer, size_t *lenp,
240 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
245 update_perf_cpu_limits();
251 * perf samples are done in some very critical code paths (NMIs).
252 * If they take too much CPU time, the system can lock up and not
253 * get any real work done. This will drop the sample rate when
254 * we detect that events are taking too long.
256 #define NR_ACCUMULATED_SAMPLES 128
257 static DEFINE_PER_CPU(u64, running_sample_length);
259 static void perf_duration_warn(struct irq_work *w)
261 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
262 u64 avg_local_sample_len;
263 u64 local_samples_len;
265 local_samples_len = __this_cpu_read(running_sample_length);
266 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
268 printk_ratelimited(KERN_WARNING
269 "perf interrupt took too long (%lld > %lld), lowering "
270 "kernel.perf_event_max_sample_rate to %d\n",
271 avg_local_sample_len, allowed_ns >> 1,
272 sysctl_perf_event_sample_rate);
275 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
277 void perf_sample_event_took(u64 sample_len_ns)
279 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
280 u64 avg_local_sample_len;
281 u64 local_samples_len;
286 /* decay the counter by 1 average sample */
287 local_samples_len = __this_cpu_read(running_sample_length);
288 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
289 local_samples_len += sample_len_ns;
290 __this_cpu_write(running_sample_length, local_samples_len);
293 * note: this will be biased artifically low until we have
294 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
295 * from having to maintain a count.
297 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
299 if (avg_local_sample_len <= allowed_ns)
302 if (max_samples_per_tick <= 1)
305 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
306 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
307 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
309 update_perf_cpu_limits();
311 if (!irq_work_queue(&perf_duration_work)) {
312 early_printk("perf interrupt took too long (%lld > %lld), lowering "
313 "kernel.perf_event_max_sample_rate to %d\n",
314 avg_local_sample_len, allowed_ns >> 1,
315 sysctl_perf_event_sample_rate);
319 static atomic64_t perf_event_id;
321 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
322 enum event_type_t event_type);
324 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
325 enum event_type_t event_type,
326 struct task_struct *task);
328 static void update_context_time(struct perf_event_context *ctx);
329 static u64 perf_event_time(struct perf_event *event);
331 void __weak perf_event_print_debug(void) { }
333 extern __weak const char *perf_pmu_name(void)
338 static inline u64 perf_clock(void)
340 return local_clock();
343 static inline u64 perf_event_clock(struct perf_event *event)
345 return event->clock();
348 static inline struct perf_cpu_context *
349 __get_cpu_context(struct perf_event_context *ctx)
351 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
354 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
355 struct perf_event_context *ctx)
357 raw_spin_lock(&cpuctx->ctx.lock);
359 raw_spin_lock(&ctx->lock);
362 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
363 struct perf_event_context *ctx)
366 raw_spin_unlock(&ctx->lock);
367 raw_spin_unlock(&cpuctx->ctx.lock);
370 #ifdef CONFIG_CGROUP_PERF
373 perf_cgroup_match(struct perf_event *event)
375 struct perf_event_context *ctx = event->ctx;
376 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
378 /* @event doesn't care about cgroup */
382 /* wants specific cgroup scope but @cpuctx isn't associated with any */
387 * Cgroup scoping is recursive. An event enabled for a cgroup is
388 * also enabled for all its descendant cgroups. If @cpuctx's
389 * cgroup is a descendant of @event's (the test covers identity
390 * case), it's a match.
392 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
393 event->cgrp->css.cgroup);
396 static inline void perf_detach_cgroup(struct perf_event *event)
398 css_put(&event->cgrp->css);
402 static inline int is_cgroup_event(struct perf_event *event)
404 return event->cgrp != NULL;
407 static inline u64 perf_cgroup_event_time(struct perf_event *event)
409 struct perf_cgroup_info *t;
411 t = per_cpu_ptr(event->cgrp->info, event->cpu);
415 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
417 struct perf_cgroup_info *info;
422 info = this_cpu_ptr(cgrp->info);
424 info->time += now - info->timestamp;
425 info->timestamp = now;
428 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
430 struct perf_cgroup *cgrp = cpuctx->cgrp;
431 struct cgroup_subsys_state *css;
434 for (css = &cgrp->css; css; css = css->parent) {
435 cgrp = container_of(css, struct perf_cgroup, css);
436 __update_cgrp_time(cgrp);
441 static inline void update_cgrp_time_from_event(struct perf_event *event)
443 struct perf_cgroup *cgrp;
446 * ensure we access cgroup data only when needed and
447 * when we know the cgroup is pinned (css_get)
449 if (!is_cgroup_event(event))
452 cgrp = perf_cgroup_from_task(current, event->ctx);
454 * Do not update time when cgroup is not active
456 if (cgrp == event->cgrp)
457 __update_cgrp_time(event->cgrp);
461 perf_cgroup_set_timestamp(struct task_struct *task,
462 struct perf_event_context *ctx)
464 struct perf_cgroup *cgrp;
465 struct perf_cgroup_info *info;
466 struct cgroup_subsys_state *css;
469 * ctx->lock held by caller
470 * ensure we do not access cgroup data
471 * unless we have the cgroup pinned (css_get)
473 if (!task || !ctx->nr_cgroups)
476 cgrp = perf_cgroup_from_task(task, ctx);
478 for (css = &cgrp->css; css; css = css->parent) {
479 cgrp = container_of(css, struct perf_cgroup, css);
480 info = this_cpu_ptr(cgrp->info);
481 info->timestamp = ctx->timestamp;
485 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
486 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
489 * reschedule events based on the cgroup constraint of task.
491 * mode SWOUT : schedule out everything
492 * mode SWIN : schedule in based on cgroup for next
494 static void perf_cgroup_switch(struct task_struct *task, int mode)
496 struct perf_cpu_context *cpuctx;
501 * disable interrupts to avoid geting nr_cgroup
502 * changes via __perf_event_disable(). Also
505 local_irq_save(flags);
508 * we reschedule only in the presence of cgroup
509 * constrained events.
512 list_for_each_entry_rcu(pmu, &pmus, entry) {
513 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
514 if (cpuctx->unique_pmu != pmu)
515 continue; /* ensure we process each cpuctx once */
518 * perf_cgroup_events says at least one
519 * context on this CPU has cgroup events.
521 * ctx->nr_cgroups reports the number of cgroup
522 * events for a context.
524 if (cpuctx->ctx.nr_cgroups > 0) {
525 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
526 perf_pmu_disable(cpuctx->ctx.pmu);
528 if (mode & PERF_CGROUP_SWOUT) {
529 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
531 * must not be done before ctxswout due
532 * to event_filter_match() in event_sched_out()
537 if (mode & PERF_CGROUP_SWIN) {
538 WARN_ON_ONCE(cpuctx->cgrp);
540 * set cgrp before ctxsw in to allow
541 * event_filter_match() to not have to pass
543 * we pass the cpuctx->ctx to perf_cgroup_from_task()
544 * because cgorup events are only per-cpu
546 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
547 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
549 perf_pmu_enable(cpuctx->ctx.pmu);
550 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
554 local_irq_restore(flags);
557 static inline void perf_cgroup_sched_out(struct task_struct *task,
558 struct task_struct *next)
560 struct perf_cgroup *cgrp1;
561 struct perf_cgroup *cgrp2 = NULL;
565 * we come here when we know perf_cgroup_events > 0
566 * we do not need to pass the ctx here because we know
567 * we are holding the rcu lock
569 cgrp1 = perf_cgroup_from_task(task, NULL);
572 * next is NULL when called from perf_event_enable_on_exec()
573 * that will systematically cause a cgroup_switch()
576 cgrp2 = perf_cgroup_from_task(next, NULL);
579 * only schedule out current cgroup events if we know
580 * that we are switching to a different cgroup. Otherwise,
581 * do no touch the cgroup events.
584 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
589 static inline void perf_cgroup_sched_in(struct task_struct *prev,
590 struct task_struct *task)
592 struct perf_cgroup *cgrp1;
593 struct perf_cgroup *cgrp2 = NULL;
597 * we come here when we know perf_cgroup_events > 0
598 * we do not need to pass the ctx here because we know
599 * we are holding the rcu lock
601 cgrp1 = perf_cgroup_from_task(task, NULL);
603 /* prev can never be NULL */
604 cgrp2 = perf_cgroup_from_task(prev, NULL);
607 * only need to schedule in cgroup events if we are changing
608 * cgroup during ctxsw. Cgroup events were not scheduled
609 * out of ctxsw out if that was not the case.
612 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
617 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
618 struct perf_event_attr *attr,
619 struct perf_event *group_leader)
621 struct perf_cgroup *cgrp;
622 struct cgroup_subsys_state *css;
623 struct fd f = fdget(fd);
629 css = css_tryget_online_from_dir(f.file->f_path.dentry,
630 &perf_event_cgrp_subsys);
636 cgrp = container_of(css, struct perf_cgroup, css);
640 * all events in a group must monitor
641 * the same cgroup because a task belongs
642 * to only one perf cgroup at a time
644 if (group_leader && group_leader->cgrp != cgrp) {
645 perf_detach_cgroup(event);
654 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
656 struct perf_cgroup_info *t;
657 t = per_cpu_ptr(event->cgrp->info, event->cpu);
658 event->shadow_ctx_time = now - t->timestamp;
662 perf_cgroup_defer_enabled(struct perf_event *event)
665 * when the current task's perf cgroup does not match
666 * the event's, we need to remember to call the
667 * perf_mark_enable() function the first time a task with
668 * a matching perf cgroup is scheduled in.
670 if (is_cgroup_event(event) && !perf_cgroup_match(event))
671 event->cgrp_defer_enabled = 1;
675 perf_cgroup_mark_enabled(struct perf_event *event,
676 struct perf_event_context *ctx)
678 struct perf_event *sub;
679 u64 tstamp = perf_event_time(event);
681 if (!event->cgrp_defer_enabled)
684 event->cgrp_defer_enabled = 0;
686 event->tstamp_enabled = tstamp - event->total_time_enabled;
687 list_for_each_entry(sub, &event->sibling_list, group_entry) {
688 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
689 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
690 sub->cgrp_defer_enabled = 0;
694 #else /* !CONFIG_CGROUP_PERF */
697 perf_cgroup_match(struct perf_event *event)
702 static inline void perf_detach_cgroup(struct perf_event *event)
705 static inline int is_cgroup_event(struct perf_event *event)
710 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
715 static inline void update_cgrp_time_from_event(struct perf_event *event)
719 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
723 static inline void perf_cgroup_sched_out(struct task_struct *task,
724 struct task_struct *next)
728 static inline void perf_cgroup_sched_in(struct task_struct *prev,
729 struct task_struct *task)
733 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
734 struct perf_event_attr *attr,
735 struct perf_event *group_leader)
741 perf_cgroup_set_timestamp(struct task_struct *task,
742 struct perf_event_context *ctx)
747 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
752 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
756 static inline u64 perf_cgroup_event_time(struct perf_event *event)
762 perf_cgroup_defer_enabled(struct perf_event *event)
767 perf_cgroup_mark_enabled(struct perf_event *event,
768 struct perf_event_context *ctx)
774 * set default to be dependent on timer tick just
777 #define PERF_CPU_HRTIMER (1000 / HZ)
779 * function must be called with interrupts disbled
781 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
783 struct perf_cpu_context *cpuctx;
786 WARN_ON(!irqs_disabled());
788 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
789 rotations = perf_rotate_context(cpuctx);
791 raw_spin_lock(&cpuctx->hrtimer_lock);
793 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
795 cpuctx->hrtimer_active = 0;
796 raw_spin_unlock(&cpuctx->hrtimer_lock);
798 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
801 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
803 struct hrtimer *timer = &cpuctx->hrtimer;
804 struct pmu *pmu = cpuctx->ctx.pmu;
807 /* no multiplexing needed for SW PMU */
808 if (pmu->task_ctx_nr == perf_sw_context)
812 * check default is sane, if not set then force to
813 * default interval (1/tick)
815 interval = pmu->hrtimer_interval_ms;
817 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
819 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
821 raw_spin_lock_init(&cpuctx->hrtimer_lock);
822 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
823 timer->function = perf_mux_hrtimer_handler;
826 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
828 struct hrtimer *timer = &cpuctx->hrtimer;
829 struct pmu *pmu = cpuctx->ctx.pmu;
833 if (pmu->task_ctx_nr == perf_sw_context)
836 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
837 if (!cpuctx->hrtimer_active) {
838 cpuctx->hrtimer_active = 1;
839 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
840 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
842 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
847 void perf_pmu_disable(struct pmu *pmu)
849 int *count = this_cpu_ptr(pmu->pmu_disable_count);
851 pmu->pmu_disable(pmu);
854 void perf_pmu_enable(struct pmu *pmu)
856 int *count = this_cpu_ptr(pmu->pmu_disable_count);
858 pmu->pmu_enable(pmu);
861 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
864 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
865 * perf_event_task_tick() are fully serialized because they're strictly cpu
866 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
867 * disabled, while perf_event_task_tick is called from IRQ context.
869 static void perf_event_ctx_activate(struct perf_event_context *ctx)
871 struct list_head *head = this_cpu_ptr(&active_ctx_list);
873 WARN_ON(!irqs_disabled());
875 WARN_ON(!list_empty(&ctx->active_ctx_list));
877 list_add(&ctx->active_ctx_list, head);
880 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
882 WARN_ON(!irqs_disabled());
884 WARN_ON(list_empty(&ctx->active_ctx_list));
886 list_del_init(&ctx->active_ctx_list);
889 static void get_ctx(struct perf_event_context *ctx)
891 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
894 static void free_ctx(struct rcu_head *head)
896 struct perf_event_context *ctx;
898 ctx = container_of(head, struct perf_event_context, rcu_head);
899 kfree(ctx->task_ctx_data);
903 static void put_ctx(struct perf_event_context *ctx)
905 if (atomic_dec_and_test(&ctx->refcount)) {
907 put_ctx(ctx->parent_ctx);
909 put_task_struct(ctx->task);
910 call_rcu(&ctx->rcu_head, free_ctx);
915 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
916 * perf_pmu_migrate_context() we need some magic.
918 * Those places that change perf_event::ctx will hold both
919 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
921 * Lock ordering is by mutex address. There are two other sites where
922 * perf_event_context::mutex nests and those are:
924 * - perf_event_exit_task_context() [ child , 0 ]
925 * __perf_event_exit_task()
927 * put_event() [ parent, 1 ]
929 * - perf_event_init_context() [ parent, 0 ]
930 * inherit_task_group()
935 * perf_try_init_event() [ child , 1 ]
937 * While it appears there is an obvious deadlock here -- the parent and child
938 * nesting levels are inverted between the two. This is in fact safe because
939 * life-time rules separate them. That is an exiting task cannot fork, and a
940 * spawning task cannot (yet) exit.
942 * But remember that that these are parent<->child context relations, and
943 * migration does not affect children, therefore these two orderings should not
946 * The change in perf_event::ctx does not affect children (as claimed above)
947 * because the sys_perf_event_open() case will install a new event and break
948 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
949 * concerned with cpuctx and that doesn't have children.
951 * The places that change perf_event::ctx will issue:
953 * perf_remove_from_context();
955 * perf_install_in_context();
957 * to affect the change. The remove_from_context() + synchronize_rcu() should
958 * quiesce the event, after which we can install it in the new location. This
959 * means that only external vectors (perf_fops, prctl) can perturb the event
960 * while in transit. Therefore all such accessors should also acquire
961 * perf_event_context::mutex to serialize against this.
963 * However; because event->ctx can change while we're waiting to acquire
964 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
969 * task_struct::perf_event_mutex
970 * perf_event_context::mutex
971 * perf_event_context::lock
972 * perf_event::child_mutex;
973 * perf_event::mmap_mutex
976 static struct perf_event_context *
977 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
979 struct perf_event_context *ctx;
983 ctx = ACCESS_ONCE(event->ctx);
984 if (!atomic_inc_not_zero(&ctx->refcount)) {
990 mutex_lock_nested(&ctx->mutex, nesting);
991 if (event->ctx != ctx) {
992 mutex_unlock(&ctx->mutex);
1000 static inline struct perf_event_context *
1001 perf_event_ctx_lock(struct perf_event *event)
1003 return perf_event_ctx_lock_nested(event, 0);
1006 static void perf_event_ctx_unlock(struct perf_event *event,
1007 struct perf_event_context *ctx)
1009 mutex_unlock(&ctx->mutex);
1014 * This must be done under the ctx->lock, such as to serialize against
1015 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1016 * calling scheduler related locks and ctx->lock nests inside those.
1018 static __must_check struct perf_event_context *
1019 unclone_ctx(struct perf_event_context *ctx)
1021 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1023 lockdep_assert_held(&ctx->lock);
1026 ctx->parent_ctx = NULL;
1032 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1035 * only top level events have the pid namespace they were created in
1038 event = event->parent;
1040 return task_tgid_nr_ns(p, event->ns);
1043 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1046 * only top level events have the pid namespace they were created in
1049 event = event->parent;
1051 return task_pid_nr_ns(p, event->ns);
1055 * If we inherit events we want to return the parent event id
1058 static u64 primary_event_id(struct perf_event *event)
1063 id = event->parent->id;
1069 * Get the perf_event_context for a task and lock it.
1070 * This has to cope with with the fact that until it is locked,
1071 * the context could get moved to another task.
1073 static struct perf_event_context *
1074 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1076 struct perf_event_context *ctx;
1080 * One of the few rules of preemptible RCU is that one cannot do
1081 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1082 * part of the read side critical section was irqs-enabled -- see
1083 * rcu_read_unlock_special().
1085 * Since ctx->lock nests under rq->lock we must ensure the entire read
1086 * side critical section has interrupts disabled.
1088 local_irq_save(*flags);
1090 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1093 * If this context is a clone of another, it might
1094 * get swapped for another underneath us by
1095 * perf_event_task_sched_out, though the
1096 * rcu_read_lock() protects us from any context
1097 * getting freed. Lock the context and check if it
1098 * got swapped before we could get the lock, and retry
1099 * if so. If we locked the right context, then it
1100 * can't get swapped on us any more.
1102 raw_spin_lock(&ctx->lock);
1103 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1104 raw_spin_unlock(&ctx->lock);
1106 local_irq_restore(*flags);
1110 if (!atomic_inc_not_zero(&ctx->refcount)) {
1111 raw_spin_unlock(&ctx->lock);
1117 local_irq_restore(*flags);
1122 * Get the context for a task and increment its pin_count so it
1123 * can't get swapped to another task. This also increments its
1124 * reference count so that the context can't get freed.
1126 static struct perf_event_context *
1127 perf_pin_task_context(struct task_struct *task, int ctxn)
1129 struct perf_event_context *ctx;
1130 unsigned long flags;
1132 ctx = perf_lock_task_context(task, ctxn, &flags);
1135 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1140 static void perf_unpin_context(struct perf_event_context *ctx)
1142 unsigned long flags;
1144 raw_spin_lock_irqsave(&ctx->lock, flags);
1146 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1150 * Update the record of the current time in a context.
1152 static void update_context_time(struct perf_event_context *ctx)
1154 u64 now = perf_clock();
1156 ctx->time += now - ctx->timestamp;
1157 ctx->timestamp = now;
1160 static u64 perf_event_time(struct perf_event *event)
1162 struct perf_event_context *ctx = event->ctx;
1164 if (is_cgroup_event(event))
1165 return perf_cgroup_event_time(event);
1167 return ctx ? ctx->time : 0;
1171 * Update the total_time_enabled and total_time_running fields for a event.
1172 * The caller of this function needs to hold the ctx->lock.
1174 static void update_event_times(struct perf_event *event)
1176 struct perf_event_context *ctx = event->ctx;
1179 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1180 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1183 * in cgroup mode, time_enabled represents
1184 * the time the event was enabled AND active
1185 * tasks were in the monitored cgroup. This is
1186 * independent of the activity of the context as
1187 * there may be a mix of cgroup and non-cgroup events.
1189 * That is why we treat cgroup events differently
1192 if (is_cgroup_event(event))
1193 run_end = perf_cgroup_event_time(event);
1194 else if (ctx->is_active)
1195 run_end = ctx->time;
1197 run_end = event->tstamp_stopped;
1199 event->total_time_enabled = run_end - event->tstamp_enabled;
1201 if (event->state == PERF_EVENT_STATE_INACTIVE)
1202 run_end = event->tstamp_stopped;
1204 run_end = perf_event_time(event);
1206 event->total_time_running = run_end - event->tstamp_running;
1211 * Update total_time_enabled and total_time_running for all events in a group.
1213 static void update_group_times(struct perf_event *leader)
1215 struct perf_event *event;
1217 update_event_times(leader);
1218 list_for_each_entry(event, &leader->sibling_list, group_entry)
1219 update_event_times(event);
1222 static struct list_head *
1223 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1225 if (event->attr.pinned)
1226 return &ctx->pinned_groups;
1228 return &ctx->flexible_groups;
1232 * Add a event from the lists for its context.
1233 * Must be called with ctx->mutex and ctx->lock held.
1236 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1238 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1239 event->attach_state |= PERF_ATTACH_CONTEXT;
1242 * If we're a stand alone event or group leader, we go to the context
1243 * list, group events are kept attached to the group so that
1244 * perf_group_detach can, at all times, locate all siblings.
1246 if (event->group_leader == event) {
1247 struct list_head *list;
1249 if (is_software_event(event))
1250 event->group_flags |= PERF_GROUP_SOFTWARE;
1252 list = ctx_group_list(event, ctx);
1253 list_add_tail(&event->group_entry, list);
1256 if (is_cgroup_event(event))
1259 list_add_rcu(&event->event_entry, &ctx->event_list);
1261 if (event->attr.inherit_stat)
1268 * Initialize event state based on the perf_event_attr::disabled.
1270 static inline void perf_event__state_init(struct perf_event *event)
1272 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1273 PERF_EVENT_STATE_INACTIVE;
1276 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1278 int entry = sizeof(u64); /* value */
1282 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1283 size += sizeof(u64);
1285 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1286 size += sizeof(u64);
1288 if (event->attr.read_format & PERF_FORMAT_ID)
1289 entry += sizeof(u64);
1291 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1293 size += sizeof(u64);
1297 event->read_size = size;
1300 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1302 struct perf_sample_data *data;
1305 if (sample_type & PERF_SAMPLE_IP)
1306 size += sizeof(data->ip);
1308 if (sample_type & PERF_SAMPLE_ADDR)
1309 size += sizeof(data->addr);
1311 if (sample_type & PERF_SAMPLE_PERIOD)
1312 size += sizeof(data->period);
1314 if (sample_type & PERF_SAMPLE_WEIGHT)
1315 size += sizeof(data->weight);
1317 if (sample_type & PERF_SAMPLE_READ)
1318 size += event->read_size;
1320 if (sample_type & PERF_SAMPLE_DATA_SRC)
1321 size += sizeof(data->data_src.val);
1323 if (sample_type & PERF_SAMPLE_TRANSACTION)
1324 size += sizeof(data->txn);
1326 event->header_size = size;
1330 * Called at perf_event creation and when events are attached/detached from a
1333 static void perf_event__header_size(struct perf_event *event)
1335 __perf_event_read_size(event,
1336 event->group_leader->nr_siblings);
1337 __perf_event_header_size(event, event->attr.sample_type);
1340 static void perf_event__id_header_size(struct perf_event *event)
1342 struct perf_sample_data *data;
1343 u64 sample_type = event->attr.sample_type;
1346 if (sample_type & PERF_SAMPLE_TID)
1347 size += sizeof(data->tid_entry);
1349 if (sample_type & PERF_SAMPLE_TIME)
1350 size += sizeof(data->time);
1352 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1353 size += sizeof(data->id);
1355 if (sample_type & PERF_SAMPLE_ID)
1356 size += sizeof(data->id);
1358 if (sample_type & PERF_SAMPLE_STREAM_ID)
1359 size += sizeof(data->stream_id);
1361 if (sample_type & PERF_SAMPLE_CPU)
1362 size += sizeof(data->cpu_entry);
1364 event->id_header_size = size;
1367 static bool perf_event_validate_size(struct perf_event *event)
1370 * The values computed here will be over-written when we actually
1373 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1374 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1375 perf_event__id_header_size(event);
1378 * Sum the lot; should not exceed the 64k limit we have on records.
1379 * Conservative limit to allow for callchains and other variable fields.
1381 if (event->read_size + event->header_size +
1382 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1388 static void perf_group_attach(struct perf_event *event)
1390 struct perf_event *group_leader = event->group_leader, *pos;
1393 * We can have double attach due to group movement in perf_event_open.
1395 if (event->attach_state & PERF_ATTACH_GROUP)
1398 event->attach_state |= PERF_ATTACH_GROUP;
1400 if (group_leader == event)
1403 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1405 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1406 !is_software_event(event))
1407 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1409 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1410 group_leader->nr_siblings++;
1412 perf_event__header_size(group_leader);
1414 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1415 perf_event__header_size(pos);
1419 * Remove a event from the lists for its context.
1420 * Must be called with ctx->mutex and ctx->lock held.
1423 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1425 struct perf_cpu_context *cpuctx;
1427 WARN_ON_ONCE(event->ctx != ctx);
1428 lockdep_assert_held(&ctx->lock);
1431 * We can have double detach due to exit/hot-unplug + close.
1433 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1436 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1438 if (is_cgroup_event(event)) {
1440 cpuctx = __get_cpu_context(ctx);
1442 * if there are no more cgroup events
1443 * then cler cgrp to avoid stale pointer
1444 * in update_cgrp_time_from_cpuctx()
1446 if (!ctx->nr_cgroups)
1447 cpuctx->cgrp = NULL;
1451 if (event->attr.inherit_stat)
1454 list_del_rcu(&event->event_entry);
1456 if (event->group_leader == event)
1457 list_del_init(&event->group_entry);
1459 update_group_times(event);
1462 * If event was in error state, then keep it
1463 * that way, otherwise bogus counts will be
1464 * returned on read(). The only way to get out
1465 * of error state is by explicit re-enabling
1468 if (event->state > PERF_EVENT_STATE_OFF)
1469 event->state = PERF_EVENT_STATE_OFF;
1474 static void perf_group_detach(struct perf_event *event)
1476 struct perf_event *sibling, *tmp;
1477 struct list_head *list = NULL;
1480 * We can have double detach due to exit/hot-unplug + close.
1482 if (!(event->attach_state & PERF_ATTACH_GROUP))
1485 event->attach_state &= ~PERF_ATTACH_GROUP;
1488 * If this is a sibling, remove it from its group.
1490 if (event->group_leader != event) {
1491 list_del_init(&event->group_entry);
1492 event->group_leader->nr_siblings--;
1496 if (!list_empty(&event->group_entry))
1497 list = &event->group_entry;
1500 * If this was a group event with sibling events then
1501 * upgrade the siblings to singleton events by adding them
1502 * to whatever list we are on.
1503 * If this isn't on a list, make sure we still remove the sibling's
1504 * group_entry from this sibling_list; otherwise, when that sibling
1505 * is later deallocated, it will try to remove itself from this
1506 * sibling_list, which may well have been deallocated already,
1507 * resulting in a use-after-free.
1509 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1511 list_move_tail(&sibling->group_entry, list);
1513 list_del_init(&sibling->group_entry);
1514 sibling->group_leader = sibling;
1516 /* Inherit group flags from the previous leader */
1517 sibling->group_flags = event->group_flags;
1519 WARN_ON_ONCE(sibling->ctx != event->ctx);
1523 perf_event__header_size(event->group_leader);
1525 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1526 perf_event__header_size(tmp);
1530 * User event without the task.
1532 static bool is_orphaned_event(struct perf_event *event)
1534 return event && !is_kernel_event(event) && !event->owner;
1538 * Event has a parent but parent's task finished and it's
1539 * alive only because of children holding refference.
1541 static bool is_orphaned_child(struct perf_event *event)
1543 return is_orphaned_event(event->parent);
1546 static void orphans_remove_work(struct work_struct *work);
1548 static void schedule_orphans_remove(struct perf_event_context *ctx)
1550 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1553 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1555 ctx->orphans_remove_sched = true;
1559 static int __init perf_workqueue_init(void)
1561 perf_wq = create_singlethread_workqueue("perf");
1562 WARN(!perf_wq, "failed to create perf workqueue\n");
1563 return perf_wq ? 0 : -1;
1566 core_initcall(perf_workqueue_init);
1568 static inline int __pmu_filter_match(struct perf_event *event)
1570 struct pmu *pmu = event->pmu;
1571 return pmu->filter_match ? pmu->filter_match(event) : 1;
1575 * Check whether we should attempt to schedule an event group based on
1576 * PMU-specific filtering. An event group can consist of HW and SW events,
1577 * potentially with a SW leader, so we must check all the filters, to
1578 * determine whether a group is schedulable:
1580 static inline int pmu_filter_match(struct perf_event *event)
1582 struct perf_event *child;
1584 if (!__pmu_filter_match(event))
1587 list_for_each_entry(child, &event->sibling_list, group_entry) {
1588 if (!__pmu_filter_match(child))
1596 event_filter_match(struct perf_event *event)
1598 return (event->cpu == -1 || event->cpu == smp_processor_id())
1599 && perf_cgroup_match(event) && pmu_filter_match(event);
1603 event_sched_out(struct perf_event *event,
1604 struct perf_cpu_context *cpuctx,
1605 struct perf_event_context *ctx)
1607 u64 tstamp = perf_event_time(event);
1610 WARN_ON_ONCE(event->ctx != ctx);
1611 lockdep_assert_held(&ctx->lock);
1614 * An event which could not be activated because of
1615 * filter mismatch still needs to have its timings
1616 * maintained, otherwise bogus information is return
1617 * via read() for time_enabled, time_running:
1619 if (event->state == PERF_EVENT_STATE_INACTIVE
1620 && !event_filter_match(event)) {
1621 delta = tstamp - event->tstamp_stopped;
1622 event->tstamp_running += delta;
1623 event->tstamp_stopped = tstamp;
1626 if (event->state != PERF_EVENT_STATE_ACTIVE)
1629 perf_pmu_disable(event->pmu);
1631 event->tstamp_stopped = tstamp;
1632 event->pmu->del(event, 0);
1634 event->state = PERF_EVENT_STATE_INACTIVE;
1635 if (event->pending_disable) {
1636 event->pending_disable = 0;
1637 event->state = PERF_EVENT_STATE_OFF;
1640 if (!is_software_event(event))
1641 cpuctx->active_oncpu--;
1642 if (!--ctx->nr_active)
1643 perf_event_ctx_deactivate(ctx);
1644 if (event->attr.freq && event->attr.sample_freq)
1646 if (event->attr.exclusive || !cpuctx->active_oncpu)
1647 cpuctx->exclusive = 0;
1649 if (is_orphaned_child(event))
1650 schedule_orphans_remove(ctx);
1652 perf_pmu_enable(event->pmu);
1656 group_sched_out(struct perf_event *group_event,
1657 struct perf_cpu_context *cpuctx,
1658 struct perf_event_context *ctx)
1660 struct perf_event *event;
1661 int state = group_event->state;
1663 event_sched_out(group_event, cpuctx, ctx);
1666 * Schedule out siblings (if any):
1668 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1669 event_sched_out(event, cpuctx, ctx);
1671 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1672 cpuctx->exclusive = 0;
1675 struct remove_event {
1676 struct perf_event *event;
1681 * Cross CPU call to remove a performance event
1683 * We disable the event on the hardware level first. After that we
1684 * remove it from the context list.
1686 static int __perf_remove_from_context(void *info)
1688 struct remove_event *re = info;
1689 struct perf_event *event = re->event;
1690 struct perf_event_context *ctx = event->ctx;
1691 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1693 raw_spin_lock(&ctx->lock);
1694 event_sched_out(event, cpuctx, ctx);
1695 if (re->detach_group)
1696 perf_group_detach(event);
1697 list_del_event(event, ctx);
1698 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1700 cpuctx->task_ctx = NULL;
1702 raw_spin_unlock(&ctx->lock);
1709 static void perf_retry_remove(struct perf_event *event,
1710 struct remove_event *rep)
1714 * CPU was offline. Bring it online so we can
1715 * gracefully exit a perf context.
1717 up_ret = cpu_up(event->cpu);
1719 /* Try the remove call once again. */
1720 cpu_function_call(event->cpu, __perf_remove_from_context,
1723 pr_err("Failed to bring up CPU: %d, ret: %d\n",
1724 event->cpu, up_ret);
1727 static void perf_retry_remove(struct perf_event *event,
1728 struct remove_event *rep)
1734 * Remove the event from a task's (or a CPU's) list of events.
1736 * CPU events are removed with a smp call. For task events we only
1737 * call when the task is on a CPU.
1739 * If event->ctx is a cloned context, callers must make sure that
1740 * every task struct that event->ctx->task could possibly point to
1741 * remains valid. This is OK when called from perf_release since
1742 * that only calls us on the top-level context, which can't be a clone.
1743 * When called from perf_event_exit_task, it's OK because the
1744 * context has been detached from its task.
1746 static void __ref perf_remove_from_context(struct perf_event *event,
1749 struct perf_event_context *ctx = event->ctx;
1750 struct task_struct *task = ctx->task;
1751 struct remove_event re = {
1753 .detach_group = detach_group,
1757 lockdep_assert_held(&ctx->mutex);
1761 * Per cpu events are removed via an smp call. The removal can
1762 * fail if the CPU is currently offline, but in that case we
1763 * already called __perf_remove_from_context from
1764 * perf_event_exit_cpu.
1766 ret = cpu_function_call(event->cpu, __perf_remove_from_context,
1769 perf_retry_remove(event, &re);
1775 if (!task_function_call(task, __perf_remove_from_context, &re))
1778 raw_spin_lock_irq(&ctx->lock);
1780 * If we failed to find a running task, but find the context active now
1781 * that we've acquired the ctx->lock, retry.
1783 if (ctx->is_active) {
1784 raw_spin_unlock_irq(&ctx->lock);
1786 * Reload the task pointer, it might have been changed by
1787 * a concurrent perf_event_context_sched_out().
1794 * Since the task isn't running, its safe to remove the event, us
1795 * holding the ctx->lock ensures the task won't get scheduled in.
1798 perf_group_detach(event);
1799 list_del_event(event, ctx);
1800 raw_spin_unlock_irq(&ctx->lock);
1804 * Cross CPU call to disable a performance event
1806 int __perf_event_disable(void *info)
1808 struct perf_event *event = info;
1809 struct perf_event_context *ctx = event->ctx;
1810 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1813 * If this is a per-task event, need to check whether this
1814 * event's task is the current task on this cpu.
1816 * Can trigger due to concurrent perf_event_context_sched_out()
1817 * flipping contexts around.
1819 if (ctx->task && cpuctx->task_ctx != ctx)
1822 raw_spin_lock(&ctx->lock);
1825 * If the event is on, turn it off.
1826 * If it is in error state, leave it in error state.
1828 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1829 update_context_time(ctx);
1830 update_cgrp_time_from_event(event);
1831 update_group_times(event);
1832 if (event == event->group_leader)
1833 group_sched_out(event, cpuctx, ctx);
1835 event_sched_out(event, cpuctx, ctx);
1836 event->state = PERF_EVENT_STATE_OFF;
1839 raw_spin_unlock(&ctx->lock);
1847 * If event->ctx is a cloned context, callers must make sure that
1848 * every task struct that event->ctx->task could possibly point to
1849 * remains valid. This condition is satisifed when called through
1850 * perf_event_for_each_child or perf_event_for_each because they
1851 * hold the top-level event's child_mutex, so any descendant that
1852 * goes to exit will block in sync_child_event.
1853 * When called from perf_pending_event it's OK because event->ctx
1854 * is the current context on this CPU and preemption is disabled,
1855 * hence we can't get into perf_event_task_sched_out for this context.
1857 static void _perf_event_disable(struct perf_event *event)
1859 struct perf_event_context *ctx = event->ctx;
1860 struct task_struct *task = ctx->task;
1864 * Disable the event on the cpu that it's on
1866 cpu_function_call(event->cpu, __perf_event_disable, event);
1871 if (!task_function_call(task, __perf_event_disable, event))
1874 raw_spin_lock_irq(&ctx->lock);
1876 * If the event is still active, we need to retry the cross-call.
1878 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1879 raw_spin_unlock_irq(&ctx->lock);
1881 * Reload the task pointer, it might have been changed by
1882 * a concurrent perf_event_context_sched_out().
1889 * Since we have the lock this context can't be scheduled
1890 * in, so we can change the state safely.
1892 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1893 update_group_times(event);
1894 event->state = PERF_EVENT_STATE_OFF;
1896 raw_spin_unlock_irq(&ctx->lock);
1900 * Strictly speaking kernel users cannot create groups and therefore this
1901 * interface does not need the perf_event_ctx_lock() magic.
1903 void perf_event_disable(struct perf_event *event)
1905 struct perf_event_context *ctx;
1907 ctx = perf_event_ctx_lock(event);
1908 _perf_event_disable(event);
1909 perf_event_ctx_unlock(event, ctx);
1911 EXPORT_SYMBOL_GPL(perf_event_disable);
1913 static void perf_set_shadow_time(struct perf_event *event,
1914 struct perf_event_context *ctx,
1918 * use the correct time source for the time snapshot
1920 * We could get by without this by leveraging the
1921 * fact that to get to this function, the caller
1922 * has most likely already called update_context_time()
1923 * and update_cgrp_time_xx() and thus both timestamp
1924 * are identical (or very close). Given that tstamp is,
1925 * already adjusted for cgroup, we could say that:
1926 * tstamp - ctx->timestamp
1928 * tstamp - cgrp->timestamp.
1930 * Then, in perf_output_read(), the calculation would
1931 * work with no changes because:
1932 * - event is guaranteed scheduled in
1933 * - no scheduled out in between
1934 * - thus the timestamp would be the same
1936 * But this is a bit hairy.
1938 * So instead, we have an explicit cgroup call to remain
1939 * within the time time source all along. We believe it
1940 * is cleaner and simpler to understand.
1942 if (is_cgroup_event(event))
1943 perf_cgroup_set_shadow_time(event, tstamp);
1945 event->shadow_ctx_time = tstamp - ctx->timestamp;
1948 #define MAX_INTERRUPTS (~0ULL)
1950 static void perf_log_throttle(struct perf_event *event, int enable);
1951 static void perf_log_itrace_start(struct perf_event *event);
1954 event_sched_in(struct perf_event *event,
1955 struct perf_cpu_context *cpuctx,
1956 struct perf_event_context *ctx)
1958 u64 tstamp = perf_event_time(event);
1961 lockdep_assert_held(&ctx->lock);
1963 if (event->state <= PERF_EVENT_STATE_OFF)
1966 WRITE_ONCE(event->oncpu, smp_processor_id());
1968 * Order event::oncpu write to happen before the ACTIVE state
1972 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
1975 * Unthrottle events, since we scheduled we might have missed several
1976 * ticks already, also for a heavily scheduling task there is little
1977 * guarantee it'll get a tick in a timely manner.
1979 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1980 perf_log_throttle(event, 1);
1981 event->hw.interrupts = 0;
1985 * The new state must be visible before we turn it on in the hardware:
1989 perf_pmu_disable(event->pmu);
1991 perf_set_shadow_time(event, ctx, tstamp);
1993 perf_log_itrace_start(event);
1995 if (event->pmu->add(event, PERF_EF_START)) {
1996 event->state = PERF_EVENT_STATE_INACTIVE;
2002 event->tstamp_running += tstamp - event->tstamp_stopped;
2004 if (!is_software_event(event))
2005 cpuctx->active_oncpu++;
2006 if (!ctx->nr_active++)
2007 perf_event_ctx_activate(ctx);
2008 if (event->attr.freq && event->attr.sample_freq)
2011 if (event->attr.exclusive)
2012 cpuctx->exclusive = 1;
2014 if (is_orphaned_child(event))
2015 schedule_orphans_remove(ctx);
2018 perf_pmu_enable(event->pmu);
2024 group_sched_in(struct perf_event *group_event,
2025 struct perf_cpu_context *cpuctx,
2026 struct perf_event_context *ctx)
2028 struct perf_event *event, *partial_group = NULL;
2029 struct pmu *pmu = ctx->pmu;
2030 u64 now = ctx->time;
2031 bool simulate = false;
2033 if (group_event->state == PERF_EVENT_STATE_OFF)
2036 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2038 if (event_sched_in(group_event, cpuctx, ctx)) {
2039 pmu->cancel_txn(pmu);
2040 perf_mux_hrtimer_restart(cpuctx);
2045 * Schedule in siblings as one group (if any):
2047 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2048 if (event_sched_in(event, cpuctx, ctx)) {
2049 partial_group = event;
2054 if (!pmu->commit_txn(pmu))
2059 * Groups can be scheduled in as one unit only, so undo any
2060 * partial group before returning:
2061 * The events up to the failed event are scheduled out normally,
2062 * tstamp_stopped will be updated.
2064 * The failed events and the remaining siblings need to have
2065 * their timings updated as if they had gone thru event_sched_in()
2066 * and event_sched_out(). This is required to get consistent timings
2067 * across the group. This also takes care of the case where the group
2068 * could never be scheduled by ensuring tstamp_stopped is set to mark
2069 * the time the event was actually stopped, such that time delta
2070 * calculation in update_event_times() is correct.
2072 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2073 if (event == partial_group)
2077 event->tstamp_running += now - event->tstamp_stopped;
2078 event->tstamp_stopped = now;
2080 event_sched_out(event, cpuctx, ctx);
2083 event_sched_out(group_event, cpuctx, ctx);
2085 pmu->cancel_txn(pmu);
2087 perf_mux_hrtimer_restart(cpuctx);
2093 * Work out whether we can put this event group on the CPU now.
2095 static int group_can_go_on(struct perf_event *event,
2096 struct perf_cpu_context *cpuctx,
2100 * Groups consisting entirely of software events can always go on.
2102 if (event->group_flags & PERF_GROUP_SOFTWARE)
2105 * If an exclusive group is already on, no other hardware
2108 if (cpuctx->exclusive)
2111 * If this group is exclusive and there are already
2112 * events on the CPU, it can't go on.
2114 if (event->attr.exclusive && cpuctx->active_oncpu)
2117 * Otherwise, try to add it if all previous groups were able
2123 static void add_event_to_ctx(struct perf_event *event,
2124 struct perf_event_context *ctx)
2126 u64 tstamp = perf_event_time(event);
2128 list_add_event(event, ctx);
2129 perf_group_attach(event);
2130 event->tstamp_enabled = tstamp;
2131 event->tstamp_running = tstamp;
2132 event->tstamp_stopped = tstamp;
2135 static void task_ctx_sched_out(struct perf_event_context *ctx);
2137 ctx_sched_in(struct perf_event_context *ctx,
2138 struct perf_cpu_context *cpuctx,
2139 enum event_type_t event_type,
2140 struct task_struct *task);
2142 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2143 struct perf_event_context *ctx,
2144 struct task_struct *task)
2146 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2148 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2149 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2151 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2155 * Cross CPU call to install and enable a performance event
2157 * Must be called with ctx->mutex held
2159 static int __perf_install_in_context(void *info)
2161 struct perf_event *event = info;
2162 struct perf_event_context *ctx = event->ctx;
2163 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2164 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2165 struct task_struct *task = current;
2167 perf_ctx_lock(cpuctx, task_ctx);
2168 perf_pmu_disable(cpuctx->ctx.pmu);
2171 * If there was an active task_ctx schedule it out.
2174 task_ctx_sched_out(task_ctx);
2177 * If the context we're installing events in is not the
2178 * active task_ctx, flip them.
2180 if (ctx->task && task_ctx != ctx) {
2182 raw_spin_unlock(&task_ctx->lock);
2183 raw_spin_lock(&ctx->lock);
2188 cpuctx->task_ctx = task_ctx;
2189 task = task_ctx->task;
2192 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2194 update_context_time(ctx);
2196 * update cgrp time only if current cgrp
2197 * matches event->cgrp. Must be done before
2198 * calling add_event_to_ctx()
2200 update_cgrp_time_from_event(event);
2202 add_event_to_ctx(event, ctx);
2205 * Schedule everything back in
2207 perf_event_sched_in(cpuctx, task_ctx, task);
2209 perf_pmu_enable(cpuctx->ctx.pmu);
2210 perf_ctx_unlock(cpuctx, task_ctx);
2216 * Attach a performance event to a context
2218 * First we add the event to the list with the hardware enable bit
2219 * in event->hw_config cleared.
2221 * If the event is attached to a task which is on a CPU we use a smp
2222 * call to enable it in the task context. The task might have been
2223 * scheduled away, but we check this in the smp call again.
2226 perf_install_in_context(struct perf_event_context *ctx,
2227 struct perf_event *event,
2230 struct task_struct *task = ctx->task;
2232 lockdep_assert_held(&ctx->mutex);
2235 if (event->cpu != -1)
2240 * Per cpu events are installed via an smp call and
2241 * the install is always successful.
2243 cpu_function_call(cpu, __perf_install_in_context, event);
2248 if (!task_function_call(task, __perf_install_in_context, event))
2251 raw_spin_lock_irq(&ctx->lock);
2253 * If we failed to find a running task, but find the context active now
2254 * that we've acquired the ctx->lock, retry.
2256 if (ctx->is_active) {
2257 raw_spin_unlock_irq(&ctx->lock);
2259 * Reload the task pointer, it might have been changed by
2260 * a concurrent perf_event_context_sched_out().
2267 * Since the task isn't running, its safe to add the event, us holding
2268 * the ctx->lock ensures the task won't get scheduled in.
2270 add_event_to_ctx(event, ctx);
2271 raw_spin_unlock_irq(&ctx->lock);
2275 * Put a event into inactive state and update time fields.
2276 * Enabling the leader of a group effectively enables all
2277 * the group members that aren't explicitly disabled, so we
2278 * have to update their ->tstamp_enabled also.
2279 * Note: this works for group members as well as group leaders
2280 * since the non-leader members' sibling_lists will be empty.
2282 static void __perf_event_mark_enabled(struct perf_event *event)
2284 struct perf_event *sub;
2285 u64 tstamp = perf_event_time(event);
2287 event->state = PERF_EVENT_STATE_INACTIVE;
2288 event->tstamp_enabled = tstamp - event->total_time_enabled;
2289 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2290 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2291 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2296 * Cross CPU call to enable a performance event
2298 static int __perf_event_enable(void *info)
2300 struct perf_event *event = info;
2301 struct perf_event_context *ctx = event->ctx;
2302 struct perf_event *leader = event->group_leader;
2303 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2307 * There's a time window between 'ctx->is_active' check
2308 * in perf_event_enable function and this place having:
2310 * - ctx->lock unlocked
2312 * where the task could be killed and 'ctx' deactivated
2313 * by perf_event_exit_task.
2315 if (!ctx->is_active)
2318 raw_spin_lock(&ctx->lock);
2319 update_context_time(ctx);
2321 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2325 * set current task's cgroup time reference point
2327 perf_cgroup_set_timestamp(current, ctx);
2329 __perf_event_mark_enabled(event);
2331 if (!event_filter_match(event)) {
2332 if (is_cgroup_event(event))
2333 perf_cgroup_defer_enabled(event);
2338 * If the event is in a group and isn't the group leader,
2339 * then don't put it on unless the group is on.
2341 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2344 if (!group_can_go_on(event, cpuctx, 1)) {
2347 if (event == leader)
2348 err = group_sched_in(event, cpuctx, ctx);
2350 err = event_sched_in(event, cpuctx, ctx);
2355 * If this event can't go on and it's part of a
2356 * group, then the whole group has to come off.
2358 if (leader != event) {
2359 group_sched_out(leader, cpuctx, ctx);
2360 perf_mux_hrtimer_restart(cpuctx);
2362 if (leader->attr.pinned) {
2363 update_group_times(leader);
2364 leader->state = PERF_EVENT_STATE_ERROR;
2369 raw_spin_unlock(&ctx->lock);
2377 * If event->ctx is a cloned context, callers must make sure that
2378 * every task struct that event->ctx->task could possibly point to
2379 * remains valid. This condition is satisfied when called through
2380 * perf_event_for_each_child or perf_event_for_each as described
2381 * for perf_event_disable.
2383 static void _perf_event_enable(struct perf_event *event)
2385 struct perf_event_context *ctx = event->ctx;
2386 struct task_struct *task = ctx->task;
2390 * Enable the event on the cpu that it's on
2392 cpu_function_call(event->cpu, __perf_event_enable, event);
2396 raw_spin_lock_irq(&ctx->lock);
2397 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2401 * If the event is in error state, clear that first.
2402 * That way, if we see the event in error state below, we
2403 * know that it has gone back into error state, as distinct
2404 * from the task having been scheduled away before the
2405 * cross-call arrived.
2407 if (event->state == PERF_EVENT_STATE_ERROR)
2408 event->state = PERF_EVENT_STATE_OFF;
2411 if (!ctx->is_active) {
2412 __perf_event_mark_enabled(event);
2416 raw_spin_unlock_irq(&ctx->lock);
2418 if (!task_function_call(task, __perf_event_enable, event))
2421 raw_spin_lock_irq(&ctx->lock);
2424 * If the context is active and the event is still off,
2425 * we need to retry the cross-call.
2427 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2429 * task could have been flipped by a concurrent
2430 * perf_event_context_sched_out()
2437 raw_spin_unlock_irq(&ctx->lock);
2441 * See perf_event_disable();
2443 void perf_event_enable(struct perf_event *event)
2445 struct perf_event_context *ctx;
2447 ctx = perf_event_ctx_lock(event);
2448 _perf_event_enable(event);
2449 perf_event_ctx_unlock(event, ctx);
2451 EXPORT_SYMBOL_GPL(perf_event_enable);
2453 static int __perf_event_stop(void *info)
2455 struct perf_event *event = info;
2457 /* for AUX events, our job is done if the event is already inactive */
2458 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2461 /* matches smp_wmb() in event_sched_in() */
2465 * There is a window with interrupts enabled before we get here,
2466 * so we need to check again lest we try to stop another CPU's event.
2468 if (READ_ONCE(event->oncpu) != smp_processor_id())
2471 event->pmu->stop(event, PERF_EF_UPDATE);
2476 static int _perf_event_refresh(struct perf_event *event, int refresh)
2479 * not supported on inherited events
2481 if (event->attr.inherit || !is_sampling_event(event))
2484 atomic_add(refresh, &event->event_limit);
2485 _perf_event_enable(event);
2491 * See perf_event_disable()
2493 int perf_event_refresh(struct perf_event *event, int refresh)
2495 struct perf_event_context *ctx;
2498 ctx = perf_event_ctx_lock(event);
2499 ret = _perf_event_refresh(event, refresh);
2500 perf_event_ctx_unlock(event, ctx);
2504 EXPORT_SYMBOL_GPL(perf_event_refresh);
2506 static void ctx_sched_out(struct perf_event_context *ctx,
2507 struct perf_cpu_context *cpuctx,
2508 enum event_type_t event_type)
2510 struct perf_event *event;
2511 int is_active = ctx->is_active;
2513 ctx->is_active &= ~event_type;
2514 if (likely(!ctx->nr_events))
2517 update_context_time(ctx);
2518 update_cgrp_time_from_cpuctx(cpuctx);
2519 if (!ctx->nr_active)
2522 perf_pmu_disable(ctx->pmu);
2523 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2524 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2525 group_sched_out(event, cpuctx, ctx);
2528 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2529 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2530 group_sched_out(event, cpuctx, ctx);
2532 perf_pmu_enable(ctx->pmu);
2536 * Test whether two contexts are equivalent, i.e. whether they have both been
2537 * cloned from the same version of the same context.
2539 * Equivalence is measured using a generation number in the context that is
2540 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2541 * and list_del_event().
2543 static int context_equiv(struct perf_event_context *ctx1,
2544 struct perf_event_context *ctx2)
2546 lockdep_assert_held(&ctx1->lock);
2547 lockdep_assert_held(&ctx2->lock);
2549 /* Pinning disables the swap optimization */
2550 if (ctx1->pin_count || ctx2->pin_count)
2553 /* If ctx1 is the parent of ctx2 */
2554 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2557 /* If ctx2 is the parent of ctx1 */
2558 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2562 * If ctx1 and ctx2 have the same parent; we flatten the parent
2563 * hierarchy, see perf_event_init_context().
2565 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2566 ctx1->parent_gen == ctx2->parent_gen)
2573 static void __perf_event_sync_stat(struct perf_event *event,
2574 struct perf_event *next_event)
2578 if (!event->attr.inherit_stat)
2582 * Update the event value, we cannot use perf_event_read()
2583 * because we're in the middle of a context switch and have IRQs
2584 * disabled, which upsets smp_call_function_single(), however
2585 * we know the event must be on the current CPU, therefore we
2586 * don't need to use it.
2588 switch (event->state) {
2589 case PERF_EVENT_STATE_ACTIVE:
2590 event->pmu->read(event);
2593 case PERF_EVENT_STATE_INACTIVE:
2594 update_event_times(event);
2602 * In order to keep per-task stats reliable we need to flip the event
2603 * values when we flip the contexts.
2605 value = local64_read(&next_event->count);
2606 value = local64_xchg(&event->count, value);
2607 local64_set(&next_event->count, value);
2609 swap(event->total_time_enabled, next_event->total_time_enabled);
2610 swap(event->total_time_running, next_event->total_time_running);
2613 * Since we swizzled the values, update the user visible data too.
2615 perf_event_update_userpage(event);
2616 perf_event_update_userpage(next_event);
2619 static void perf_event_sync_stat(struct perf_event_context *ctx,
2620 struct perf_event_context *next_ctx)
2622 struct perf_event *event, *next_event;
2627 update_context_time(ctx);
2629 event = list_first_entry(&ctx->event_list,
2630 struct perf_event, event_entry);
2632 next_event = list_first_entry(&next_ctx->event_list,
2633 struct perf_event, event_entry);
2635 while (&event->event_entry != &ctx->event_list &&
2636 &next_event->event_entry != &next_ctx->event_list) {
2638 __perf_event_sync_stat(event, next_event);
2640 event = list_next_entry(event, event_entry);
2641 next_event = list_next_entry(next_event, event_entry);
2645 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2646 struct task_struct *next)
2648 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2649 struct perf_event_context *next_ctx;
2650 struct perf_event_context *parent, *next_parent;
2651 struct perf_cpu_context *cpuctx;
2657 cpuctx = __get_cpu_context(ctx);
2658 if (!cpuctx->task_ctx)
2662 next_ctx = next->perf_event_ctxp[ctxn];
2666 parent = rcu_dereference(ctx->parent_ctx);
2667 next_parent = rcu_dereference(next_ctx->parent_ctx);
2669 /* If neither context have a parent context; they cannot be clones. */
2670 if (!parent && !next_parent)
2673 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2675 * Looks like the two contexts are clones, so we might be
2676 * able to optimize the context switch. We lock both
2677 * contexts and check that they are clones under the
2678 * lock (including re-checking that neither has been
2679 * uncloned in the meantime). It doesn't matter which
2680 * order we take the locks because no other cpu could
2681 * be trying to lock both of these tasks.
2683 raw_spin_lock(&ctx->lock);
2684 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2685 if (context_equiv(ctx, next_ctx)) {
2687 * XXX do we need a memory barrier of sorts
2688 * wrt to rcu_dereference() of perf_event_ctxp
2690 task->perf_event_ctxp[ctxn] = next_ctx;
2691 next->perf_event_ctxp[ctxn] = ctx;
2693 next_ctx->task = task;
2695 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2699 perf_event_sync_stat(ctx, next_ctx);
2701 raw_spin_unlock(&next_ctx->lock);
2702 raw_spin_unlock(&ctx->lock);
2708 raw_spin_lock(&ctx->lock);
2709 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2710 cpuctx->task_ctx = NULL;
2711 raw_spin_unlock(&ctx->lock);
2715 void perf_sched_cb_dec(struct pmu *pmu)
2717 this_cpu_dec(perf_sched_cb_usages);
2720 void perf_sched_cb_inc(struct pmu *pmu)
2722 this_cpu_inc(perf_sched_cb_usages);
2726 * This function provides the context switch callback to the lower code
2727 * layer. It is invoked ONLY when the context switch callback is enabled.
2729 static void perf_pmu_sched_task(struct task_struct *prev,
2730 struct task_struct *next,
2733 struct perf_cpu_context *cpuctx;
2735 unsigned long flags;
2740 local_irq_save(flags);
2744 list_for_each_entry_rcu(pmu, &pmus, entry) {
2745 if (pmu->sched_task) {
2746 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2748 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2750 perf_pmu_disable(pmu);
2752 pmu->sched_task(cpuctx->task_ctx, sched_in);
2754 perf_pmu_enable(pmu);
2756 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2762 local_irq_restore(flags);
2765 static void perf_event_switch(struct task_struct *task,
2766 struct task_struct *next_prev, bool sched_in);
2768 #define for_each_task_context_nr(ctxn) \
2769 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2772 * Called from scheduler to remove the events of the current task,
2773 * with interrupts disabled.
2775 * We stop each event and update the event value in event->count.
2777 * This does not protect us against NMI, but disable()
2778 * sets the disabled bit in the control field of event _before_
2779 * accessing the event control register. If a NMI hits, then it will
2780 * not restart the event.
2782 void __perf_event_task_sched_out(struct task_struct *task,
2783 struct task_struct *next)
2787 if (__this_cpu_read(perf_sched_cb_usages))
2788 perf_pmu_sched_task(task, next, false);
2790 if (atomic_read(&nr_switch_events))
2791 perf_event_switch(task, next, false);
2793 for_each_task_context_nr(ctxn)
2794 perf_event_context_sched_out(task, ctxn, next);
2797 * if cgroup events exist on this CPU, then we need
2798 * to check if we have to switch out PMU state.
2799 * cgroup event are system-wide mode only
2801 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2802 perf_cgroup_sched_out(task, next);
2805 static void task_ctx_sched_out(struct perf_event_context *ctx)
2807 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2809 if (!cpuctx->task_ctx)
2812 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2815 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2816 cpuctx->task_ctx = NULL;
2820 * Called with IRQs disabled
2822 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2823 enum event_type_t event_type)
2825 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2829 ctx_pinned_sched_in(struct perf_event_context *ctx,
2830 struct perf_cpu_context *cpuctx)
2832 struct perf_event *event;
2834 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2835 if (event->state <= PERF_EVENT_STATE_OFF)
2837 if (!event_filter_match(event))
2840 /* may need to reset tstamp_enabled */
2841 if (is_cgroup_event(event))
2842 perf_cgroup_mark_enabled(event, ctx);
2844 if (group_can_go_on(event, cpuctx, 1))
2845 group_sched_in(event, cpuctx, ctx);
2848 * If this pinned group hasn't been scheduled,
2849 * put it in error state.
2851 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2852 update_group_times(event);
2853 event->state = PERF_EVENT_STATE_ERROR;
2859 ctx_flexible_sched_in(struct perf_event_context *ctx,
2860 struct perf_cpu_context *cpuctx)
2862 struct perf_event *event;
2865 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2866 /* Ignore events in OFF or ERROR state */
2867 if (event->state <= PERF_EVENT_STATE_OFF)
2870 * Listen to the 'cpu' scheduling filter constraint
2873 if (!event_filter_match(event))
2876 /* may need to reset tstamp_enabled */
2877 if (is_cgroup_event(event))
2878 perf_cgroup_mark_enabled(event, ctx);
2880 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2881 if (group_sched_in(event, cpuctx, ctx))
2888 ctx_sched_in(struct perf_event_context *ctx,
2889 struct perf_cpu_context *cpuctx,
2890 enum event_type_t event_type,
2891 struct task_struct *task)
2894 int is_active = ctx->is_active;
2896 ctx->is_active |= event_type;
2897 if (likely(!ctx->nr_events))
2901 ctx->timestamp = now;
2902 perf_cgroup_set_timestamp(task, ctx);
2904 * First go through the list and put on any pinned groups
2905 * in order to give them the best chance of going on.
2907 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2908 ctx_pinned_sched_in(ctx, cpuctx);
2910 /* Then walk through the lower prio flexible groups */
2911 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2912 ctx_flexible_sched_in(ctx, cpuctx);
2915 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2916 enum event_type_t event_type,
2917 struct task_struct *task)
2919 struct perf_event_context *ctx = &cpuctx->ctx;
2921 ctx_sched_in(ctx, cpuctx, event_type, task);
2924 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2925 struct task_struct *task)
2927 struct perf_cpu_context *cpuctx;
2929 cpuctx = __get_cpu_context(ctx);
2930 if (cpuctx->task_ctx == ctx)
2933 perf_ctx_lock(cpuctx, ctx);
2934 perf_pmu_disable(ctx->pmu);
2936 * We want to keep the following priority order:
2937 * cpu pinned (that don't need to move), task pinned,
2938 * cpu flexible, task flexible.
2940 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2943 cpuctx->task_ctx = ctx;
2945 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2947 perf_pmu_enable(ctx->pmu);
2948 perf_ctx_unlock(cpuctx, ctx);
2952 * Called from scheduler to add the events of the current task
2953 * with interrupts disabled.
2955 * We restore the event value and then enable it.
2957 * This does not protect us against NMI, but enable()
2958 * sets the enabled bit in the control field of event _before_
2959 * accessing the event control register. If a NMI hits, then it will
2960 * keep the event running.
2962 void __perf_event_task_sched_in(struct task_struct *prev,
2963 struct task_struct *task)
2965 struct perf_event_context *ctx;
2968 for_each_task_context_nr(ctxn) {
2969 ctx = task->perf_event_ctxp[ctxn];
2973 perf_event_context_sched_in(ctx, task);
2976 * if cgroup events exist on this CPU, then we need
2977 * to check if we have to switch in PMU state.
2978 * cgroup event are system-wide mode only
2980 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2981 perf_cgroup_sched_in(prev, task);
2983 if (atomic_read(&nr_switch_events))
2984 perf_event_switch(task, prev, true);
2986 if (__this_cpu_read(perf_sched_cb_usages))
2987 perf_pmu_sched_task(prev, task, true);
2990 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2992 u64 frequency = event->attr.sample_freq;
2993 u64 sec = NSEC_PER_SEC;
2994 u64 divisor, dividend;
2996 int count_fls, nsec_fls, frequency_fls, sec_fls;
2998 count_fls = fls64(count);
2999 nsec_fls = fls64(nsec);
3000 frequency_fls = fls64(frequency);
3004 * We got @count in @nsec, with a target of sample_freq HZ
3005 * the target period becomes:
3008 * period = -------------------
3009 * @nsec * sample_freq
3014 * Reduce accuracy by one bit such that @a and @b converge
3015 * to a similar magnitude.
3017 #define REDUCE_FLS(a, b) \
3019 if (a##_fls > b##_fls) { \
3029 * Reduce accuracy until either term fits in a u64, then proceed with
3030 * the other, so that finally we can do a u64/u64 division.
3032 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3033 REDUCE_FLS(nsec, frequency);
3034 REDUCE_FLS(sec, count);
3037 if (count_fls + sec_fls > 64) {
3038 divisor = nsec * frequency;
3040 while (count_fls + sec_fls > 64) {
3041 REDUCE_FLS(count, sec);
3045 dividend = count * sec;
3047 dividend = count * sec;
3049 while (nsec_fls + frequency_fls > 64) {
3050 REDUCE_FLS(nsec, frequency);
3054 divisor = nsec * frequency;
3060 return div64_u64(dividend, divisor);
3063 static DEFINE_PER_CPU(int, perf_throttled_count);
3064 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3066 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3068 struct hw_perf_event *hwc = &event->hw;
3069 s64 period, sample_period;
3072 period = perf_calculate_period(event, nsec, count);
3074 delta = (s64)(period - hwc->sample_period);
3075 delta = (delta + 7) / 8; /* low pass filter */
3077 sample_period = hwc->sample_period + delta;
3082 hwc->sample_period = sample_period;
3084 if (local64_read(&hwc->period_left) > 8*sample_period) {
3086 event->pmu->stop(event, PERF_EF_UPDATE);
3088 local64_set(&hwc->period_left, 0);
3091 event->pmu->start(event, PERF_EF_RELOAD);
3096 * combine freq adjustment with unthrottling to avoid two passes over the
3097 * events. At the same time, make sure, having freq events does not change
3098 * the rate of unthrottling as that would introduce bias.
3100 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3103 struct perf_event *event;
3104 struct hw_perf_event *hwc;
3105 u64 now, period = TICK_NSEC;
3109 * only need to iterate over all events iff:
3110 * - context have events in frequency mode (needs freq adjust)
3111 * - there are events to unthrottle on this cpu
3113 if (!(ctx->nr_freq || needs_unthr))
3116 raw_spin_lock(&ctx->lock);
3117 perf_pmu_disable(ctx->pmu);
3119 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3120 if (event->state != PERF_EVENT_STATE_ACTIVE)
3123 if (!event_filter_match(event))
3126 perf_pmu_disable(event->pmu);
3130 if (hwc->interrupts == MAX_INTERRUPTS) {
3131 hwc->interrupts = 0;
3132 perf_log_throttle(event, 1);
3133 event->pmu->start(event, 0);
3136 if (!event->attr.freq || !event->attr.sample_freq)
3140 * stop the event and update event->count
3142 event->pmu->stop(event, PERF_EF_UPDATE);
3144 now = local64_read(&event->count);
3145 delta = now - hwc->freq_count_stamp;
3146 hwc->freq_count_stamp = now;
3150 * reload only if value has changed
3151 * we have stopped the event so tell that
3152 * to perf_adjust_period() to avoid stopping it
3156 perf_adjust_period(event, period, delta, false);
3158 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3160 perf_pmu_enable(event->pmu);
3163 perf_pmu_enable(ctx->pmu);
3164 raw_spin_unlock(&ctx->lock);
3168 * Round-robin a context's events:
3170 static void rotate_ctx(struct perf_event_context *ctx)
3173 * Rotate the first entry last of non-pinned groups. Rotation might be
3174 * disabled by the inheritance code.
3176 if (!ctx->rotate_disable)
3177 list_rotate_left(&ctx->flexible_groups);
3180 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3182 struct perf_event_context *ctx = NULL;
3185 if (cpuctx->ctx.nr_events) {
3186 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3190 ctx = cpuctx->task_ctx;
3191 if (ctx && ctx->nr_events) {
3192 if (ctx->nr_events != ctx->nr_active)
3199 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3200 perf_pmu_disable(cpuctx->ctx.pmu);
3202 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3204 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3206 rotate_ctx(&cpuctx->ctx);
3210 perf_event_sched_in(cpuctx, ctx, current);
3212 perf_pmu_enable(cpuctx->ctx.pmu);
3213 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3219 #ifdef CONFIG_NO_HZ_FULL
3220 bool perf_event_can_stop_tick(void)
3222 if (atomic_read(&nr_freq_events) ||
3223 __this_cpu_read(perf_throttled_count))
3230 void perf_event_task_tick(void)
3232 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3233 struct perf_event_context *ctx, *tmp;
3236 WARN_ON(!irqs_disabled());
3238 __this_cpu_inc(perf_throttled_seq);
3239 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3241 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3242 perf_adjust_freq_unthr_context(ctx, throttled);
3245 static int event_enable_on_exec(struct perf_event *event,
3246 struct perf_event_context *ctx)
3248 if (!event->attr.enable_on_exec)
3251 event->attr.enable_on_exec = 0;
3252 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3255 __perf_event_mark_enabled(event);
3261 * Enable all of a task's events that have been marked enable-on-exec.
3262 * This expects task == current.
3264 static void perf_event_enable_on_exec(int ctxn)
3266 struct perf_event_context *ctx, *clone_ctx = NULL;
3267 struct perf_event *event;
3268 unsigned long flags;
3272 local_irq_save(flags);
3273 ctx = current->perf_event_ctxp[ctxn];
3274 if (!ctx || !ctx->nr_events)
3278 * We must ctxsw out cgroup events to avoid conflict
3279 * when invoking perf_task_event_sched_in() later on
3280 * in this function. Otherwise we end up trying to
3281 * ctxswin cgroup events which are already scheduled
3284 perf_cgroup_sched_out(current, NULL);
3286 raw_spin_lock(&ctx->lock);
3287 task_ctx_sched_out(ctx);
3289 list_for_each_entry(event, &ctx->event_list, event_entry) {
3290 ret = event_enable_on_exec(event, ctx);
3296 * Unclone this context if we enabled any event.
3299 clone_ctx = unclone_ctx(ctx);
3301 raw_spin_unlock(&ctx->lock);
3304 * Also calls ctxswin for cgroup events, if any:
3306 perf_event_context_sched_in(ctx, ctx->task);
3308 local_irq_restore(flags);
3314 void perf_event_exec(void)
3319 for_each_task_context_nr(ctxn)
3320 perf_event_enable_on_exec(ctxn);
3324 struct perf_read_data {
3325 struct perf_event *event;
3331 * Cross CPU call to read the hardware event
3333 static void __perf_event_read(void *info)
3335 struct perf_read_data *data = info;
3336 struct perf_event *sub, *event = data->event;
3337 struct perf_event_context *ctx = event->ctx;
3338 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3339 struct pmu *pmu = event->pmu;
3342 * If this is a task context, we need to check whether it is
3343 * the current task context of this cpu. If not it has been
3344 * scheduled out before the smp call arrived. In that case
3345 * event->count would have been updated to a recent sample
3346 * when the event was scheduled out.
3348 if (ctx->task && cpuctx->task_ctx != ctx)
3351 raw_spin_lock(&ctx->lock);
3352 if (ctx->is_active) {
3353 update_context_time(ctx);
3354 update_cgrp_time_from_event(event);
3357 update_event_times(event);
3358 if (event->state != PERF_EVENT_STATE_ACTIVE)
3367 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3371 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3372 update_event_times(sub);
3373 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3375 * Use sibling's PMU rather than @event's since
3376 * sibling could be on different (eg: software) PMU.
3378 sub->pmu->read(sub);
3382 data->ret = pmu->commit_txn(pmu);
3385 raw_spin_unlock(&ctx->lock);
3388 static inline u64 perf_event_count(struct perf_event *event)
3390 if (event->pmu->count)
3391 return event->pmu->count(event);
3393 return __perf_event_count(event);
3397 * NMI-safe method to read a local event, that is an event that
3399 * - either for the current task, or for this CPU
3400 * - does not have inherit set, for inherited task events
3401 * will not be local and we cannot read them atomically
3402 * - must not have a pmu::count method
3404 u64 perf_event_read_local(struct perf_event *event)
3406 unsigned long flags;
3410 * Disabling interrupts avoids all counter scheduling (context
3411 * switches, timer based rotation and IPIs).
3413 local_irq_save(flags);
3415 /* If this is a per-task event, it must be for current */
3416 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3417 event->hw.target != current);
3419 /* If this is a per-CPU event, it must be for this CPU */
3420 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3421 event->cpu != smp_processor_id());
3424 * It must not be an event with inherit set, we cannot read
3425 * all child counters from atomic context.
3427 WARN_ON_ONCE(event->attr.inherit);
3430 * It must not have a pmu::count method, those are not
3433 WARN_ON_ONCE(event->pmu->count);
3436 * If the event is currently on this CPU, its either a per-task event,
3437 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3440 if (event->oncpu == smp_processor_id())
3441 event->pmu->read(event);
3443 val = local64_read(&event->count);
3444 local_irq_restore(flags);
3449 static int perf_event_read(struct perf_event *event, bool group)
3451 int event_cpu, ret = 0;
3454 * If event is enabled and currently active on a CPU, update the
3455 * value in the event structure:
3457 event_cpu = READ_ONCE(event->oncpu);
3459 if (event->state == PERF_EVENT_STATE_ACTIVE &&
3460 !cpu_isolated(event_cpu)) {
3461 struct perf_read_data data = {
3467 if ((unsigned int)event_cpu >= nr_cpu_ids)
3469 if (!event->attr.exclude_idle ||
3470 !per_cpu(is_idle, event_cpu)) {
3471 smp_call_function_single(event_cpu,
3472 __perf_event_read, &data, 1);
3475 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3476 struct perf_event_context *ctx = event->ctx;
3477 unsigned long flags;
3479 raw_spin_lock_irqsave(&ctx->lock, flags);
3481 * may read while context is not active
3482 * (e.g., thread is blocked), in that case
3483 * we cannot update context time
3485 if (ctx->is_active) {
3486 update_context_time(ctx);
3487 update_cgrp_time_from_event(event);
3490 update_group_times(event);
3492 update_event_times(event);
3493 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3500 * Initialize the perf_event context in a task_struct:
3502 static void __perf_event_init_context(struct perf_event_context *ctx)
3504 raw_spin_lock_init(&ctx->lock);
3505 mutex_init(&ctx->mutex);
3506 INIT_LIST_HEAD(&ctx->active_ctx_list);
3507 INIT_LIST_HEAD(&ctx->pinned_groups);
3508 INIT_LIST_HEAD(&ctx->flexible_groups);
3509 INIT_LIST_HEAD(&ctx->event_list);
3510 atomic_set(&ctx->refcount, 1);
3511 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3514 static struct perf_event_context *
3515 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3517 struct perf_event_context *ctx;
3519 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3523 __perf_event_init_context(ctx);
3526 get_task_struct(task);
3533 static struct task_struct *
3534 find_lively_task_by_vpid(pid_t vpid)
3536 struct task_struct *task;
3542 task = find_task_by_vpid(vpid);
3544 get_task_struct(task);
3548 return ERR_PTR(-ESRCH);
3554 * Returns a matching context with refcount and pincount.
3556 static struct perf_event_context *
3557 find_get_context(struct pmu *pmu, struct task_struct *task,
3558 struct perf_event *event)
3560 struct perf_event_context *ctx, *clone_ctx = NULL;
3561 struct perf_cpu_context *cpuctx;
3562 void *task_ctx_data = NULL;
3563 unsigned long flags;
3565 int cpu = event->cpu;
3568 /* Must be root to operate on a CPU event: */
3569 if (event->owner != EVENT_OWNER_KERNEL && perf_paranoid_cpu() &&
3570 !capable(CAP_SYS_ADMIN))
3571 return ERR_PTR(-EACCES);
3574 * We could be clever and allow to attach a event to an
3575 * offline CPU and activate it when the CPU comes up, but
3578 if (!cpu_online(cpu))
3579 return ERR_PTR(-ENODEV);
3581 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3590 ctxn = pmu->task_ctx_nr;
3594 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3595 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3596 if (!task_ctx_data) {
3603 ctx = perf_lock_task_context(task, ctxn, &flags);
3605 clone_ctx = unclone_ctx(ctx);
3608 if (task_ctx_data && !ctx->task_ctx_data) {
3609 ctx->task_ctx_data = task_ctx_data;
3610 task_ctx_data = NULL;
3612 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3617 ctx = alloc_perf_context(pmu, task);
3622 if (task_ctx_data) {
3623 ctx->task_ctx_data = task_ctx_data;
3624 task_ctx_data = NULL;
3628 mutex_lock(&task->perf_event_mutex);
3630 * If it has already passed perf_event_exit_task().
3631 * we must see PF_EXITING, it takes this mutex too.
3633 if (task->flags & PF_EXITING)
3635 else if (task->perf_event_ctxp[ctxn])
3640 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3642 mutex_unlock(&task->perf_event_mutex);
3644 if (unlikely(err)) {
3653 kfree(task_ctx_data);
3657 kfree(task_ctx_data);
3658 return ERR_PTR(err);
3661 static void perf_event_free_filter(struct perf_event *event);
3662 static void perf_event_free_bpf_prog(struct perf_event *event);
3664 static void free_event_rcu(struct rcu_head *head)
3666 struct perf_event *event;
3668 event = container_of(head, struct perf_event, rcu_head);
3670 put_pid_ns(event->ns);
3671 perf_event_free_filter(event);
3675 static void ring_buffer_attach(struct perf_event *event,
3676 struct ring_buffer *rb);
3678 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3683 if (is_cgroup_event(event))
3684 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3687 static void unaccount_event(struct perf_event *event)
3692 if (event->attach_state & PERF_ATTACH_TASK)
3693 static_key_slow_dec_deferred(&perf_sched_events);
3694 if (event->attr.mmap || event->attr.mmap_data)
3695 atomic_dec(&nr_mmap_events);
3696 if (event->attr.comm)
3697 atomic_dec(&nr_comm_events);
3698 if (event->attr.task)
3699 atomic_dec(&nr_task_events);
3700 if (event->attr.freq)
3701 atomic_dec(&nr_freq_events);
3702 if (event->attr.context_switch) {
3703 static_key_slow_dec_deferred(&perf_sched_events);
3704 atomic_dec(&nr_switch_events);
3706 if (is_cgroup_event(event))
3707 static_key_slow_dec_deferred(&perf_sched_events);
3708 if (has_branch_stack(event))
3709 static_key_slow_dec_deferred(&perf_sched_events);
3711 unaccount_event_cpu(event, event->cpu);
3715 * The following implement mutual exclusion of events on "exclusive" pmus
3716 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3717 * at a time, so we disallow creating events that might conflict, namely:
3719 * 1) cpu-wide events in the presence of per-task events,
3720 * 2) per-task events in the presence of cpu-wide events,
3721 * 3) two matching events on the same context.
3723 * The former two cases are handled in the allocation path (perf_event_alloc(),
3724 * __free_event()), the latter -- before the first perf_install_in_context().
3726 static int exclusive_event_init(struct perf_event *event)
3728 struct pmu *pmu = event->pmu;
3730 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3734 * Prevent co-existence of per-task and cpu-wide events on the
3735 * same exclusive pmu.
3737 * Negative pmu::exclusive_cnt means there are cpu-wide
3738 * events on this "exclusive" pmu, positive means there are
3741 * Since this is called in perf_event_alloc() path, event::ctx
3742 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3743 * to mean "per-task event", because unlike other attach states it
3744 * never gets cleared.
3746 if (event->attach_state & PERF_ATTACH_TASK) {
3747 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3750 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3757 static void exclusive_event_destroy(struct perf_event *event)
3759 struct pmu *pmu = event->pmu;
3761 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3764 /* see comment in exclusive_event_init() */
3765 if (event->attach_state & PERF_ATTACH_TASK)
3766 atomic_dec(&pmu->exclusive_cnt);
3768 atomic_inc(&pmu->exclusive_cnt);
3771 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3773 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3774 (e1->cpu == e2->cpu ||
3781 /* Called under the same ctx::mutex as perf_install_in_context() */
3782 static bool exclusive_event_installable(struct perf_event *event,
3783 struct perf_event_context *ctx)
3785 struct perf_event *iter_event;
3786 struct pmu *pmu = event->pmu;
3788 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3791 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3792 if (exclusive_event_match(iter_event, event))
3799 static void __free_event(struct perf_event *event)
3801 if (!event->parent) {
3802 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3803 put_callchain_buffers();
3806 perf_event_free_bpf_prog(event);
3809 event->destroy(event);
3811 if (event->pmu->free_drv_configs)
3812 event->pmu->free_drv_configs(event);
3815 put_ctx(event->ctx);
3818 exclusive_event_destroy(event);
3819 module_put(event->pmu->module);
3822 call_rcu(&event->rcu_head, free_event_rcu);
3825 static void _free_event(struct perf_event *event)
3827 irq_work_sync(&event->pending);
3829 unaccount_event(event);
3833 * Can happen when we close an event with re-directed output.
3835 * Since we have a 0 refcount, perf_mmap_close() will skip
3836 * over us; possibly making our ring_buffer_put() the last.
3838 mutex_lock(&event->mmap_mutex);
3839 ring_buffer_attach(event, NULL);
3840 mutex_unlock(&event->mmap_mutex);
3843 if (is_cgroup_event(event))
3844 perf_detach_cgroup(event);
3846 __free_event(event);
3850 * Used to free events which have a known refcount of 1, such as in error paths
3851 * where the event isn't exposed yet and inherited events.
3853 static void free_event(struct perf_event *event)
3855 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3856 "unexpected event refcount: %ld; ptr=%p\n",
3857 atomic_long_read(&event->refcount), event)) {
3858 /* leak to avoid use-after-free */
3866 * Remove user event from the owner task.
3868 static void perf_remove_from_owner(struct perf_event *event)
3870 struct task_struct *owner;
3873 owner = ACCESS_ONCE(event->owner);
3875 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3876 * !owner it means the list deletion is complete and we can indeed
3877 * free this event, otherwise we need to serialize on
3878 * owner->perf_event_mutex.
3880 smp_read_barrier_depends();
3883 * Since delayed_put_task_struct() also drops the last
3884 * task reference we can safely take a new reference
3885 * while holding the rcu_read_lock().
3887 get_task_struct(owner);
3893 * If we're here through perf_event_exit_task() we're already
3894 * holding ctx->mutex which would be an inversion wrt. the
3895 * normal lock order.
3897 * However we can safely take this lock because its the child
3900 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3903 * We have to re-check the event->owner field, if it is cleared
3904 * we raced with perf_event_exit_task(), acquiring the mutex
3905 * ensured they're done, and we can proceed with freeing the
3909 list_del_init(&event->owner_entry);
3910 mutex_unlock(&owner->perf_event_mutex);
3911 put_task_struct(owner);
3915 static void put_event(struct perf_event *event)
3917 struct perf_event_context *ctx;
3919 if (!atomic_long_dec_and_test(&event->refcount))
3922 if (!is_kernel_event(event))
3923 perf_remove_from_owner(event);
3926 * There are two ways this annotation is useful:
3928 * 1) there is a lock recursion from perf_event_exit_task
3929 * see the comment there.
3931 * 2) there is a lock-inversion with mmap_sem through
3932 * perf_read_group(), which takes faults while
3933 * holding ctx->mutex, however this is called after
3934 * the last filedesc died, so there is no possibility
3935 * to trigger the AB-BA case.
3937 ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3938 WARN_ON_ONCE(ctx->parent_ctx);
3939 perf_remove_from_context(event, true);
3940 perf_event_ctx_unlock(event, ctx);
3945 int perf_event_release_kernel(struct perf_event *event)
3950 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3953 * Called when the last reference to the file is gone.
3955 static int perf_release(struct inode *inode, struct file *file)
3957 struct perf_event *event = file->private_data;
3960 * Event can be in state OFF because of a constraint check.
3961 * Change to ACTIVE so that it gets cleaned up correctly.
3963 if ((event->state == PERF_EVENT_STATE_OFF) &&
3964 event->attr.constraint_duplicate)
3965 event->state = PERF_EVENT_STATE_ACTIVE;
3966 put_event(file->private_data);
3971 * Remove all orphanes events from the context.
3973 static void orphans_remove_work(struct work_struct *work)
3975 struct perf_event_context *ctx;
3976 struct perf_event *event, *tmp;
3978 ctx = container_of(work, struct perf_event_context,
3979 orphans_remove.work);
3981 mutex_lock(&ctx->mutex);
3982 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3983 struct perf_event *parent_event = event->parent;
3985 if (!is_orphaned_child(event))
3988 perf_remove_from_context(event, true);
3990 mutex_lock(&parent_event->child_mutex);
3991 list_del_init(&event->child_list);
3992 mutex_unlock(&parent_event->child_mutex);
3995 put_event(parent_event);
3998 raw_spin_lock_irq(&ctx->lock);
3999 ctx->orphans_remove_sched = false;
4000 raw_spin_unlock_irq(&ctx->lock);
4001 mutex_unlock(&ctx->mutex);
4006 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4008 struct perf_event *child;
4014 mutex_lock(&event->child_mutex);
4016 (void)perf_event_read(event, false);
4017 total += perf_event_count(event);
4019 *enabled += event->total_time_enabled +
4020 atomic64_read(&event->child_total_time_enabled);
4021 *running += event->total_time_running +
4022 atomic64_read(&event->child_total_time_running);
4024 list_for_each_entry(child, &event->child_list, child_list) {
4025 (void)perf_event_read(child, false);
4026 total += perf_event_count(child);
4027 *enabled += child->total_time_enabled;
4028 *running += child->total_time_running;
4030 mutex_unlock(&event->child_mutex);
4034 EXPORT_SYMBOL_GPL(perf_event_read_value);
4036 static int __perf_read_group_add(struct perf_event *leader,
4037 u64 read_format, u64 *values)
4039 struct perf_event *sub;
4040 int n = 1; /* skip @nr */
4043 ret = perf_event_read(leader, true);
4048 * Since we co-schedule groups, {enabled,running} times of siblings
4049 * will be identical to those of the leader, so we only publish one
4052 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4053 values[n++] += leader->total_time_enabled +
4054 atomic64_read(&leader->child_total_time_enabled);
4057 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4058 values[n++] += leader->total_time_running +
4059 atomic64_read(&leader->child_total_time_running);
4063 * Write {count,id} tuples for every sibling.
4065 values[n++] += perf_event_count(leader);
4066 if (read_format & PERF_FORMAT_ID)
4067 values[n++] = primary_event_id(leader);
4069 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4070 values[n++] += perf_event_count(sub);
4071 if (read_format & PERF_FORMAT_ID)
4072 values[n++] = primary_event_id(sub);
4078 static int perf_read_group(struct perf_event *event,
4079 u64 read_format, char __user *buf)
4081 struct perf_event *leader = event->group_leader, *child;
4082 struct perf_event_context *ctx = leader->ctx;
4086 lockdep_assert_held(&ctx->mutex);
4088 values = kzalloc(event->read_size, GFP_KERNEL);
4092 values[0] = 1 + leader->nr_siblings;
4095 * By locking the child_mutex of the leader we effectively
4096 * lock the child list of all siblings.. XXX explain how.
4098 mutex_lock(&leader->child_mutex);
4100 ret = __perf_read_group_add(leader, read_format, values);
4104 list_for_each_entry(child, &leader->child_list, child_list) {
4105 ret = __perf_read_group_add(child, read_format, values);
4110 mutex_unlock(&leader->child_mutex);
4112 ret = event->read_size;
4113 if (copy_to_user(buf, values, event->read_size))
4118 mutex_unlock(&leader->child_mutex);
4124 static int perf_read_one(struct perf_event *event,
4125 u64 read_format, char __user *buf)
4127 u64 enabled, running;
4131 values[n++] = perf_event_read_value(event, &enabled, &running);
4132 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4133 values[n++] = enabled;
4134 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4135 values[n++] = running;
4136 if (read_format & PERF_FORMAT_ID)
4137 values[n++] = primary_event_id(event);
4139 if (copy_to_user(buf, values, n * sizeof(u64)))
4142 return n * sizeof(u64);
4145 static bool is_event_hup(struct perf_event *event)
4149 if (event->state != PERF_EVENT_STATE_EXIT)
4152 mutex_lock(&event->child_mutex);
4153 no_children = list_empty(&event->child_list);
4154 mutex_unlock(&event->child_mutex);
4159 * Read the performance event - simple non blocking version for now
4162 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4164 u64 read_format = event->attr.read_format;
4168 * Return end-of-file for a read on a event that is in
4169 * error state (i.e. because it was pinned but it couldn't be
4170 * scheduled on to the CPU at some point).
4172 if (event->state == PERF_EVENT_STATE_ERROR)
4175 if (count < event->read_size)
4178 WARN_ON_ONCE(event->ctx->parent_ctx);
4179 if (read_format & PERF_FORMAT_GROUP)
4180 ret = perf_read_group(event, read_format, buf);
4182 ret = perf_read_one(event, read_format, buf);
4188 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4190 struct perf_event *event = file->private_data;
4191 struct perf_event_context *ctx;
4194 ctx = perf_event_ctx_lock(event);
4195 ret = __perf_read(event, buf, count);
4196 perf_event_ctx_unlock(event, ctx);
4201 static unsigned int perf_poll(struct file *file, poll_table *wait)
4203 struct perf_event *event = file->private_data;
4204 struct ring_buffer *rb;
4205 unsigned int events = POLLHUP;
4207 poll_wait(file, &event->waitq, wait);
4209 if (is_event_hup(event))
4213 * Pin the event->rb by taking event->mmap_mutex; otherwise
4214 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4216 mutex_lock(&event->mmap_mutex);
4219 events = atomic_xchg(&rb->poll, 0);
4220 mutex_unlock(&event->mmap_mutex);
4224 static void _perf_event_reset(struct perf_event *event)
4226 (void)perf_event_read(event, false);
4227 local64_set(&event->count, 0);
4228 perf_event_update_userpage(event);
4232 * Holding the top-level event's child_mutex means that any
4233 * descendant process that has inherited this event will block
4234 * in sync_child_event if it goes to exit, thus satisfying the
4235 * task existence requirements of perf_event_enable/disable.
4237 static void perf_event_for_each_child(struct perf_event *event,
4238 void (*func)(struct perf_event *))
4240 struct perf_event *child;
4242 WARN_ON_ONCE(event->ctx->parent_ctx);
4244 mutex_lock(&event->child_mutex);
4246 list_for_each_entry(child, &event->child_list, child_list)
4248 mutex_unlock(&event->child_mutex);
4251 static void perf_event_for_each(struct perf_event *event,
4252 void (*func)(struct perf_event *))
4254 struct perf_event_context *ctx = event->ctx;
4255 struct perf_event *sibling;
4257 lockdep_assert_held(&ctx->mutex);
4259 event = event->group_leader;
4261 perf_event_for_each_child(event, func);
4262 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4263 perf_event_for_each_child(sibling, func);
4266 struct period_event {
4267 struct perf_event *event;
4271 static int __perf_event_period(void *info)
4273 struct period_event *pe = info;
4274 struct perf_event *event = pe->event;
4275 struct perf_event_context *ctx = event->ctx;
4276 u64 value = pe->value;
4279 raw_spin_lock(&ctx->lock);
4280 if (event->attr.freq) {
4281 event->attr.sample_freq = value;
4283 event->attr.sample_period = value;
4284 event->hw.sample_period = value;
4287 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4289 perf_pmu_disable(ctx->pmu);
4290 event->pmu->stop(event, PERF_EF_UPDATE);
4293 local64_set(&event->hw.period_left, 0);
4296 event->pmu->start(event, PERF_EF_RELOAD);
4297 perf_pmu_enable(ctx->pmu);
4299 raw_spin_unlock(&ctx->lock);
4304 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4306 struct period_event pe = { .event = event, };
4307 struct perf_event_context *ctx = event->ctx;
4308 struct task_struct *task;
4311 if (!is_sampling_event(event))
4314 if (copy_from_user(&value, arg, sizeof(value)))
4320 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4327 cpu_function_call(event->cpu, __perf_event_period, &pe);
4332 if (!task_function_call(task, __perf_event_period, &pe))
4335 raw_spin_lock_irq(&ctx->lock);
4336 if (ctx->is_active) {
4337 raw_spin_unlock_irq(&ctx->lock);
4342 if (event->attr.freq) {
4343 event->attr.sample_freq = value;
4345 event->attr.sample_period = value;
4346 event->hw.sample_period = value;
4349 local64_set(&event->hw.period_left, 0);
4350 raw_spin_unlock_irq(&ctx->lock);
4355 static const struct file_operations perf_fops;
4357 static inline int perf_fget_light(int fd, struct fd *p)
4359 struct fd f = fdget(fd);
4363 if (f.file->f_op != &perf_fops) {
4371 static int perf_event_set_output(struct perf_event *event,
4372 struct perf_event *output_event);
4373 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4374 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4375 static int perf_event_drv_configs(struct perf_event *event,
4378 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4380 void (*func)(struct perf_event *);
4384 case PERF_EVENT_IOC_ENABLE:
4385 func = _perf_event_enable;
4387 case PERF_EVENT_IOC_DISABLE:
4388 func = _perf_event_disable;
4390 case PERF_EVENT_IOC_RESET:
4391 func = _perf_event_reset;
4394 case PERF_EVENT_IOC_REFRESH:
4395 return _perf_event_refresh(event, arg);
4397 case PERF_EVENT_IOC_PERIOD:
4398 return perf_event_period(event, (u64 __user *)arg);
4400 case PERF_EVENT_IOC_ID:
4402 u64 id = primary_event_id(event);
4404 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4409 case PERF_EVENT_IOC_SET_OUTPUT:
4413 struct perf_event *output_event;
4415 ret = perf_fget_light(arg, &output);
4418 output_event = output.file->private_data;
4419 ret = perf_event_set_output(event, output_event);
4422 ret = perf_event_set_output(event, NULL);
4427 case PERF_EVENT_IOC_SET_FILTER:
4428 return perf_event_set_filter(event, (void __user *)arg);
4430 case PERF_EVENT_IOC_SET_BPF:
4431 return perf_event_set_bpf_prog(event, arg);
4433 case PERF_EVENT_IOC_SET_DRV_CONFIGS:
4434 return perf_event_drv_configs(event, (void __user *)arg);
4440 if (flags & PERF_IOC_FLAG_GROUP)
4441 perf_event_for_each(event, func);
4443 perf_event_for_each_child(event, func);
4448 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4450 struct perf_event *event = file->private_data;
4451 struct perf_event_context *ctx;
4454 ctx = perf_event_ctx_lock(event);
4455 ret = _perf_ioctl(event, cmd, arg);
4456 perf_event_ctx_unlock(event, ctx);
4461 #ifdef CONFIG_COMPAT
4462 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4465 switch (_IOC_NR(cmd)) {
4466 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4467 case _IOC_NR(PERF_EVENT_IOC_ID):
4468 case _IOC_NR(PERF_EVENT_IOC_SET_DRV_CONFIGS):
4469 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4470 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4471 cmd &= ~IOCSIZE_MASK;
4472 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4476 return perf_ioctl(file, cmd, arg);
4479 # define perf_compat_ioctl NULL
4482 int perf_event_task_enable(void)
4484 struct perf_event_context *ctx;
4485 struct perf_event *event;
4487 mutex_lock(¤t->perf_event_mutex);
4488 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4489 ctx = perf_event_ctx_lock(event);
4490 perf_event_for_each_child(event, _perf_event_enable);
4491 perf_event_ctx_unlock(event, ctx);
4493 mutex_unlock(¤t->perf_event_mutex);
4498 int perf_event_task_disable(void)
4500 struct perf_event_context *ctx;
4501 struct perf_event *event;
4503 mutex_lock(¤t->perf_event_mutex);
4504 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4505 ctx = perf_event_ctx_lock(event);
4506 perf_event_for_each_child(event, _perf_event_disable);
4507 perf_event_ctx_unlock(event, ctx);
4509 mutex_unlock(¤t->perf_event_mutex);
4514 static int perf_event_index(struct perf_event *event)
4516 if (event->hw.state & PERF_HES_STOPPED)
4519 if (event->state != PERF_EVENT_STATE_ACTIVE)
4522 return event->pmu->event_idx(event);
4525 static void calc_timer_values(struct perf_event *event,
4532 *now = perf_clock();
4533 ctx_time = event->shadow_ctx_time + *now;
4534 *enabled = ctx_time - event->tstamp_enabled;
4535 *running = ctx_time - event->tstamp_running;
4538 static void perf_event_init_userpage(struct perf_event *event)
4540 struct perf_event_mmap_page *userpg;
4541 struct ring_buffer *rb;
4544 rb = rcu_dereference(event->rb);
4548 userpg = rb->user_page;
4550 /* Allow new userspace to detect that bit 0 is deprecated */
4551 userpg->cap_bit0_is_deprecated = 1;
4552 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4553 userpg->data_offset = PAGE_SIZE;
4554 userpg->data_size = perf_data_size(rb);
4560 void __weak arch_perf_update_userpage(
4561 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4566 * Callers need to ensure there can be no nesting of this function, otherwise
4567 * the seqlock logic goes bad. We can not serialize this because the arch
4568 * code calls this from NMI context.
4570 void perf_event_update_userpage(struct perf_event *event)
4572 struct perf_event_mmap_page *userpg;
4573 struct ring_buffer *rb;
4574 u64 enabled, running, now;
4577 rb = rcu_dereference(event->rb);
4582 * compute total_time_enabled, total_time_running
4583 * based on snapshot values taken when the event
4584 * was last scheduled in.
4586 * we cannot simply called update_context_time()
4587 * because of locking issue as we can be called in
4590 calc_timer_values(event, &now, &enabled, &running);
4592 userpg = rb->user_page;
4594 * Disable preemption so as to not let the corresponding user-space
4595 * spin too long if we get preempted.
4600 userpg->index = perf_event_index(event);
4601 userpg->offset = perf_event_count(event);
4603 userpg->offset -= local64_read(&event->hw.prev_count);
4605 userpg->time_enabled = enabled +
4606 atomic64_read(&event->child_total_time_enabled);
4608 userpg->time_running = running +
4609 atomic64_read(&event->child_total_time_running);
4611 arch_perf_update_userpage(event, userpg, now);
4620 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4622 struct perf_event *event = vma->vm_file->private_data;
4623 struct ring_buffer *rb;
4624 int ret = VM_FAULT_SIGBUS;
4626 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4627 if (vmf->pgoff == 0)
4633 rb = rcu_dereference(event->rb);
4637 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4640 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4644 get_page(vmf->page);
4645 vmf->page->mapping = vma->vm_file->f_mapping;
4646 vmf->page->index = vmf->pgoff;
4655 static void ring_buffer_attach(struct perf_event *event,
4656 struct ring_buffer *rb)
4658 struct ring_buffer *old_rb = NULL;
4659 unsigned long flags;
4663 * Should be impossible, we set this when removing
4664 * event->rb_entry and wait/clear when adding event->rb_entry.
4666 WARN_ON_ONCE(event->rcu_pending);
4669 spin_lock_irqsave(&old_rb->event_lock, flags);
4670 list_del_rcu(&event->rb_entry);
4671 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4673 event->rcu_batches = get_state_synchronize_rcu();
4674 event->rcu_pending = 1;
4678 if (event->rcu_pending) {
4679 cond_synchronize_rcu(event->rcu_batches);
4680 event->rcu_pending = 0;
4683 spin_lock_irqsave(&rb->event_lock, flags);
4684 list_add_rcu(&event->rb_entry, &rb->event_list);
4685 spin_unlock_irqrestore(&rb->event_lock, flags);
4688 rcu_assign_pointer(event->rb, rb);
4691 ring_buffer_put(old_rb);
4693 * Since we detached before setting the new rb, so that we
4694 * could attach the new rb, we could have missed a wakeup.
4697 wake_up_all(&event->waitq);
4701 static void ring_buffer_wakeup(struct perf_event *event)
4703 struct ring_buffer *rb;
4706 rb = rcu_dereference(event->rb);
4708 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4709 wake_up_all(&event->waitq);
4714 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4716 struct ring_buffer *rb;
4719 rb = rcu_dereference(event->rb);
4721 if (!atomic_inc_not_zero(&rb->refcount))
4729 void ring_buffer_put(struct ring_buffer *rb)
4731 if (!atomic_dec_and_test(&rb->refcount))
4734 WARN_ON_ONCE(!list_empty(&rb->event_list));
4736 call_rcu(&rb->rcu_head, rb_free_rcu);
4739 static void perf_mmap_open(struct vm_area_struct *vma)
4741 struct perf_event *event = vma->vm_file->private_data;
4743 atomic_inc(&event->mmap_count);
4744 atomic_inc(&event->rb->mmap_count);
4747 atomic_inc(&event->rb->aux_mmap_count);
4749 if (event->pmu->event_mapped)
4750 event->pmu->event_mapped(event);
4753 static void perf_pmu_output_stop(struct perf_event *event);
4756 * A buffer can be mmap()ed multiple times; either directly through the same
4757 * event, or through other events by use of perf_event_set_output().
4759 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4760 * the buffer here, where we still have a VM context. This means we need
4761 * to detach all events redirecting to us.
4763 static void perf_mmap_close(struct vm_area_struct *vma)
4765 struct perf_event *event = vma->vm_file->private_data;
4767 struct ring_buffer *rb = ring_buffer_get(event);
4768 struct user_struct *mmap_user = rb->mmap_user;
4769 int mmap_locked = rb->mmap_locked;
4770 unsigned long size = perf_data_size(rb);
4772 if (event->pmu->event_unmapped)
4773 event->pmu->event_unmapped(event);
4776 * rb->aux_mmap_count will always drop before rb->mmap_count and
4777 * event->mmap_count, so it is ok to use event->mmap_mutex to
4778 * serialize with perf_mmap here.
4780 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4781 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4783 * Stop all AUX events that are writing to this buffer,
4784 * so that we can free its AUX pages and corresponding PMU
4785 * data. Note that after rb::aux_mmap_count dropped to zero,
4786 * they won't start any more (see perf_aux_output_begin()).
4788 perf_pmu_output_stop(event);
4790 /* now it's safe to free the pages */
4791 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4792 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4794 /* this has to be the last one */
4796 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
4798 mutex_unlock(&event->mmap_mutex);
4801 atomic_dec(&rb->mmap_count);
4803 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4806 ring_buffer_attach(event, NULL);
4807 mutex_unlock(&event->mmap_mutex);
4809 /* If there's still other mmap()s of this buffer, we're done. */
4810 if (atomic_read(&rb->mmap_count))
4814 * No other mmap()s, detach from all other events that might redirect
4815 * into the now unreachable buffer. Somewhat complicated by the
4816 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4820 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4821 if (!atomic_long_inc_not_zero(&event->refcount)) {
4823 * This event is en-route to free_event() which will
4824 * detach it and remove it from the list.
4830 mutex_lock(&event->mmap_mutex);
4832 * Check we didn't race with perf_event_set_output() which can
4833 * swizzle the rb from under us while we were waiting to
4834 * acquire mmap_mutex.
4836 * If we find a different rb; ignore this event, a next
4837 * iteration will no longer find it on the list. We have to
4838 * still restart the iteration to make sure we're not now
4839 * iterating the wrong list.
4841 if (event->rb == rb)
4842 ring_buffer_attach(event, NULL);
4844 mutex_unlock(&event->mmap_mutex);
4848 * Restart the iteration; either we're on the wrong list or
4849 * destroyed its integrity by doing a deletion.
4856 * It could be there's still a few 0-ref events on the list; they'll
4857 * get cleaned up by free_event() -- they'll also still have their
4858 * ref on the rb and will free it whenever they are done with it.
4860 * Aside from that, this buffer is 'fully' detached and unmapped,
4861 * undo the VM accounting.
4864 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4865 vma->vm_mm->pinned_vm -= mmap_locked;
4866 free_uid(mmap_user);
4869 ring_buffer_put(rb); /* could be last */
4872 static const struct vm_operations_struct perf_mmap_vmops = {
4873 .open = perf_mmap_open,
4874 .close = perf_mmap_close, /* non mergable */
4875 .fault = perf_mmap_fault,
4876 .page_mkwrite = perf_mmap_fault,
4879 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4881 struct perf_event *event = file->private_data;
4882 unsigned long user_locked, user_lock_limit;
4883 struct user_struct *user = current_user();
4884 unsigned long locked, lock_limit;
4885 struct ring_buffer *rb = NULL;
4886 unsigned long vma_size;
4887 unsigned long nr_pages;
4888 long user_extra = 0, extra = 0;
4889 int ret = 0, flags = 0;
4892 * Don't allow mmap() of inherited per-task counters. This would
4893 * create a performance issue due to all children writing to the
4896 if (event->cpu == -1 && event->attr.inherit)
4899 if (!(vma->vm_flags & VM_SHARED))
4902 vma_size = vma->vm_end - vma->vm_start;
4904 if (vma->vm_pgoff == 0) {
4905 nr_pages = (vma_size / PAGE_SIZE) - 1;
4908 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4909 * mapped, all subsequent mappings should have the same size
4910 * and offset. Must be above the normal perf buffer.
4912 u64 aux_offset, aux_size;
4917 nr_pages = vma_size / PAGE_SIZE;
4919 mutex_lock(&event->mmap_mutex);
4926 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4927 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4929 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4932 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4935 /* already mapped with a different offset */
4936 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4939 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4942 /* already mapped with a different size */
4943 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4946 if (!is_power_of_2(nr_pages))
4949 if (!atomic_inc_not_zero(&rb->mmap_count))
4952 if (rb_has_aux(rb)) {
4953 atomic_inc(&rb->aux_mmap_count);
4958 atomic_set(&rb->aux_mmap_count, 1);
4959 user_extra = nr_pages;
4965 * If we have rb pages ensure they're a power-of-two number, so we
4966 * can do bitmasks instead of modulo.
4968 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4971 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4974 WARN_ON_ONCE(event->ctx->parent_ctx);
4976 mutex_lock(&event->mmap_mutex);
4978 if (event->rb->nr_pages != nr_pages) {
4983 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4985 * Raced against perf_mmap_close() through
4986 * perf_event_set_output(). Try again, hope for better
4989 mutex_unlock(&event->mmap_mutex);
4996 user_extra = nr_pages + 1;
4999 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5002 * Increase the limit linearly with more CPUs:
5004 user_lock_limit *= num_online_cpus();
5006 user_locked = atomic_long_read(&user->locked_vm);
5009 * sysctl_perf_event_mlock may have changed, so that
5010 * user->locked_vm > user_lock_limit
5012 if (user_locked > user_lock_limit)
5013 user_locked = user_lock_limit;
5014 user_locked += user_extra;
5016 if (user_locked > user_lock_limit)
5017 extra = user_locked - user_lock_limit;
5019 lock_limit = rlimit(RLIMIT_MEMLOCK);
5020 lock_limit >>= PAGE_SHIFT;
5021 locked = vma->vm_mm->pinned_vm + extra;
5023 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5024 !capable(CAP_IPC_LOCK)) {
5029 WARN_ON(!rb && event->rb);
5031 if (vma->vm_flags & VM_WRITE)
5032 flags |= RING_BUFFER_WRITABLE;
5035 rb = rb_alloc(nr_pages,
5036 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5044 atomic_set(&rb->mmap_count, 1);
5045 rb->mmap_user = get_current_user();
5046 rb->mmap_locked = extra;
5048 ring_buffer_attach(event, rb);
5050 perf_event_init_userpage(event);
5051 perf_event_update_userpage(event);
5053 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5054 event->attr.aux_watermark, flags);
5056 rb->aux_mmap_locked = extra;
5061 atomic_long_add(user_extra, &user->locked_vm);
5062 vma->vm_mm->pinned_vm += extra;
5064 atomic_inc(&event->mmap_count);
5066 atomic_dec(&rb->mmap_count);
5069 mutex_unlock(&event->mmap_mutex);
5072 * Since pinned accounting is per vm we cannot allow fork() to copy our
5075 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5076 vma->vm_ops = &perf_mmap_vmops;
5078 if (event->pmu->event_mapped)
5079 event->pmu->event_mapped(event);
5084 static int perf_fasync(int fd, struct file *filp, int on)
5086 struct inode *inode = file_inode(filp);
5087 struct perf_event *event = filp->private_data;
5090 mutex_lock(&inode->i_mutex);
5091 retval = fasync_helper(fd, filp, on, &event->fasync);
5092 mutex_unlock(&inode->i_mutex);
5100 static const struct file_operations perf_fops = {
5101 .llseek = no_llseek,
5102 .release = perf_release,
5105 .unlocked_ioctl = perf_ioctl,
5106 .compat_ioctl = perf_compat_ioctl,
5108 .fasync = perf_fasync,
5114 * If there's data, ensure we set the poll() state and publish everything
5115 * to user-space before waking everybody up.
5118 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5120 /* only the parent has fasync state */
5122 event = event->parent;
5123 return &event->fasync;
5126 void perf_event_wakeup(struct perf_event *event)
5128 ring_buffer_wakeup(event);
5130 if (event->pending_kill) {
5131 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5132 event->pending_kill = 0;
5136 static void perf_pending_event(struct irq_work *entry)
5138 struct perf_event *event = container_of(entry,
5139 struct perf_event, pending);
5142 rctx = perf_swevent_get_recursion_context();
5144 * If we 'fail' here, that's OK, it means recursion is already disabled
5145 * and we won't recurse 'further'.
5148 if (event->pending_disable) {
5149 event->pending_disable = 0;
5150 __perf_event_disable(event);
5153 if (event->pending_wakeup) {
5154 event->pending_wakeup = 0;
5155 perf_event_wakeup(event);
5159 perf_swevent_put_recursion_context(rctx);
5163 * We assume there is only KVM supporting the callbacks.
5164 * Later on, we might change it to a list if there is
5165 * another virtualization implementation supporting the callbacks.
5167 struct perf_guest_info_callbacks *perf_guest_cbs;
5169 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5171 perf_guest_cbs = cbs;
5174 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5176 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5178 perf_guest_cbs = NULL;
5181 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5184 perf_output_sample_regs(struct perf_output_handle *handle,
5185 struct pt_regs *regs, u64 mask)
5189 for_each_set_bit(bit, (const unsigned long *) &mask,
5190 sizeof(mask) * BITS_PER_BYTE) {
5193 val = perf_reg_value(regs, bit);
5194 perf_output_put(handle, val);
5198 static void perf_sample_regs_user(struct perf_regs *regs_user,
5199 struct pt_regs *regs,
5200 struct pt_regs *regs_user_copy)
5202 if (user_mode(regs)) {
5203 regs_user->abi = perf_reg_abi(current);
5204 regs_user->regs = regs;
5205 } else if (!(current->flags & PF_KTHREAD)) {
5206 perf_get_regs_user(regs_user, regs, regs_user_copy);
5208 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5209 regs_user->regs = NULL;
5213 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5214 struct pt_regs *regs)
5216 regs_intr->regs = regs;
5217 regs_intr->abi = perf_reg_abi(current);
5222 * Get remaining task size from user stack pointer.
5224 * It'd be better to take stack vma map and limit this more
5225 * precisly, but there's no way to get it safely under interrupt,
5226 * so using TASK_SIZE as limit.
5228 static u64 perf_ustack_task_size(struct pt_regs *regs)
5230 unsigned long addr = perf_user_stack_pointer(regs);
5232 if (!addr || addr >= TASK_SIZE)
5235 return TASK_SIZE - addr;
5239 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5240 struct pt_regs *regs)
5244 /* No regs, no stack pointer, no dump. */
5249 * Check if we fit in with the requested stack size into the:
5251 * If we don't, we limit the size to the TASK_SIZE.
5253 * - remaining sample size
5254 * If we don't, we customize the stack size to
5255 * fit in to the remaining sample size.
5258 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5259 stack_size = min(stack_size, (u16) task_size);
5261 /* Current header size plus static size and dynamic size. */
5262 header_size += 2 * sizeof(u64);
5264 /* Do we fit in with the current stack dump size? */
5265 if ((u16) (header_size + stack_size) < header_size) {
5267 * If we overflow the maximum size for the sample,
5268 * we customize the stack dump size to fit in.
5270 stack_size = USHRT_MAX - header_size - sizeof(u64);
5271 stack_size = round_up(stack_size, sizeof(u64));
5278 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5279 struct pt_regs *regs)
5281 /* Case of a kernel thread, nothing to dump */
5284 perf_output_put(handle, size);
5293 * - the size requested by user or the best one we can fit
5294 * in to the sample max size
5296 * - user stack dump data
5298 * - the actual dumped size
5302 perf_output_put(handle, dump_size);
5305 sp = perf_user_stack_pointer(regs);
5306 rem = __output_copy_user(handle, (void *) sp, dump_size);
5307 dyn_size = dump_size - rem;
5309 perf_output_skip(handle, rem);
5312 perf_output_put(handle, dyn_size);
5316 static void __perf_event_header__init_id(struct perf_event_header *header,
5317 struct perf_sample_data *data,
5318 struct perf_event *event)
5320 u64 sample_type = event->attr.sample_type;
5322 data->type = sample_type;
5323 header->size += event->id_header_size;
5325 if (sample_type & PERF_SAMPLE_TID) {
5326 /* namespace issues */
5327 data->tid_entry.pid = perf_event_pid(event, current);
5328 data->tid_entry.tid = perf_event_tid(event, current);
5331 if (sample_type & PERF_SAMPLE_TIME)
5332 data->time = perf_event_clock(event);
5334 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5335 data->id = primary_event_id(event);
5337 if (sample_type & PERF_SAMPLE_STREAM_ID)
5338 data->stream_id = event->id;
5340 if (sample_type & PERF_SAMPLE_CPU) {
5341 data->cpu_entry.cpu = raw_smp_processor_id();
5342 data->cpu_entry.reserved = 0;
5346 void perf_event_header__init_id(struct perf_event_header *header,
5347 struct perf_sample_data *data,
5348 struct perf_event *event)
5350 if (event->attr.sample_id_all)
5351 __perf_event_header__init_id(header, data, event);
5354 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5355 struct perf_sample_data *data)
5357 u64 sample_type = data->type;
5359 if (sample_type & PERF_SAMPLE_TID)
5360 perf_output_put(handle, data->tid_entry);
5362 if (sample_type & PERF_SAMPLE_TIME)
5363 perf_output_put(handle, data->time);
5365 if (sample_type & PERF_SAMPLE_ID)
5366 perf_output_put(handle, data->id);
5368 if (sample_type & PERF_SAMPLE_STREAM_ID)
5369 perf_output_put(handle, data->stream_id);
5371 if (sample_type & PERF_SAMPLE_CPU)
5372 perf_output_put(handle, data->cpu_entry);
5374 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5375 perf_output_put(handle, data->id);
5378 void perf_event__output_id_sample(struct perf_event *event,
5379 struct perf_output_handle *handle,
5380 struct perf_sample_data *sample)
5382 if (event->attr.sample_id_all)
5383 __perf_event__output_id_sample(handle, sample);
5386 static void perf_output_read_one(struct perf_output_handle *handle,
5387 struct perf_event *event,
5388 u64 enabled, u64 running)
5390 u64 read_format = event->attr.read_format;
5394 values[n++] = perf_event_count(event);
5395 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5396 values[n++] = enabled +
5397 atomic64_read(&event->child_total_time_enabled);
5399 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5400 values[n++] = running +
5401 atomic64_read(&event->child_total_time_running);
5403 if (read_format & PERF_FORMAT_ID)
5404 values[n++] = primary_event_id(event);
5406 __output_copy(handle, values, n * sizeof(u64));
5409 static void perf_output_read_group(struct perf_output_handle *handle,
5410 struct perf_event *event,
5411 u64 enabled, u64 running)
5413 struct perf_event *leader = event->group_leader, *sub;
5414 u64 read_format = event->attr.read_format;
5418 values[n++] = 1 + leader->nr_siblings;
5420 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5421 values[n++] = enabled;
5423 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5424 values[n++] = running;
5426 if ((leader != event) &&
5427 (leader->state == PERF_EVENT_STATE_ACTIVE))
5428 leader->pmu->read(leader);
5430 values[n++] = perf_event_count(leader);
5431 if (read_format & PERF_FORMAT_ID)
5432 values[n++] = primary_event_id(leader);
5434 __output_copy(handle, values, n * sizeof(u64));
5436 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5439 if ((sub != event) &&
5440 (sub->state == PERF_EVENT_STATE_ACTIVE))
5441 sub->pmu->read(sub);
5443 values[n++] = perf_event_count(sub);
5444 if (read_format & PERF_FORMAT_ID)
5445 values[n++] = primary_event_id(sub);
5447 __output_copy(handle, values, n * sizeof(u64));
5451 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5452 PERF_FORMAT_TOTAL_TIME_RUNNING)
5455 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5457 * The problem is that its both hard and excessively expensive to iterate the
5458 * child list, not to mention that its impossible to IPI the children running
5459 * on another CPU, from interrupt/NMI context.
5461 static void perf_output_read(struct perf_output_handle *handle,
5462 struct perf_event *event)
5464 u64 enabled = 0, running = 0, now;
5465 u64 read_format = event->attr.read_format;
5468 * compute total_time_enabled, total_time_running
5469 * based on snapshot values taken when the event
5470 * was last scheduled in.
5472 * we cannot simply called update_context_time()
5473 * because of locking issue as we are called in
5476 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5477 calc_timer_values(event, &now, &enabled, &running);
5479 if (event->attr.read_format & PERF_FORMAT_GROUP)
5480 perf_output_read_group(handle, event, enabled, running);
5482 perf_output_read_one(handle, event, enabled, running);
5485 void perf_output_sample(struct perf_output_handle *handle,
5486 struct perf_event_header *header,
5487 struct perf_sample_data *data,
5488 struct perf_event *event)
5490 u64 sample_type = data->type;
5492 perf_output_put(handle, *header);
5494 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5495 perf_output_put(handle, data->id);
5497 if (sample_type & PERF_SAMPLE_IP)
5498 perf_output_put(handle, data->ip);
5500 if (sample_type & PERF_SAMPLE_TID)
5501 perf_output_put(handle, data->tid_entry);
5503 if (sample_type & PERF_SAMPLE_TIME)
5504 perf_output_put(handle, data->time);
5506 if (sample_type & PERF_SAMPLE_ADDR)
5507 perf_output_put(handle, data->addr);
5509 if (sample_type & PERF_SAMPLE_ID)
5510 perf_output_put(handle, data->id);
5512 if (sample_type & PERF_SAMPLE_STREAM_ID)
5513 perf_output_put(handle, data->stream_id);
5515 if (sample_type & PERF_SAMPLE_CPU)
5516 perf_output_put(handle, data->cpu_entry);
5518 if (sample_type & PERF_SAMPLE_PERIOD)
5519 perf_output_put(handle, data->period);
5521 if (sample_type & PERF_SAMPLE_READ)
5522 perf_output_read(handle, event);
5524 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5525 if (data->callchain) {
5528 if (data->callchain)
5529 size += data->callchain->nr;
5531 size *= sizeof(u64);
5533 __output_copy(handle, data->callchain, size);
5536 perf_output_put(handle, nr);
5540 if (sample_type & PERF_SAMPLE_RAW) {
5542 u32 raw_size = data->raw->size;
5543 u32 real_size = round_up(raw_size + sizeof(u32),
5544 sizeof(u64)) - sizeof(u32);
5547 perf_output_put(handle, real_size);
5548 __output_copy(handle, data->raw->data, raw_size);
5549 if (real_size - raw_size)
5550 __output_copy(handle, &zero, real_size - raw_size);
5556 .size = sizeof(u32),
5559 perf_output_put(handle, raw);
5563 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5564 if (data->br_stack) {
5567 size = data->br_stack->nr
5568 * sizeof(struct perf_branch_entry);
5570 perf_output_put(handle, data->br_stack->nr);
5571 perf_output_copy(handle, data->br_stack->entries, size);
5574 * we always store at least the value of nr
5577 perf_output_put(handle, nr);
5581 if (sample_type & PERF_SAMPLE_REGS_USER) {
5582 u64 abi = data->regs_user.abi;
5585 * If there are no regs to dump, notice it through
5586 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5588 perf_output_put(handle, abi);
5591 u64 mask = event->attr.sample_regs_user;
5592 perf_output_sample_regs(handle,
5593 data->regs_user.regs,
5598 if (sample_type & PERF_SAMPLE_STACK_USER) {
5599 perf_output_sample_ustack(handle,
5600 data->stack_user_size,
5601 data->regs_user.regs);
5604 if (sample_type & PERF_SAMPLE_WEIGHT)
5605 perf_output_put(handle, data->weight);
5607 if (sample_type & PERF_SAMPLE_DATA_SRC)
5608 perf_output_put(handle, data->data_src.val);
5610 if (sample_type & PERF_SAMPLE_TRANSACTION)
5611 perf_output_put(handle, data->txn);
5613 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5614 u64 abi = data->regs_intr.abi;
5616 * If there are no regs to dump, notice it through
5617 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5619 perf_output_put(handle, abi);
5622 u64 mask = event->attr.sample_regs_intr;
5624 perf_output_sample_regs(handle,
5625 data->regs_intr.regs,
5630 if (!event->attr.watermark) {
5631 int wakeup_events = event->attr.wakeup_events;
5633 if (wakeup_events) {
5634 struct ring_buffer *rb = handle->rb;
5635 int events = local_inc_return(&rb->events);
5637 if (events >= wakeup_events) {
5638 local_sub(wakeup_events, &rb->events);
5639 local_inc(&rb->wakeup);
5645 void perf_prepare_sample(struct perf_event_header *header,
5646 struct perf_sample_data *data,
5647 struct perf_event *event,
5648 struct pt_regs *regs)
5650 u64 sample_type = event->attr.sample_type;
5652 header->type = PERF_RECORD_SAMPLE;
5653 header->size = sizeof(*header) + event->header_size;
5656 header->misc |= perf_misc_flags(regs);
5658 __perf_event_header__init_id(header, data, event);
5660 if (sample_type & PERF_SAMPLE_IP)
5661 data->ip = perf_instruction_pointer(regs);
5663 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5666 data->callchain = perf_callchain(event, regs);
5668 if (data->callchain)
5669 size += data->callchain->nr;
5671 header->size += size * sizeof(u64);
5674 if (sample_type & PERF_SAMPLE_RAW) {
5675 int size = sizeof(u32);
5678 size += data->raw->size;
5680 size += sizeof(u32);
5682 header->size += round_up(size, sizeof(u64));
5685 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5686 int size = sizeof(u64); /* nr */
5687 if (data->br_stack) {
5688 size += data->br_stack->nr
5689 * sizeof(struct perf_branch_entry);
5691 header->size += size;
5694 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5695 perf_sample_regs_user(&data->regs_user, regs,
5696 &data->regs_user_copy);
5698 if (sample_type & PERF_SAMPLE_REGS_USER) {
5699 /* regs dump ABI info */
5700 int size = sizeof(u64);
5702 if (data->regs_user.regs) {
5703 u64 mask = event->attr.sample_regs_user;
5704 size += hweight64(mask) * sizeof(u64);
5707 header->size += size;
5710 if (sample_type & PERF_SAMPLE_STACK_USER) {
5712 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5713 * processed as the last one or have additional check added
5714 * in case new sample type is added, because we could eat
5715 * up the rest of the sample size.
5717 u16 stack_size = event->attr.sample_stack_user;
5718 u16 size = sizeof(u64);
5720 stack_size = perf_sample_ustack_size(stack_size, header->size,
5721 data->regs_user.regs);
5724 * If there is something to dump, add space for the dump
5725 * itself and for the field that tells the dynamic size,
5726 * which is how many have been actually dumped.
5729 size += sizeof(u64) + stack_size;
5731 data->stack_user_size = stack_size;
5732 header->size += size;
5735 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5736 /* regs dump ABI info */
5737 int size = sizeof(u64);
5739 perf_sample_regs_intr(&data->regs_intr, regs);
5741 if (data->regs_intr.regs) {
5742 u64 mask = event->attr.sample_regs_intr;
5744 size += hweight64(mask) * sizeof(u64);
5747 header->size += size;
5751 void perf_event_output(struct perf_event *event,
5752 struct perf_sample_data *data,
5753 struct pt_regs *regs)
5755 struct perf_output_handle handle;
5756 struct perf_event_header header;
5758 /* protect the callchain buffers */
5761 perf_prepare_sample(&header, data, event, regs);
5763 if (perf_output_begin(&handle, event, header.size))
5766 perf_output_sample(&handle, &header, data, event);
5768 perf_output_end(&handle);
5778 struct perf_read_event {
5779 struct perf_event_header header;
5786 perf_event_read_event(struct perf_event *event,
5787 struct task_struct *task)
5789 struct perf_output_handle handle;
5790 struct perf_sample_data sample;
5791 struct perf_read_event read_event = {
5793 .type = PERF_RECORD_READ,
5795 .size = sizeof(read_event) + event->read_size,
5797 .pid = perf_event_pid(event, task),
5798 .tid = perf_event_tid(event, task),
5802 perf_event_header__init_id(&read_event.header, &sample, event);
5803 ret = perf_output_begin(&handle, event, read_event.header.size);
5807 perf_output_put(&handle, read_event);
5808 perf_output_read(&handle, event);
5809 perf_event__output_id_sample(event, &handle, &sample);
5811 perf_output_end(&handle);
5814 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5817 perf_event_aux_ctx(struct perf_event_context *ctx,
5818 perf_event_aux_output_cb output,
5821 struct perf_event *event;
5823 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5824 if (event->state < PERF_EVENT_STATE_INACTIVE)
5826 if (!event_filter_match(event))
5828 output(event, data);
5833 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5834 struct perf_event_context *task_ctx)
5838 perf_event_aux_ctx(task_ctx, output, data);
5844 perf_event_aux(perf_event_aux_output_cb output, void *data,
5845 struct perf_event_context *task_ctx)
5847 struct perf_cpu_context *cpuctx;
5848 struct perf_event_context *ctx;
5853 * If we have task_ctx != NULL we only notify
5854 * the task context itself. The task_ctx is set
5855 * only for EXIT events before releasing task
5859 perf_event_aux_task_ctx(output, data, task_ctx);
5864 list_for_each_entry_rcu(pmu, &pmus, entry) {
5865 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5866 if (cpuctx->unique_pmu != pmu)
5868 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5869 ctxn = pmu->task_ctx_nr;
5872 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5874 perf_event_aux_ctx(ctx, output, data);
5876 put_cpu_ptr(pmu->pmu_cpu_context);
5881 struct remote_output {
5882 struct ring_buffer *rb;
5886 static void __perf_event_output_stop(struct perf_event *event, void *data)
5888 struct perf_event *parent = event->parent;
5889 struct remote_output *ro = data;
5890 struct ring_buffer *rb = ro->rb;
5892 if (!has_aux(event))
5899 * In case of inheritance, it will be the parent that links to the
5900 * ring-buffer, but it will be the child that's actually using it:
5902 if (rcu_dereference(parent->rb) == rb)
5903 ro->err = __perf_event_stop(event);
5906 static int __perf_pmu_output_stop(void *info)
5908 struct perf_event *event = info;
5909 struct pmu *pmu = event->pmu;
5910 struct perf_cpu_context *cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5911 struct remote_output ro = {
5916 perf_event_aux_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro);
5917 if (cpuctx->task_ctx)
5918 perf_event_aux_ctx(cpuctx->task_ctx, __perf_event_output_stop,
5925 static void perf_pmu_output_stop(struct perf_event *event)
5927 struct perf_event *iter;
5932 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
5934 * For per-CPU events, we need to make sure that neither they
5935 * nor their children are running; for cpu==-1 events it's
5936 * sufficient to stop the event itself if it's active, since
5937 * it can't have children.
5941 cpu = READ_ONCE(iter->oncpu);
5946 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
5947 if (err == -EAGAIN) {
5956 * task tracking -- fork/exit
5958 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5961 struct perf_task_event {
5962 struct task_struct *task;
5963 struct perf_event_context *task_ctx;
5966 struct perf_event_header header;
5976 static int perf_event_task_match(struct perf_event *event)
5978 return event->attr.comm || event->attr.mmap ||
5979 event->attr.mmap2 || event->attr.mmap_data ||
5983 static void perf_event_task_output(struct perf_event *event,
5986 struct perf_task_event *task_event = data;
5987 struct perf_output_handle handle;
5988 struct perf_sample_data sample;
5989 struct task_struct *task = task_event->task;
5990 int ret, size = task_event->event_id.header.size;
5992 if (!perf_event_task_match(event))
5995 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5997 ret = perf_output_begin(&handle, event,
5998 task_event->event_id.header.size);
6002 task_event->event_id.pid = perf_event_pid(event, task);
6003 task_event->event_id.ppid = perf_event_pid(event, current);
6005 task_event->event_id.tid = perf_event_tid(event, task);
6006 task_event->event_id.ptid = perf_event_tid(event, current);
6008 task_event->event_id.time = perf_event_clock(event);
6010 perf_output_put(&handle, task_event->event_id);
6012 perf_event__output_id_sample(event, &handle, &sample);
6014 perf_output_end(&handle);
6016 task_event->event_id.header.size = size;
6019 static void perf_event_task(struct task_struct *task,
6020 struct perf_event_context *task_ctx,
6023 struct perf_task_event task_event;
6025 if (!atomic_read(&nr_comm_events) &&
6026 !atomic_read(&nr_mmap_events) &&
6027 !atomic_read(&nr_task_events))
6030 task_event = (struct perf_task_event){
6032 .task_ctx = task_ctx,
6035 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6037 .size = sizeof(task_event.event_id),
6047 perf_event_aux(perf_event_task_output,
6052 void perf_event_fork(struct task_struct *task)
6054 perf_event_task(task, NULL, 1);
6061 struct perf_comm_event {
6062 struct task_struct *task;
6067 struct perf_event_header header;
6074 static int perf_event_comm_match(struct perf_event *event)
6076 return event->attr.comm;
6079 static void perf_event_comm_output(struct perf_event *event,
6082 struct perf_comm_event *comm_event = data;
6083 struct perf_output_handle handle;
6084 struct perf_sample_data sample;
6085 int size = comm_event->event_id.header.size;
6088 if (!perf_event_comm_match(event))
6091 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6092 ret = perf_output_begin(&handle, event,
6093 comm_event->event_id.header.size);
6098 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6099 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6101 perf_output_put(&handle, comm_event->event_id);
6102 __output_copy(&handle, comm_event->comm,
6103 comm_event->comm_size);
6105 perf_event__output_id_sample(event, &handle, &sample);
6107 perf_output_end(&handle);
6109 comm_event->event_id.header.size = size;
6112 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6114 char comm[TASK_COMM_LEN];
6117 memset(comm, 0, sizeof(comm));
6118 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6119 size = ALIGN(strlen(comm)+1, sizeof(u64));
6121 comm_event->comm = comm;
6122 comm_event->comm_size = size;
6124 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6126 perf_event_aux(perf_event_comm_output,
6131 void perf_event_comm(struct task_struct *task, bool exec)
6133 struct perf_comm_event comm_event;
6135 if (!atomic_read(&nr_comm_events))
6138 comm_event = (struct perf_comm_event){
6144 .type = PERF_RECORD_COMM,
6145 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6153 perf_event_comm_event(&comm_event);
6160 struct perf_mmap_event {
6161 struct vm_area_struct *vma;
6163 const char *file_name;
6171 struct perf_event_header header;
6181 static int perf_event_mmap_match(struct perf_event *event,
6184 struct perf_mmap_event *mmap_event = data;
6185 struct vm_area_struct *vma = mmap_event->vma;
6186 int executable = vma->vm_flags & VM_EXEC;
6188 return (!executable && event->attr.mmap_data) ||
6189 (executable && (event->attr.mmap || event->attr.mmap2));
6192 static void perf_event_mmap_output(struct perf_event *event,
6195 struct perf_mmap_event *mmap_event = data;
6196 struct perf_output_handle handle;
6197 struct perf_sample_data sample;
6198 int size = mmap_event->event_id.header.size;
6199 u32 type = mmap_event->event_id.header.type;
6202 if (!perf_event_mmap_match(event, data))
6205 if (event->attr.mmap2) {
6206 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6207 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6208 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6209 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6210 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6211 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6212 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6215 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6216 ret = perf_output_begin(&handle, event,
6217 mmap_event->event_id.header.size);
6221 mmap_event->event_id.pid = perf_event_pid(event, current);
6222 mmap_event->event_id.tid = perf_event_tid(event, current);
6224 perf_output_put(&handle, mmap_event->event_id);
6226 if (event->attr.mmap2) {
6227 perf_output_put(&handle, mmap_event->maj);
6228 perf_output_put(&handle, mmap_event->min);
6229 perf_output_put(&handle, mmap_event->ino);
6230 perf_output_put(&handle, mmap_event->ino_generation);
6231 perf_output_put(&handle, mmap_event->prot);
6232 perf_output_put(&handle, mmap_event->flags);
6235 __output_copy(&handle, mmap_event->file_name,
6236 mmap_event->file_size);
6238 perf_event__output_id_sample(event, &handle, &sample);
6240 perf_output_end(&handle);
6242 mmap_event->event_id.header.size = size;
6243 mmap_event->event_id.header.type = type;
6246 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6248 struct vm_area_struct *vma = mmap_event->vma;
6249 struct file *file = vma->vm_file;
6250 int maj = 0, min = 0;
6251 u64 ino = 0, gen = 0;
6252 u32 prot = 0, flags = 0;
6258 if (vma->vm_flags & VM_READ)
6260 if (vma->vm_flags & VM_WRITE)
6262 if (vma->vm_flags & VM_EXEC)
6265 if (vma->vm_flags & VM_MAYSHARE)
6268 flags = MAP_PRIVATE;
6270 if (vma->vm_flags & VM_DENYWRITE)
6271 flags |= MAP_DENYWRITE;
6272 if (vma->vm_flags & VM_MAYEXEC)
6273 flags |= MAP_EXECUTABLE;
6274 if (vma->vm_flags & VM_LOCKED)
6275 flags |= MAP_LOCKED;
6276 if (vma->vm_flags & VM_HUGETLB)
6277 flags |= MAP_HUGETLB;
6280 struct inode *inode;
6283 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6289 * d_path() works from the end of the rb backwards, so we
6290 * need to add enough zero bytes after the string to handle
6291 * the 64bit alignment we do later.
6293 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6298 inode = file_inode(vma->vm_file);
6299 dev = inode->i_sb->s_dev;
6301 gen = inode->i_generation;
6307 if (vma->vm_ops && vma->vm_ops->name) {
6308 name = (char *) vma->vm_ops->name(vma);
6313 name = (char *)arch_vma_name(vma);
6317 if (vma->vm_start <= vma->vm_mm->start_brk &&
6318 vma->vm_end >= vma->vm_mm->brk) {
6322 if (vma->vm_start <= vma->vm_mm->start_stack &&
6323 vma->vm_end >= vma->vm_mm->start_stack) {
6333 strlcpy(tmp, name, sizeof(tmp));
6337 * Since our buffer works in 8 byte units we need to align our string
6338 * size to a multiple of 8. However, we must guarantee the tail end is
6339 * zero'd out to avoid leaking random bits to userspace.
6341 size = strlen(name)+1;
6342 while (!IS_ALIGNED(size, sizeof(u64)))
6343 name[size++] = '\0';
6345 mmap_event->file_name = name;
6346 mmap_event->file_size = size;
6347 mmap_event->maj = maj;
6348 mmap_event->min = min;
6349 mmap_event->ino = ino;
6350 mmap_event->ino_generation = gen;
6351 mmap_event->prot = prot;
6352 mmap_event->flags = flags;
6354 if (!(vma->vm_flags & VM_EXEC))
6355 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6357 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6359 perf_event_aux(perf_event_mmap_output,
6366 void perf_event_mmap(struct vm_area_struct *vma)
6368 struct perf_mmap_event mmap_event;
6370 if (!atomic_read(&nr_mmap_events))
6373 mmap_event = (struct perf_mmap_event){
6379 .type = PERF_RECORD_MMAP,
6380 .misc = PERF_RECORD_MISC_USER,
6385 .start = vma->vm_start,
6386 .len = vma->vm_end - vma->vm_start,
6387 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6389 /* .maj (attr_mmap2 only) */
6390 /* .min (attr_mmap2 only) */
6391 /* .ino (attr_mmap2 only) */
6392 /* .ino_generation (attr_mmap2 only) */
6393 /* .prot (attr_mmap2 only) */
6394 /* .flags (attr_mmap2 only) */
6397 perf_event_mmap_event(&mmap_event);
6400 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6401 unsigned long size, u64 flags)
6403 struct perf_output_handle handle;
6404 struct perf_sample_data sample;
6405 struct perf_aux_event {
6406 struct perf_event_header header;
6412 .type = PERF_RECORD_AUX,
6414 .size = sizeof(rec),
6422 perf_event_header__init_id(&rec.header, &sample, event);
6423 ret = perf_output_begin(&handle, event, rec.header.size);
6428 perf_output_put(&handle, rec);
6429 perf_event__output_id_sample(event, &handle, &sample);
6431 perf_output_end(&handle);
6435 * Lost/dropped samples logging
6437 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6439 struct perf_output_handle handle;
6440 struct perf_sample_data sample;
6444 struct perf_event_header header;
6446 } lost_samples_event = {
6448 .type = PERF_RECORD_LOST_SAMPLES,
6450 .size = sizeof(lost_samples_event),
6455 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6457 ret = perf_output_begin(&handle, event,
6458 lost_samples_event.header.size);
6462 perf_output_put(&handle, lost_samples_event);
6463 perf_event__output_id_sample(event, &handle, &sample);
6464 perf_output_end(&handle);
6468 * context_switch tracking
6471 struct perf_switch_event {
6472 struct task_struct *task;
6473 struct task_struct *next_prev;
6476 struct perf_event_header header;
6482 static int perf_event_switch_match(struct perf_event *event)
6484 return event->attr.context_switch;
6487 static void perf_event_switch_output(struct perf_event *event, void *data)
6489 struct perf_switch_event *se = data;
6490 struct perf_output_handle handle;
6491 struct perf_sample_data sample;
6494 if (!perf_event_switch_match(event))
6497 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6498 if (event->ctx->task) {
6499 se->event_id.header.type = PERF_RECORD_SWITCH;
6500 se->event_id.header.size = sizeof(se->event_id.header);
6502 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6503 se->event_id.header.size = sizeof(se->event_id);
6504 se->event_id.next_prev_pid =
6505 perf_event_pid(event, se->next_prev);
6506 se->event_id.next_prev_tid =
6507 perf_event_tid(event, se->next_prev);
6510 perf_event_header__init_id(&se->event_id.header, &sample, event);
6512 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6516 if (event->ctx->task)
6517 perf_output_put(&handle, se->event_id.header);
6519 perf_output_put(&handle, se->event_id);
6521 perf_event__output_id_sample(event, &handle, &sample);
6523 perf_output_end(&handle);
6526 static void perf_event_switch(struct task_struct *task,
6527 struct task_struct *next_prev, bool sched_in)
6529 struct perf_switch_event switch_event;
6531 /* N.B. caller checks nr_switch_events != 0 */
6533 switch_event = (struct perf_switch_event){
6535 .next_prev = next_prev,
6539 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6542 /* .next_prev_pid */
6543 /* .next_prev_tid */
6547 perf_event_aux(perf_event_switch_output,
6553 * IRQ throttle logging
6556 static void perf_log_throttle(struct perf_event *event, int enable)
6558 struct perf_output_handle handle;
6559 struct perf_sample_data sample;
6563 struct perf_event_header header;
6567 } throttle_event = {
6569 .type = PERF_RECORD_THROTTLE,
6571 .size = sizeof(throttle_event),
6573 .time = perf_event_clock(event),
6574 .id = primary_event_id(event),
6575 .stream_id = event->id,
6579 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6581 perf_event_header__init_id(&throttle_event.header, &sample, event);
6583 ret = perf_output_begin(&handle, event,
6584 throttle_event.header.size);
6588 perf_output_put(&handle, throttle_event);
6589 perf_event__output_id_sample(event, &handle, &sample);
6590 perf_output_end(&handle);
6593 static void perf_log_itrace_start(struct perf_event *event)
6595 struct perf_output_handle handle;
6596 struct perf_sample_data sample;
6597 struct perf_aux_event {
6598 struct perf_event_header header;
6605 event = event->parent;
6607 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6608 event->hw.itrace_started)
6611 rec.header.type = PERF_RECORD_ITRACE_START;
6612 rec.header.misc = 0;
6613 rec.header.size = sizeof(rec);
6614 rec.pid = perf_event_pid(event, current);
6615 rec.tid = perf_event_tid(event, current);
6617 perf_event_header__init_id(&rec.header, &sample, event);
6618 ret = perf_output_begin(&handle, event, rec.header.size);
6623 perf_output_put(&handle, rec);
6624 perf_event__output_id_sample(event, &handle, &sample);
6626 perf_output_end(&handle);
6630 * Generic event overflow handling, sampling.
6633 static int __perf_event_overflow(struct perf_event *event,
6634 int throttle, struct perf_sample_data *data,
6635 struct pt_regs *regs)
6637 int events = atomic_read(&event->event_limit);
6638 struct hw_perf_event *hwc = &event->hw;
6643 * Non-sampling counters might still use the PMI to fold short
6644 * hardware counters, ignore those.
6646 if (unlikely(!is_sampling_event(event)))
6649 seq = __this_cpu_read(perf_throttled_seq);
6650 if (seq != hwc->interrupts_seq) {
6651 hwc->interrupts_seq = seq;
6652 hwc->interrupts = 1;
6655 if (unlikely(throttle
6656 && hwc->interrupts >= max_samples_per_tick)) {
6657 __this_cpu_inc(perf_throttled_count);
6658 hwc->interrupts = MAX_INTERRUPTS;
6659 perf_log_throttle(event, 0);
6660 tick_nohz_full_kick();
6665 if (event->attr.freq) {
6666 u64 now = perf_clock();
6667 s64 delta = now - hwc->freq_time_stamp;
6669 hwc->freq_time_stamp = now;
6671 if (delta > 0 && delta < 2*TICK_NSEC)
6672 perf_adjust_period(event, delta, hwc->last_period, true);
6676 * XXX event_limit might not quite work as expected on inherited
6680 event->pending_kill = POLL_IN;
6681 if (events && atomic_dec_and_test(&event->event_limit)) {
6683 event->pending_kill = POLL_HUP;
6684 event->pending_disable = 1;
6685 irq_work_queue(&event->pending);
6688 if (event->overflow_handler)
6689 event->overflow_handler(event, data, regs);
6691 perf_event_output(event, data, regs);
6693 if (*perf_event_fasync(event) && event->pending_kill) {
6694 event->pending_wakeup = 1;
6695 irq_work_queue(&event->pending);
6701 int perf_event_overflow(struct perf_event *event,
6702 struct perf_sample_data *data,
6703 struct pt_regs *regs)
6705 return __perf_event_overflow(event, 1, data, regs);
6709 * Generic software event infrastructure
6712 struct swevent_htable {
6713 struct swevent_hlist *swevent_hlist;
6714 struct mutex hlist_mutex;
6717 /* Recursion avoidance in each contexts */
6718 int recursion[PERF_NR_CONTEXTS];
6721 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6724 * We directly increment event->count and keep a second value in
6725 * event->hw.period_left to count intervals. This period event
6726 * is kept in the range [-sample_period, 0] so that we can use the
6730 u64 perf_swevent_set_period(struct perf_event *event)
6732 struct hw_perf_event *hwc = &event->hw;
6733 u64 period = hwc->last_period;
6737 hwc->last_period = hwc->sample_period;
6740 old = val = local64_read(&hwc->period_left);
6744 nr = div64_u64(period + val, period);
6745 offset = nr * period;
6747 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6753 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6754 struct perf_sample_data *data,
6755 struct pt_regs *regs)
6757 struct hw_perf_event *hwc = &event->hw;
6761 overflow = perf_swevent_set_period(event);
6763 if (hwc->interrupts == MAX_INTERRUPTS)
6766 for (; overflow; overflow--) {
6767 if (__perf_event_overflow(event, throttle,
6770 * We inhibit the overflow from happening when
6771 * hwc->interrupts == MAX_INTERRUPTS.
6779 static void perf_swevent_event(struct perf_event *event, u64 nr,
6780 struct perf_sample_data *data,
6781 struct pt_regs *regs)
6783 struct hw_perf_event *hwc = &event->hw;
6785 local64_add(nr, &event->count);
6790 if (!is_sampling_event(event))
6793 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6795 return perf_swevent_overflow(event, 1, data, regs);
6797 data->period = event->hw.last_period;
6799 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6800 return perf_swevent_overflow(event, 1, data, regs);
6802 if (local64_add_negative(nr, &hwc->period_left))
6805 perf_swevent_overflow(event, 0, data, regs);
6808 static int perf_exclude_event(struct perf_event *event,
6809 struct pt_regs *regs)
6811 if (event->hw.state & PERF_HES_STOPPED)
6815 if (event->attr.exclude_user && user_mode(regs))
6818 if (event->attr.exclude_kernel && !user_mode(regs))
6825 static int perf_swevent_match(struct perf_event *event,
6826 enum perf_type_id type,
6828 struct perf_sample_data *data,
6829 struct pt_regs *regs)
6831 if (event->attr.type != type)
6834 if (event->attr.config != event_id)
6837 if (perf_exclude_event(event, regs))
6843 static inline u64 swevent_hash(u64 type, u32 event_id)
6845 u64 val = event_id | (type << 32);
6847 return hash_64(val, SWEVENT_HLIST_BITS);
6850 static inline struct hlist_head *
6851 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6853 u64 hash = swevent_hash(type, event_id);
6855 return &hlist->heads[hash];
6858 /* For the read side: events when they trigger */
6859 static inline struct hlist_head *
6860 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6862 struct swevent_hlist *hlist;
6864 hlist = rcu_dereference(swhash->swevent_hlist);
6868 return __find_swevent_head(hlist, type, event_id);
6871 /* For the event head insertion and removal in the hlist */
6872 static inline struct hlist_head *
6873 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6875 struct swevent_hlist *hlist;
6876 u32 event_id = event->attr.config;
6877 u64 type = event->attr.type;
6880 * Event scheduling is always serialized against hlist allocation
6881 * and release. Which makes the protected version suitable here.
6882 * The context lock guarantees that.
6884 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6885 lockdep_is_held(&event->ctx->lock));
6889 return __find_swevent_head(hlist, type, event_id);
6892 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6894 struct perf_sample_data *data,
6895 struct pt_regs *regs)
6897 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6898 struct perf_event *event;
6899 struct hlist_head *head;
6902 head = find_swevent_head_rcu(swhash, type, event_id);
6906 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6907 if (perf_swevent_match(event, type, event_id, data, regs))
6908 perf_swevent_event(event, nr, data, regs);
6914 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6916 int perf_swevent_get_recursion_context(void)
6918 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6920 return get_recursion_context(swhash->recursion);
6922 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6924 inline void perf_swevent_put_recursion_context(int rctx)
6926 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6928 put_recursion_context(swhash->recursion, rctx);
6931 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6933 struct perf_sample_data data;
6935 if (WARN_ON_ONCE(!regs))
6938 perf_sample_data_init(&data, addr, 0);
6939 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6942 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6946 preempt_disable_notrace();
6947 rctx = perf_swevent_get_recursion_context();
6948 if (unlikely(rctx < 0))
6951 ___perf_sw_event(event_id, nr, regs, addr);
6953 perf_swevent_put_recursion_context(rctx);
6955 preempt_enable_notrace();
6958 static void perf_swevent_read(struct perf_event *event)
6962 static int perf_swevent_add(struct perf_event *event, int flags)
6964 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6965 struct hw_perf_event *hwc = &event->hw;
6966 struct hlist_head *head;
6968 if (is_sampling_event(event)) {
6969 hwc->last_period = hwc->sample_period;
6970 perf_swevent_set_period(event);
6973 hwc->state = !(flags & PERF_EF_START);
6975 head = find_swevent_head(swhash, event);
6976 if (WARN_ON_ONCE(!head))
6979 hlist_add_head_rcu(&event->hlist_entry, head);
6980 perf_event_update_userpage(event);
6985 static void perf_swevent_del(struct perf_event *event, int flags)
6987 hlist_del_rcu(&event->hlist_entry);
6990 static void perf_swevent_start(struct perf_event *event, int flags)
6992 event->hw.state = 0;
6995 static void perf_swevent_stop(struct perf_event *event, int flags)
6997 event->hw.state = PERF_HES_STOPPED;
7000 /* Deref the hlist from the update side */
7001 static inline struct swevent_hlist *
7002 swevent_hlist_deref(struct swevent_htable *swhash)
7004 return rcu_dereference_protected(swhash->swevent_hlist,
7005 lockdep_is_held(&swhash->hlist_mutex));
7008 static void swevent_hlist_release(struct swevent_htable *swhash)
7010 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7015 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7016 kfree_rcu(hlist, rcu_head);
7019 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
7021 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7023 mutex_lock(&swhash->hlist_mutex);
7025 if (!--swhash->hlist_refcount)
7026 swevent_hlist_release(swhash);
7028 mutex_unlock(&swhash->hlist_mutex);
7031 static void swevent_hlist_put(struct perf_event *event)
7035 for_each_possible_cpu(cpu)
7036 swevent_hlist_put_cpu(event, cpu);
7039 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
7041 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7044 mutex_lock(&swhash->hlist_mutex);
7045 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7046 struct swevent_hlist *hlist;
7048 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7053 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7055 swhash->hlist_refcount++;
7057 mutex_unlock(&swhash->hlist_mutex);
7062 static int swevent_hlist_get(struct perf_event *event)
7065 int cpu, failed_cpu;
7068 for_each_possible_cpu(cpu) {
7069 err = swevent_hlist_get_cpu(event, cpu);
7079 for_each_possible_cpu(cpu) {
7080 if (cpu == failed_cpu)
7082 swevent_hlist_put_cpu(event, cpu);
7089 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7091 static void sw_perf_event_destroy(struct perf_event *event)
7093 u64 event_id = event->attr.config;
7095 WARN_ON(event->parent);
7097 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7098 swevent_hlist_put(event);
7101 static int perf_swevent_init(struct perf_event *event)
7103 u64 event_id = event->attr.config;
7105 if (event->attr.type != PERF_TYPE_SOFTWARE)
7109 * no branch sampling for software events
7111 if (has_branch_stack(event))
7115 case PERF_COUNT_SW_CPU_CLOCK:
7116 case PERF_COUNT_SW_TASK_CLOCK:
7123 if (event_id >= PERF_COUNT_SW_MAX)
7126 if (!event->parent) {
7129 err = swevent_hlist_get(event);
7133 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7134 event->destroy = sw_perf_event_destroy;
7140 static struct pmu perf_swevent = {
7141 .task_ctx_nr = perf_sw_context,
7143 .capabilities = PERF_PMU_CAP_NO_NMI,
7145 .event_init = perf_swevent_init,
7146 .add = perf_swevent_add,
7147 .del = perf_swevent_del,
7148 .start = perf_swevent_start,
7149 .stop = perf_swevent_stop,
7150 .read = perf_swevent_read,
7152 .events_across_hotplug = 1,
7155 #ifdef CONFIG_EVENT_TRACING
7157 static int perf_tp_filter_match(struct perf_event *event,
7158 struct perf_sample_data *data)
7160 void *record = data->raw->data;
7162 /* only top level events have filters set */
7164 event = event->parent;
7166 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7171 static int perf_tp_event_match(struct perf_event *event,
7172 struct perf_sample_data *data,
7173 struct pt_regs *regs)
7175 if (event->hw.state & PERF_HES_STOPPED)
7178 * All tracepoints are from kernel-space.
7180 if (event->attr.exclude_kernel)
7183 if (!perf_tp_filter_match(event, data))
7189 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
7190 struct pt_regs *regs, struct hlist_head *head, int rctx,
7191 struct task_struct *task)
7193 struct perf_sample_data data;
7194 struct perf_event *event;
7196 struct perf_raw_record raw = {
7201 perf_sample_data_init(&data, addr, 0);
7204 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7205 if (perf_tp_event_match(event, &data, regs))
7206 perf_swevent_event(event, count, &data, regs);
7210 * If we got specified a target task, also iterate its context and
7211 * deliver this event there too.
7213 if (task && task != current) {
7214 struct perf_event_context *ctx;
7215 struct trace_entry *entry = record;
7218 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7222 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7223 if (event->cpu != smp_processor_id())
7225 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7227 if (event->attr.config != entry->type)
7229 if (perf_tp_event_match(event, &data, regs))
7230 perf_swevent_event(event, count, &data, regs);
7236 perf_swevent_put_recursion_context(rctx);
7238 EXPORT_SYMBOL_GPL(perf_tp_event);
7240 static void tp_perf_event_destroy(struct perf_event *event)
7242 perf_trace_destroy(event);
7245 static int perf_tp_event_init(struct perf_event *event)
7249 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7253 * no branch sampling for tracepoint events
7255 if (has_branch_stack(event))
7258 err = perf_trace_init(event);
7262 event->destroy = tp_perf_event_destroy;
7267 static struct pmu perf_tracepoint = {
7268 .task_ctx_nr = perf_sw_context,
7270 .event_init = perf_tp_event_init,
7271 .add = perf_trace_add,
7272 .del = perf_trace_del,
7273 .start = perf_swevent_start,
7274 .stop = perf_swevent_stop,
7275 .read = perf_swevent_read,
7277 .events_across_hotplug = 1,
7280 static inline void perf_tp_register(void)
7282 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7285 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7290 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7293 filter_str = strndup_user(arg, PAGE_SIZE);
7294 if (IS_ERR(filter_str))
7295 return PTR_ERR(filter_str);
7297 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7303 static void perf_event_free_filter(struct perf_event *event)
7305 ftrace_profile_free_filter(event);
7308 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7310 struct bpf_prog *prog;
7312 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7315 if (event->tp_event->prog)
7318 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7319 /* bpf programs can only be attached to u/kprobes */
7322 prog = bpf_prog_get(prog_fd);
7324 return PTR_ERR(prog);
7326 if (prog->type != BPF_PROG_TYPE_KPROBE) {
7327 /* valid fd, but invalid bpf program type */
7332 event->tp_event->prog = prog;
7333 event->tp_event->bpf_prog_owner = event;
7338 static void perf_event_free_bpf_prog(struct perf_event *event)
7340 struct bpf_prog *prog;
7342 if (!event->tp_event)
7345 prog = event->tp_event->prog;
7346 if (prog && event->tp_event->bpf_prog_owner == event) {
7347 event->tp_event->prog = NULL;
7354 static inline void perf_tp_register(void)
7358 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7363 static void perf_event_free_filter(struct perf_event *event)
7367 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7372 static void perf_event_free_bpf_prog(struct perf_event *event)
7375 #endif /* CONFIG_EVENT_TRACING */
7377 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7378 void perf_bp_event(struct perf_event *bp, void *data)
7380 struct perf_sample_data sample;
7381 struct pt_regs *regs = data;
7383 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7385 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7386 perf_swevent_event(bp, 1, &sample, regs);
7390 static int perf_event_drv_configs(struct perf_event *event,
7393 if (!event->pmu->get_drv_configs)
7396 return event->pmu->get_drv_configs(event, arg);
7400 * hrtimer based swevent callback
7403 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7405 enum hrtimer_restart ret = HRTIMER_RESTART;
7406 struct perf_sample_data data;
7407 struct pt_regs *regs;
7408 struct perf_event *event;
7411 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7413 if (event->state != PERF_EVENT_STATE_ACTIVE)
7414 return HRTIMER_NORESTART;
7416 event->pmu->read(event);
7418 perf_sample_data_init(&data, 0, event->hw.last_period);
7419 regs = get_irq_regs();
7421 if (regs && !perf_exclude_event(event, regs)) {
7422 if (!(event->attr.exclude_idle && is_idle_task(current)))
7423 if (__perf_event_overflow(event, 1, &data, regs))
7424 ret = HRTIMER_NORESTART;
7427 period = max_t(u64, 10000, event->hw.sample_period);
7428 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7433 static void perf_swevent_start_hrtimer(struct perf_event *event)
7435 struct hw_perf_event *hwc = &event->hw;
7438 if (!is_sampling_event(event))
7441 period = local64_read(&hwc->period_left);
7446 local64_set(&hwc->period_left, 0);
7448 period = max_t(u64, 10000, hwc->sample_period);
7450 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7451 HRTIMER_MODE_REL_PINNED);
7454 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7456 struct hw_perf_event *hwc = &event->hw;
7458 if (is_sampling_event(event)) {
7459 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7460 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7462 hrtimer_cancel(&hwc->hrtimer);
7466 static void perf_swevent_init_hrtimer(struct perf_event *event)
7468 struct hw_perf_event *hwc = &event->hw;
7470 if (!is_sampling_event(event))
7473 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7474 hwc->hrtimer.function = perf_swevent_hrtimer;
7477 * Since hrtimers have a fixed rate, we can do a static freq->period
7478 * mapping and avoid the whole period adjust feedback stuff.
7480 if (event->attr.freq) {
7481 long freq = event->attr.sample_freq;
7483 event->attr.sample_period = NSEC_PER_SEC / freq;
7484 hwc->sample_period = event->attr.sample_period;
7485 local64_set(&hwc->period_left, hwc->sample_period);
7486 hwc->last_period = hwc->sample_period;
7487 event->attr.freq = 0;
7492 * Software event: cpu wall time clock
7495 static void cpu_clock_event_update(struct perf_event *event)
7500 now = local_clock();
7501 prev = local64_xchg(&event->hw.prev_count, now);
7502 local64_add(now - prev, &event->count);
7505 static void cpu_clock_event_start(struct perf_event *event, int flags)
7507 local64_set(&event->hw.prev_count, local_clock());
7508 perf_swevent_start_hrtimer(event);
7511 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7513 perf_swevent_cancel_hrtimer(event);
7514 cpu_clock_event_update(event);
7517 static int cpu_clock_event_add(struct perf_event *event, int flags)
7519 if (flags & PERF_EF_START)
7520 cpu_clock_event_start(event, flags);
7521 perf_event_update_userpage(event);
7526 static void cpu_clock_event_del(struct perf_event *event, int flags)
7528 cpu_clock_event_stop(event, flags);
7531 static void cpu_clock_event_read(struct perf_event *event)
7533 cpu_clock_event_update(event);
7536 static int cpu_clock_event_init(struct perf_event *event)
7538 if (event->attr.type != PERF_TYPE_SOFTWARE)
7541 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7545 * no branch sampling for software events
7547 if (has_branch_stack(event))
7550 perf_swevent_init_hrtimer(event);
7555 static struct pmu perf_cpu_clock = {
7556 .task_ctx_nr = perf_sw_context,
7558 .capabilities = PERF_PMU_CAP_NO_NMI,
7560 .event_init = cpu_clock_event_init,
7561 .add = cpu_clock_event_add,
7562 .del = cpu_clock_event_del,
7563 .start = cpu_clock_event_start,
7564 .stop = cpu_clock_event_stop,
7565 .read = cpu_clock_event_read,
7567 .events_across_hotplug = 1,
7571 * Software event: task time clock
7574 static void task_clock_event_update(struct perf_event *event, u64 now)
7579 prev = local64_xchg(&event->hw.prev_count, now);
7581 local64_add(delta, &event->count);
7584 static void task_clock_event_start(struct perf_event *event, int flags)
7586 local64_set(&event->hw.prev_count, event->ctx->time);
7587 perf_swevent_start_hrtimer(event);
7590 static void task_clock_event_stop(struct perf_event *event, int flags)
7592 perf_swevent_cancel_hrtimer(event);
7593 task_clock_event_update(event, event->ctx->time);
7596 static int task_clock_event_add(struct perf_event *event, int flags)
7598 if (flags & PERF_EF_START)
7599 task_clock_event_start(event, flags);
7600 perf_event_update_userpage(event);
7605 static void task_clock_event_del(struct perf_event *event, int flags)
7607 task_clock_event_stop(event, PERF_EF_UPDATE);
7610 static void task_clock_event_read(struct perf_event *event)
7612 u64 now = perf_clock();
7613 u64 delta = now - event->ctx->timestamp;
7614 u64 time = event->ctx->time + delta;
7616 task_clock_event_update(event, time);
7619 static int task_clock_event_init(struct perf_event *event)
7621 if (event->attr.type != PERF_TYPE_SOFTWARE)
7624 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7628 * no branch sampling for software events
7630 if (has_branch_stack(event))
7633 perf_swevent_init_hrtimer(event);
7638 static struct pmu perf_task_clock = {
7639 .task_ctx_nr = perf_sw_context,
7641 .capabilities = PERF_PMU_CAP_NO_NMI,
7643 .event_init = task_clock_event_init,
7644 .add = task_clock_event_add,
7645 .del = task_clock_event_del,
7646 .start = task_clock_event_start,
7647 .stop = task_clock_event_stop,
7648 .read = task_clock_event_read,
7650 .events_across_hotplug = 1,
7653 static void perf_pmu_nop_void(struct pmu *pmu)
7657 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7661 static int perf_pmu_nop_int(struct pmu *pmu)
7666 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7668 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7670 __this_cpu_write(nop_txn_flags, flags);
7672 if (flags & ~PERF_PMU_TXN_ADD)
7675 perf_pmu_disable(pmu);
7678 static int perf_pmu_commit_txn(struct pmu *pmu)
7680 unsigned int flags = __this_cpu_read(nop_txn_flags);
7682 __this_cpu_write(nop_txn_flags, 0);
7684 if (flags & ~PERF_PMU_TXN_ADD)
7687 perf_pmu_enable(pmu);
7691 static void perf_pmu_cancel_txn(struct pmu *pmu)
7693 unsigned int flags = __this_cpu_read(nop_txn_flags);
7695 __this_cpu_write(nop_txn_flags, 0);
7697 if (flags & ~PERF_PMU_TXN_ADD)
7700 perf_pmu_enable(pmu);
7703 static int perf_event_idx_default(struct perf_event *event)
7709 * Ensures all contexts with the same task_ctx_nr have the same
7710 * pmu_cpu_context too.
7712 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7719 list_for_each_entry(pmu, &pmus, entry) {
7720 if (pmu->task_ctx_nr == ctxn)
7721 return pmu->pmu_cpu_context;
7727 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7731 for_each_possible_cpu(cpu) {
7732 struct perf_cpu_context *cpuctx;
7734 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7736 if (cpuctx->unique_pmu == old_pmu)
7737 cpuctx->unique_pmu = pmu;
7741 static void free_pmu_context(struct pmu *pmu)
7745 mutex_lock(&pmus_lock);
7747 * Like a real lame refcount.
7749 list_for_each_entry(i, &pmus, entry) {
7750 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7751 update_pmu_context(i, pmu);
7756 free_percpu(pmu->pmu_cpu_context);
7758 mutex_unlock(&pmus_lock);
7760 static struct idr pmu_idr;
7763 type_show(struct device *dev, struct device_attribute *attr, char *page)
7765 struct pmu *pmu = dev_get_drvdata(dev);
7767 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7769 static DEVICE_ATTR_RO(type);
7772 perf_event_mux_interval_ms_show(struct device *dev,
7773 struct device_attribute *attr,
7776 struct pmu *pmu = dev_get_drvdata(dev);
7778 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7781 static DEFINE_MUTEX(mux_interval_mutex);
7784 perf_event_mux_interval_ms_store(struct device *dev,
7785 struct device_attribute *attr,
7786 const char *buf, size_t count)
7788 struct pmu *pmu = dev_get_drvdata(dev);
7789 int timer, cpu, ret;
7791 ret = kstrtoint(buf, 0, &timer);
7798 /* same value, noting to do */
7799 if (timer == pmu->hrtimer_interval_ms)
7802 mutex_lock(&mux_interval_mutex);
7803 pmu->hrtimer_interval_ms = timer;
7805 /* update all cpuctx for this PMU */
7807 for_each_online_cpu(cpu) {
7808 struct perf_cpu_context *cpuctx;
7809 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7810 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7812 cpu_function_call(cpu,
7813 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7816 mutex_unlock(&mux_interval_mutex);
7820 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7822 static struct attribute *pmu_dev_attrs[] = {
7823 &dev_attr_type.attr,
7824 &dev_attr_perf_event_mux_interval_ms.attr,
7827 ATTRIBUTE_GROUPS(pmu_dev);
7829 static int pmu_bus_running;
7830 static struct bus_type pmu_bus = {
7831 .name = "event_source",
7832 .dev_groups = pmu_dev_groups,
7835 static void pmu_dev_release(struct device *dev)
7840 static int pmu_dev_alloc(struct pmu *pmu)
7844 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7848 pmu->dev->groups = pmu->attr_groups;
7849 device_initialize(pmu->dev);
7850 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7854 dev_set_drvdata(pmu->dev, pmu);
7855 pmu->dev->bus = &pmu_bus;
7856 pmu->dev->release = pmu_dev_release;
7857 ret = device_add(pmu->dev);
7865 put_device(pmu->dev);
7869 static struct lock_class_key cpuctx_mutex;
7870 static struct lock_class_key cpuctx_lock;
7872 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7876 mutex_lock(&pmus_lock);
7878 pmu->pmu_disable_count = alloc_percpu(int);
7879 if (!pmu->pmu_disable_count)
7888 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7896 if (pmu_bus_running) {
7897 ret = pmu_dev_alloc(pmu);
7903 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7904 if (pmu->pmu_cpu_context)
7905 goto got_cpu_context;
7908 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7909 if (!pmu->pmu_cpu_context)
7912 for_each_possible_cpu(cpu) {
7913 struct perf_cpu_context *cpuctx;
7915 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7916 __perf_event_init_context(&cpuctx->ctx);
7917 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7918 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7919 cpuctx->ctx.pmu = pmu;
7921 __perf_mux_hrtimer_init(cpuctx, cpu);
7923 cpuctx->unique_pmu = pmu;
7927 if (!pmu->start_txn) {
7928 if (pmu->pmu_enable) {
7930 * If we have pmu_enable/pmu_disable calls, install
7931 * transaction stubs that use that to try and batch
7932 * hardware accesses.
7934 pmu->start_txn = perf_pmu_start_txn;
7935 pmu->commit_txn = perf_pmu_commit_txn;
7936 pmu->cancel_txn = perf_pmu_cancel_txn;
7938 pmu->start_txn = perf_pmu_nop_txn;
7939 pmu->commit_txn = perf_pmu_nop_int;
7940 pmu->cancel_txn = perf_pmu_nop_void;
7944 if (!pmu->pmu_enable) {
7945 pmu->pmu_enable = perf_pmu_nop_void;
7946 pmu->pmu_disable = perf_pmu_nop_void;
7949 if (!pmu->event_idx)
7950 pmu->event_idx = perf_event_idx_default;
7952 list_add_rcu(&pmu->entry, &pmus);
7953 atomic_set(&pmu->exclusive_cnt, 0);
7956 mutex_unlock(&pmus_lock);
7961 device_del(pmu->dev);
7962 put_device(pmu->dev);
7965 if (pmu->type >= PERF_TYPE_MAX)
7966 idr_remove(&pmu_idr, pmu->type);
7969 free_percpu(pmu->pmu_disable_count);
7972 EXPORT_SYMBOL_GPL(perf_pmu_register);
7974 void perf_pmu_unregister(struct pmu *pmu)
7976 mutex_lock(&pmus_lock);
7977 list_del_rcu(&pmu->entry);
7978 mutex_unlock(&pmus_lock);
7981 * We dereference the pmu list under both SRCU and regular RCU, so
7982 * synchronize against both of those.
7984 synchronize_srcu(&pmus_srcu);
7987 free_percpu(pmu->pmu_disable_count);
7988 if (pmu->type >= PERF_TYPE_MAX)
7989 idr_remove(&pmu_idr, pmu->type);
7990 device_del(pmu->dev);
7991 put_device(pmu->dev);
7992 free_pmu_context(pmu);
7994 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7996 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7998 struct perf_event_context *ctx = NULL;
8001 if (!try_module_get(pmu->module))
8004 if (event->group_leader != event) {
8006 * This ctx->mutex can nest when we're called through
8007 * inheritance. See the perf_event_ctx_lock_nested() comment.
8009 ctx = perf_event_ctx_lock_nested(event->group_leader,
8010 SINGLE_DEPTH_NESTING);
8015 ret = pmu->event_init(event);
8018 perf_event_ctx_unlock(event->group_leader, ctx);
8021 module_put(pmu->module);
8026 static struct pmu *perf_init_event(struct perf_event *event)
8028 struct pmu *pmu = NULL;
8032 idx = srcu_read_lock(&pmus_srcu);
8035 pmu = idr_find(&pmu_idr, event->attr.type);
8038 ret = perf_try_init_event(pmu, event);
8044 list_for_each_entry_rcu(pmu, &pmus, entry) {
8045 ret = perf_try_init_event(pmu, event);
8049 if (ret != -ENOENT) {
8054 pmu = ERR_PTR(-ENOENT);
8056 srcu_read_unlock(&pmus_srcu, idx);
8061 static void account_event_cpu(struct perf_event *event, int cpu)
8066 if (is_cgroup_event(event))
8067 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
8070 static void account_event(struct perf_event *event)
8075 if (event->attach_state & PERF_ATTACH_TASK)
8076 static_key_slow_inc(&perf_sched_events.key);
8077 if (event->attr.mmap || event->attr.mmap_data)
8078 atomic_inc(&nr_mmap_events);
8079 if (event->attr.comm)
8080 atomic_inc(&nr_comm_events);
8081 if (event->attr.task)
8082 atomic_inc(&nr_task_events);
8083 if (event->attr.freq) {
8084 if (atomic_inc_return(&nr_freq_events) == 1)
8085 tick_nohz_full_kick_all();
8087 if (event->attr.context_switch) {
8088 atomic_inc(&nr_switch_events);
8089 static_key_slow_inc(&perf_sched_events.key);
8091 if (has_branch_stack(event))
8092 static_key_slow_inc(&perf_sched_events.key);
8093 if (is_cgroup_event(event))
8094 static_key_slow_inc(&perf_sched_events.key);
8096 account_event_cpu(event, event->cpu);
8100 * Allocate and initialize a event structure
8102 static struct perf_event *
8103 perf_event_alloc(struct perf_event_attr *attr, int cpu,
8104 struct task_struct *task,
8105 struct perf_event *group_leader,
8106 struct perf_event *parent_event,
8107 perf_overflow_handler_t overflow_handler,
8108 void *context, int cgroup_fd)
8111 struct perf_event *event;
8112 struct hw_perf_event *hwc;
8115 if ((unsigned)cpu >= nr_cpu_ids) {
8116 if (!task || cpu != -1)
8117 return ERR_PTR(-EINVAL);
8120 event = kzalloc(sizeof(*event), GFP_KERNEL);
8122 return ERR_PTR(-ENOMEM);
8125 * Single events are their own group leaders, with an
8126 * empty sibling list:
8129 group_leader = event;
8131 mutex_init(&event->group_leader_mutex);
8132 mutex_init(&event->child_mutex);
8133 INIT_LIST_HEAD(&event->child_list);
8135 INIT_LIST_HEAD(&event->group_entry);
8136 INIT_LIST_HEAD(&event->event_entry);
8137 INIT_LIST_HEAD(&event->sibling_list);
8138 INIT_LIST_HEAD(&event->rb_entry);
8139 INIT_LIST_HEAD(&event->active_entry);
8140 INIT_LIST_HEAD(&event->drv_configs);
8141 INIT_HLIST_NODE(&event->hlist_entry);
8144 init_waitqueue_head(&event->waitq);
8145 init_irq_work(&event->pending, perf_pending_event);
8147 mutex_init(&event->mmap_mutex);
8149 atomic_long_set(&event->refcount, 1);
8151 event->attr = *attr;
8152 event->group_leader = group_leader;
8156 event->parent = parent_event;
8158 event->ns = get_pid_ns(task_active_pid_ns(current));
8159 event->id = atomic64_inc_return(&perf_event_id);
8161 event->state = PERF_EVENT_STATE_INACTIVE;
8164 event->attach_state = PERF_ATTACH_TASK;
8166 * XXX pmu::event_init needs to know what task to account to
8167 * and we cannot use the ctx information because we need the
8168 * pmu before we get a ctx.
8170 event->hw.target = task;
8173 event->clock = &local_clock;
8175 event->clock = parent_event->clock;
8177 if (!overflow_handler && parent_event) {
8178 overflow_handler = parent_event->overflow_handler;
8179 context = parent_event->overflow_handler_context;
8182 event->overflow_handler = overflow_handler;
8183 event->overflow_handler_context = context;
8185 perf_event__state_init(event);
8190 hwc->sample_period = attr->sample_period;
8191 if (attr->freq && attr->sample_freq)
8192 hwc->sample_period = 1;
8193 hwc->last_period = hwc->sample_period;
8195 local64_set(&hwc->period_left, hwc->sample_period);
8198 * We currently do not support PERF_SAMPLE_READ on inherited events.
8199 * See perf_output_read().
8201 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
8204 if (!has_branch_stack(event))
8205 event->attr.branch_sample_type = 0;
8207 if (cgroup_fd != -1) {
8208 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8213 pmu = perf_init_event(event);
8216 else if (IS_ERR(pmu)) {
8221 err = exclusive_event_init(event);
8225 if (!event->parent) {
8226 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8227 err = get_callchain_buffers();
8233 /* symmetric to unaccount_event() in _free_event() */
8234 account_event(event);
8239 exclusive_event_destroy(event);
8243 event->destroy(event);
8244 module_put(pmu->module);
8246 if (is_cgroup_event(event))
8247 perf_detach_cgroup(event);
8249 put_pid_ns(event->ns);
8252 return ERR_PTR(err);
8255 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8256 struct perf_event_attr *attr)
8261 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8265 * zero the full structure, so that a short copy will be nice.
8267 memset(attr, 0, sizeof(*attr));
8269 ret = get_user(size, &uattr->size);
8273 if (size > PAGE_SIZE) /* silly large */
8276 if (!size) /* abi compat */
8277 size = PERF_ATTR_SIZE_VER0;
8279 if (size < PERF_ATTR_SIZE_VER0)
8283 * If we're handed a bigger struct than we know of,
8284 * ensure all the unknown bits are 0 - i.e. new
8285 * user-space does not rely on any kernel feature
8286 * extensions we dont know about yet.
8288 if (size > sizeof(*attr)) {
8289 unsigned char __user *addr;
8290 unsigned char __user *end;
8293 addr = (void __user *)uattr + sizeof(*attr);
8294 end = (void __user *)uattr + size;
8296 for (; addr < end; addr++) {
8297 ret = get_user(val, addr);
8303 size = sizeof(*attr);
8306 ret = copy_from_user(attr, uattr, size);
8310 if (attr->__reserved_1)
8313 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8316 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8319 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8320 u64 mask = attr->branch_sample_type;
8322 /* only using defined bits */
8323 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8326 /* at least one branch bit must be set */
8327 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8330 /* propagate priv level, when not set for branch */
8331 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8333 /* exclude_kernel checked on syscall entry */
8334 if (!attr->exclude_kernel)
8335 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8337 if (!attr->exclude_user)
8338 mask |= PERF_SAMPLE_BRANCH_USER;
8340 if (!attr->exclude_hv)
8341 mask |= PERF_SAMPLE_BRANCH_HV;
8343 * adjust user setting (for HW filter setup)
8345 attr->branch_sample_type = mask;
8347 /* privileged levels capture (kernel, hv): check permissions */
8348 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8349 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8353 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8354 ret = perf_reg_validate(attr->sample_regs_user);
8359 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8360 if (!arch_perf_have_user_stack_dump())
8364 * We have __u32 type for the size, but so far
8365 * we can only use __u16 as maximum due to the
8366 * __u16 sample size limit.
8368 if (attr->sample_stack_user >= USHRT_MAX)
8370 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8374 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8375 ret = perf_reg_validate(attr->sample_regs_intr);
8380 put_user(sizeof(*attr), &uattr->size);
8386 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8388 struct ring_buffer *rb = NULL;
8394 /* don't allow circular references */
8395 if (event == output_event)
8399 * Don't allow cross-cpu buffers
8401 if (output_event->cpu != event->cpu)
8405 * If its not a per-cpu rb, it must be the same task.
8407 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8411 * Mixing clocks in the same buffer is trouble you don't need.
8413 if (output_event->clock != event->clock)
8417 * If both events generate aux data, they must be on the same PMU
8419 if (has_aux(event) && has_aux(output_event) &&
8420 event->pmu != output_event->pmu)
8424 mutex_lock(&event->mmap_mutex);
8425 /* Can't redirect output if we've got an active mmap() */
8426 if (atomic_read(&event->mmap_count))
8430 /* get the rb we want to redirect to */
8431 rb = ring_buffer_get(output_event);
8436 ring_buffer_attach(event, rb);
8440 mutex_unlock(&event->mmap_mutex);
8446 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8452 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8455 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8457 bool nmi_safe = false;
8460 case CLOCK_MONOTONIC:
8461 event->clock = &ktime_get_mono_fast_ns;
8465 case CLOCK_MONOTONIC_RAW:
8466 event->clock = &ktime_get_raw_fast_ns;
8470 case CLOCK_REALTIME:
8471 event->clock = &ktime_get_real_ns;
8474 case CLOCK_BOOTTIME:
8475 event->clock = &ktime_get_boot_ns;
8479 event->clock = &ktime_get_tai_ns;
8486 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8493 * Variation on perf_event_ctx_lock_nested(), except we take two context
8496 static struct perf_event_context *
8497 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8498 struct perf_event_context *ctx)
8500 struct perf_event_context *gctx;
8504 gctx = READ_ONCE(group_leader->ctx);
8505 if (!atomic_inc_not_zero(&gctx->refcount)) {
8511 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8513 if (group_leader->ctx != gctx) {
8514 mutex_unlock(&ctx->mutex);
8515 mutex_unlock(&gctx->mutex);
8524 * sys_perf_event_open - open a performance event, associate it to a task/cpu
8526 * @attr_uptr: event_id type attributes for monitoring/sampling
8529 * @group_fd: group leader event fd
8531 SYSCALL_DEFINE5(perf_event_open,
8532 struct perf_event_attr __user *, attr_uptr,
8533 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8535 struct perf_event *group_leader = NULL, *output_event = NULL;
8536 struct perf_event *event, *sibling;
8537 struct perf_event_attr attr;
8538 struct perf_event_context *ctx, *uninitialized_var(gctx);
8539 struct file *event_file = NULL;
8540 struct fd group = {NULL, 0};
8541 struct task_struct *task = NULL;
8546 int f_flags = O_RDWR;
8549 /* for future expandability... */
8550 if (flags & ~PERF_FLAG_ALL)
8553 if (perf_paranoid_any() && !capable(CAP_SYS_ADMIN))
8556 err = perf_copy_attr(attr_uptr, &attr);
8560 if (attr.constraint_duplicate || attr.__reserved_1)
8563 if (!attr.exclude_kernel) {
8564 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8569 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8572 if (attr.sample_period & (1ULL << 63))
8577 * In cgroup mode, the pid argument is used to pass the fd
8578 * opened to the cgroup directory in cgroupfs. The cpu argument
8579 * designates the cpu on which to monitor threads from that
8582 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8585 if (flags & PERF_FLAG_FD_CLOEXEC)
8586 f_flags |= O_CLOEXEC;
8588 event_fd = get_unused_fd_flags(f_flags);
8592 if (group_fd != -1) {
8593 err = perf_fget_light(group_fd, &group);
8596 group_leader = group.file->private_data;
8597 if (flags & PERF_FLAG_FD_OUTPUT)
8598 output_event = group_leader;
8599 if (flags & PERF_FLAG_FD_NO_GROUP)
8600 group_leader = NULL;
8604 * Take the group_leader's group_leader_mutex before observing
8605 * anything in the group leader that leads to changes in ctx,
8606 * many of which may be changing on another thread.
8607 * In particular, we want to take this lock before deciding
8608 * whether we need to move_group.
8611 mutex_lock(&group_leader->group_leader_mutex);
8613 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8614 task = find_lively_task_by_vpid(pid);
8616 err = PTR_ERR(task);
8621 if (task && group_leader &&
8622 group_leader->attr.inherit != attr.inherit) {
8630 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8635 * Reuse ptrace permission checks for now.
8637 * We must hold cred_guard_mutex across this and any potential
8638 * perf_install_in_context() call for this new event to
8639 * serialize against exec() altering our credentials (and the
8640 * perf_event_exit_task() that could imply).
8643 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8647 if (flags & PERF_FLAG_PID_CGROUP)
8650 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8651 NULL, NULL, cgroup_fd);
8652 if (IS_ERR(event)) {
8653 err = PTR_ERR(event);
8657 if (is_sampling_event(event)) {
8658 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8665 * Special case software events and allow them to be part of
8666 * any hardware group.
8670 if (attr.use_clockid) {
8671 err = perf_event_set_clock(event, attr.clockid);
8677 (is_software_event(event) != is_software_event(group_leader))) {
8678 if (is_software_event(event)) {
8680 * If event and group_leader are not both a software
8681 * event, and event is, then group leader is not.
8683 * Allow the addition of software events to !software
8684 * groups, this is safe because software events never
8687 pmu = group_leader->pmu;
8688 } else if (is_software_event(group_leader) &&
8689 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8691 * In case the group is a pure software group, and we
8692 * try to add a hardware event, move the whole group to
8693 * the hardware context.
8700 * Get the target context (task or percpu):
8702 ctx = find_get_context(pmu, task, event);
8708 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8714 * Look up the group leader (we will attach this event to it):
8720 * Do not allow a recursive hierarchy (this new sibling
8721 * becoming part of another group-sibling):
8723 if (group_leader->group_leader != group_leader)
8726 /* All events in a group should have the same clock */
8727 if (group_leader->clock != event->clock)
8731 * Make sure we're both events for the same CPU;
8732 * grouping events for different CPUs is broken; since
8733 * you can never concurrently schedule them anyhow.
8735 if (group_leader->cpu != event->cpu)
8739 * Make sure we're both on the same task, or both
8742 if (group_leader->ctx->task != ctx->task)
8746 * Do not allow to attach to a group in a different task
8747 * or CPU context. If we're moving SW events, we'll fix
8748 * this up later, so allow that.
8750 if (!move_group && group_leader->ctx != ctx)
8754 * Only a group leader can be exclusive or pinned
8756 if (attr.exclusive || attr.pinned)
8761 err = perf_event_set_output(event, output_event);
8766 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8768 if (IS_ERR(event_file)) {
8769 err = PTR_ERR(event_file);
8775 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8778 * Check if we raced against another sys_perf_event_open() call
8779 * moving the software group underneath us.
8781 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8783 * If someone moved the group out from under us, check
8784 * if this new event wound up on the same ctx, if so
8785 * its the regular !move_group case, otherwise fail.
8791 perf_event_ctx_unlock(group_leader, gctx);
8796 mutex_lock(&ctx->mutex);
8799 if (!perf_event_validate_size(event)) {
8805 * Must be under the same ctx::mutex as perf_install_in_context(),
8806 * because we need to serialize with concurrent event creation.
8808 if (!exclusive_event_installable(event, ctx)) {
8809 /* exclusive and group stuff are assumed mutually exclusive */
8810 WARN_ON_ONCE(move_group);
8816 WARN_ON_ONCE(ctx->parent_ctx);
8819 * This is the point on no return; we cannot fail hereafter. This is
8820 * where we start modifying current state.
8825 * See perf_event_ctx_lock() for comments on the details
8826 * of swizzling perf_event::ctx.
8828 perf_remove_from_context(group_leader, false);
8830 list_for_each_entry(sibling, &group_leader->sibling_list,
8832 perf_remove_from_context(sibling, false);
8837 * Wait for everybody to stop referencing the events through
8838 * the old lists, before installing it on new lists.
8843 * Install the group siblings before the group leader.
8845 * Because a group leader will try and install the entire group
8846 * (through the sibling list, which is still in-tact), we can
8847 * end up with siblings installed in the wrong context.
8849 * By installing siblings first we NO-OP because they're not
8850 * reachable through the group lists.
8852 list_for_each_entry(sibling, &group_leader->sibling_list,
8854 perf_event__state_init(sibling);
8855 perf_install_in_context(ctx, sibling, sibling->cpu);
8860 * Removing from the context ends up with disabled
8861 * event. What we want here is event in the initial
8862 * startup state, ready to be add into new context.
8864 perf_event__state_init(group_leader);
8865 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8869 * Now that all events are installed in @ctx, nothing
8870 * references @gctx anymore, so drop the last reference we have
8877 * Precalculate sample_data sizes; do while holding ctx::mutex such
8878 * that we're serialized against further additions and before
8879 * perf_install_in_context() which is the point the event is active and
8880 * can use these values.
8882 perf_event__header_size(event);
8883 perf_event__id_header_size(event);
8885 perf_install_in_context(ctx, event, event->cpu);
8886 perf_unpin_context(ctx);
8889 perf_event_ctx_unlock(group_leader, gctx);
8890 mutex_unlock(&ctx->mutex);
8892 mutex_unlock(&group_leader->group_leader_mutex);
8895 mutex_unlock(&task->signal->cred_guard_mutex);
8896 put_task_struct(task);
8901 event->owner = current;
8903 mutex_lock(¤t->perf_event_mutex);
8904 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8905 mutex_unlock(¤t->perf_event_mutex);
8908 * Drop the reference on the group_event after placing the
8909 * new event on the sibling_list. This ensures destruction
8910 * of the group leader will find the pointer to itself in
8911 * perf_group_detach().
8914 fd_install(event_fd, event_file);
8919 perf_event_ctx_unlock(group_leader, gctx);
8920 mutex_unlock(&ctx->mutex);
8924 perf_unpin_context(ctx);
8928 * If event_file is set, the fput() above will have called ->release()
8929 * and that will take care of freeing the event.
8935 mutex_unlock(&task->signal->cred_guard_mutex);
8940 put_task_struct(task);
8943 mutex_unlock(&group_leader->group_leader_mutex);
8946 put_unused_fd(event_fd);
8951 * perf_event_create_kernel_counter
8953 * @attr: attributes of the counter to create
8954 * @cpu: cpu in which the counter is bound
8955 * @task: task to profile (NULL for percpu)
8958 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8959 struct task_struct *task,
8960 perf_overflow_handler_t overflow_handler,
8963 struct perf_event_context *ctx;
8964 struct perf_event *event;
8968 * Get the target context (task or percpu):
8971 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8972 overflow_handler, context, -1);
8973 if (IS_ERR(event)) {
8974 err = PTR_ERR(event);
8978 /* Mark owner so we could distinguish it from user events. */
8979 event->owner = EVENT_OWNER_KERNEL;
8981 ctx = find_get_context(event->pmu, task, event);
8987 WARN_ON_ONCE(ctx->parent_ctx);
8988 mutex_lock(&ctx->mutex);
8989 if (!exclusive_event_installable(event, ctx)) {
8990 mutex_unlock(&ctx->mutex);
8991 perf_unpin_context(ctx);
8997 perf_install_in_context(ctx, event, event->cpu);
8998 perf_unpin_context(ctx);
8999 mutex_unlock(&ctx->mutex);
9006 return ERR_PTR(err);
9008 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9010 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
9012 struct perf_event_context *src_ctx;
9013 struct perf_event_context *dst_ctx;
9014 struct perf_event *event, *tmp;
9017 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
9018 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
9021 * See perf_event_ctx_lock() for comments on the details
9022 * of swizzling perf_event::ctx.
9024 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
9025 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
9027 perf_remove_from_context(event, false);
9028 unaccount_event_cpu(event, src_cpu);
9030 list_add(&event->migrate_entry, &events);
9034 * Wait for the events to quiesce before re-instating them.
9039 * Re-instate events in 2 passes.
9041 * Skip over group leaders and only install siblings on this first
9042 * pass, siblings will not get enabled without a leader, however a
9043 * leader will enable its siblings, even if those are still on the old
9046 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9047 if (event->group_leader == event)
9050 list_del(&event->migrate_entry);
9051 if (event->state >= PERF_EVENT_STATE_OFF)
9052 event->state = PERF_EVENT_STATE_INACTIVE;
9053 account_event_cpu(event, dst_cpu);
9054 perf_install_in_context(dst_ctx, event, dst_cpu);
9059 * Once all the siblings are setup properly, install the group leaders
9062 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9063 list_del(&event->migrate_entry);
9064 if (event->state >= PERF_EVENT_STATE_OFF)
9065 event->state = PERF_EVENT_STATE_INACTIVE;
9066 account_event_cpu(event, dst_cpu);
9067 perf_install_in_context(dst_ctx, event, dst_cpu);
9070 mutex_unlock(&dst_ctx->mutex);
9071 mutex_unlock(&src_ctx->mutex);
9073 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
9075 static void sync_child_event(struct perf_event *child_event,
9076 struct task_struct *child)
9078 struct perf_event *parent_event = child_event->parent;
9081 if (child_event->attr.inherit_stat)
9082 perf_event_read_event(child_event, child);
9084 child_val = perf_event_count(child_event);
9087 * Add back the child's count to the parent's count:
9089 atomic64_add(child_val, &parent_event->child_count);
9090 atomic64_add(child_event->total_time_enabled,
9091 &parent_event->child_total_time_enabled);
9092 atomic64_add(child_event->total_time_running,
9093 &parent_event->child_total_time_running);
9096 * Remove this event from the parent's list
9098 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9099 mutex_lock(&parent_event->child_mutex);
9100 list_del_init(&child_event->child_list);
9101 mutex_unlock(&parent_event->child_mutex);
9104 * Make sure user/parent get notified, that we just
9107 perf_event_wakeup(parent_event);
9110 * Release the parent event, if this was the last
9113 put_event(parent_event);
9117 __perf_event_exit_task(struct perf_event *child_event,
9118 struct perf_event_context *child_ctx,
9119 struct task_struct *child)
9122 * Do not destroy the 'original' grouping; because of the context
9123 * switch optimization the original events could've ended up in a
9124 * random child task.
9126 * If we were to destroy the original group, all group related
9127 * operations would cease to function properly after this random
9130 * Do destroy all inherited groups, we don't care about those
9131 * and being thorough is better.
9133 perf_remove_from_context(child_event, !!child_event->parent);
9136 * It can happen that the parent exits first, and has events
9137 * that are still around due to the child reference. These
9138 * events need to be zapped.
9140 if (child_event->parent) {
9141 sync_child_event(child_event, child);
9142 free_event(child_event);
9144 child_event->state = PERF_EVENT_STATE_EXIT;
9145 perf_event_wakeup(child_event);
9149 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9151 struct perf_event *child_event, *next;
9152 struct perf_event_context *child_ctx, *clone_ctx = NULL;
9153 unsigned long flags;
9155 if (likely(!child->perf_event_ctxp[ctxn]))
9158 local_irq_save(flags);
9160 * We can't reschedule here because interrupts are disabled,
9161 * and either child is current or it is a task that can't be
9162 * scheduled, so we are now safe from rescheduling changing
9165 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
9168 * Take the context lock here so that if find_get_context is
9169 * reading child->perf_event_ctxp, we wait until it has
9170 * incremented the context's refcount before we do put_ctx below.
9172 raw_spin_lock(&child_ctx->lock);
9173 task_ctx_sched_out(child_ctx);
9174 child->perf_event_ctxp[ctxn] = NULL;
9177 * If this context is a clone; unclone it so it can't get
9178 * swapped to another process while we're removing all
9179 * the events from it.
9181 clone_ctx = unclone_ctx(child_ctx);
9182 update_context_time(child_ctx);
9183 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9189 * Report the task dead after unscheduling the events so that we
9190 * won't get any samples after PERF_RECORD_EXIT. We can however still
9191 * get a few PERF_RECORD_READ events.
9193 perf_event_task(child, child_ctx, 0);
9196 * We can recurse on the same lock type through:
9198 * __perf_event_exit_task()
9199 * sync_child_event()
9201 * mutex_lock(&ctx->mutex)
9203 * But since its the parent context it won't be the same instance.
9205 mutex_lock(&child_ctx->mutex);
9207 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9208 __perf_event_exit_task(child_event, child_ctx, child);
9210 mutex_unlock(&child_ctx->mutex);
9216 * When a child task exits, feed back event values to parent events.
9218 * Can be called with cred_guard_mutex held when called from
9219 * install_exec_creds().
9221 void perf_event_exit_task(struct task_struct *child)
9223 struct perf_event *event, *tmp;
9226 mutex_lock(&child->perf_event_mutex);
9227 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9229 list_del_init(&event->owner_entry);
9232 * Ensure the list deletion is visible before we clear
9233 * the owner, closes a race against perf_release() where
9234 * we need to serialize on the owner->perf_event_mutex.
9237 event->owner = NULL;
9239 mutex_unlock(&child->perf_event_mutex);
9241 for_each_task_context_nr(ctxn)
9242 perf_event_exit_task_context(child, ctxn);
9245 * The perf_event_exit_task_context calls perf_event_task
9246 * with child's task_ctx, which generates EXIT events for
9247 * child contexts and sets child->perf_event_ctxp[] to NULL.
9248 * At this point we need to send EXIT events to cpu contexts.
9250 perf_event_task(child, NULL, 0);
9253 static void perf_free_event(struct perf_event *event,
9254 struct perf_event_context *ctx)
9256 struct perf_event *parent = event->parent;
9258 if (WARN_ON_ONCE(!parent))
9261 mutex_lock(&parent->child_mutex);
9262 list_del_init(&event->child_list);
9263 mutex_unlock(&parent->child_mutex);
9267 raw_spin_lock_irq(&ctx->lock);
9268 perf_group_detach(event);
9269 list_del_event(event, ctx);
9270 raw_spin_unlock_irq(&ctx->lock);
9275 * Free an unexposed, unused context as created by inheritance by
9276 * perf_event_init_task below, used by fork() in case of fail.
9278 * Not all locks are strictly required, but take them anyway to be nice and
9279 * help out with the lockdep assertions.
9281 void perf_event_free_task(struct task_struct *task)
9283 struct perf_event_context *ctx;
9284 struct perf_event *event, *tmp;
9287 for_each_task_context_nr(ctxn) {
9288 ctx = task->perf_event_ctxp[ctxn];
9292 mutex_lock(&ctx->mutex);
9294 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9296 perf_free_event(event, ctx);
9298 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9300 perf_free_event(event, ctx);
9302 if (!list_empty(&ctx->pinned_groups) ||
9303 !list_empty(&ctx->flexible_groups))
9306 mutex_unlock(&ctx->mutex);
9312 void perf_event_delayed_put(struct task_struct *task)
9316 for_each_task_context_nr(ctxn)
9317 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9320 struct perf_event *perf_event_get(unsigned int fd)
9324 struct perf_event *event;
9326 err = perf_fget_light(fd, &f);
9328 return ERR_PTR(err);
9330 event = f.file->private_data;
9331 atomic_long_inc(&event->refcount);
9337 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9340 return ERR_PTR(-EINVAL);
9342 return &event->attr;
9346 * inherit a event from parent task to child task:
9348 static struct perf_event *
9349 inherit_event(struct perf_event *parent_event,
9350 struct task_struct *parent,
9351 struct perf_event_context *parent_ctx,
9352 struct task_struct *child,
9353 struct perf_event *group_leader,
9354 struct perf_event_context *child_ctx)
9356 enum perf_event_active_state parent_state = parent_event->state;
9357 struct perf_event *child_event;
9358 unsigned long flags;
9361 * Instead of creating recursive hierarchies of events,
9362 * we link inherited events back to the original parent,
9363 * which has a filp for sure, which we use as the reference
9366 if (parent_event->parent)
9367 parent_event = parent_event->parent;
9369 child_event = perf_event_alloc(&parent_event->attr,
9372 group_leader, parent_event,
9374 if (IS_ERR(child_event))
9377 if (is_orphaned_event(parent_event) ||
9378 !atomic_long_inc_not_zero(&parent_event->refcount)) {
9379 free_event(child_event);
9386 * Make the child state follow the state of the parent event,
9387 * not its attr.disabled bit. We hold the parent's mutex,
9388 * so we won't race with perf_event_{en, dis}able_family.
9390 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9391 child_event->state = PERF_EVENT_STATE_INACTIVE;
9393 child_event->state = PERF_EVENT_STATE_OFF;
9395 if (parent_event->attr.freq) {
9396 u64 sample_period = parent_event->hw.sample_period;
9397 struct hw_perf_event *hwc = &child_event->hw;
9399 hwc->sample_period = sample_period;
9400 hwc->last_period = sample_period;
9402 local64_set(&hwc->period_left, sample_period);
9405 child_event->ctx = child_ctx;
9406 child_event->overflow_handler = parent_event->overflow_handler;
9407 child_event->overflow_handler_context
9408 = parent_event->overflow_handler_context;
9411 * Precalculate sample_data sizes
9413 perf_event__header_size(child_event);
9414 perf_event__id_header_size(child_event);
9417 * Link it up in the child's context:
9419 raw_spin_lock_irqsave(&child_ctx->lock, flags);
9420 add_event_to_ctx(child_event, child_ctx);
9421 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9424 * Link this into the parent event's child list
9426 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9427 mutex_lock(&parent_event->child_mutex);
9428 list_add_tail(&child_event->child_list, &parent_event->child_list);
9429 mutex_unlock(&parent_event->child_mutex);
9434 static int inherit_group(struct perf_event *parent_event,
9435 struct task_struct *parent,
9436 struct perf_event_context *parent_ctx,
9437 struct task_struct *child,
9438 struct perf_event_context *child_ctx)
9440 struct perf_event *leader;
9441 struct perf_event *sub;
9442 struct perf_event *child_ctr;
9444 leader = inherit_event(parent_event, parent, parent_ctx,
9445 child, NULL, child_ctx);
9447 return PTR_ERR(leader);
9448 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9449 child_ctr = inherit_event(sub, parent, parent_ctx,
9450 child, leader, child_ctx);
9451 if (IS_ERR(child_ctr))
9452 return PTR_ERR(child_ctr);
9458 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9459 struct perf_event_context *parent_ctx,
9460 struct task_struct *child, int ctxn,
9464 struct perf_event_context *child_ctx;
9466 if (!event->attr.inherit) {
9471 child_ctx = child->perf_event_ctxp[ctxn];
9474 * This is executed from the parent task context, so
9475 * inherit events that have been marked for cloning.
9476 * First allocate and initialize a context for the
9480 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9484 child->perf_event_ctxp[ctxn] = child_ctx;
9487 ret = inherit_group(event, parent, parent_ctx,
9497 * Initialize the perf_event context in task_struct
9499 static int perf_event_init_context(struct task_struct *child, int ctxn)
9501 struct perf_event_context *child_ctx, *parent_ctx;
9502 struct perf_event_context *cloned_ctx;
9503 struct perf_event *event;
9504 struct task_struct *parent = current;
9505 int inherited_all = 1;
9506 unsigned long flags;
9509 if (likely(!parent->perf_event_ctxp[ctxn]))
9513 * If the parent's context is a clone, pin it so it won't get
9516 parent_ctx = perf_pin_task_context(parent, ctxn);
9521 * No need to check if parent_ctx != NULL here; since we saw
9522 * it non-NULL earlier, the only reason for it to become NULL
9523 * is if we exit, and since we're currently in the middle of
9524 * a fork we can't be exiting at the same time.
9528 * Lock the parent list. No need to lock the child - not PID
9529 * hashed yet and not running, so nobody can access it.
9531 mutex_lock(&parent_ctx->mutex);
9534 * We dont have to disable NMIs - we are only looking at
9535 * the list, not manipulating it:
9537 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9538 ret = inherit_task_group(event, parent, parent_ctx,
9539 child, ctxn, &inherited_all);
9545 * We can't hold ctx->lock when iterating the ->flexible_group list due
9546 * to allocations, but we need to prevent rotation because
9547 * rotate_ctx() will change the list from interrupt context.
9549 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9550 parent_ctx->rotate_disable = 1;
9551 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9553 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9554 ret = inherit_task_group(event, parent, parent_ctx,
9555 child, ctxn, &inherited_all);
9560 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9561 parent_ctx->rotate_disable = 0;
9563 child_ctx = child->perf_event_ctxp[ctxn];
9565 if (child_ctx && inherited_all) {
9567 * Mark the child context as a clone of the parent
9568 * context, or of whatever the parent is a clone of.
9570 * Note that if the parent is a clone, the holding of
9571 * parent_ctx->lock avoids it from being uncloned.
9573 cloned_ctx = parent_ctx->parent_ctx;
9575 child_ctx->parent_ctx = cloned_ctx;
9576 child_ctx->parent_gen = parent_ctx->parent_gen;
9578 child_ctx->parent_ctx = parent_ctx;
9579 child_ctx->parent_gen = parent_ctx->generation;
9581 get_ctx(child_ctx->parent_ctx);
9584 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9586 mutex_unlock(&parent_ctx->mutex);
9588 perf_unpin_context(parent_ctx);
9589 put_ctx(parent_ctx);
9595 * Initialize the perf_event context in task_struct
9597 int perf_event_init_task(struct task_struct *child)
9601 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9602 mutex_init(&child->perf_event_mutex);
9603 INIT_LIST_HEAD(&child->perf_event_list);
9605 for_each_task_context_nr(ctxn) {
9606 ret = perf_event_init_context(child, ctxn);
9608 perf_event_free_task(child);
9616 static void __init perf_event_init_all_cpus(void)
9618 struct swevent_htable *swhash;
9621 for_each_possible_cpu(cpu) {
9622 swhash = &per_cpu(swevent_htable, cpu);
9623 mutex_init(&swhash->hlist_mutex);
9624 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9628 static void perf_event_init_cpu(int cpu)
9630 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9632 mutex_lock(&swhash->hlist_mutex);
9633 if (swhash->hlist_refcount > 0) {
9634 struct swevent_hlist *hlist;
9636 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9638 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9640 mutex_unlock(&swhash->hlist_mutex);
9643 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9644 static void __perf_event_exit_context(void *__info)
9646 struct remove_event re = { .detach_group = true };
9647 struct perf_event_context *ctx = __info;
9650 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9651 __perf_remove_from_context(&re);
9655 static void __perf_event_stop_swclock(void *__info)
9657 struct perf_event_context *ctx = __info;
9658 struct perf_event *event, *tmp;
9660 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
9661 if (event->attr.config == PERF_COUNT_SW_CPU_CLOCK &&
9662 event->attr.type == PERF_TYPE_SOFTWARE)
9663 cpu_clock_event_stop(event, 0);
9667 static void perf_event_exit_cpu_context(int cpu)
9669 struct perf_cpu_context *cpuctx;
9670 struct perf_event_context *ctx;
9671 unsigned long flags;
9675 idx = srcu_read_lock(&pmus_srcu);
9676 list_for_each_entry_rcu(pmu, &pmus, entry) {
9677 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9680 /* Cancel the mux hrtimer to avoid CPU migration */
9681 if (pmu->task_ctx_nr != perf_sw_context) {
9682 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
9683 hrtimer_cancel(&cpuctx->hrtimer);
9684 cpuctx->hrtimer_active = 0;
9685 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock,
9689 mutex_lock(&ctx->mutex);
9691 * If keeping events across hotplugging is supported, do not
9692 * remove the event list, but keep it alive across CPU hotplug.
9693 * The context is exited via an fd close path when userspace
9694 * is done and the target CPU is online. If software clock
9695 * event is active, then stop hrtimer associated with it.
9696 * Start the timer when the CPU comes back online.
9698 if (!pmu->events_across_hotplug)
9699 smp_call_function_single(cpu, __perf_event_exit_context,
9702 smp_call_function_single(cpu, __perf_event_stop_swclock,
9704 mutex_unlock(&ctx->mutex);
9706 srcu_read_unlock(&pmus_srcu, idx);
9709 static void perf_event_start_swclock(int cpu)
9711 struct perf_event_context *ctx;
9714 struct perf_event *event, *tmp;
9716 idx = srcu_read_lock(&pmus_srcu);
9717 list_for_each_entry_rcu(pmu, &pmus, entry) {
9718 if (pmu->events_across_hotplug) {
9719 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9720 list_for_each_entry_safe(event, tmp, &ctx->event_list,
9722 if (event->attr.config ==
9723 PERF_COUNT_SW_CPU_CLOCK &&
9724 event->attr.type == PERF_TYPE_SOFTWARE)
9725 cpu_clock_event_start(event, 0);
9729 srcu_read_unlock(&pmus_srcu, idx);
9732 static void perf_event_exit_cpu(int cpu)
9734 perf_event_exit_cpu_context(cpu);
9737 static inline void perf_event_exit_cpu(int cpu) { }
9738 static inline void perf_event_start_swclock(int cpu) { }
9742 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9746 for_each_online_cpu(cpu)
9747 perf_event_exit_cpu(cpu);
9753 * Run the perf reboot notifier at the very last possible moment so that
9754 * the generic watchdog code runs as long as possible.
9756 static struct notifier_block perf_reboot_notifier = {
9757 .notifier_call = perf_reboot,
9758 .priority = INT_MIN,
9762 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9764 unsigned int cpu = (long)hcpu;
9766 switch (action & ~CPU_TASKS_FROZEN) {
9768 case CPU_UP_PREPARE:
9769 case CPU_DOWN_FAILED:
9770 perf_event_init_cpu(cpu);
9773 case CPU_UP_CANCELED:
9774 case CPU_DOWN_PREPARE:
9775 perf_event_exit_cpu(cpu);
9779 perf_event_start_swclock(cpu);
9789 static int event_idle_notif(struct notifier_block *nb, unsigned long action,
9794 __this_cpu_write(is_idle, true);
9797 __this_cpu_write(is_idle, false);
9804 static struct notifier_block perf_event_idle_nb = {
9805 .notifier_call = event_idle_notif,
9808 void __init perf_event_init(void)
9814 perf_event_init_all_cpus();
9815 init_srcu_struct(&pmus_srcu);
9816 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9817 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9818 perf_pmu_register(&perf_task_clock, NULL, -1);
9820 perf_cpu_notifier(perf_cpu_notify);
9821 idle_notifier_register(&perf_event_idle_nb);
9822 register_reboot_notifier(&perf_reboot_notifier);
9824 ret = init_hw_breakpoint();
9825 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9827 /* do not patch jump label more than once per second */
9828 jump_label_rate_limit(&perf_sched_events, HZ);
9831 * Build time assertion that we keep the data_head at the intended
9832 * location. IOW, validation we got the __reserved[] size right.
9834 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9838 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9841 struct perf_pmu_events_attr *pmu_attr =
9842 container_of(attr, struct perf_pmu_events_attr, attr);
9844 if (pmu_attr->event_str)
9845 return sprintf(page, "%s\n", pmu_attr->event_str);
9850 static int __init perf_event_sysfs_init(void)
9855 mutex_lock(&pmus_lock);
9857 ret = bus_register(&pmu_bus);
9861 list_for_each_entry(pmu, &pmus, entry) {
9862 if (!pmu->name || pmu->type < 0)
9865 ret = pmu_dev_alloc(pmu);
9866 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9868 pmu_bus_running = 1;
9872 mutex_unlock(&pmus_lock);
9876 device_initcall(perf_event_sysfs_init);
9878 #ifdef CONFIG_CGROUP_PERF
9879 static struct cgroup_subsys_state *
9880 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9882 struct perf_cgroup *jc;
9884 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9886 return ERR_PTR(-ENOMEM);
9888 jc->info = alloc_percpu(struct perf_cgroup_info);
9891 return ERR_PTR(-ENOMEM);
9897 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9899 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9901 free_percpu(jc->info);
9905 static int __perf_cgroup_move(void *info)
9907 struct task_struct *task = info;
9909 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9914 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9916 struct task_struct *task;
9917 struct cgroup_subsys_state *css;
9919 cgroup_taskset_for_each(task, css, tset)
9920 task_function_call(task, __perf_cgroup_move, task);
9923 struct cgroup_subsys perf_event_cgrp_subsys = {
9924 .css_alloc = perf_cgroup_css_alloc,
9925 .css_free = perf_cgroup_css_free,
9926 .attach = perf_cgroup_attach,
9928 #endif /* CONFIG_CGROUP_PERF */