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);
162 static atomic_t nr_mmap_events __read_mostly;
163 static atomic_t nr_comm_events __read_mostly;
164 static atomic_t nr_task_events __read_mostly;
165 static atomic_t nr_freq_events __read_mostly;
166 static atomic_t nr_switch_events __read_mostly;
168 static LIST_HEAD(pmus);
169 static DEFINE_MUTEX(pmus_lock);
170 static struct srcu_struct pmus_srcu;
173 * perf event paranoia level:
174 * -1 - not paranoid at all
175 * 0 - disallow raw tracepoint access for unpriv
176 * 1 - disallow cpu events for unpriv
177 * 2 - disallow kernel profiling for unpriv
179 int sysctl_perf_event_paranoid __read_mostly = 1;
181 /* Minimum for 512 kiB + 1 user control page */
182 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
185 * max perf event sample rate
187 #define DEFAULT_MAX_SAMPLE_RATE 100000
188 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
189 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
191 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
193 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
194 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
196 static int perf_sample_allowed_ns __read_mostly =
197 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
199 static void update_perf_cpu_limits(void)
201 u64 tmp = perf_sample_period_ns;
203 tmp *= sysctl_perf_cpu_time_max_percent;
205 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
208 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
210 int perf_proc_update_handler(struct ctl_table *table, int write,
211 void __user *buffer, size_t *lenp,
214 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
219 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
220 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
221 update_perf_cpu_limits();
226 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
228 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
229 void __user *buffer, size_t *lenp,
232 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
237 update_perf_cpu_limits();
243 * perf samples are done in some very critical code paths (NMIs).
244 * If they take too much CPU time, the system can lock up and not
245 * get any real work done. This will drop the sample rate when
246 * we detect that events are taking too long.
248 #define NR_ACCUMULATED_SAMPLES 128
249 static DEFINE_PER_CPU(u64, running_sample_length);
251 static void perf_duration_warn(struct irq_work *w)
253 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
254 u64 avg_local_sample_len;
255 u64 local_samples_len;
257 local_samples_len = __this_cpu_read(running_sample_length);
258 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
260 printk_ratelimited(KERN_WARNING
261 "perf interrupt took too long (%lld > %lld), lowering "
262 "kernel.perf_event_max_sample_rate to %d\n",
263 avg_local_sample_len, allowed_ns >> 1,
264 sysctl_perf_event_sample_rate);
267 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
269 void perf_sample_event_took(u64 sample_len_ns)
271 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
272 u64 avg_local_sample_len;
273 u64 local_samples_len;
278 /* decay the counter by 1 average sample */
279 local_samples_len = __this_cpu_read(running_sample_length);
280 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
281 local_samples_len += sample_len_ns;
282 __this_cpu_write(running_sample_length, local_samples_len);
285 * note: this will be biased artifically low until we have
286 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
287 * from having to maintain a count.
289 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
291 if (avg_local_sample_len <= allowed_ns)
294 if (max_samples_per_tick <= 1)
297 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
298 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
299 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
301 update_perf_cpu_limits();
303 if (!irq_work_queue(&perf_duration_work)) {
304 early_printk("perf interrupt took too long (%lld > %lld), lowering "
305 "kernel.perf_event_max_sample_rate to %d\n",
306 avg_local_sample_len, allowed_ns >> 1,
307 sysctl_perf_event_sample_rate);
311 static atomic64_t perf_event_id;
313 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
314 enum event_type_t event_type);
316 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
317 enum event_type_t event_type,
318 struct task_struct *task);
320 static void update_context_time(struct perf_event_context *ctx);
321 static u64 perf_event_time(struct perf_event *event);
323 void __weak perf_event_print_debug(void) { }
325 extern __weak const char *perf_pmu_name(void)
330 static inline u64 perf_clock(void)
332 return local_clock();
335 static inline u64 perf_event_clock(struct perf_event *event)
337 return event->clock();
340 static inline struct perf_cpu_context *
341 __get_cpu_context(struct perf_event_context *ctx)
343 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
346 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
347 struct perf_event_context *ctx)
349 raw_spin_lock(&cpuctx->ctx.lock);
351 raw_spin_lock(&ctx->lock);
354 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
355 struct perf_event_context *ctx)
358 raw_spin_unlock(&ctx->lock);
359 raw_spin_unlock(&cpuctx->ctx.lock);
362 #ifdef CONFIG_CGROUP_PERF
365 perf_cgroup_match(struct perf_event *event)
367 struct perf_event_context *ctx = event->ctx;
368 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
370 /* @event doesn't care about cgroup */
374 /* wants specific cgroup scope but @cpuctx isn't associated with any */
379 * Cgroup scoping is recursive. An event enabled for a cgroup is
380 * also enabled for all its descendant cgroups. If @cpuctx's
381 * cgroup is a descendant of @event's (the test covers identity
382 * case), it's a match.
384 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
385 event->cgrp->css.cgroup);
388 static inline void perf_detach_cgroup(struct perf_event *event)
390 css_put(&event->cgrp->css);
394 static inline int is_cgroup_event(struct perf_event *event)
396 return event->cgrp != NULL;
399 static inline u64 perf_cgroup_event_time(struct perf_event *event)
401 struct perf_cgroup_info *t;
403 t = per_cpu_ptr(event->cgrp->info, event->cpu);
407 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
409 struct perf_cgroup_info *info;
414 info = this_cpu_ptr(cgrp->info);
416 info->time += now - info->timestamp;
417 info->timestamp = now;
420 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
422 struct perf_cgroup *cgrp = cpuctx->cgrp;
423 struct cgroup_subsys_state *css;
426 for (css = &cgrp->css; css; css = css->parent) {
427 cgrp = container_of(css, struct perf_cgroup, css);
428 __update_cgrp_time(cgrp);
433 static inline void update_cgrp_time_from_event(struct perf_event *event)
435 struct perf_cgroup *cgrp;
438 * ensure we access cgroup data only when needed and
439 * when we know the cgroup is pinned (css_get)
441 if (!is_cgroup_event(event))
444 cgrp = perf_cgroup_from_task(current, event->ctx);
446 * Do not update time when cgroup is not active
448 if (cgrp == event->cgrp)
449 __update_cgrp_time(event->cgrp);
453 perf_cgroup_set_timestamp(struct task_struct *task,
454 struct perf_event_context *ctx)
456 struct perf_cgroup *cgrp;
457 struct perf_cgroup_info *info;
458 struct cgroup_subsys_state *css;
461 * ctx->lock held by caller
462 * ensure we do not access cgroup data
463 * unless we have the cgroup pinned (css_get)
465 if (!task || !ctx->nr_cgroups)
468 cgrp = perf_cgroup_from_task(task, ctx);
470 for (css = &cgrp->css; css; css = css->parent) {
471 cgrp = container_of(css, struct perf_cgroup, css);
472 info = this_cpu_ptr(cgrp->info);
473 info->timestamp = ctx->timestamp;
477 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
478 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
481 * reschedule events based on the cgroup constraint of task.
483 * mode SWOUT : schedule out everything
484 * mode SWIN : schedule in based on cgroup for next
486 static void perf_cgroup_switch(struct task_struct *task, int mode)
488 struct perf_cpu_context *cpuctx;
493 * disable interrupts to avoid geting nr_cgroup
494 * changes via __perf_event_disable(). Also
497 local_irq_save(flags);
500 * we reschedule only in the presence of cgroup
501 * constrained events.
504 list_for_each_entry_rcu(pmu, &pmus, entry) {
505 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
506 if (cpuctx->unique_pmu != pmu)
507 continue; /* ensure we process each cpuctx once */
510 * perf_cgroup_events says at least one
511 * context on this CPU has cgroup events.
513 * ctx->nr_cgroups reports the number of cgroup
514 * events for a context.
516 if (cpuctx->ctx.nr_cgroups > 0) {
517 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
518 perf_pmu_disable(cpuctx->ctx.pmu);
520 if (mode & PERF_CGROUP_SWOUT) {
521 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
523 * must not be done before ctxswout due
524 * to event_filter_match() in event_sched_out()
529 if (mode & PERF_CGROUP_SWIN) {
530 WARN_ON_ONCE(cpuctx->cgrp);
532 * set cgrp before ctxsw in to allow
533 * event_filter_match() to not have to pass
535 * we pass the cpuctx->ctx to perf_cgroup_from_task()
536 * because cgorup events are only per-cpu
538 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
539 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
541 perf_pmu_enable(cpuctx->ctx.pmu);
542 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
546 local_irq_restore(flags);
549 static inline void perf_cgroup_sched_out(struct task_struct *task,
550 struct task_struct *next)
552 struct perf_cgroup *cgrp1;
553 struct perf_cgroup *cgrp2 = NULL;
557 * we come here when we know perf_cgroup_events > 0
558 * we do not need to pass the ctx here because we know
559 * we are holding the rcu lock
561 cgrp1 = perf_cgroup_from_task(task, NULL);
564 * next is NULL when called from perf_event_enable_on_exec()
565 * that will systematically cause a cgroup_switch()
568 cgrp2 = perf_cgroup_from_task(next, NULL);
571 * only schedule out current cgroup events if we know
572 * that we are switching to a different cgroup. Otherwise,
573 * do no touch the cgroup events.
576 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
581 static inline void perf_cgroup_sched_in(struct task_struct *prev,
582 struct task_struct *task)
584 struct perf_cgroup *cgrp1;
585 struct perf_cgroup *cgrp2 = NULL;
589 * we come here when we know perf_cgroup_events > 0
590 * we do not need to pass the ctx here because we know
591 * we are holding the rcu lock
593 cgrp1 = perf_cgroup_from_task(task, NULL);
595 /* prev can never be NULL */
596 cgrp2 = perf_cgroup_from_task(prev, NULL);
599 * only need to schedule in cgroup events if we are changing
600 * cgroup during ctxsw. Cgroup events were not scheduled
601 * out of ctxsw out if that was not the case.
604 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
609 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
610 struct perf_event_attr *attr,
611 struct perf_event *group_leader)
613 struct perf_cgroup *cgrp;
614 struct cgroup_subsys_state *css;
615 struct fd f = fdget(fd);
621 css = css_tryget_online_from_dir(f.file->f_path.dentry,
622 &perf_event_cgrp_subsys);
628 cgrp = container_of(css, struct perf_cgroup, css);
632 * all events in a group must monitor
633 * the same cgroup because a task belongs
634 * to only one perf cgroup at a time
636 if (group_leader && group_leader->cgrp != cgrp) {
637 perf_detach_cgroup(event);
646 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
648 struct perf_cgroup_info *t;
649 t = per_cpu_ptr(event->cgrp->info, event->cpu);
650 event->shadow_ctx_time = now - t->timestamp;
654 perf_cgroup_defer_enabled(struct perf_event *event)
657 * when the current task's perf cgroup does not match
658 * the event's, we need to remember to call the
659 * perf_mark_enable() function the first time a task with
660 * a matching perf cgroup is scheduled in.
662 if (is_cgroup_event(event) && !perf_cgroup_match(event))
663 event->cgrp_defer_enabled = 1;
667 perf_cgroup_mark_enabled(struct perf_event *event,
668 struct perf_event_context *ctx)
670 struct perf_event *sub;
671 u64 tstamp = perf_event_time(event);
673 if (!event->cgrp_defer_enabled)
676 event->cgrp_defer_enabled = 0;
678 event->tstamp_enabled = tstamp - event->total_time_enabled;
679 list_for_each_entry(sub, &event->sibling_list, group_entry) {
680 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
681 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
682 sub->cgrp_defer_enabled = 0;
686 #else /* !CONFIG_CGROUP_PERF */
689 perf_cgroup_match(struct perf_event *event)
694 static inline void perf_detach_cgroup(struct perf_event *event)
697 static inline int is_cgroup_event(struct perf_event *event)
702 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
707 static inline void update_cgrp_time_from_event(struct perf_event *event)
711 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
715 static inline void perf_cgroup_sched_out(struct task_struct *task,
716 struct task_struct *next)
720 static inline void perf_cgroup_sched_in(struct task_struct *prev,
721 struct task_struct *task)
725 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
726 struct perf_event_attr *attr,
727 struct perf_event *group_leader)
733 perf_cgroup_set_timestamp(struct task_struct *task,
734 struct perf_event_context *ctx)
739 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
744 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
748 static inline u64 perf_cgroup_event_time(struct perf_event *event)
754 perf_cgroup_defer_enabled(struct perf_event *event)
759 perf_cgroup_mark_enabled(struct perf_event *event,
760 struct perf_event_context *ctx)
766 * set default to be dependent on timer tick just
769 #define PERF_CPU_HRTIMER (1000 / HZ)
771 * function must be called with interrupts disbled
773 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
775 struct perf_cpu_context *cpuctx;
778 WARN_ON(!irqs_disabled());
780 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
781 rotations = perf_rotate_context(cpuctx);
783 raw_spin_lock(&cpuctx->hrtimer_lock);
785 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
787 cpuctx->hrtimer_active = 0;
788 raw_spin_unlock(&cpuctx->hrtimer_lock);
790 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
793 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
795 struct hrtimer *timer = &cpuctx->hrtimer;
796 struct pmu *pmu = cpuctx->ctx.pmu;
799 /* no multiplexing needed for SW PMU */
800 if (pmu->task_ctx_nr == perf_sw_context)
804 * check default is sane, if not set then force to
805 * default interval (1/tick)
807 interval = pmu->hrtimer_interval_ms;
809 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
811 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
813 raw_spin_lock_init(&cpuctx->hrtimer_lock);
814 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
815 timer->function = perf_mux_hrtimer_handler;
818 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
820 struct hrtimer *timer = &cpuctx->hrtimer;
821 struct pmu *pmu = cpuctx->ctx.pmu;
825 if (pmu->task_ctx_nr == perf_sw_context)
828 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
829 if (!cpuctx->hrtimer_active) {
830 cpuctx->hrtimer_active = 1;
831 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
832 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
834 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
839 void perf_pmu_disable(struct pmu *pmu)
841 int *count = this_cpu_ptr(pmu->pmu_disable_count);
843 pmu->pmu_disable(pmu);
846 void perf_pmu_enable(struct pmu *pmu)
848 int *count = this_cpu_ptr(pmu->pmu_disable_count);
850 pmu->pmu_enable(pmu);
853 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
856 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
857 * perf_event_task_tick() are fully serialized because they're strictly cpu
858 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
859 * disabled, while perf_event_task_tick is called from IRQ context.
861 static void perf_event_ctx_activate(struct perf_event_context *ctx)
863 struct list_head *head = this_cpu_ptr(&active_ctx_list);
865 WARN_ON(!irqs_disabled());
867 WARN_ON(!list_empty(&ctx->active_ctx_list));
869 list_add(&ctx->active_ctx_list, head);
872 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
874 WARN_ON(!irqs_disabled());
876 WARN_ON(list_empty(&ctx->active_ctx_list));
878 list_del_init(&ctx->active_ctx_list);
881 static void get_ctx(struct perf_event_context *ctx)
883 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
886 static void free_ctx(struct rcu_head *head)
888 struct perf_event_context *ctx;
890 ctx = container_of(head, struct perf_event_context, rcu_head);
891 kfree(ctx->task_ctx_data);
895 static void put_ctx(struct perf_event_context *ctx)
897 if (atomic_dec_and_test(&ctx->refcount)) {
899 put_ctx(ctx->parent_ctx);
901 put_task_struct(ctx->task);
902 call_rcu(&ctx->rcu_head, free_ctx);
907 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
908 * perf_pmu_migrate_context() we need some magic.
910 * Those places that change perf_event::ctx will hold both
911 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
913 * Lock ordering is by mutex address. There are two other sites where
914 * perf_event_context::mutex nests and those are:
916 * - perf_event_exit_task_context() [ child , 0 ]
917 * __perf_event_exit_task()
919 * put_event() [ parent, 1 ]
921 * - perf_event_init_context() [ parent, 0 ]
922 * inherit_task_group()
927 * perf_try_init_event() [ child , 1 ]
929 * While it appears there is an obvious deadlock here -- the parent and child
930 * nesting levels are inverted between the two. This is in fact safe because
931 * life-time rules separate them. That is an exiting task cannot fork, and a
932 * spawning task cannot (yet) exit.
934 * But remember that that these are parent<->child context relations, and
935 * migration does not affect children, therefore these two orderings should not
938 * The change in perf_event::ctx does not affect children (as claimed above)
939 * because the sys_perf_event_open() case will install a new event and break
940 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
941 * concerned with cpuctx and that doesn't have children.
943 * The places that change perf_event::ctx will issue:
945 * perf_remove_from_context();
947 * perf_install_in_context();
949 * to affect the change. The remove_from_context() + synchronize_rcu() should
950 * quiesce the event, after which we can install it in the new location. This
951 * means that only external vectors (perf_fops, prctl) can perturb the event
952 * while in transit. Therefore all such accessors should also acquire
953 * perf_event_context::mutex to serialize against this.
955 * However; because event->ctx can change while we're waiting to acquire
956 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
961 * task_struct::perf_event_mutex
962 * perf_event_context::mutex
963 * perf_event_context::lock
964 * perf_event::child_mutex;
965 * perf_event::mmap_mutex
968 static struct perf_event_context *
969 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
971 struct perf_event_context *ctx;
975 ctx = ACCESS_ONCE(event->ctx);
976 if (!atomic_inc_not_zero(&ctx->refcount)) {
982 mutex_lock_nested(&ctx->mutex, nesting);
983 if (event->ctx != ctx) {
984 mutex_unlock(&ctx->mutex);
992 static inline struct perf_event_context *
993 perf_event_ctx_lock(struct perf_event *event)
995 return perf_event_ctx_lock_nested(event, 0);
998 static void perf_event_ctx_unlock(struct perf_event *event,
999 struct perf_event_context *ctx)
1001 mutex_unlock(&ctx->mutex);
1006 * This must be done under the ctx->lock, such as to serialize against
1007 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1008 * calling scheduler related locks and ctx->lock nests inside those.
1010 static __must_check struct perf_event_context *
1011 unclone_ctx(struct perf_event_context *ctx)
1013 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1015 lockdep_assert_held(&ctx->lock);
1018 ctx->parent_ctx = NULL;
1024 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1027 * only top level events have the pid namespace they were created in
1030 event = event->parent;
1032 return task_tgid_nr_ns(p, event->ns);
1035 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1038 * only top level events have the pid namespace they were created in
1041 event = event->parent;
1043 return task_pid_nr_ns(p, event->ns);
1047 * If we inherit events we want to return the parent event id
1050 static u64 primary_event_id(struct perf_event *event)
1055 id = event->parent->id;
1061 * Get the perf_event_context for a task and lock it.
1062 * This has to cope with with the fact that until it is locked,
1063 * the context could get moved to another task.
1065 static struct perf_event_context *
1066 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1068 struct perf_event_context *ctx;
1072 * One of the few rules of preemptible RCU is that one cannot do
1073 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1074 * part of the read side critical section was irqs-enabled -- see
1075 * rcu_read_unlock_special().
1077 * Since ctx->lock nests under rq->lock we must ensure the entire read
1078 * side critical section has interrupts disabled.
1080 local_irq_save(*flags);
1082 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1085 * If this context is a clone of another, it might
1086 * get swapped for another underneath us by
1087 * perf_event_task_sched_out, though the
1088 * rcu_read_lock() protects us from any context
1089 * getting freed. Lock the context and check if it
1090 * got swapped before we could get the lock, and retry
1091 * if so. If we locked the right context, then it
1092 * can't get swapped on us any more.
1094 raw_spin_lock(&ctx->lock);
1095 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1096 raw_spin_unlock(&ctx->lock);
1098 local_irq_restore(*flags);
1102 if (!atomic_inc_not_zero(&ctx->refcount)) {
1103 raw_spin_unlock(&ctx->lock);
1109 local_irq_restore(*flags);
1114 * Get the context for a task and increment its pin_count so it
1115 * can't get swapped to another task. This also increments its
1116 * reference count so that the context can't get freed.
1118 static struct perf_event_context *
1119 perf_pin_task_context(struct task_struct *task, int ctxn)
1121 struct perf_event_context *ctx;
1122 unsigned long flags;
1124 ctx = perf_lock_task_context(task, ctxn, &flags);
1127 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1132 static void perf_unpin_context(struct perf_event_context *ctx)
1134 unsigned long flags;
1136 raw_spin_lock_irqsave(&ctx->lock, flags);
1138 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1142 * Update the record of the current time in a context.
1144 static void update_context_time(struct perf_event_context *ctx)
1146 u64 now = perf_clock();
1148 ctx->time += now - ctx->timestamp;
1149 ctx->timestamp = now;
1152 static u64 perf_event_time(struct perf_event *event)
1154 struct perf_event_context *ctx = event->ctx;
1156 if (is_cgroup_event(event))
1157 return perf_cgroup_event_time(event);
1159 return ctx ? ctx->time : 0;
1163 * Update the total_time_enabled and total_time_running fields for a event.
1164 * The caller of this function needs to hold the ctx->lock.
1166 static void update_event_times(struct perf_event *event)
1168 struct perf_event_context *ctx = event->ctx;
1171 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1172 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1175 * in cgroup mode, time_enabled represents
1176 * the time the event was enabled AND active
1177 * tasks were in the monitored cgroup. This is
1178 * independent of the activity of the context as
1179 * there may be a mix of cgroup and non-cgroup events.
1181 * That is why we treat cgroup events differently
1184 if (is_cgroup_event(event))
1185 run_end = perf_cgroup_event_time(event);
1186 else if (ctx->is_active)
1187 run_end = ctx->time;
1189 run_end = event->tstamp_stopped;
1191 event->total_time_enabled = run_end - event->tstamp_enabled;
1193 if (event->state == PERF_EVENT_STATE_INACTIVE)
1194 run_end = event->tstamp_stopped;
1196 run_end = perf_event_time(event);
1198 event->total_time_running = run_end - event->tstamp_running;
1203 * Update total_time_enabled and total_time_running for all events in a group.
1205 static void update_group_times(struct perf_event *leader)
1207 struct perf_event *event;
1209 update_event_times(leader);
1210 list_for_each_entry(event, &leader->sibling_list, group_entry)
1211 update_event_times(event);
1214 static struct list_head *
1215 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1217 if (event->attr.pinned)
1218 return &ctx->pinned_groups;
1220 return &ctx->flexible_groups;
1224 * Add a event from the lists for its context.
1225 * Must be called with ctx->mutex and ctx->lock held.
1228 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1230 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1231 event->attach_state |= PERF_ATTACH_CONTEXT;
1234 * If we're a stand alone event or group leader, we go to the context
1235 * list, group events are kept attached to the group so that
1236 * perf_group_detach can, at all times, locate all siblings.
1238 if (event->group_leader == event) {
1239 struct list_head *list;
1241 if (is_software_event(event))
1242 event->group_flags |= PERF_GROUP_SOFTWARE;
1244 list = ctx_group_list(event, ctx);
1245 list_add_tail(&event->group_entry, list);
1248 if (is_cgroup_event(event))
1251 list_add_rcu(&event->event_entry, &ctx->event_list);
1253 if (event->attr.inherit_stat)
1260 * Initialize event state based on the perf_event_attr::disabled.
1262 static inline void perf_event__state_init(struct perf_event *event)
1264 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1265 PERF_EVENT_STATE_INACTIVE;
1268 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1270 int entry = sizeof(u64); /* value */
1274 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1275 size += sizeof(u64);
1277 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1278 size += sizeof(u64);
1280 if (event->attr.read_format & PERF_FORMAT_ID)
1281 entry += sizeof(u64);
1283 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1285 size += sizeof(u64);
1289 event->read_size = size;
1292 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1294 struct perf_sample_data *data;
1297 if (sample_type & PERF_SAMPLE_IP)
1298 size += sizeof(data->ip);
1300 if (sample_type & PERF_SAMPLE_ADDR)
1301 size += sizeof(data->addr);
1303 if (sample_type & PERF_SAMPLE_PERIOD)
1304 size += sizeof(data->period);
1306 if (sample_type & PERF_SAMPLE_WEIGHT)
1307 size += sizeof(data->weight);
1309 if (sample_type & PERF_SAMPLE_READ)
1310 size += event->read_size;
1312 if (sample_type & PERF_SAMPLE_DATA_SRC)
1313 size += sizeof(data->data_src.val);
1315 if (sample_type & PERF_SAMPLE_TRANSACTION)
1316 size += sizeof(data->txn);
1318 event->header_size = size;
1322 * Called at perf_event creation and when events are attached/detached from a
1325 static void perf_event__header_size(struct perf_event *event)
1327 __perf_event_read_size(event,
1328 event->group_leader->nr_siblings);
1329 __perf_event_header_size(event, event->attr.sample_type);
1332 static void perf_event__id_header_size(struct perf_event *event)
1334 struct perf_sample_data *data;
1335 u64 sample_type = event->attr.sample_type;
1338 if (sample_type & PERF_SAMPLE_TID)
1339 size += sizeof(data->tid_entry);
1341 if (sample_type & PERF_SAMPLE_TIME)
1342 size += sizeof(data->time);
1344 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1345 size += sizeof(data->id);
1347 if (sample_type & PERF_SAMPLE_ID)
1348 size += sizeof(data->id);
1350 if (sample_type & PERF_SAMPLE_STREAM_ID)
1351 size += sizeof(data->stream_id);
1353 if (sample_type & PERF_SAMPLE_CPU)
1354 size += sizeof(data->cpu_entry);
1356 event->id_header_size = size;
1359 static bool perf_event_validate_size(struct perf_event *event)
1362 * The values computed here will be over-written when we actually
1365 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1366 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1367 perf_event__id_header_size(event);
1370 * Sum the lot; should not exceed the 64k limit we have on records.
1371 * Conservative limit to allow for callchains and other variable fields.
1373 if (event->read_size + event->header_size +
1374 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1380 static void perf_group_attach(struct perf_event *event)
1382 struct perf_event *group_leader = event->group_leader, *pos;
1385 * We can have double attach due to group movement in perf_event_open.
1387 if (event->attach_state & PERF_ATTACH_GROUP)
1390 event->attach_state |= PERF_ATTACH_GROUP;
1392 if (group_leader == event)
1395 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1397 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1398 !is_software_event(event))
1399 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1401 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1402 group_leader->nr_siblings++;
1404 perf_event__header_size(group_leader);
1406 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1407 perf_event__header_size(pos);
1411 * Remove a event from the lists for its context.
1412 * Must be called with ctx->mutex and ctx->lock held.
1415 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1417 struct perf_cpu_context *cpuctx;
1419 WARN_ON_ONCE(event->ctx != ctx);
1420 lockdep_assert_held(&ctx->lock);
1423 * We can have double detach due to exit/hot-unplug + close.
1425 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1428 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1430 if (is_cgroup_event(event)) {
1432 cpuctx = __get_cpu_context(ctx);
1434 * if there are no more cgroup events
1435 * then cler cgrp to avoid stale pointer
1436 * in update_cgrp_time_from_cpuctx()
1438 if (!ctx->nr_cgroups)
1439 cpuctx->cgrp = NULL;
1443 if (event->attr.inherit_stat)
1446 list_del_rcu(&event->event_entry);
1448 if (event->group_leader == event)
1449 list_del_init(&event->group_entry);
1451 update_group_times(event);
1454 * If event was in error state, then keep it
1455 * that way, otherwise bogus counts will be
1456 * returned on read(). The only way to get out
1457 * of error state is by explicit re-enabling
1460 if (event->state > PERF_EVENT_STATE_OFF)
1461 event->state = PERF_EVENT_STATE_OFF;
1466 static void perf_group_detach(struct perf_event *event)
1468 struct perf_event *sibling, *tmp;
1469 struct list_head *list = NULL;
1472 * We can have double detach due to exit/hot-unplug + close.
1474 if (!(event->attach_state & PERF_ATTACH_GROUP))
1477 event->attach_state &= ~PERF_ATTACH_GROUP;
1480 * If this is a sibling, remove it from its group.
1482 if (event->group_leader != event) {
1483 list_del_init(&event->group_entry);
1484 event->group_leader->nr_siblings--;
1488 if (!list_empty(&event->group_entry))
1489 list = &event->group_entry;
1492 * If this was a group event with sibling events then
1493 * upgrade the siblings to singleton events by adding them
1494 * to whatever list we are on.
1496 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1498 list_move_tail(&sibling->group_entry, list);
1499 sibling->group_leader = sibling;
1501 /* Inherit group flags from the previous leader */
1502 sibling->group_flags = event->group_flags;
1504 WARN_ON_ONCE(sibling->ctx != event->ctx);
1508 perf_event__header_size(event->group_leader);
1510 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1511 perf_event__header_size(tmp);
1515 * User event without the task.
1517 static bool is_orphaned_event(struct perf_event *event)
1519 return event && !is_kernel_event(event) && !event->owner;
1523 * Event has a parent but parent's task finished and it's
1524 * alive only because of children holding refference.
1526 static bool is_orphaned_child(struct perf_event *event)
1528 return is_orphaned_event(event->parent);
1531 static void orphans_remove_work(struct work_struct *work);
1533 static void schedule_orphans_remove(struct perf_event_context *ctx)
1535 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1538 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1540 ctx->orphans_remove_sched = true;
1544 static int __init perf_workqueue_init(void)
1546 perf_wq = create_singlethread_workqueue("perf");
1547 WARN(!perf_wq, "failed to create perf workqueue\n");
1548 return perf_wq ? 0 : -1;
1551 core_initcall(perf_workqueue_init);
1553 static inline int __pmu_filter_match(struct perf_event *event)
1555 struct pmu *pmu = event->pmu;
1556 return pmu->filter_match ? pmu->filter_match(event) : 1;
1560 * Check whether we should attempt to schedule an event group based on
1561 * PMU-specific filtering. An event group can consist of HW and SW events,
1562 * potentially with a SW leader, so we must check all the filters, to
1563 * determine whether a group is schedulable:
1565 static inline int pmu_filter_match(struct perf_event *event)
1567 struct perf_event *child;
1569 if (!__pmu_filter_match(event))
1572 list_for_each_entry(child, &event->sibling_list, group_entry) {
1573 if (!__pmu_filter_match(child))
1581 event_filter_match(struct perf_event *event)
1583 return (event->cpu == -1 || event->cpu == smp_processor_id())
1584 && perf_cgroup_match(event) && pmu_filter_match(event);
1588 event_sched_out(struct perf_event *event,
1589 struct perf_cpu_context *cpuctx,
1590 struct perf_event_context *ctx)
1592 u64 tstamp = perf_event_time(event);
1595 WARN_ON_ONCE(event->ctx != ctx);
1596 lockdep_assert_held(&ctx->lock);
1599 * An event which could not be activated because of
1600 * filter mismatch still needs to have its timings
1601 * maintained, otherwise bogus information is return
1602 * via read() for time_enabled, time_running:
1604 if (event->state == PERF_EVENT_STATE_INACTIVE
1605 && !event_filter_match(event)) {
1606 delta = tstamp - event->tstamp_stopped;
1607 event->tstamp_running += delta;
1608 event->tstamp_stopped = tstamp;
1611 if (event->state != PERF_EVENT_STATE_ACTIVE)
1614 perf_pmu_disable(event->pmu);
1616 event->tstamp_stopped = tstamp;
1617 event->pmu->del(event, 0);
1619 event->state = PERF_EVENT_STATE_INACTIVE;
1620 if (event->pending_disable) {
1621 event->pending_disable = 0;
1622 event->state = PERF_EVENT_STATE_OFF;
1625 if (!is_software_event(event))
1626 cpuctx->active_oncpu--;
1627 if (!--ctx->nr_active)
1628 perf_event_ctx_deactivate(ctx);
1629 if (event->attr.freq && event->attr.sample_freq)
1631 if (event->attr.exclusive || !cpuctx->active_oncpu)
1632 cpuctx->exclusive = 0;
1634 if (is_orphaned_child(event))
1635 schedule_orphans_remove(ctx);
1637 perf_pmu_enable(event->pmu);
1641 group_sched_out(struct perf_event *group_event,
1642 struct perf_cpu_context *cpuctx,
1643 struct perf_event_context *ctx)
1645 struct perf_event *event;
1646 int state = group_event->state;
1648 event_sched_out(group_event, cpuctx, ctx);
1651 * Schedule out siblings (if any):
1653 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1654 event_sched_out(event, cpuctx, ctx);
1656 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1657 cpuctx->exclusive = 0;
1660 struct remove_event {
1661 struct perf_event *event;
1666 * Cross CPU call to remove a performance event
1668 * We disable the event on the hardware level first. After that we
1669 * remove it from the context list.
1671 static int __perf_remove_from_context(void *info)
1673 struct remove_event *re = info;
1674 struct perf_event *event = re->event;
1675 struct perf_event_context *ctx = event->ctx;
1676 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1678 raw_spin_lock(&ctx->lock);
1679 event_sched_out(event, cpuctx, ctx);
1680 if (re->detach_group)
1681 perf_group_detach(event);
1682 list_del_event(event, ctx);
1683 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1685 cpuctx->task_ctx = NULL;
1687 raw_spin_unlock(&ctx->lock);
1694 * Remove the event from a task's (or a CPU's) list of events.
1696 * CPU events are removed with a smp call. For task events we only
1697 * call when the task is on a CPU.
1699 * If event->ctx is a cloned context, callers must make sure that
1700 * every task struct that event->ctx->task could possibly point to
1701 * remains valid. This is OK when called from perf_release since
1702 * that only calls us on the top-level context, which can't be a clone.
1703 * When called from perf_event_exit_task, it's OK because the
1704 * context has been detached from its task.
1706 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1708 struct perf_event_context *ctx = event->ctx;
1709 struct task_struct *task = ctx->task;
1710 struct remove_event re = {
1712 .detach_group = detach_group,
1715 lockdep_assert_held(&ctx->mutex);
1719 * Per cpu events are removed via an smp call. The removal can
1720 * fail if the CPU is currently offline, but in that case we
1721 * already called __perf_remove_from_context from
1722 * perf_event_exit_cpu.
1724 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1729 if (!task_function_call(task, __perf_remove_from_context, &re))
1732 raw_spin_lock_irq(&ctx->lock);
1734 * If we failed to find a running task, but find the context active now
1735 * that we've acquired the ctx->lock, retry.
1737 if (ctx->is_active) {
1738 raw_spin_unlock_irq(&ctx->lock);
1740 * Reload the task pointer, it might have been changed by
1741 * a concurrent perf_event_context_sched_out().
1748 * Since the task isn't running, its safe to remove the event, us
1749 * holding the ctx->lock ensures the task won't get scheduled in.
1752 perf_group_detach(event);
1753 list_del_event(event, ctx);
1754 raw_spin_unlock_irq(&ctx->lock);
1758 * Cross CPU call to disable a performance event
1760 int __perf_event_disable(void *info)
1762 struct perf_event *event = info;
1763 struct perf_event_context *ctx = event->ctx;
1764 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1767 * If this is a per-task event, need to check whether this
1768 * event's task is the current task on this cpu.
1770 * Can trigger due to concurrent perf_event_context_sched_out()
1771 * flipping contexts around.
1773 if (ctx->task && cpuctx->task_ctx != ctx)
1776 raw_spin_lock(&ctx->lock);
1779 * If the event is on, turn it off.
1780 * If it is in error state, leave it in error state.
1782 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1783 update_context_time(ctx);
1784 update_cgrp_time_from_event(event);
1785 update_group_times(event);
1786 if (event == event->group_leader)
1787 group_sched_out(event, cpuctx, ctx);
1789 event_sched_out(event, cpuctx, ctx);
1790 event->state = PERF_EVENT_STATE_OFF;
1793 raw_spin_unlock(&ctx->lock);
1801 * If event->ctx is a cloned context, callers must make sure that
1802 * every task struct that event->ctx->task could possibly point to
1803 * remains valid. This condition is satisifed when called through
1804 * perf_event_for_each_child or perf_event_for_each because they
1805 * hold the top-level event's child_mutex, so any descendant that
1806 * goes to exit will block in sync_child_event.
1807 * When called from perf_pending_event it's OK because event->ctx
1808 * is the current context on this CPU and preemption is disabled,
1809 * hence we can't get into perf_event_task_sched_out for this context.
1811 static void _perf_event_disable(struct perf_event *event)
1813 struct perf_event_context *ctx = event->ctx;
1814 struct task_struct *task = ctx->task;
1818 * Disable the event on the cpu that it's on
1820 cpu_function_call(event->cpu, __perf_event_disable, event);
1825 if (!task_function_call(task, __perf_event_disable, event))
1828 raw_spin_lock_irq(&ctx->lock);
1830 * If the event is still active, we need to retry the cross-call.
1832 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1833 raw_spin_unlock_irq(&ctx->lock);
1835 * Reload the task pointer, it might have been changed by
1836 * a concurrent perf_event_context_sched_out().
1843 * Since we have the lock this context can't be scheduled
1844 * in, so we can change the state safely.
1846 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1847 update_group_times(event);
1848 event->state = PERF_EVENT_STATE_OFF;
1850 raw_spin_unlock_irq(&ctx->lock);
1854 * Strictly speaking kernel users cannot create groups and therefore this
1855 * interface does not need the perf_event_ctx_lock() magic.
1857 void perf_event_disable(struct perf_event *event)
1859 struct perf_event_context *ctx;
1861 ctx = perf_event_ctx_lock(event);
1862 _perf_event_disable(event);
1863 perf_event_ctx_unlock(event, ctx);
1865 EXPORT_SYMBOL_GPL(perf_event_disable);
1867 static void perf_set_shadow_time(struct perf_event *event,
1868 struct perf_event_context *ctx,
1872 * use the correct time source for the time snapshot
1874 * We could get by without this by leveraging the
1875 * fact that to get to this function, the caller
1876 * has most likely already called update_context_time()
1877 * and update_cgrp_time_xx() and thus both timestamp
1878 * are identical (or very close). Given that tstamp is,
1879 * already adjusted for cgroup, we could say that:
1880 * tstamp - ctx->timestamp
1882 * tstamp - cgrp->timestamp.
1884 * Then, in perf_output_read(), the calculation would
1885 * work with no changes because:
1886 * - event is guaranteed scheduled in
1887 * - no scheduled out in between
1888 * - thus the timestamp would be the same
1890 * But this is a bit hairy.
1892 * So instead, we have an explicit cgroup call to remain
1893 * within the time time source all along. We believe it
1894 * is cleaner and simpler to understand.
1896 if (is_cgroup_event(event))
1897 perf_cgroup_set_shadow_time(event, tstamp);
1899 event->shadow_ctx_time = tstamp - ctx->timestamp;
1902 #define MAX_INTERRUPTS (~0ULL)
1904 static void perf_log_throttle(struct perf_event *event, int enable);
1905 static void perf_log_itrace_start(struct perf_event *event);
1908 event_sched_in(struct perf_event *event,
1909 struct perf_cpu_context *cpuctx,
1910 struct perf_event_context *ctx)
1912 u64 tstamp = perf_event_time(event);
1915 lockdep_assert_held(&ctx->lock);
1917 if (event->state <= PERF_EVENT_STATE_OFF)
1920 event->state = PERF_EVENT_STATE_ACTIVE;
1921 event->oncpu = smp_processor_id();
1924 * Unthrottle events, since we scheduled we might have missed several
1925 * ticks already, also for a heavily scheduling task there is little
1926 * guarantee it'll get a tick in a timely manner.
1928 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1929 perf_log_throttle(event, 1);
1930 event->hw.interrupts = 0;
1934 * The new state must be visible before we turn it on in the hardware:
1938 perf_pmu_disable(event->pmu);
1940 perf_set_shadow_time(event, ctx, tstamp);
1942 perf_log_itrace_start(event);
1944 if (event->pmu->add(event, PERF_EF_START)) {
1945 event->state = PERF_EVENT_STATE_INACTIVE;
1951 event->tstamp_running += tstamp - event->tstamp_stopped;
1953 if (!is_software_event(event))
1954 cpuctx->active_oncpu++;
1955 if (!ctx->nr_active++)
1956 perf_event_ctx_activate(ctx);
1957 if (event->attr.freq && event->attr.sample_freq)
1960 if (event->attr.exclusive)
1961 cpuctx->exclusive = 1;
1963 if (is_orphaned_child(event))
1964 schedule_orphans_remove(ctx);
1967 perf_pmu_enable(event->pmu);
1973 group_sched_in(struct perf_event *group_event,
1974 struct perf_cpu_context *cpuctx,
1975 struct perf_event_context *ctx)
1977 struct perf_event *event, *partial_group = NULL;
1978 struct pmu *pmu = ctx->pmu;
1979 u64 now = ctx->time;
1980 bool simulate = false;
1982 if (group_event->state == PERF_EVENT_STATE_OFF)
1985 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
1987 if (event_sched_in(group_event, cpuctx, ctx)) {
1988 pmu->cancel_txn(pmu);
1989 perf_mux_hrtimer_restart(cpuctx);
1994 * Schedule in siblings as one group (if any):
1996 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1997 if (event_sched_in(event, cpuctx, ctx)) {
1998 partial_group = event;
2003 if (!pmu->commit_txn(pmu))
2008 * Groups can be scheduled in as one unit only, so undo any
2009 * partial group before returning:
2010 * The events up to the failed event are scheduled out normally,
2011 * tstamp_stopped will be updated.
2013 * The failed events and the remaining siblings need to have
2014 * their timings updated as if they had gone thru event_sched_in()
2015 * and event_sched_out(). This is required to get consistent timings
2016 * across the group. This also takes care of the case where the group
2017 * could never be scheduled by ensuring tstamp_stopped is set to mark
2018 * the time the event was actually stopped, such that time delta
2019 * calculation in update_event_times() is correct.
2021 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2022 if (event == partial_group)
2026 event->tstamp_running += now - event->tstamp_stopped;
2027 event->tstamp_stopped = now;
2029 event_sched_out(event, cpuctx, ctx);
2032 event_sched_out(group_event, cpuctx, ctx);
2034 pmu->cancel_txn(pmu);
2036 perf_mux_hrtimer_restart(cpuctx);
2042 * Work out whether we can put this event group on the CPU now.
2044 static int group_can_go_on(struct perf_event *event,
2045 struct perf_cpu_context *cpuctx,
2049 * Groups consisting entirely of software events can always go on.
2051 if (event->group_flags & PERF_GROUP_SOFTWARE)
2054 * If an exclusive group is already on, no other hardware
2057 if (cpuctx->exclusive)
2060 * If this group is exclusive and there are already
2061 * events on the CPU, it can't go on.
2063 if (event->attr.exclusive && cpuctx->active_oncpu)
2066 * Otherwise, try to add it if all previous groups were able
2072 static void add_event_to_ctx(struct perf_event *event,
2073 struct perf_event_context *ctx)
2075 u64 tstamp = perf_event_time(event);
2077 list_add_event(event, ctx);
2078 perf_group_attach(event);
2079 event->tstamp_enabled = tstamp;
2080 event->tstamp_running = tstamp;
2081 event->tstamp_stopped = tstamp;
2084 static void task_ctx_sched_out(struct perf_event_context *ctx);
2086 ctx_sched_in(struct perf_event_context *ctx,
2087 struct perf_cpu_context *cpuctx,
2088 enum event_type_t event_type,
2089 struct task_struct *task);
2091 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2092 struct perf_event_context *ctx,
2093 struct task_struct *task)
2095 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2097 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2098 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2100 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2104 * Cross CPU call to install and enable a performance event
2106 * Must be called with ctx->mutex held
2108 static int __perf_install_in_context(void *info)
2110 struct perf_event *event = info;
2111 struct perf_event_context *ctx = event->ctx;
2112 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2113 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2114 struct task_struct *task = current;
2116 perf_ctx_lock(cpuctx, task_ctx);
2117 perf_pmu_disable(cpuctx->ctx.pmu);
2120 * If there was an active task_ctx schedule it out.
2123 task_ctx_sched_out(task_ctx);
2126 * If the context we're installing events in is not the
2127 * active task_ctx, flip them.
2129 if (ctx->task && task_ctx != ctx) {
2131 raw_spin_unlock(&task_ctx->lock);
2132 raw_spin_lock(&ctx->lock);
2137 cpuctx->task_ctx = task_ctx;
2138 task = task_ctx->task;
2141 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2143 update_context_time(ctx);
2145 * update cgrp time only if current cgrp
2146 * matches event->cgrp. Must be done before
2147 * calling add_event_to_ctx()
2149 update_cgrp_time_from_event(event);
2151 add_event_to_ctx(event, ctx);
2154 * Schedule everything back in
2156 perf_event_sched_in(cpuctx, task_ctx, task);
2158 perf_pmu_enable(cpuctx->ctx.pmu);
2159 perf_ctx_unlock(cpuctx, task_ctx);
2165 * Attach a performance event to a context
2167 * First we add the event to the list with the hardware enable bit
2168 * in event->hw_config cleared.
2170 * If the event is attached to a task which is on a CPU we use a smp
2171 * call to enable it in the task context. The task might have been
2172 * scheduled away, but we check this in the smp call again.
2175 perf_install_in_context(struct perf_event_context *ctx,
2176 struct perf_event *event,
2179 struct task_struct *task = ctx->task;
2181 lockdep_assert_held(&ctx->mutex);
2184 if (event->cpu != -1)
2189 * Per cpu events are installed via an smp call and
2190 * the install is always successful.
2192 cpu_function_call(cpu, __perf_install_in_context, event);
2197 if (!task_function_call(task, __perf_install_in_context, event))
2200 raw_spin_lock_irq(&ctx->lock);
2202 * If we failed to find a running task, but find the context active now
2203 * that we've acquired the ctx->lock, retry.
2205 if (ctx->is_active) {
2206 raw_spin_unlock_irq(&ctx->lock);
2208 * Reload the task pointer, it might have been changed by
2209 * a concurrent perf_event_context_sched_out().
2216 * Since the task isn't running, its safe to add the event, us holding
2217 * the ctx->lock ensures the task won't get scheduled in.
2219 add_event_to_ctx(event, ctx);
2220 raw_spin_unlock_irq(&ctx->lock);
2224 * Put a event into inactive state and update time fields.
2225 * Enabling the leader of a group effectively enables all
2226 * the group members that aren't explicitly disabled, so we
2227 * have to update their ->tstamp_enabled also.
2228 * Note: this works for group members as well as group leaders
2229 * since the non-leader members' sibling_lists will be empty.
2231 static void __perf_event_mark_enabled(struct perf_event *event)
2233 struct perf_event *sub;
2234 u64 tstamp = perf_event_time(event);
2236 event->state = PERF_EVENT_STATE_INACTIVE;
2237 event->tstamp_enabled = tstamp - event->total_time_enabled;
2238 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2239 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2240 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2245 * Cross CPU call to enable a performance event
2247 static int __perf_event_enable(void *info)
2249 struct perf_event *event = info;
2250 struct perf_event_context *ctx = event->ctx;
2251 struct perf_event *leader = event->group_leader;
2252 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2256 * There's a time window between 'ctx->is_active' check
2257 * in perf_event_enable function and this place having:
2259 * - ctx->lock unlocked
2261 * where the task could be killed and 'ctx' deactivated
2262 * by perf_event_exit_task.
2264 if (!ctx->is_active)
2267 raw_spin_lock(&ctx->lock);
2268 update_context_time(ctx);
2270 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2274 * set current task's cgroup time reference point
2276 perf_cgroup_set_timestamp(current, ctx);
2278 __perf_event_mark_enabled(event);
2280 if (!event_filter_match(event)) {
2281 if (is_cgroup_event(event))
2282 perf_cgroup_defer_enabled(event);
2287 * If the event is in a group and isn't the group leader,
2288 * then don't put it on unless the group is on.
2290 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2293 if (!group_can_go_on(event, cpuctx, 1)) {
2296 if (event == leader)
2297 err = group_sched_in(event, cpuctx, ctx);
2299 err = event_sched_in(event, cpuctx, ctx);
2304 * If this event can't go on and it's part of a
2305 * group, then the whole group has to come off.
2307 if (leader != event) {
2308 group_sched_out(leader, cpuctx, ctx);
2309 perf_mux_hrtimer_restart(cpuctx);
2311 if (leader->attr.pinned) {
2312 update_group_times(leader);
2313 leader->state = PERF_EVENT_STATE_ERROR;
2318 raw_spin_unlock(&ctx->lock);
2326 * If event->ctx is a cloned context, callers must make sure that
2327 * every task struct that event->ctx->task could possibly point to
2328 * remains valid. This condition is satisfied when called through
2329 * perf_event_for_each_child or perf_event_for_each as described
2330 * for perf_event_disable.
2332 static void _perf_event_enable(struct perf_event *event)
2334 struct perf_event_context *ctx = event->ctx;
2335 struct task_struct *task = ctx->task;
2339 * Enable the event on the cpu that it's on
2341 cpu_function_call(event->cpu, __perf_event_enable, event);
2345 raw_spin_lock_irq(&ctx->lock);
2346 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2350 * If the event is in error state, clear that first.
2351 * That way, if we see the event in error state below, we
2352 * know that it has gone back into error state, as distinct
2353 * from the task having been scheduled away before the
2354 * cross-call arrived.
2356 if (event->state == PERF_EVENT_STATE_ERROR)
2357 event->state = PERF_EVENT_STATE_OFF;
2360 if (!ctx->is_active) {
2361 __perf_event_mark_enabled(event);
2365 raw_spin_unlock_irq(&ctx->lock);
2367 if (!task_function_call(task, __perf_event_enable, event))
2370 raw_spin_lock_irq(&ctx->lock);
2373 * If the context is active and the event is still off,
2374 * we need to retry the cross-call.
2376 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2378 * task could have been flipped by a concurrent
2379 * perf_event_context_sched_out()
2386 raw_spin_unlock_irq(&ctx->lock);
2390 * See perf_event_disable();
2392 void perf_event_enable(struct perf_event *event)
2394 struct perf_event_context *ctx;
2396 ctx = perf_event_ctx_lock(event);
2397 _perf_event_enable(event);
2398 perf_event_ctx_unlock(event, ctx);
2400 EXPORT_SYMBOL_GPL(perf_event_enable);
2402 static int _perf_event_refresh(struct perf_event *event, int refresh)
2405 * not supported on inherited events
2407 if (event->attr.inherit || !is_sampling_event(event))
2410 atomic_add(refresh, &event->event_limit);
2411 _perf_event_enable(event);
2417 * See perf_event_disable()
2419 int perf_event_refresh(struct perf_event *event, int refresh)
2421 struct perf_event_context *ctx;
2424 ctx = perf_event_ctx_lock(event);
2425 ret = _perf_event_refresh(event, refresh);
2426 perf_event_ctx_unlock(event, ctx);
2430 EXPORT_SYMBOL_GPL(perf_event_refresh);
2432 static void ctx_sched_out(struct perf_event_context *ctx,
2433 struct perf_cpu_context *cpuctx,
2434 enum event_type_t event_type)
2436 struct perf_event *event;
2437 int is_active = ctx->is_active;
2439 ctx->is_active &= ~event_type;
2440 if (likely(!ctx->nr_events))
2443 update_context_time(ctx);
2444 update_cgrp_time_from_cpuctx(cpuctx);
2445 if (!ctx->nr_active)
2448 perf_pmu_disable(ctx->pmu);
2449 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2450 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2451 group_sched_out(event, cpuctx, ctx);
2454 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2455 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2456 group_sched_out(event, cpuctx, ctx);
2458 perf_pmu_enable(ctx->pmu);
2462 * Test whether two contexts are equivalent, i.e. whether they have both been
2463 * cloned from the same version of the same context.
2465 * Equivalence is measured using a generation number in the context that is
2466 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2467 * and list_del_event().
2469 static int context_equiv(struct perf_event_context *ctx1,
2470 struct perf_event_context *ctx2)
2472 lockdep_assert_held(&ctx1->lock);
2473 lockdep_assert_held(&ctx2->lock);
2475 /* Pinning disables the swap optimization */
2476 if (ctx1->pin_count || ctx2->pin_count)
2479 /* If ctx1 is the parent of ctx2 */
2480 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2483 /* If ctx2 is the parent of ctx1 */
2484 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2488 * If ctx1 and ctx2 have the same parent; we flatten the parent
2489 * hierarchy, see perf_event_init_context().
2491 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2492 ctx1->parent_gen == ctx2->parent_gen)
2499 static void __perf_event_sync_stat(struct perf_event *event,
2500 struct perf_event *next_event)
2504 if (!event->attr.inherit_stat)
2508 * Update the event value, we cannot use perf_event_read()
2509 * because we're in the middle of a context switch and have IRQs
2510 * disabled, which upsets smp_call_function_single(), however
2511 * we know the event must be on the current CPU, therefore we
2512 * don't need to use it.
2514 switch (event->state) {
2515 case PERF_EVENT_STATE_ACTIVE:
2516 event->pmu->read(event);
2519 case PERF_EVENT_STATE_INACTIVE:
2520 update_event_times(event);
2528 * In order to keep per-task stats reliable we need to flip the event
2529 * values when we flip the contexts.
2531 value = local64_read(&next_event->count);
2532 value = local64_xchg(&event->count, value);
2533 local64_set(&next_event->count, value);
2535 swap(event->total_time_enabled, next_event->total_time_enabled);
2536 swap(event->total_time_running, next_event->total_time_running);
2539 * Since we swizzled the values, update the user visible data too.
2541 perf_event_update_userpage(event);
2542 perf_event_update_userpage(next_event);
2545 static void perf_event_sync_stat(struct perf_event_context *ctx,
2546 struct perf_event_context *next_ctx)
2548 struct perf_event *event, *next_event;
2553 update_context_time(ctx);
2555 event = list_first_entry(&ctx->event_list,
2556 struct perf_event, event_entry);
2558 next_event = list_first_entry(&next_ctx->event_list,
2559 struct perf_event, event_entry);
2561 while (&event->event_entry != &ctx->event_list &&
2562 &next_event->event_entry != &next_ctx->event_list) {
2564 __perf_event_sync_stat(event, next_event);
2566 event = list_next_entry(event, event_entry);
2567 next_event = list_next_entry(next_event, event_entry);
2571 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2572 struct task_struct *next)
2574 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2575 struct perf_event_context *next_ctx;
2576 struct perf_event_context *parent, *next_parent;
2577 struct perf_cpu_context *cpuctx;
2583 cpuctx = __get_cpu_context(ctx);
2584 if (!cpuctx->task_ctx)
2588 next_ctx = next->perf_event_ctxp[ctxn];
2592 parent = rcu_dereference(ctx->parent_ctx);
2593 next_parent = rcu_dereference(next_ctx->parent_ctx);
2595 /* If neither context have a parent context; they cannot be clones. */
2596 if (!parent && !next_parent)
2599 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2601 * Looks like the two contexts are clones, so we might be
2602 * able to optimize the context switch. We lock both
2603 * contexts and check that they are clones under the
2604 * lock (including re-checking that neither has been
2605 * uncloned in the meantime). It doesn't matter which
2606 * order we take the locks because no other cpu could
2607 * be trying to lock both of these tasks.
2609 raw_spin_lock(&ctx->lock);
2610 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2611 if (context_equiv(ctx, next_ctx)) {
2613 * XXX do we need a memory barrier of sorts
2614 * wrt to rcu_dereference() of perf_event_ctxp
2616 task->perf_event_ctxp[ctxn] = next_ctx;
2617 next->perf_event_ctxp[ctxn] = ctx;
2619 next_ctx->task = task;
2621 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2625 perf_event_sync_stat(ctx, next_ctx);
2627 raw_spin_unlock(&next_ctx->lock);
2628 raw_spin_unlock(&ctx->lock);
2634 raw_spin_lock(&ctx->lock);
2635 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2636 cpuctx->task_ctx = NULL;
2637 raw_spin_unlock(&ctx->lock);
2641 void perf_sched_cb_dec(struct pmu *pmu)
2643 this_cpu_dec(perf_sched_cb_usages);
2646 void perf_sched_cb_inc(struct pmu *pmu)
2648 this_cpu_inc(perf_sched_cb_usages);
2652 * This function provides the context switch callback to the lower code
2653 * layer. It is invoked ONLY when the context switch callback is enabled.
2655 static void perf_pmu_sched_task(struct task_struct *prev,
2656 struct task_struct *next,
2659 struct perf_cpu_context *cpuctx;
2661 unsigned long flags;
2666 local_irq_save(flags);
2670 list_for_each_entry_rcu(pmu, &pmus, entry) {
2671 if (pmu->sched_task) {
2672 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2674 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2676 perf_pmu_disable(pmu);
2678 pmu->sched_task(cpuctx->task_ctx, sched_in);
2680 perf_pmu_enable(pmu);
2682 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2688 local_irq_restore(flags);
2691 static void perf_event_switch(struct task_struct *task,
2692 struct task_struct *next_prev, bool sched_in);
2694 #define for_each_task_context_nr(ctxn) \
2695 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2698 * Called from scheduler to remove the events of the current task,
2699 * with interrupts disabled.
2701 * We stop each event and update the event value in event->count.
2703 * This does not protect us against NMI, but disable()
2704 * sets the disabled bit in the control field of event _before_
2705 * accessing the event control register. If a NMI hits, then it will
2706 * not restart the event.
2708 void __perf_event_task_sched_out(struct task_struct *task,
2709 struct task_struct *next)
2713 if (__this_cpu_read(perf_sched_cb_usages))
2714 perf_pmu_sched_task(task, next, false);
2716 if (atomic_read(&nr_switch_events))
2717 perf_event_switch(task, next, false);
2719 for_each_task_context_nr(ctxn)
2720 perf_event_context_sched_out(task, ctxn, next);
2723 * if cgroup events exist on this CPU, then we need
2724 * to check if we have to switch out PMU state.
2725 * cgroup event are system-wide mode only
2727 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2728 perf_cgroup_sched_out(task, next);
2731 static void task_ctx_sched_out(struct perf_event_context *ctx)
2733 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2735 if (!cpuctx->task_ctx)
2738 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2741 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2742 cpuctx->task_ctx = NULL;
2746 * Called with IRQs disabled
2748 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2749 enum event_type_t event_type)
2751 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2755 ctx_pinned_sched_in(struct perf_event_context *ctx,
2756 struct perf_cpu_context *cpuctx)
2758 struct perf_event *event;
2760 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2761 if (event->state <= PERF_EVENT_STATE_OFF)
2763 if (!event_filter_match(event))
2766 /* may need to reset tstamp_enabled */
2767 if (is_cgroup_event(event))
2768 perf_cgroup_mark_enabled(event, ctx);
2770 if (group_can_go_on(event, cpuctx, 1))
2771 group_sched_in(event, cpuctx, ctx);
2774 * If this pinned group hasn't been scheduled,
2775 * put it in error state.
2777 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2778 update_group_times(event);
2779 event->state = PERF_EVENT_STATE_ERROR;
2785 ctx_flexible_sched_in(struct perf_event_context *ctx,
2786 struct perf_cpu_context *cpuctx)
2788 struct perf_event *event;
2791 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2792 /* Ignore events in OFF or ERROR state */
2793 if (event->state <= PERF_EVENT_STATE_OFF)
2796 * Listen to the 'cpu' scheduling filter constraint
2799 if (!event_filter_match(event))
2802 /* may need to reset tstamp_enabled */
2803 if (is_cgroup_event(event))
2804 perf_cgroup_mark_enabled(event, ctx);
2806 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2807 if (group_sched_in(event, cpuctx, ctx))
2814 ctx_sched_in(struct perf_event_context *ctx,
2815 struct perf_cpu_context *cpuctx,
2816 enum event_type_t event_type,
2817 struct task_struct *task)
2820 int is_active = ctx->is_active;
2822 ctx->is_active |= event_type;
2823 if (likely(!ctx->nr_events))
2827 ctx->timestamp = now;
2828 perf_cgroup_set_timestamp(task, ctx);
2830 * First go through the list and put on any pinned groups
2831 * in order to give them the best chance of going on.
2833 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2834 ctx_pinned_sched_in(ctx, cpuctx);
2836 /* Then walk through the lower prio flexible groups */
2837 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2838 ctx_flexible_sched_in(ctx, cpuctx);
2841 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2842 enum event_type_t event_type,
2843 struct task_struct *task)
2845 struct perf_event_context *ctx = &cpuctx->ctx;
2847 ctx_sched_in(ctx, cpuctx, event_type, task);
2850 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2851 struct task_struct *task)
2853 struct perf_cpu_context *cpuctx;
2855 cpuctx = __get_cpu_context(ctx);
2856 if (cpuctx->task_ctx == ctx)
2859 perf_ctx_lock(cpuctx, ctx);
2860 perf_pmu_disable(ctx->pmu);
2862 * We want to keep the following priority order:
2863 * cpu pinned (that don't need to move), task pinned,
2864 * cpu flexible, task flexible.
2866 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2869 cpuctx->task_ctx = ctx;
2871 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2873 perf_pmu_enable(ctx->pmu);
2874 perf_ctx_unlock(cpuctx, ctx);
2878 * Called from scheduler to add the events of the current task
2879 * with interrupts disabled.
2881 * We restore the event value and then enable it.
2883 * This does not protect us against NMI, but enable()
2884 * sets the enabled bit in the control field of event _before_
2885 * accessing the event control register. If a NMI hits, then it will
2886 * keep the event running.
2888 void __perf_event_task_sched_in(struct task_struct *prev,
2889 struct task_struct *task)
2891 struct perf_event_context *ctx;
2894 for_each_task_context_nr(ctxn) {
2895 ctx = task->perf_event_ctxp[ctxn];
2899 perf_event_context_sched_in(ctx, task);
2902 * if cgroup events exist on this CPU, then we need
2903 * to check if we have to switch in PMU state.
2904 * cgroup event are system-wide mode only
2906 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2907 perf_cgroup_sched_in(prev, task);
2909 if (atomic_read(&nr_switch_events))
2910 perf_event_switch(task, prev, true);
2912 if (__this_cpu_read(perf_sched_cb_usages))
2913 perf_pmu_sched_task(prev, task, true);
2916 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2918 u64 frequency = event->attr.sample_freq;
2919 u64 sec = NSEC_PER_SEC;
2920 u64 divisor, dividend;
2922 int count_fls, nsec_fls, frequency_fls, sec_fls;
2924 count_fls = fls64(count);
2925 nsec_fls = fls64(nsec);
2926 frequency_fls = fls64(frequency);
2930 * We got @count in @nsec, with a target of sample_freq HZ
2931 * the target period becomes:
2934 * period = -------------------
2935 * @nsec * sample_freq
2940 * Reduce accuracy by one bit such that @a and @b converge
2941 * to a similar magnitude.
2943 #define REDUCE_FLS(a, b) \
2945 if (a##_fls > b##_fls) { \
2955 * Reduce accuracy until either term fits in a u64, then proceed with
2956 * the other, so that finally we can do a u64/u64 division.
2958 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2959 REDUCE_FLS(nsec, frequency);
2960 REDUCE_FLS(sec, count);
2963 if (count_fls + sec_fls > 64) {
2964 divisor = nsec * frequency;
2966 while (count_fls + sec_fls > 64) {
2967 REDUCE_FLS(count, sec);
2971 dividend = count * sec;
2973 dividend = count * sec;
2975 while (nsec_fls + frequency_fls > 64) {
2976 REDUCE_FLS(nsec, frequency);
2980 divisor = nsec * frequency;
2986 return div64_u64(dividend, divisor);
2989 static DEFINE_PER_CPU(int, perf_throttled_count);
2990 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2992 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2994 struct hw_perf_event *hwc = &event->hw;
2995 s64 period, sample_period;
2998 period = perf_calculate_period(event, nsec, count);
3000 delta = (s64)(period - hwc->sample_period);
3001 delta = (delta + 7) / 8; /* low pass filter */
3003 sample_period = hwc->sample_period + delta;
3008 hwc->sample_period = sample_period;
3010 if (local64_read(&hwc->period_left) > 8*sample_period) {
3012 event->pmu->stop(event, PERF_EF_UPDATE);
3014 local64_set(&hwc->period_left, 0);
3017 event->pmu->start(event, PERF_EF_RELOAD);
3022 * combine freq adjustment with unthrottling to avoid two passes over the
3023 * events. At the same time, make sure, having freq events does not change
3024 * the rate of unthrottling as that would introduce bias.
3026 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3029 struct perf_event *event;
3030 struct hw_perf_event *hwc;
3031 u64 now, period = TICK_NSEC;
3035 * only need to iterate over all events iff:
3036 * - context have events in frequency mode (needs freq adjust)
3037 * - there are events to unthrottle on this cpu
3039 if (!(ctx->nr_freq || needs_unthr))
3042 raw_spin_lock(&ctx->lock);
3043 perf_pmu_disable(ctx->pmu);
3045 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3046 if (event->state != PERF_EVENT_STATE_ACTIVE)
3049 if (!event_filter_match(event))
3052 perf_pmu_disable(event->pmu);
3056 if (hwc->interrupts == MAX_INTERRUPTS) {
3057 hwc->interrupts = 0;
3058 perf_log_throttle(event, 1);
3059 event->pmu->start(event, 0);
3062 if (!event->attr.freq || !event->attr.sample_freq)
3066 * stop the event and update event->count
3068 event->pmu->stop(event, PERF_EF_UPDATE);
3070 now = local64_read(&event->count);
3071 delta = now - hwc->freq_count_stamp;
3072 hwc->freq_count_stamp = now;
3076 * reload only if value has changed
3077 * we have stopped the event so tell that
3078 * to perf_adjust_period() to avoid stopping it
3082 perf_adjust_period(event, period, delta, false);
3084 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3086 perf_pmu_enable(event->pmu);
3089 perf_pmu_enable(ctx->pmu);
3090 raw_spin_unlock(&ctx->lock);
3094 * Round-robin a context's events:
3096 static void rotate_ctx(struct perf_event_context *ctx)
3099 * Rotate the first entry last of non-pinned groups. Rotation might be
3100 * disabled by the inheritance code.
3102 if (!ctx->rotate_disable)
3103 list_rotate_left(&ctx->flexible_groups);
3106 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3108 struct perf_event_context *ctx = NULL;
3111 if (cpuctx->ctx.nr_events) {
3112 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3116 ctx = cpuctx->task_ctx;
3117 if (ctx && ctx->nr_events) {
3118 if (ctx->nr_events != ctx->nr_active)
3125 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3126 perf_pmu_disable(cpuctx->ctx.pmu);
3128 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3130 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3132 rotate_ctx(&cpuctx->ctx);
3136 perf_event_sched_in(cpuctx, ctx, current);
3138 perf_pmu_enable(cpuctx->ctx.pmu);
3139 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3145 #ifdef CONFIG_NO_HZ_FULL
3146 bool perf_event_can_stop_tick(void)
3148 if (atomic_read(&nr_freq_events) ||
3149 __this_cpu_read(perf_throttled_count))
3156 void perf_event_task_tick(void)
3158 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3159 struct perf_event_context *ctx, *tmp;
3162 WARN_ON(!irqs_disabled());
3164 __this_cpu_inc(perf_throttled_seq);
3165 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3167 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3168 perf_adjust_freq_unthr_context(ctx, throttled);
3171 static int event_enable_on_exec(struct perf_event *event,
3172 struct perf_event_context *ctx)
3174 if (!event->attr.enable_on_exec)
3177 event->attr.enable_on_exec = 0;
3178 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3181 __perf_event_mark_enabled(event);
3187 * Enable all of a task's events that have been marked enable-on-exec.
3188 * This expects task == current.
3190 static void perf_event_enable_on_exec(int ctxn)
3192 struct perf_event_context *ctx, *clone_ctx = NULL;
3193 struct perf_event *event;
3194 unsigned long flags;
3198 local_irq_save(flags);
3199 ctx = current->perf_event_ctxp[ctxn];
3200 if (!ctx || !ctx->nr_events)
3204 * We must ctxsw out cgroup events to avoid conflict
3205 * when invoking perf_task_event_sched_in() later on
3206 * in this function. Otherwise we end up trying to
3207 * ctxswin cgroup events which are already scheduled
3210 perf_cgroup_sched_out(current, NULL);
3212 raw_spin_lock(&ctx->lock);
3213 task_ctx_sched_out(ctx);
3215 list_for_each_entry(event, &ctx->event_list, event_entry) {
3216 ret = event_enable_on_exec(event, ctx);
3222 * Unclone this context if we enabled any event.
3225 clone_ctx = unclone_ctx(ctx);
3227 raw_spin_unlock(&ctx->lock);
3230 * Also calls ctxswin for cgroup events, if any:
3232 perf_event_context_sched_in(ctx, ctx->task);
3234 local_irq_restore(flags);
3240 void perf_event_exec(void)
3245 for_each_task_context_nr(ctxn)
3246 perf_event_enable_on_exec(ctxn);
3250 struct perf_read_data {
3251 struct perf_event *event;
3257 * Cross CPU call to read the hardware event
3259 static void __perf_event_read(void *info)
3261 struct perf_read_data *data = info;
3262 struct perf_event *sub, *event = data->event;
3263 struct perf_event_context *ctx = event->ctx;
3264 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3265 struct pmu *pmu = event->pmu;
3268 * If this is a task context, we need to check whether it is
3269 * the current task context of this cpu. If not it has been
3270 * scheduled out before the smp call arrived. In that case
3271 * event->count would have been updated to a recent sample
3272 * when the event was scheduled out.
3274 if (ctx->task && cpuctx->task_ctx != ctx)
3277 raw_spin_lock(&ctx->lock);
3278 if (ctx->is_active) {
3279 update_context_time(ctx);
3280 update_cgrp_time_from_event(event);
3283 update_event_times(event);
3284 if (event->state != PERF_EVENT_STATE_ACTIVE)
3293 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3297 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3298 update_event_times(sub);
3299 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3301 * Use sibling's PMU rather than @event's since
3302 * sibling could be on different (eg: software) PMU.
3304 sub->pmu->read(sub);
3308 data->ret = pmu->commit_txn(pmu);
3311 raw_spin_unlock(&ctx->lock);
3314 static inline u64 perf_event_count(struct perf_event *event)
3316 if (event->pmu->count)
3317 return event->pmu->count(event);
3319 return __perf_event_count(event);
3323 * NMI-safe method to read a local event, that is an event that
3325 * - either for the current task, or for this CPU
3326 * - does not have inherit set, for inherited task events
3327 * will not be local and we cannot read them atomically
3328 * - must not have a pmu::count method
3330 u64 perf_event_read_local(struct perf_event *event)
3332 unsigned long flags;
3336 * Disabling interrupts avoids all counter scheduling (context
3337 * switches, timer based rotation and IPIs).
3339 local_irq_save(flags);
3341 /* If this is a per-task event, it must be for current */
3342 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3343 event->hw.target != current);
3345 /* If this is a per-CPU event, it must be for this CPU */
3346 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3347 event->cpu != smp_processor_id());
3350 * It must not be an event with inherit set, we cannot read
3351 * all child counters from atomic context.
3353 WARN_ON_ONCE(event->attr.inherit);
3356 * It must not have a pmu::count method, those are not
3359 WARN_ON_ONCE(event->pmu->count);
3362 * If the event is currently on this CPU, its either a per-task event,
3363 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3366 if (event->oncpu == smp_processor_id())
3367 event->pmu->read(event);
3369 val = local64_read(&event->count);
3370 local_irq_restore(flags);
3375 static int perf_event_read(struct perf_event *event, bool group)
3380 * If event is enabled and currently active on a CPU, update the
3381 * value in the event structure:
3383 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3384 struct perf_read_data data = {
3389 smp_call_function_single(event->oncpu,
3390 __perf_event_read, &data, 1);
3392 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3393 struct perf_event_context *ctx = event->ctx;
3394 unsigned long flags;
3396 raw_spin_lock_irqsave(&ctx->lock, flags);
3398 * may read while context is not active
3399 * (e.g., thread is blocked), in that case
3400 * we cannot update context time
3402 if (ctx->is_active) {
3403 update_context_time(ctx);
3404 update_cgrp_time_from_event(event);
3407 update_group_times(event);
3409 update_event_times(event);
3410 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3417 * Initialize the perf_event context in a task_struct:
3419 static void __perf_event_init_context(struct perf_event_context *ctx)
3421 raw_spin_lock_init(&ctx->lock);
3422 mutex_init(&ctx->mutex);
3423 INIT_LIST_HEAD(&ctx->active_ctx_list);
3424 INIT_LIST_HEAD(&ctx->pinned_groups);
3425 INIT_LIST_HEAD(&ctx->flexible_groups);
3426 INIT_LIST_HEAD(&ctx->event_list);
3427 atomic_set(&ctx->refcount, 1);
3428 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3431 static struct perf_event_context *
3432 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3434 struct perf_event_context *ctx;
3436 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3440 __perf_event_init_context(ctx);
3443 get_task_struct(task);
3450 static struct task_struct *
3451 find_lively_task_by_vpid(pid_t vpid)
3453 struct task_struct *task;
3459 task = find_task_by_vpid(vpid);
3461 get_task_struct(task);
3465 return ERR_PTR(-ESRCH);
3471 * Returns a matching context with refcount and pincount.
3473 static struct perf_event_context *
3474 find_get_context(struct pmu *pmu, struct task_struct *task,
3475 struct perf_event *event)
3477 struct perf_event_context *ctx, *clone_ctx = NULL;
3478 struct perf_cpu_context *cpuctx;
3479 void *task_ctx_data = NULL;
3480 unsigned long flags;
3482 int cpu = event->cpu;
3485 /* Must be root to operate on a CPU event: */
3486 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3487 return ERR_PTR(-EACCES);
3490 * We could be clever and allow to attach a event to an
3491 * offline CPU and activate it when the CPU comes up, but
3494 if (!cpu_online(cpu))
3495 return ERR_PTR(-ENODEV);
3497 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3500 raw_spin_lock_irqsave(&ctx->lock, flags);
3502 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3508 ctxn = pmu->task_ctx_nr;
3512 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3513 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3514 if (!task_ctx_data) {
3521 ctx = perf_lock_task_context(task, ctxn, &flags);
3523 clone_ctx = unclone_ctx(ctx);
3526 if (task_ctx_data && !ctx->task_ctx_data) {
3527 ctx->task_ctx_data = task_ctx_data;
3528 task_ctx_data = NULL;
3530 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3535 ctx = alloc_perf_context(pmu, task);
3540 if (task_ctx_data) {
3541 ctx->task_ctx_data = task_ctx_data;
3542 task_ctx_data = NULL;
3546 mutex_lock(&task->perf_event_mutex);
3548 * If it has already passed perf_event_exit_task().
3549 * we must see PF_EXITING, it takes this mutex too.
3551 if (task->flags & PF_EXITING)
3553 else if (task->perf_event_ctxp[ctxn])
3558 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3560 mutex_unlock(&task->perf_event_mutex);
3562 if (unlikely(err)) {
3571 kfree(task_ctx_data);
3575 kfree(task_ctx_data);
3576 return ERR_PTR(err);
3579 static void perf_event_free_filter(struct perf_event *event);
3580 static void perf_event_free_bpf_prog(struct perf_event *event);
3582 static void free_event_rcu(struct rcu_head *head)
3584 struct perf_event *event;
3586 event = container_of(head, struct perf_event, rcu_head);
3588 put_pid_ns(event->ns);
3589 perf_event_free_filter(event);
3593 static void ring_buffer_attach(struct perf_event *event,
3594 struct ring_buffer *rb);
3596 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3601 if (is_cgroup_event(event))
3602 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3605 static void unaccount_event(struct perf_event *event)
3610 if (event->attach_state & PERF_ATTACH_TASK)
3611 static_key_slow_dec_deferred(&perf_sched_events);
3612 if (event->attr.mmap || event->attr.mmap_data)
3613 atomic_dec(&nr_mmap_events);
3614 if (event->attr.comm)
3615 atomic_dec(&nr_comm_events);
3616 if (event->attr.task)
3617 atomic_dec(&nr_task_events);
3618 if (event->attr.freq)
3619 atomic_dec(&nr_freq_events);
3620 if (event->attr.context_switch) {
3621 static_key_slow_dec_deferred(&perf_sched_events);
3622 atomic_dec(&nr_switch_events);
3624 if (is_cgroup_event(event))
3625 static_key_slow_dec_deferred(&perf_sched_events);
3626 if (has_branch_stack(event))
3627 static_key_slow_dec_deferred(&perf_sched_events);
3629 unaccount_event_cpu(event, event->cpu);
3633 * The following implement mutual exclusion of events on "exclusive" pmus
3634 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3635 * at a time, so we disallow creating events that might conflict, namely:
3637 * 1) cpu-wide events in the presence of per-task events,
3638 * 2) per-task events in the presence of cpu-wide events,
3639 * 3) two matching events on the same context.
3641 * The former two cases are handled in the allocation path (perf_event_alloc(),
3642 * __free_event()), the latter -- before the first perf_install_in_context().
3644 static int exclusive_event_init(struct perf_event *event)
3646 struct pmu *pmu = event->pmu;
3648 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3652 * Prevent co-existence of per-task and cpu-wide events on the
3653 * same exclusive pmu.
3655 * Negative pmu::exclusive_cnt means there are cpu-wide
3656 * events on this "exclusive" pmu, positive means there are
3659 * Since this is called in perf_event_alloc() path, event::ctx
3660 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3661 * to mean "per-task event", because unlike other attach states it
3662 * never gets cleared.
3664 if (event->attach_state & PERF_ATTACH_TASK) {
3665 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3668 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3675 static void exclusive_event_destroy(struct perf_event *event)
3677 struct pmu *pmu = event->pmu;
3679 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3682 /* see comment in exclusive_event_init() */
3683 if (event->attach_state & PERF_ATTACH_TASK)
3684 atomic_dec(&pmu->exclusive_cnt);
3686 atomic_inc(&pmu->exclusive_cnt);
3689 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3691 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3692 (e1->cpu == e2->cpu ||
3699 /* Called under the same ctx::mutex as perf_install_in_context() */
3700 static bool exclusive_event_installable(struct perf_event *event,
3701 struct perf_event_context *ctx)
3703 struct perf_event *iter_event;
3704 struct pmu *pmu = event->pmu;
3706 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3709 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3710 if (exclusive_event_match(iter_event, event))
3717 static void __free_event(struct perf_event *event)
3719 if (!event->parent) {
3720 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3721 put_callchain_buffers();
3724 perf_event_free_bpf_prog(event);
3727 event->destroy(event);
3730 put_ctx(event->ctx);
3733 exclusive_event_destroy(event);
3734 module_put(event->pmu->module);
3737 call_rcu(&event->rcu_head, free_event_rcu);
3740 static void _free_event(struct perf_event *event)
3742 irq_work_sync(&event->pending);
3744 unaccount_event(event);
3748 * Can happen when we close an event with re-directed output.
3750 * Since we have a 0 refcount, perf_mmap_close() will skip
3751 * over us; possibly making our ring_buffer_put() the last.
3753 mutex_lock(&event->mmap_mutex);
3754 ring_buffer_attach(event, NULL);
3755 mutex_unlock(&event->mmap_mutex);
3758 if (is_cgroup_event(event))
3759 perf_detach_cgroup(event);
3761 __free_event(event);
3765 * Used to free events which have a known refcount of 1, such as in error paths
3766 * where the event isn't exposed yet and inherited events.
3768 static void free_event(struct perf_event *event)
3770 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3771 "unexpected event refcount: %ld; ptr=%p\n",
3772 atomic_long_read(&event->refcount), event)) {
3773 /* leak to avoid use-after-free */
3781 * Remove user event from the owner task.
3783 static void perf_remove_from_owner(struct perf_event *event)
3785 struct task_struct *owner;
3788 owner = ACCESS_ONCE(event->owner);
3790 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3791 * !owner it means the list deletion is complete and we can indeed
3792 * free this event, otherwise we need to serialize on
3793 * owner->perf_event_mutex.
3795 smp_read_barrier_depends();
3798 * Since delayed_put_task_struct() also drops the last
3799 * task reference we can safely take a new reference
3800 * while holding the rcu_read_lock().
3802 get_task_struct(owner);
3808 * If we're here through perf_event_exit_task() we're already
3809 * holding ctx->mutex which would be an inversion wrt. the
3810 * normal lock order.
3812 * However we can safely take this lock because its the child
3815 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3818 * We have to re-check the event->owner field, if it is cleared
3819 * we raced with perf_event_exit_task(), acquiring the mutex
3820 * ensured they're done, and we can proceed with freeing the
3824 list_del_init(&event->owner_entry);
3825 mutex_unlock(&owner->perf_event_mutex);
3826 put_task_struct(owner);
3830 static void put_event(struct perf_event *event)
3832 struct perf_event_context *ctx;
3834 if (!atomic_long_dec_and_test(&event->refcount))
3837 if (!is_kernel_event(event))
3838 perf_remove_from_owner(event);
3841 * There are two ways this annotation is useful:
3843 * 1) there is a lock recursion from perf_event_exit_task
3844 * see the comment there.
3846 * 2) there is a lock-inversion with mmap_sem through
3847 * perf_read_group(), which takes faults while
3848 * holding ctx->mutex, however this is called after
3849 * the last filedesc died, so there is no possibility
3850 * to trigger the AB-BA case.
3852 ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3853 WARN_ON_ONCE(ctx->parent_ctx);
3854 perf_remove_from_context(event, true);
3855 perf_event_ctx_unlock(event, ctx);
3860 int perf_event_release_kernel(struct perf_event *event)
3865 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3868 * Called when the last reference to the file is gone.
3870 static int perf_release(struct inode *inode, struct file *file)
3872 put_event(file->private_data);
3877 * Remove all orphanes events from the context.
3879 static void orphans_remove_work(struct work_struct *work)
3881 struct perf_event_context *ctx;
3882 struct perf_event *event, *tmp;
3884 ctx = container_of(work, struct perf_event_context,
3885 orphans_remove.work);
3887 mutex_lock(&ctx->mutex);
3888 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3889 struct perf_event *parent_event = event->parent;
3891 if (!is_orphaned_child(event))
3894 perf_remove_from_context(event, true);
3896 mutex_lock(&parent_event->child_mutex);
3897 list_del_init(&event->child_list);
3898 mutex_unlock(&parent_event->child_mutex);
3901 put_event(parent_event);
3904 raw_spin_lock_irq(&ctx->lock);
3905 ctx->orphans_remove_sched = false;
3906 raw_spin_unlock_irq(&ctx->lock);
3907 mutex_unlock(&ctx->mutex);
3912 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3914 struct perf_event *child;
3920 mutex_lock(&event->child_mutex);
3922 (void)perf_event_read(event, false);
3923 total += perf_event_count(event);
3925 *enabled += event->total_time_enabled +
3926 atomic64_read(&event->child_total_time_enabled);
3927 *running += event->total_time_running +
3928 atomic64_read(&event->child_total_time_running);
3930 list_for_each_entry(child, &event->child_list, child_list) {
3931 (void)perf_event_read(child, false);
3932 total += perf_event_count(child);
3933 *enabled += child->total_time_enabled;
3934 *running += child->total_time_running;
3936 mutex_unlock(&event->child_mutex);
3940 EXPORT_SYMBOL_GPL(perf_event_read_value);
3942 static int __perf_read_group_add(struct perf_event *leader,
3943 u64 read_format, u64 *values)
3945 struct perf_event_context *ctx = leader->ctx;
3946 struct perf_event *sub;
3947 unsigned long flags;
3948 int n = 1; /* skip @nr */
3951 ret = perf_event_read(leader, true);
3956 * Since we co-schedule groups, {enabled,running} times of siblings
3957 * will be identical to those of the leader, so we only publish one
3960 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3961 values[n++] += leader->total_time_enabled +
3962 atomic64_read(&leader->child_total_time_enabled);
3965 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3966 values[n++] += leader->total_time_running +
3967 atomic64_read(&leader->child_total_time_running);
3971 * Write {count,id} tuples for every sibling.
3973 values[n++] += perf_event_count(leader);
3974 if (read_format & PERF_FORMAT_ID)
3975 values[n++] = primary_event_id(leader);
3977 raw_spin_lock_irqsave(&ctx->lock, flags);
3979 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3980 values[n++] += perf_event_count(sub);
3981 if (read_format & PERF_FORMAT_ID)
3982 values[n++] = primary_event_id(sub);
3985 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3989 static int perf_read_group(struct perf_event *event,
3990 u64 read_format, char __user *buf)
3992 struct perf_event *leader = event->group_leader, *child;
3993 struct perf_event_context *ctx = leader->ctx;
3997 lockdep_assert_held(&ctx->mutex);
3999 values = kzalloc(event->read_size, GFP_KERNEL);
4003 values[0] = 1 + leader->nr_siblings;
4006 * By locking the child_mutex of the leader we effectively
4007 * lock the child list of all siblings.. XXX explain how.
4009 mutex_lock(&leader->child_mutex);
4011 ret = __perf_read_group_add(leader, read_format, values);
4015 list_for_each_entry(child, &leader->child_list, child_list) {
4016 ret = __perf_read_group_add(child, read_format, values);
4021 mutex_unlock(&leader->child_mutex);
4023 ret = event->read_size;
4024 if (copy_to_user(buf, values, event->read_size))
4029 mutex_unlock(&leader->child_mutex);
4035 static int perf_read_one(struct perf_event *event,
4036 u64 read_format, char __user *buf)
4038 u64 enabled, running;
4042 values[n++] = perf_event_read_value(event, &enabled, &running);
4043 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4044 values[n++] = enabled;
4045 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4046 values[n++] = running;
4047 if (read_format & PERF_FORMAT_ID)
4048 values[n++] = primary_event_id(event);
4050 if (copy_to_user(buf, values, n * sizeof(u64)))
4053 return n * sizeof(u64);
4056 static bool is_event_hup(struct perf_event *event)
4060 if (event->state != PERF_EVENT_STATE_EXIT)
4063 mutex_lock(&event->child_mutex);
4064 no_children = list_empty(&event->child_list);
4065 mutex_unlock(&event->child_mutex);
4070 * Read the performance event - simple non blocking version for now
4073 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4075 u64 read_format = event->attr.read_format;
4079 * Return end-of-file for a read on a event that is in
4080 * error state (i.e. because it was pinned but it couldn't be
4081 * scheduled on to the CPU at some point).
4083 if (event->state == PERF_EVENT_STATE_ERROR)
4086 if (count < event->read_size)
4089 WARN_ON_ONCE(event->ctx->parent_ctx);
4090 if (read_format & PERF_FORMAT_GROUP)
4091 ret = perf_read_group(event, read_format, buf);
4093 ret = perf_read_one(event, read_format, buf);
4099 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4101 struct perf_event *event = file->private_data;
4102 struct perf_event_context *ctx;
4105 ctx = perf_event_ctx_lock(event);
4106 ret = __perf_read(event, buf, count);
4107 perf_event_ctx_unlock(event, ctx);
4112 static unsigned int perf_poll(struct file *file, poll_table *wait)
4114 struct perf_event *event = file->private_data;
4115 struct ring_buffer *rb;
4116 unsigned int events = POLLHUP;
4118 poll_wait(file, &event->waitq, wait);
4120 if (is_event_hup(event))
4124 * Pin the event->rb by taking event->mmap_mutex; otherwise
4125 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4127 mutex_lock(&event->mmap_mutex);
4130 events = atomic_xchg(&rb->poll, 0);
4131 mutex_unlock(&event->mmap_mutex);
4135 static void _perf_event_reset(struct perf_event *event)
4137 (void)perf_event_read(event, false);
4138 local64_set(&event->count, 0);
4139 perf_event_update_userpage(event);
4143 * Holding the top-level event's child_mutex means that any
4144 * descendant process that has inherited this event will block
4145 * in sync_child_event if it goes to exit, thus satisfying the
4146 * task existence requirements of perf_event_enable/disable.
4148 static void perf_event_for_each_child(struct perf_event *event,
4149 void (*func)(struct perf_event *))
4151 struct perf_event *child;
4153 WARN_ON_ONCE(event->ctx->parent_ctx);
4155 mutex_lock(&event->child_mutex);
4157 list_for_each_entry(child, &event->child_list, child_list)
4159 mutex_unlock(&event->child_mutex);
4162 static void perf_event_for_each(struct perf_event *event,
4163 void (*func)(struct perf_event *))
4165 struct perf_event_context *ctx = event->ctx;
4166 struct perf_event *sibling;
4168 lockdep_assert_held(&ctx->mutex);
4170 event = event->group_leader;
4172 perf_event_for_each_child(event, func);
4173 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4174 perf_event_for_each_child(sibling, func);
4177 struct period_event {
4178 struct perf_event *event;
4182 static int __perf_event_period(void *info)
4184 struct period_event *pe = info;
4185 struct perf_event *event = pe->event;
4186 struct perf_event_context *ctx = event->ctx;
4187 u64 value = pe->value;
4190 raw_spin_lock(&ctx->lock);
4191 if (event->attr.freq) {
4192 event->attr.sample_freq = value;
4194 event->attr.sample_period = value;
4195 event->hw.sample_period = value;
4198 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4200 perf_pmu_disable(ctx->pmu);
4201 event->pmu->stop(event, PERF_EF_UPDATE);
4204 local64_set(&event->hw.period_left, 0);
4207 event->pmu->start(event, PERF_EF_RELOAD);
4208 perf_pmu_enable(ctx->pmu);
4210 raw_spin_unlock(&ctx->lock);
4215 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4217 struct period_event pe = { .event = event, };
4218 struct perf_event_context *ctx = event->ctx;
4219 struct task_struct *task;
4222 if (!is_sampling_event(event))
4225 if (copy_from_user(&value, arg, sizeof(value)))
4231 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4238 cpu_function_call(event->cpu, __perf_event_period, &pe);
4243 if (!task_function_call(task, __perf_event_period, &pe))
4246 raw_spin_lock_irq(&ctx->lock);
4247 if (ctx->is_active) {
4248 raw_spin_unlock_irq(&ctx->lock);
4253 if (event->attr.freq) {
4254 event->attr.sample_freq = value;
4256 event->attr.sample_period = value;
4257 event->hw.sample_period = value;
4260 local64_set(&event->hw.period_left, 0);
4261 raw_spin_unlock_irq(&ctx->lock);
4266 static const struct file_operations perf_fops;
4268 static inline int perf_fget_light(int fd, struct fd *p)
4270 struct fd f = fdget(fd);
4274 if (f.file->f_op != &perf_fops) {
4282 static int perf_event_set_output(struct perf_event *event,
4283 struct perf_event *output_event);
4284 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4285 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4287 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4289 void (*func)(struct perf_event *);
4293 case PERF_EVENT_IOC_ENABLE:
4294 func = _perf_event_enable;
4296 case PERF_EVENT_IOC_DISABLE:
4297 func = _perf_event_disable;
4299 case PERF_EVENT_IOC_RESET:
4300 func = _perf_event_reset;
4303 case PERF_EVENT_IOC_REFRESH:
4304 return _perf_event_refresh(event, arg);
4306 case PERF_EVENT_IOC_PERIOD:
4307 return perf_event_period(event, (u64 __user *)arg);
4309 case PERF_EVENT_IOC_ID:
4311 u64 id = primary_event_id(event);
4313 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4318 case PERF_EVENT_IOC_SET_OUTPUT:
4322 struct perf_event *output_event;
4324 ret = perf_fget_light(arg, &output);
4327 output_event = output.file->private_data;
4328 ret = perf_event_set_output(event, output_event);
4331 ret = perf_event_set_output(event, NULL);
4336 case PERF_EVENT_IOC_SET_FILTER:
4337 return perf_event_set_filter(event, (void __user *)arg);
4339 case PERF_EVENT_IOC_SET_BPF:
4340 return perf_event_set_bpf_prog(event, arg);
4346 if (flags & PERF_IOC_FLAG_GROUP)
4347 perf_event_for_each(event, func);
4349 perf_event_for_each_child(event, func);
4354 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4356 struct perf_event *event = file->private_data;
4357 struct perf_event_context *ctx;
4360 ctx = perf_event_ctx_lock(event);
4361 ret = _perf_ioctl(event, cmd, arg);
4362 perf_event_ctx_unlock(event, ctx);
4367 #ifdef CONFIG_COMPAT
4368 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4371 switch (_IOC_NR(cmd)) {
4372 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4373 case _IOC_NR(PERF_EVENT_IOC_ID):
4374 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4375 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4376 cmd &= ~IOCSIZE_MASK;
4377 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4381 return perf_ioctl(file, cmd, arg);
4384 # define perf_compat_ioctl NULL
4387 int perf_event_task_enable(void)
4389 struct perf_event_context *ctx;
4390 struct perf_event *event;
4392 mutex_lock(¤t->perf_event_mutex);
4393 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4394 ctx = perf_event_ctx_lock(event);
4395 perf_event_for_each_child(event, _perf_event_enable);
4396 perf_event_ctx_unlock(event, ctx);
4398 mutex_unlock(¤t->perf_event_mutex);
4403 int perf_event_task_disable(void)
4405 struct perf_event_context *ctx;
4406 struct perf_event *event;
4408 mutex_lock(¤t->perf_event_mutex);
4409 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4410 ctx = perf_event_ctx_lock(event);
4411 perf_event_for_each_child(event, _perf_event_disable);
4412 perf_event_ctx_unlock(event, ctx);
4414 mutex_unlock(¤t->perf_event_mutex);
4419 static int perf_event_index(struct perf_event *event)
4421 if (event->hw.state & PERF_HES_STOPPED)
4424 if (event->state != PERF_EVENT_STATE_ACTIVE)
4427 return event->pmu->event_idx(event);
4430 static void calc_timer_values(struct perf_event *event,
4437 *now = perf_clock();
4438 ctx_time = event->shadow_ctx_time + *now;
4439 *enabled = ctx_time - event->tstamp_enabled;
4440 *running = ctx_time - event->tstamp_running;
4443 static void perf_event_init_userpage(struct perf_event *event)
4445 struct perf_event_mmap_page *userpg;
4446 struct ring_buffer *rb;
4449 rb = rcu_dereference(event->rb);
4453 userpg = rb->user_page;
4455 /* Allow new userspace to detect that bit 0 is deprecated */
4456 userpg->cap_bit0_is_deprecated = 1;
4457 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4458 userpg->data_offset = PAGE_SIZE;
4459 userpg->data_size = perf_data_size(rb);
4465 void __weak arch_perf_update_userpage(
4466 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4471 * Callers need to ensure there can be no nesting of this function, otherwise
4472 * the seqlock logic goes bad. We can not serialize this because the arch
4473 * code calls this from NMI context.
4475 void perf_event_update_userpage(struct perf_event *event)
4477 struct perf_event_mmap_page *userpg;
4478 struct ring_buffer *rb;
4479 u64 enabled, running, now;
4482 rb = rcu_dereference(event->rb);
4487 * compute total_time_enabled, total_time_running
4488 * based on snapshot values taken when the event
4489 * was last scheduled in.
4491 * we cannot simply called update_context_time()
4492 * because of locking issue as we can be called in
4495 calc_timer_values(event, &now, &enabled, &running);
4497 userpg = rb->user_page;
4499 * Disable preemption so as to not let the corresponding user-space
4500 * spin too long if we get preempted.
4505 userpg->index = perf_event_index(event);
4506 userpg->offset = perf_event_count(event);
4508 userpg->offset -= local64_read(&event->hw.prev_count);
4510 userpg->time_enabled = enabled +
4511 atomic64_read(&event->child_total_time_enabled);
4513 userpg->time_running = running +
4514 atomic64_read(&event->child_total_time_running);
4516 arch_perf_update_userpage(event, userpg, now);
4525 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4527 struct perf_event *event = vma->vm_file->private_data;
4528 struct ring_buffer *rb;
4529 int ret = VM_FAULT_SIGBUS;
4531 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4532 if (vmf->pgoff == 0)
4538 rb = rcu_dereference(event->rb);
4542 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4545 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4549 get_page(vmf->page);
4550 vmf->page->mapping = vma->vm_file->f_mapping;
4551 vmf->page->index = vmf->pgoff;
4560 static void ring_buffer_attach(struct perf_event *event,
4561 struct ring_buffer *rb)
4563 struct ring_buffer *old_rb = NULL;
4564 unsigned long flags;
4568 * Should be impossible, we set this when removing
4569 * event->rb_entry and wait/clear when adding event->rb_entry.
4571 WARN_ON_ONCE(event->rcu_pending);
4574 spin_lock_irqsave(&old_rb->event_lock, flags);
4575 list_del_rcu(&event->rb_entry);
4576 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4578 event->rcu_batches = get_state_synchronize_rcu();
4579 event->rcu_pending = 1;
4583 if (event->rcu_pending) {
4584 cond_synchronize_rcu(event->rcu_batches);
4585 event->rcu_pending = 0;
4588 spin_lock_irqsave(&rb->event_lock, flags);
4589 list_add_rcu(&event->rb_entry, &rb->event_list);
4590 spin_unlock_irqrestore(&rb->event_lock, flags);
4593 rcu_assign_pointer(event->rb, rb);
4596 ring_buffer_put(old_rb);
4598 * Since we detached before setting the new rb, so that we
4599 * could attach the new rb, we could have missed a wakeup.
4602 wake_up_all(&event->waitq);
4606 static void ring_buffer_wakeup(struct perf_event *event)
4608 struct ring_buffer *rb;
4611 rb = rcu_dereference(event->rb);
4613 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4614 wake_up_all(&event->waitq);
4619 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4621 struct ring_buffer *rb;
4624 rb = rcu_dereference(event->rb);
4626 if (!atomic_inc_not_zero(&rb->refcount))
4634 void ring_buffer_put(struct ring_buffer *rb)
4636 if (!atomic_dec_and_test(&rb->refcount))
4639 WARN_ON_ONCE(!list_empty(&rb->event_list));
4641 call_rcu(&rb->rcu_head, rb_free_rcu);
4644 static void perf_mmap_open(struct vm_area_struct *vma)
4646 struct perf_event *event = vma->vm_file->private_data;
4648 atomic_inc(&event->mmap_count);
4649 atomic_inc(&event->rb->mmap_count);
4652 atomic_inc(&event->rb->aux_mmap_count);
4654 if (event->pmu->event_mapped)
4655 event->pmu->event_mapped(event);
4659 * A buffer can be mmap()ed multiple times; either directly through the same
4660 * event, or through other events by use of perf_event_set_output().
4662 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4663 * the buffer here, where we still have a VM context. This means we need
4664 * to detach all events redirecting to us.
4666 static void perf_mmap_close(struct vm_area_struct *vma)
4668 struct perf_event *event = vma->vm_file->private_data;
4669 struct ring_buffer *rb = ring_buffer_get(event);
4670 struct user_struct *mmap_user = rb->mmap_user;
4671 int mmap_locked = rb->mmap_locked;
4672 unsigned long size = perf_data_size(rb);
4673 bool detach_rest = false;
4675 if (event->pmu->event_unmapped)
4676 event->pmu->event_unmapped(event);
4679 * rb->aux_mmap_count will always drop before rb->mmap_count and
4680 * event->mmap_count, so it is ok to use event->mmap_mutex to
4681 * serialize with perf_mmap here.
4683 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4684 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4685 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4686 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4689 mutex_unlock(&event->mmap_mutex);
4692 if (atomic_dec_and_test(&rb->mmap_count))
4695 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4698 ring_buffer_attach(event, NULL);
4699 mutex_unlock(&event->mmap_mutex);
4701 /* If there's still other mmap()s of this buffer, we're done. */
4706 * No other mmap()s, detach from all other events that might redirect
4707 * into the now unreachable buffer. Somewhat complicated by the
4708 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4712 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4713 if (!atomic_long_inc_not_zero(&event->refcount)) {
4715 * This event is en-route to free_event() which will
4716 * detach it and remove it from the list.
4722 mutex_lock(&event->mmap_mutex);
4724 * Check we didn't race with perf_event_set_output() which can
4725 * swizzle the rb from under us while we were waiting to
4726 * acquire mmap_mutex.
4728 * If we find a different rb; ignore this event, a next
4729 * iteration will no longer find it on the list. We have to
4730 * still restart the iteration to make sure we're not now
4731 * iterating the wrong list.
4733 if (event->rb == rb)
4734 ring_buffer_attach(event, NULL);
4736 mutex_unlock(&event->mmap_mutex);
4740 * Restart the iteration; either we're on the wrong list or
4741 * destroyed its integrity by doing a deletion.
4748 * It could be there's still a few 0-ref events on the list; they'll
4749 * get cleaned up by free_event() -- they'll also still have their
4750 * ref on the rb and will free it whenever they are done with it.
4752 * Aside from that, this buffer is 'fully' detached and unmapped,
4753 * undo the VM accounting.
4756 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4757 vma->vm_mm->pinned_vm -= mmap_locked;
4758 free_uid(mmap_user);
4761 ring_buffer_put(rb); /* could be last */
4764 static const struct vm_operations_struct perf_mmap_vmops = {
4765 .open = perf_mmap_open,
4766 .close = perf_mmap_close, /* non mergable */
4767 .fault = perf_mmap_fault,
4768 .page_mkwrite = perf_mmap_fault,
4771 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4773 struct perf_event *event = file->private_data;
4774 unsigned long user_locked, user_lock_limit;
4775 struct user_struct *user = current_user();
4776 unsigned long locked, lock_limit;
4777 struct ring_buffer *rb = NULL;
4778 unsigned long vma_size;
4779 unsigned long nr_pages;
4780 long user_extra = 0, extra = 0;
4781 int ret = 0, flags = 0;
4784 * Don't allow mmap() of inherited per-task counters. This would
4785 * create a performance issue due to all children writing to the
4788 if (event->cpu == -1 && event->attr.inherit)
4791 if (!(vma->vm_flags & VM_SHARED))
4794 vma_size = vma->vm_end - vma->vm_start;
4796 if (vma->vm_pgoff == 0) {
4797 nr_pages = (vma_size / PAGE_SIZE) - 1;
4800 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4801 * mapped, all subsequent mappings should have the same size
4802 * and offset. Must be above the normal perf buffer.
4804 u64 aux_offset, aux_size;
4809 nr_pages = vma_size / PAGE_SIZE;
4811 mutex_lock(&event->mmap_mutex);
4818 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4819 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4821 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4824 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4827 /* already mapped with a different offset */
4828 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4831 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4834 /* already mapped with a different size */
4835 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4838 if (!is_power_of_2(nr_pages))
4841 if (!atomic_inc_not_zero(&rb->mmap_count))
4844 if (rb_has_aux(rb)) {
4845 atomic_inc(&rb->aux_mmap_count);
4850 atomic_set(&rb->aux_mmap_count, 1);
4851 user_extra = nr_pages;
4857 * If we have rb pages ensure they're a power-of-two number, so we
4858 * can do bitmasks instead of modulo.
4860 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4863 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4866 WARN_ON_ONCE(event->ctx->parent_ctx);
4868 mutex_lock(&event->mmap_mutex);
4870 if (event->rb->nr_pages != nr_pages) {
4875 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4877 * Raced against perf_mmap_close() through
4878 * perf_event_set_output(). Try again, hope for better
4881 mutex_unlock(&event->mmap_mutex);
4888 user_extra = nr_pages + 1;
4891 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4894 * Increase the limit linearly with more CPUs:
4896 user_lock_limit *= num_online_cpus();
4898 user_locked = atomic_long_read(&user->locked_vm);
4901 * sysctl_perf_event_mlock may have changed, so that
4902 * user->locked_vm > user_lock_limit
4904 if (user_locked > user_lock_limit)
4905 user_locked = user_lock_limit;
4906 user_locked += user_extra;
4908 if (user_locked > user_lock_limit)
4909 extra = user_locked - user_lock_limit;
4911 lock_limit = rlimit(RLIMIT_MEMLOCK);
4912 lock_limit >>= PAGE_SHIFT;
4913 locked = vma->vm_mm->pinned_vm + extra;
4915 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4916 !capable(CAP_IPC_LOCK)) {
4921 WARN_ON(!rb && event->rb);
4923 if (vma->vm_flags & VM_WRITE)
4924 flags |= RING_BUFFER_WRITABLE;
4927 rb = rb_alloc(nr_pages,
4928 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4936 atomic_set(&rb->mmap_count, 1);
4937 rb->mmap_user = get_current_user();
4938 rb->mmap_locked = extra;
4940 ring_buffer_attach(event, rb);
4942 perf_event_init_userpage(event);
4943 perf_event_update_userpage(event);
4945 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4946 event->attr.aux_watermark, flags);
4948 rb->aux_mmap_locked = extra;
4953 atomic_long_add(user_extra, &user->locked_vm);
4954 vma->vm_mm->pinned_vm += extra;
4956 atomic_inc(&event->mmap_count);
4958 atomic_dec(&rb->mmap_count);
4961 mutex_unlock(&event->mmap_mutex);
4964 * Since pinned accounting is per vm we cannot allow fork() to copy our
4967 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4968 vma->vm_ops = &perf_mmap_vmops;
4970 if (event->pmu->event_mapped)
4971 event->pmu->event_mapped(event);
4976 static int perf_fasync(int fd, struct file *filp, int on)
4978 struct inode *inode = file_inode(filp);
4979 struct perf_event *event = filp->private_data;
4982 mutex_lock(&inode->i_mutex);
4983 retval = fasync_helper(fd, filp, on, &event->fasync);
4984 mutex_unlock(&inode->i_mutex);
4992 static const struct file_operations perf_fops = {
4993 .llseek = no_llseek,
4994 .release = perf_release,
4997 .unlocked_ioctl = perf_ioctl,
4998 .compat_ioctl = perf_compat_ioctl,
5000 .fasync = perf_fasync,
5006 * If there's data, ensure we set the poll() state and publish everything
5007 * to user-space before waking everybody up.
5010 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5012 /* only the parent has fasync state */
5014 event = event->parent;
5015 return &event->fasync;
5018 void perf_event_wakeup(struct perf_event *event)
5020 ring_buffer_wakeup(event);
5022 if (event->pending_kill) {
5023 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5024 event->pending_kill = 0;
5028 static void perf_pending_event(struct irq_work *entry)
5030 struct perf_event *event = container_of(entry,
5031 struct perf_event, pending);
5034 rctx = perf_swevent_get_recursion_context();
5036 * If we 'fail' here, that's OK, it means recursion is already disabled
5037 * and we won't recurse 'further'.
5040 if (event->pending_disable) {
5041 event->pending_disable = 0;
5042 __perf_event_disable(event);
5045 if (event->pending_wakeup) {
5046 event->pending_wakeup = 0;
5047 perf_event_wakeup(event);
5051 perf_swevent_put_recursion_context(rctx);
5055 * We assume there is only KVM supporting the callbacks.
5056 * Later on, we might change it to a list if there is
5057 * another virtualization implementation supporting the callbacks.
5059 struct perf_guest_info_callbacks *perf_guest_cbs;
5061 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5063 perf_guest_cbs = cbs;
5066 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5068 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5070 perf_guest_cbs = NULL;
5073 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5076 perf_output_sample_regs(struct perf_output_handle *handle,
5077 struct pt_regs *regs, u64 mask)
5081 for_each_set_bit(bit, (const unsigned long *) &mask,
5082 sizeof(mask) * BITS_PER_BYTE) {
5085 val = perf_reg_value(regs, bit);
5086 perf_output_put(handle, val);
5090 static void perf_sample_regs_user(struct perf_regs *regs_user,
5091 struct pt_regs *regs,
5092 struct pt_regs *regs_user_copy)
5094 if (user_mode(regs)) {
5095 regs_user->abi = perf_reg_abi(current);
5096 regs_user->regs = regs;
5097 } else if (!(current->flags & PF_KTHREAD)) {
5098 perf_get_regs_user(regs_user, regs, regs_user_copy);
5100 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5101 regs_user->regs = NULL;
5105 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5106 struct pt_regs *regs)
5108 regs_intr->regs = regs;
5109 regs_intr->abi = perf_reg_abi(current);
5114 * Get remaining task size from user stack pointer.
5116 * It'd be better to take stack vma map and limit this more
5117 * precisly, but there's no way to get it safely under interrupt,
5118 * so using TASK_SIZE as limit.
5120 static u64 perf_ustack_task_size(struct pt_regs *regs)
5122 unsigned long addr = perf_user_stack_pointer(regs);
5124 if (!addr || addr >= TASK_SIZE)
5127 return TASK_SIZE - addr;
5131 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5132 struct pt_regs *regs)
5136 /* No regs, no stack pointer, no dump. */
5141 * Check if we fit in with the requested stack size into the:
5143 * If we don't, we limit the size to the TASK_SIZE.
5145 * - remaining sample size
5146 * If we don't, we customize the stack size to
5147 * fit in to the remaining sample size.
5150 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5151 stack_size = min(stack_size, (u16) task_size);
5153 /* Current header size plus static size and dynamic size. */
5154 header_size += 2 * sizeof(u64);
5156 /* Do we fit in with the current stack dump size? */
5157 if ((u16) (header_size + stack_size) < header_size) {
5159 * If we overflow the maximum size for the sample,
5160 * we customize the stack dump size to fit in.
5162 stack_size = USHRT_MAX - header_size - sizeof(u64);
5163 stack_size = round_up(stack_size, sizeof(u64));
5170 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5171 struct pt_regs *regs)
5173 /* Case of a kernel thread, nothing to dump */
5176 perf_output_put(handle, size);
5185 * - the size requested by user or the best one we can fit
5186 * in to the sample max size
5188 * - user stack dump data
5190 * - the actual dumped size
5194 perf_output_put(handle, dump_size);
5197 sp = perf_user_stack_pointer(regs);
5198 rem = __output_copy_user(handle, (void *) sp, dump_size);
5199 dyn_size = dump_size - rem;
5201 perf_output_skip(handle, rem);
5204 perf_output_put(handle, dyn_size);
5208 static void __perf_event_header__init_id(struct perf_event_header *header,
5209 struct perf_sample_data *data,
5210 struct perf_event *event)
5212 u64 sample_type = event->attr.sample_type;
5214 data->type = sample_type;
5215 header->size += event->id_header_size;
5217 if (sample_type & PERF_SAMPLE_TID) {
5218 /* namespace issues */
5219 data->tid_entry.pid = perf_event_pid(event, current);
5220 data->tid_entry.tid = perf_event_tid(event, current);
5223 if (sample_type & PERF_SAMPLE_TIME)
5224 data->time = perf_event_clock(event);
5226 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5227 data->id = primary_event_id(event);
5229 if (sample_type & PERF_SAMPLE_STREAM_ID)
5230 data->stream_id = event->id;
5232 if (sample_type & PERF_SAMPLE_CPU) {
5233 data->cpu_entry.cpu = raw_smp_processor_id();
5234 data->cpu_entry.reserved = 0;
5238 void perf_event_header__init_id(struct perf_event_header *header,
5239 struct perf_sample_data *data,
5240 struct perf_event *event)
5242 if (event->attr.sample_id_all)
5243 __perf_event_header__init_id(header, data, event);
5246 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5247 struct perf_sample_data *data)
5249 u64 sample_type = data->type;
5251 if (sample_type & PERF_SAMPLE_TID)
5252 perf_output_put(handle, data->tid_entry);
5254 if (sample_type & PERF_SAMPLE_TIME)
5255 perf_output_put(handle, data->time);
5257 if (sample_type & PERF_SAMPLE_ID)
5258 perf_output_put(handle, data->id);
5260 if (sample_type & PERF_SAMPLE_STREAM_ID)
5261 perf_output_put(handle, data->stream_id);
5263 if (sample_type & PERF_SAMPLE_CPU)
5264 perf_output_put(handle, data->cpu_entry);
5266 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5267 perf_output_put(handle, data->id);
5270 void perf_event__output_id_sample(struct perf_event *event,
5271 struct perf_output_handle *handle,
5272 struct perf_sample_data *sample)
5274 if (event->attr.sample_id_all)
5275 __perf_event__output_id_sample(handle, sample);
5278 static void perf_output_read_one(struct perf_output_handle *handle,
5279 struct perf_event *event,
5280 u64 enabled, u64 running)
5282 u64 read_format = event->attr.read_format;
5286 values[n++] = perf_event_count(event);
5287 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5288 values[n++] = enabled +
5289 atomic64_read(&event->child_total_time_enabled);
5291 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5292 values[n++] = running +
5293 atomic64_read(&event->child_total_time_running);
5295 if (read_format & PERF_FORMAT_ID)
5296 values[n++] = primary_event_id(event);
5298 __output_copy(handle, values, n * sizeof(u64));
5301 static void perf_output_read_group(struct perf_output_handle *handle,
5302 struct perf_event *event,
5303 u64 enabled, u64 running)
5305 struct perf_event *leader = event->group_leader, *sub;
5306 u64 read_format = event->attr.read_format;
5310 values[n++] = 1 + leader->nr_siblings;
5312 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5313 values[n++] = enabled;
5315 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5316 values[n++] = running;
5318 if ((leader != event) &&
5319 (leader->state == PERF_EVENT_STATE_ACTIVE))
5320 leader->pmu->read(leader);
5322 values[n++] = perf_event_count(leader);
5323 if (read_format & PERF_FORMAT_ID)
5324 values[n++] = primary_event_id(leader);
5326 __output_copy(handle, values, n * sizeof(u64));
5328 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5331 if ((sub != event) &&
5332 (sub->state == PERF_EVENT_STATE_ACTIVE))
5333 sub->pmu->read(sub);
5335 values[n++] = perf_event_count(sub);
5336 if (read_format & PERF_FORMAT_ID)
5337 values[n++] = primary_event_id(sub);
5339 __output_copy(handle, values, n * sizeof(u64));
5343 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5344 PERF_FORMAT_TOTAL_TIME_RUNNING)
5347 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5349 * The problem is that its both hard and excessively expensive to iterate the
5350 * child list, not to mention that its impossible to IPI the children running
5351 * on another CPU, from interrupt/NMI context.
5353 static void perf_output_read(struct perf_output_handle *handle,
5354 struct perf_event *event)
5356 u64 enabled = 0, running = 0, now;
5357 u64 read_format = event->attr.read_format;
5360 * compute total_time_enabled, total_time_running
5361 * based on snapshot values taken when the event
5362 * was last scheduled in.
5364 * we cannot simply called update_context_time()
5365 * because of locking issue as we are called in
5368 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5369 calc_timer_values(event, &now, &enabled, &running);
5371 if (event->attr.read_format & PERF_FORMAT_GROUP)
5372 perf_output_read_group(handle, event, enabled, running);
5374 perf_output_read_one(handle, event, enabled, running);
5377 void perf_output_sample(struct perf_output_handle *handle,
5378 struct perf_event_header *header,
5379 struct perf_sample_data *data,
5380 struct perf_event *event)
5382 u64 sample_type = data->type;
5384 perf_output_put(handle, *header);
5386 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5387 perf_output_put(handle, data->id);
5389 if (sample_type & PERF_SAMPLE_IP)
5390 perf_output_put(handle, data->ip);
5392 if (sample_type & PERF_SAMPLE_TID)
5393 perf_output_put(handle, data->tid_entry);
5395 if (sample_type & PERF_SAMPLE_TIME)
5396 perf_output_put(handle, data->time);
5398 if (sample_type & PERF_SAMPLE_ADDR)
5399 perf_output_put(handle, data->addr);
5401 if (sample_type & PERF_SAMPLE_ID)
5402 perf_output_put(handle, data->id);
5404 if (sample_type & PERF_SAMPLE_STREAM_ID)
5405 perf_output_put(handle, data->stream_id);
5407 if (sample_type & PERF_SAMPLE_CPU)
5408 perf_output_put(handle, data->cpu_entry);
5410 if (sample_type & PERF_SAMPLE_PERIOD)
5411 perf_output_put(handle, data->period);
5413 if (sample_type & PERF_SAMPLE_READ)
5414 perf_output_read(handle, event);
5416 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5417 if (data->callchain) {
5420 if (data->callchain)
5421 size += data->callchain->nr;
5423 size *= sizeof(u64);
5425 __output_copy(handle, data->callchain, size);
5428 perf_output_put(handle, nr);
5432 if (sample_type & PERF_SAMPLE_RAW) {
5434 u32 raw_size = data->raw->size;
5435 u32 real_size = round_up(raw_size + sizeof(u32),
5436 sizeof(u64)) - sizeof(u32);
5439 perf_output_put(handle, real_size);
5440 __output_copy(handle, data->raw->data, raw_size);
5441 if (real_size - raw_size)
5442 __output_copy(handle, &zero, real_size - raw_size);
5448 .size = sizeof(u32),
5451 perf_output_put(handle, raw);
5455 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5456 if (data->br_stack) {
5459 size = data->br_stack->nr
5460 * sizeof(struct perf_branch_entry);
5462 perf_output_put(handle, data->br_stack->nr);
5463 perf_output_copy(handle, data->br_stack->entries, size);
5466 * we always store at least the value of nr
5469 perf_output_put(handle, nr);
5473 if (sample_type & PERF_SAMPLE_REGS_USER) {
5474 u64 abi = data->regs_user.abi;
5477 * If there are no regs to dump, notice it through
5478 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5480 perf_output_put(handle, abi);
5483 u64 mask = event->attr.sample_regs_user;
5484 perf_output_sample_regs(handle,
5485 data->regs_user.regs,
5490 if (sample_type & PERF_SAMPLE_STACK_USER) {
5491 perf_output_sample_ustack(handle,
5492 data->stack_user_size,
5493 data->regs_user.regs);
5496 if (sample_type & PERF_SAMPLE_WEIGHT)
5497 perf_output_put(handle, data->weight);
5499 if (sample_type & PERF_SAMPLE_DATA_SRC)
5500 perf_output_put(handle, data->data_src.val);
5502 if (sample_type & PERF_SAMPLE_TRANSACTION)
5503 perf_output_put(handle, data->txn);
5505 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5506 u64 abi = data->regs_intr.abi;
5508 * If there are no regs to dump, notice it through
5509 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5511 perf_output_put(handle, abi);
5514 u64 mask = event->attr.sample_regs_intr;
5516 perf_output_sample_regs(handle,
5517 data->regs_intr.regs,
5522 if (!event->attr.watermark) {
5523 int wakeup_events = event->attr.wakeup_events;
5525 if (wakeup_events) {
5526 struct ring_buffer *rb = handle->rb;
5527 int events = local_inc_return(&rb->events);
5529 if (events >= wakeup_events) {
5530 local_sub(wakeup_events, &rb->events);
5531 local_inc(&rb->wakeup);
5537 void perf_prepare_sample(struct perf_event_header *header,
5538 struct perf_sample_data *data,
5539 struct perf_event *event,
5540 struct pt_regs *regs)
5542 u64 sample_type = event->attr.sample_type;
5544 header->type = PERF_RECORD_SAMPLE;
5545 header->size = sizeof(*header) + event->header_size;
5548 header->misc |= perf_misc_flags(regs);
5550 __perf_event_header__init_id(header, data, event);
5552 if (sample_type & PERF_SAMPLE_IP)
5553 data->ip = perf_instruction_pointer(regs);
5555 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5558 data->callchain = perf_callchain(event, regs);
5560 if (data->callchain)
5561 size += data->callchain->nr;
5563 header->size += size * sizeof(u64);
5566 if (sample_type & PERF_SAMPLE_RAW) {
5567 int size = sizeof(u32);
5570 size += data->raw->size;
5572 size += sizeof(u32);
5574 header->size += round_up(size, sizeof(u64));
5577 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5578 int size = sizeof(u64); /* nr */
5579 if (data->br_stack) {
5580 size += data->br_stack->nr
5581 * sizeof(struct perf_branch_entry);
5583 header->size += size;
5586 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5587 perf_sample_regs_user(&data->regs_user, regs,
5588 &data->regs_user_copy);
5590 if (sample_type & PERF_SAMPLE_REGS_USER) {
5591 /* regs dump ABI info */
5592 int size = sizeof(u64);
5594 if (data->regs_user.regs) {
5595 u64 mask = event->attr.sample_regs_user;
5596 size += hweight64(mask) * sizeof(u64);
5599 header->size += size;
5602 if (sample_type & PERF_SAMPLE_STACK_USER) {
5604 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5605 * processed as the last one or have additional check added
5606 * in case new sample type is added, because we could eat
5607 * up the rest of the sample size.
5609 u16 stack_size = event->attr.sample_stack_user;
5610 u16 size = sizeof(u64);
5612 stack_size = perf_sample_ustack_size(stack_size, header->size,
5613 data->regs_user.regs);
5616 * If there is something to dump, add space for the dump
5617 * itself and for the field that tells the dynamic size,
5618 * which is how many have been actually dumped.
5621 size += sizeof(u64) + stack_size;
5623 data->stack_user_size = stack_size;
5624 header->size += size;
5627 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5628 /* regs dump ABI info */
5629 int size = sizeof(u64);
5631 perf_sample_regs_intr(&data->regs_intr, regs);
5633 if (data->regs_intr.regs) {
5634 u64 mask = event->attr.sample_regs_intr;
5636 size += hweight64(mask) * sizeof(u64);
5639 header->size += size;
5643 void perf_event_output(struct perf_event *event,
5644 struct perf_sample_data *data,
5645 struct pt_regs *regs)
5647 struct perf_output_handle handle;
5648 struct perf_event_header header;
5650 /* protect the callchain buffers */
5653 perf_prepare_sample(&header, data, event, regs);
5655 if (perf_output_begin(&handle, event, header.size))
5658 perf_output_sample(&handle, &header, data, event);
5660 perf_output_end(&handle);
5670 struct perf_read_event {
5671 struct perf_event_header header;
5678 perf_event_read_event(struct perf_event *event,
5679 struct task_struct *task)
5681 struct perf_output_handle handle;
5682 struct perf_sample_data sample;
5683 struct perf_read_event read_event = {
5685 .type = PERF_RECORD_READ,
5687 .size = sizeof(read_event) + event->read_size,
5689 .pid = perf_event_pid(event, task),
5690 .tid = perf_event_tid(event, task),
5694 perf_event_header__init_id(&read_event.header, &sample, event);
5695 ret = perf_output_begin(&handle, event, read_event.header.size);
5699 perf_output_put(&handle, read_event);
5700 perf_output_read(&handle, event);
5701 perf_event__output_id_sample(event, &handle, &sample);
5703 perf_output_end(&handle);
5706 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5709 perf_event_aux_ctx(struct perf_event_context *ctx,
5710 perf_event_aux_output_cb output,
5713 struct perf_event *event;
5715 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5716 if (event->state < PERF_EVENT_STATE_INACTIVE)
5718 if (!event_filter_match(event))
5720 output(event, data);
5725 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5726 struct perf_event_context *task_ctx)
5730 perf_event_aux_ctx(task_ctx, output, data);
5736 perf_event_aux(perf_event_aux_output_cb output, void *data,
5737 struct perf_event_context *task_ctx)
5739 struct perf_cpu_context *cpuctx;
5740 struct perf_event_context *ctx;
5745 * If we have task_ctx != NULL we only notify
5746 * the task context itself. The task_ctx is set
5747 * only for EXIT events before releasing task
5751 perf_event_aux_task_ctx(output, data, task_ctx);
5756 list_for_each_entry_rcu(pmu, &pmus, entry) {
5757 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5758 if (cpuctx->unique_pmu != pmu)
5760 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5761 ctxn = pmu->task_ctx_nr;
5764 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5766 perf_event_aux_ctx(ctx, output, data);
5768 put_cpu_ptr(pmu->pmu_cpu_context);
5774 * task tracking -- fork/exit
5776 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5779 struct perf_task_event {
5780 struct task_struct *task;
5781 struct perf_event_context *task_ctx;
5784 struct perf_event_header header;
5794 static int perf_event_task_match(struct perf_event *event)
5796 return event->attr.comm || event->attr.mmap ||
5797 event->attr.mmap2 || event->attr.mmap_data ||
5801 static void perf_event_task_output(struct perf_event *event,
5804 struct perf_task_event *task_event = data;
5805 struct perf_output_handle handle;
5806 struct perf_sample_data sample;
5807 struct task_struct *task = task_event->task;
5808 int ret, size = task_event->event_id.header.size;
5810 if (!perf_event_task_match(event))
5813 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5815 ret = perf_output_begin(&handle, event,
5816 task_event->event_id.header.size);
5820 task_event->event_id.pid = perf_event_pid(event, task);
5821 task_event->event_id.tid = perf_event_tid(event, task);
5823 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
5824 task_event->event_id.ppid = perf_event_pid(event,
5826 task_event->event_id.ptid = perf_event_pid(event,
5828 } else { /* PERF_RECORD_FORK */
5829 task_event->event_id.ppid = perf_event_pid(event, current);
5830 task_event->event_id.ptid = perf_event_tid(event, current);
5833 task_event->event_id.time = perf_event_clock(event);
5835 perf_output_put(&handle, task_event->event_id);
5837 perf_event__output_id_sample(event, &handle, &sample);
5839 perf_output_end(&handle);
5841 task_event->event_id.header.size = size;
5844 static void perf_event_task(struct task_struct *task,
5845 struct perf_event_context *task_ctx,
5848 struct perf_task_event task_event;
5850 if (!atomic_read(&nr_comm_events) &&
5851 !atomic_read(&nr_mmap_events) &&
5852 !atomic_read(&nr_task_events))
5855 task_event = (struct perf_task_event){
5857 .task_ctx = task_ctx,
5860 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5862 .size = sizeof(task_event.event_id),
5872 perf_event_aux(perf_event_task_output,
5877 void perf_event_fork(struct task_struct *task)
5879 perf_event_task(task, NULL, 1);
5886 struct perf_comm_event {
5887 struct task_struct *task;
5892 struct perf_event_header header;
5899 static int perf_event_comm_match(struct perf_event *event)
5901 return event->attr.comm;
5904 static void perf_event_comm_output(struct perf_event *event,
5907 struct perf_comm_event *comm_event = data;
5908 struct perf_output_handle handle;
5909 struct perf_sample_data sample;
5910 int size = comm_event->event_id.header.size;
5913 if (!perf_event_comm_match(event))
5916 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5917 ret = perf_output_begin(&handle, event,
5918 comm_event->event_id.header.size);
5923 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5924 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5926 perf_output_put(&handle, comm_event->event_id);
5927 __output_copy(&handle, comm_event->comm,
5928 comm_event->comm_size);
5930 perf_event__output_id_sample(event, &handle, &sample);
5932 perf_output_end(&handle);
5934 comm_event->event_id.header.size = size;
5937 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5939 char comm[TASK_COMM_LEN];
5942 memset(comm, 0, sizeof(comm));
5943 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5944 size = ALIGN(strlen(comm)+1, sizeof(u64));
5946 comm_event->comm = comm;
5947 comm_event->comm_size = size;
5949 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5951 perf_event_aux(perf_event_comm_output,
5956 void perf_event_comm(struct task_struct *task, bool exec)
5958 struct perf_comm_event comm_event;
5960 if (!atomic_read(&nr_comm_events))
5963 comm_event = (struct perf_comm_event){
5969 .type = PERF_RECORD_COMM,
5970 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5978 perf_event_comm_event(&comm_event);
5985 struct perf_mmap_event {
5986 struct vm_area_struct *vma;
5988 const char *file_name;
5996 struct perf_event_header header;
6006 static int perf_event_mmap_match(struct perf_event *event,
6009 struct perf_mmap_event *mmap_event = data;
6010 struct vm_area_struct *vma = mmap_event->vma;
6011 int executable = vma->vm_flags & VM_EXEC;
6013 return (!executable && event->attr.mmap_data) ||
6014 (executable && (event->attr.mmap || event->attr.mmap2));
6017 static void perf_event_mmap_output(struct perf_event *event,
6020 struct perf_mmap_event *mmap_event = data;
6021 struct perf_output_handle handle;
6022 struct perf_sample_data sample;
6023 int size = mmap_event->event_id.header.size;
6024 u32 type = mmap_event->event_id.header.type;
6027 if (!perf_event_mmap_match(event, data))
6030 if (event->attr.mmap2) {
6031 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6032 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6033 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6034 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6035 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6036 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6037 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6040 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6041 ret = perf_output_begin(&handle, event,
6042 mmap_event->event_id.header.size);
6046 mmap_event->event_id.pid = perf_event_pid(event, current);
6047 mmap_event->event_id.tid = perf_event_tid(event, current);
6049 perf_output_put(&handle, mmap_event->event_id);
6051 if (event->attr.mmap2) {
6052 perf_output_put(&handle, mmap_event->maj);
6053 perf_output_put(&handle, mmap_event->min);
6054 perf_output_put(&handle, mmap_event->ino);
6055 perf_output_put(&handle, mmap_event->ino_generation);
6056 perf_output_put(&handle, mmap_event->prot);
6057 perf_output_put(&handle, mmap_event->flags);
6060 __output_copy(&handle, mmap_event->file_name,
6061 mmap_event->file_size);
6063 perf_event__output_id_sample(event, &handle, &sample);
6065 perf_output_end(&handle);
6067 mmap_event->event_id.header.size = size;
6068 mmap_event->event_id.header.type = type;
6071 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6073 struct vm_area_struct *vma = mmap_event->vma;
6074 struct file *file = vma->vm_file;
6075 int maj = 0, min = 0;
6076 u64 ino = 0, gen = 0;
6077 u32 prot = 0, flags = 0;
6083 if (vma->vm_flags & VM_READ)
6085 if (vma->vm_flags & VM_WRITE)
6087 if (vma->vm_flags & VM_EXEC)
6090 if (vma->vm_flags & VM_MAYSHARE)
6093 flags = MAP_PRIVATE;
6095 if (vma->vm_flags & VM_DENYWRITE)
6096 flags |= MAP_DENYWRITE;
6097 if (vma->vm_flags & VM_MAYEXEC)
6098 flags |= MAP_EXECUTABLE;
6099 if (vma->vm_flags & VM_LOCKED)
6100 flags |= MAP_LOCKED;
6101 if (vma->vm_flags & VM_HUGETLB)
6102 flags |= MAP_HUGETLB;
6105 struct inode *inode;
6108 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6114 * d_path() works from the end of the rb backwards, so we
6115 * need to add enough zero bytes after the string to handle
6116 * the 64bit alignment we do later.
6118 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6123 inode = file_inode(vma->vm_file);
6124 dev = inode->i_sb->s_dev;
6126 gen = inode->i_generation;
6132 if (vma->vm_ops && vma->vm_ops->name) {
6133 name = (char *) vma->vm_ops->name(vma);
6138 name = (char *)arch_vma_name(vma);
6142 if (vma->vm_start <= vma->vm_mm->start_brk &&
6143 vma->vm_end >= vma->vm_mm->brk) {
6147 if (vma->vm_start <= vma->vm_mm->start_stack &&
6148 vma->vm_end >= vma->vm_mm->start_stack) {
6158 strlcpy(tmp, name, sizeof(tmp));
6162 * Since our buffer works in 8 byte units we need to align our string
6163 * size to a multiple of 8. However, we must guarantee the tail end is
6164 * zero'd out to avoid leaking random bits to userspace.
6166 size = strlen(name)+1;
6167 while (!IS_ALIGNED(size, sizeof(u64)))
6168 name[size++] = '\0';
6170 mmap_event->file_name = name;
6171 mmap_event->file_size = size;
6172 mmap_event->maj = maj;
6173 mmap_event->min = min;
6174 mmap_event->ino = ino;
6175 mmap_event->ino_generation = gen;
6176 mmap_event->prot = prot;
6177 mmap_event->flags = flags;
6179 if (!(vma->vm_flags & VM_EXEC))
6180 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6182 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6184 perf_event_aux(perf_event_mmap_output,
6191 void perf_event_mmap(struct vm_area_struct *vma)
6193 struct perf_mmap_event mmap_event;
6195 if (!atomic_read(&nr_mmap_events))
6198 mmap_event = (struct perf_mmap_event){
6204 .type = PERF_RECORD_MMAP,
6205 .misc = PERF_RECORD_MISC_USER,
6210 .start = vma->vm_start,
6211 .len = vma->vm_end - vma->vm_start,
6212 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6214 /* .maj (attr_mmap2 only) */
6215 /* .min (attr_mmap2 only) */
6216 /* .ino (attr_mmap2 only) */
6217 /* .ino_generation (attr_mmap2 only) */
6218 /* .prot (attr_mmap2 only) */
6219 /* .flags (attr_mmap2 only) */
6222 perf_event_mmap_event(&mmap_event);
6225 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6226 unsigned long size, u64 flags)
6228 struct perf_output_handle handle;
6229 struct perf_sample_data sample;
6230 struct perf_aux_event {
6231 struct perf_event_header header;
6237 .type = PERF_RECORD_AUX,
6239 .size = sizeof(rec),
6247 perf_event_header__init_id(&rec.header, &sample, event);
6248 ret = perf_output_begin(&handle, event, rec.header.size);
6253 perf_output_put(&handle, rec);
6254 perf_event__output_id_sample(event, &handle, &sample);
6256 perf_output_end(&handle);
6260 * Lost/dropped samples logging
6262 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6264 struct perf_output_handle handle;
6265 struct perf_sample_data sample;
6269 struct perf_event_header header;
6271 } lost_samples_event = {
6273 .type = PERF_RECORD_LOST_SAMPLES,
6275 .size = sizeof(lost_samples_event),
6280 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6282 ret = perf_output_begin(&handle, event,
6283 lost_samples_event.header.size);
6287 perf_output_put(&handle, lost_samples_event);
6288 perf_event__output_id_sample(event, &handle, &sample);
6289 perf_output_end(&handle);
6293 * context_switch tracking
6296 struct perf_switch_event {
6297 struct task_struct *task;
6298 struct task_struct *next_prev;
6301 struct perf_event_header header;
6307 static int perf_event_switch_match(struct perf_event *event)
6309 return event->attr.context_switch;
6312 static void perf_event_switch_output(struct perf_event *event, void *data)
6314 struct perf_switch_event *se = data;
6315 struct perf_output_handle handle;
6316 struct perf_sample_data sample;
6319 if (!perf_event_switch_match(event))
6322 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6323 if (event->ctx->task) {
6324 se->event_id.header.type = PERF_RECORD_SWITCH;
6325 se->event_id.header.size = sizeof(se->event_id.header);
6327 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6328 se->event_id.header.size = sizeof(se->event_id);
6329 se->event_id.next_prev_pid =
6330 perf_event_pid(event, se->next_prev);
6331 se->event_id.next_prev_tid =
6332 perf_event_tid(event, se->next_prev);
6335 perf_event_header__init_id(&se->event_id.header, &sample, event);
6337 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6341 if (event->ctx->task)
6342 perf_output_put(&handle, se->event_id.header);
6344 perf_output_put(&handle, se->event_id);
6346 perf_event__output_id_sample(event, &handle, &sample);
6348 perf_output_end(&handle);
6351 static void perf_event_switch(struct task_struct *task,
6352 struct task_struct *next_prev, bool sched_in)
6354 struct perf_switch_event switch_event;
6356 /* N.B. caller checks nr_switch_events != 0 */
6358 switch_event = (struct perf_switch_event){
6360 .next_prev = next_prev,
6364 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6367 /* .next_prev_pid */
6368 /* .next_prev_tid */
6372 perf_event_aux(perf_event_switch_output,
6378 * IRQ throttle logging
6381 static void perf_log_throttle(struct perf_event *event, int enable)
6383 struct perf_output_handle handle;
6384 struct perf_sample_data sample;
6388 struct perf_event_header header;
6392 } throttle_event = {
6394 .type = PERF_RECORD_THROTTLE,
6396 .size = sizeof(throttle_event),
6398 .time = perf_event_clock(event),
6399 .id = primary_event_id(event),
6400 .stream_id = event->id,
6404 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6406 perf_event_header__init_id(&throttle_event.header, &sample, event);
6408 ret = perf_output_begin(&handle, event,
6409 throttle_event.header.size);
6413 perf_output_put(&handle, throttle_event);
6414 perf_event__output_id_sample(event, &handle, &sample);
6415 perf_output_end(&handle);
6418 static void perf_log_itrace_start(struct perf_event *event)
6420 struct perf_output_handle handle;
6421 struct perf_sample_data sample;
6422 struct perf_aux_event {
6423 struct perf_event_header header;
6430 event = event->parent;
6432 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6433 event->hw.itrace_started)
6436 rec.header.type = PERF_RECORD_ITRACE_START;
6437 rec.header.misc = 0;
6438 rec.header.size = sizeof(rec);
6439 rec.pid = perf_event_pid(event, current);
6440 rec.tid = perf_event_tid(event, current);
6442 perf_event_header__init_id(&rec.header, &sample, event);
6443 ret = perf_output_begin(&handle, event, rec.header.size);
6448 perf_output_put(&handle, rec);
6449 perf_event__output_id_sample(event, &handle, &sample);
6451 perf_output_end(&handle);
6455 * Generic event overflow handling, sampling.
6458 static int __perf_event_overflow(struct perf_event *event,
6459 int throttle, struct perf_sample_data *data,
6460 struct pt_regs *regs)
6462 int events = atomic_read(&event->event_limit);
6463 struct hw_perf_event *hwc = &event->hw;
6468 * Non-sampling counters might still use the PMI to fold short
6469 * hardware counters, ignore those.
6471 if (unlikely(!is_sampling_event(event)))
6474 seq = __this_cpu_read(perf_throttled_seq);
6475 if (seq != hwc->interrupts_seq) {
6476 hwc->interrupts_seq = seq;
6477 hwc->interrupts = 1;
6480 if (unlikely(throttle
6481 && hwc->interrupts >= max_samples_per_tick)) {
6482 __this_cpu_inc(perf_throttled_count);
6483 hwc->interrupts = MAX_INTERRUPTS;
6484 perf_log_throttle(event, 0);
6485 tick_nohz_full_kick();
6490 if (event->attr.freq) {
6491 u64 now = perf_clock();
6492 s64 delta = now - hwc->freq_time_stamp;
6494 hwc->freq_time_stamp = now;
6496 if (delta > 0 && delta < 2*TICK_NSEC)
6497 perf_adjust_period(event, delta, hwc->last_period, true);
6501 * XXX event_limit might not quite work as expected on inherited
6505 event->pending_kill = POLL_IN;
6506 if (events && atomic_dec_and_test(&event->event_limit)) {
6508 event->pending_kill = POLL_HUP;
6509 event->pending_disable = 1;
6510 irq_work_queue(&event->pending);
6513 if (event->overflow_handler)
6514 event->overflow_handler(event, data, regs);
6516 perf_event_output(event, data, regs);
6518 if (*perf_event_fasync(event) && event->pending_kill) {
6519 event->pending_wakeup = 1;
6520 irq_work_queue(&event->pending);
6526 int perf_event_overflow(struct perf_event *event,
6527 struct perf_sample_data *data,
6528 struct pt_regs *regs)
6530 return __perf_event_overflow(event, 1, data, regs);
6534 * Generic software event infrastructure
6537 struct swevent_htable {
6538 struct swevent_hlist *swevent_hlist;
6539 struct mutex hlist_mutex;
6542 /* Recursion avoidance in each contexts */
6543 int recursion[PERF_NR_CONTEXTS];
6546 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6549 * We directly increment event->count and keep a second value in
6550 * event->hw.period_left to count intervals. This period event
6551 * is kept in the range [-sample_period, 0] so that we can use the
6555 u64 perf_swevent_set_period(struct perf_event *event)
6557 struct hw_perf_event *hwc = &event->hw;
6558 u64 period = hwc->last_period;
6562 hwc->last_period = hwc->sample_period;
6565 old = val = local64_read(&hwc->period_left);
6569 nr = div64_u64(period + val, period);
6570 offset = nr * period;
6572 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6578 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6579 struct perf_sample_data *data,
6580 struct pt_regs *regs)
6582 struct hw_perf_event *hwc = &event->hw;
6586 overflow = perf_swevent_set_period(event);
6588 if (hwc->interrupts == MAX_INTERRUPTS)
6591 for (; overflow; overflow--) {
6592 if (__perf_event_overflow(event, throttle,
6595 * We inhibit the overflow from happening when
6596 * hwc->interrupts == MAX_INTERRUPTS.
6604 static void perf_swevent_event(struct perf_event *event, u64 nr,
6605 struct perf_sample_data *data,
6606 struct pt_regs *regs)
6608 struct hw_perf_event *hwc = &event->hw;
6610 local64_add(nr, &event->count);
6615 if (!is_sampling_event(event))
6618 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6620 return perf_swevent_overflow(event, 1, data, regs);
6622 data->period = event->hw.last_period;
6624 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6625 return perf_swevent_overflow(event, 1, data, regs);
6627 if (local64_add_negative(nr, &hwc->period_left))
6630 perf_swevent_overflow(event, 0, data, regs);
6633 static int perf_exclude_event(struct perf_event *event,
6634 struct pt_regs *regs)
6636 if (event->hw.state & PERF_HES_STOPPED)
6640 if (event->attr.exclude_user && user_mode(regs))
6643 if (event->attr.exclude_kernel && !user_mode(regs))
6650 static int perf_swevent_match(struct perf_event *event,
6651 enum perf_type_id type,
6653 struct perf_sample_data *data,
6654 struct pt_regs *regs)
6656 if (event->attr.type != type)
6659 if (event->attr.config != event_id)
6662 if (perf_exclude_event(event, regs))
6668 static inline u64 swevent_hash(u64 type, u32 event_id)
6670 u64 val = event_id | (type << 32);
6672 return hash_64(val, SWEVENT_HLIST_BITS);
6675 static inline struct hlist_head *
6676 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6678 u64 hash = swevent_hash(type, event_id);
6680 return &hlist->heads[hash];
6683 /* For the read side: events when they trigger */
6684 static inline struct hlist_head *
6685 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6687 struct swevent_hlist *hlist;
6689 hlist = rcu_dereference(swhash->swevent_hlist);
6693 return __find_swevent_head(hlist, type, event_id);
6696 /* For the event head insertion and removal in the hlist */
6697 static inline struct hlist_head *
6698 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6700 struct swevent_hlist *hlist;
6701 u32 event_id = event->attr.config;
6702 u64 type = event->attr.type;
6705 * Event scheduling is always serialized against hlist allocation
6706 * and release. Which makes the protected version suitable here.
6707 * The context lock guarantees that.
6709 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6710 lockdep_is_held(&event->ctx->lock));
6714 return __find_swevent_head(hlist, type, event_id);
6717 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6719 struct perf_sample_data *data,
6720 struct pt_regs *regs)
6722 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6723 struct perf_event *event;
6724 struct hlist_head *head;
6727 head = find_swevent_head_rcu(swhash, type, event_id);
6731 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6732 if (perf_swevent_match(event, type, event_id, data, regs))
6733 perf_swevent_event(event, nr, data, regs);
6739 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6741 int perf_swevent_get_recursion_context(void)
6743 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6745 return get_recursion_context(swhash->recursion);
6747 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6749 inline void perf_swevent_put_recursion_context(int rctx)
6751 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6753 put_recursion_context(swhash->recursion, rctx);
6756 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6758 struct perf_sample_data data;
6760 if (WARN_ON_ONCE(!regs))
6763 perf_sample_data_init(&data, addr, 0);
6764 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6767 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6771 preempt_disable_notrace();
6772 rctx = perf_swevent_get_recursion_context();
6773 if (unlikely(rctx < 0))
6776 ___perf_sw_event(event_id, nr, regs, addr);
6778 perf_swevent_put_recursion_context(rctx);
6780 preempt_enable_notrace();
6783 static void perf_swevent_read(struct perf_event *event)
6787 static int perf_swevent_add(struct perf_event *event, int flags)
6789 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6790 struct hw_perf_event *hwc = &event->hw;
6791 struct hlist_head *head;
6793 if (is_sampling_event(event)) {
6794 hwc->last_period = hwc->sample_period;
6795 perf_swevent_set_period(event);
6798 hwc->state = !(flags & PERF_EF_START);
6800 head = find_swevent_head(swhash, event);
6801 if (WARN_ON_ONCE(!head))
6804 hlist_add_head_rcu(&event->hlist_entry, head);
6805 perf_event_update_userpage(event);
6810 static void perf_swevent_del(struct perf_event *event, int flags)
6812 hlist_del_rcu(&event->hlist_entry);
6815 static void perf_swevent_start(struct perf_event *event, int flags)
6817 event->hw.state = 0;
6820 static void perf_swevent_stop(struct perf_event *event, int flags)
6822 event->hw.state = PERF_HES_STOPPED;
6825 /* Deref the hlist from the update side */
6826 static inline struct swevent_hlist *
6827 swevent_hlist_deref(struct swevent_htable *swhash)
6829 return rcu_dereference_protected(swhash->swevent_hlist,
6830 lockdep_is_held(&swhash->hlist_mutex));
6833 static void swevent_hlist_release(struct swevent_htable *swhash)
6835 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6840 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6841 kfree_rcu(hlist, rcu_head);
6844 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6846 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6848 mutex_lock(&swhash->hlist_mutex);
6850 if (!--swhash->hlist_refcount)
6851 swevent_hlist_release(swhash);
6853 mutex_unlock(&swhash->hlist_mutex);
6856 static void swevent_hlist_put(struct perf_event *event)
6860 for_each_possible_cpu(cpu)
6861 swevent_hlist_put_cpu(event, cpu);
6864 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6866 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6869 mutex_lock(&swhash->hlist_mutex);
6870 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6871 struct swevent_hlist *hlist;
6873 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6878 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6880 swhash->hlist_refcount++;
6882 mutex_unlock(&swhash->hlist_mutex);
6887 static int swevent_hlist_get(struct perf_event *event)
6890 int cpu, failed_cpu;
6893 for_each_possible_cpu(cpu) {
6894 err = swevent_hlist_get_cpu(event, cpu);
6904 for_each_possible_cpu(cpu) {
6905 if (cpu == failed_cpu)
6907 swevent_hlist_put_cpu(event, cpu);
6914 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6916 static void sw_perf_event_destroy(struct perf_event *event)
6918 u64 event_id = event->attr.config;
6920 WARN_ON(event->parent);
6922 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6923 swevent_hlist_put(event);
6926 static int perf_swevent_init(struct perf_event *event)
6928 u64 event_id = event->attr.config;
6930 if (event->attr.type != PERF_TYPE_SOFTWARE)
6934 * no branch sampling for software events
6936 if (has_branch_stack(event))
6940 case PERF_COUNT_SW_CPU_CLOCK:
6941 case PERF_COUNT_SW_TASK_CLOCK:
6948 if (event_id >= PERF_COUNT_SW_MAX)
6951 if (!event->parent) {
6954 err = swevent_hlist_get(event);
6958 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6959 event->destroy = sw_perf_event_destroy;
6965 static struct pmu perf_swevent = {
6966 .task_ctx_nr = perf_sw_context,
6968 .capabilities = PERF_PMU_CAP_NO_NMI,
6970 .event_init = perf_swevent_init,
6971 .add = perf_swevent_add,
6972 .del = perf_swevent_del,
6973 .start = perf_swevent_start,
6974 .stop = perf_swevent_stop,
6975 .read = perf_swevent_read,
6978 #ifdef CONFIG_EVENT_TRACING
6980 static int perf_tp_filter_match(struct perf_event *event,
6981 struct perf_sample_data *data)
6983 void *record = data->raw->data;
6985 /* only top level events have filters set */
6987 event = event->parent;
6989 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6994 static int perf_tp_event_match(struct perf_event *event,
6995 struct perf_sample_data *data,
6996 struct pt_regs *regs)
6998 if (event->hw.state & PERF_HES_STOPPED)
7001 * All tracepoints are from kernel-space.
7003 if (event->attr.exclude_kernel)
7006 if (!perf_tp_filter_match(event, data))
7012 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
7013 struct pt_regs *regs, struct hlist_head *head, int rctx,
7014 struct task_struct *task)
7016 struct perf_sample_data data;
7017 struct perf_event *event;
7019 struct perf_raw_record raw = {
7024 perf_sample_data_init(&data, addr, 0);
7027 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7028 if (perf_tp_event_match(event, &data, regs))
7029 perf_swevent_event(event, count, &data, regs);
7033 * If we got specified a target task, also iterate its context and
7034 * deliver this event there too.
7036 if (task && task != current) {
7037 struct perf_event_context *ctx;
7038 struct trace_entry *entry = record;
7041 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7045 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7046 if (event->cpu != smp_processor_id())
7048 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7050 if (event->attr.config != entry->type)
7052 if (perf_tp_event_match(event, &data, regs))
7053 perf_swevent_event(event, count, &data, regs);
7059 perf_swevent_put_recursion_context(rctx);
7061 EXPORT_SYMBOL_GPL(perf_tp_event);
7063 static void tp_perf_event_destroy(struct perf_event *event)
7065 perf_trace_destroy(event);
7068 static int perf_tp_event_init(struct perf_event *event)
7072 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7076 * no branch sampling for tracepoint events
7078 if (has_branch_stack(event))
7081 err = perf_trace_init(event);
7085 event->destroy = tp_perf_event_destroy;
7090 static struct pmu perf_tracepoint = {
7091 .task_ctx_nr = perf_sw_context,
7093 .event_init = perf_tp_event_init,
7094 .add = perf_trace_add,
7095 .del = perf_trace_del,
7096 .start = perf_swevent_start,
7097 .stop = perf_swevent_stop,
7098 .read = perf_swevent_read,
7101 static inline void perf_tp_register(void)
7103 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7106 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7111 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7114 filter_str = strndup_user(arg, PAGE_SIZE);
7115 if (IS_ERR(filter_str))
7116 return PTR_ERR(filter_str);
7118 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7124 static void perf_event_free_filter(struct perf_event *event)
7126 ftrace_profile_free_filter(event);
7129 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7131 struct bpf_prog *prog;
7133 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7136 if (event->tp_event->prog)
7139 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7140 /* bpf programs can only be attached to u/kprobes */
7143 prog = bpf_prog_get(prog_fd);
7145 return PTR_ERR(prog);
7147 if (prog->type != BPF_PROG_TYPE_KPROBE) {
7148 /* valid fd, but invalid bpf program type */
7153 event->tp_event->prog = prog;
7154 event->tp_event->bpf_prog_owner = event;
7159 static void perf_event_free_bpf_prog(struct perf_event *event)
7161 struct bpf_prog *prog;
7163 if (!event->tp_event)
7166 prog = event->tp_event->prog;
7167 if (prog && event->tp_event->bpf_prog_owner == event) {
7168 event->tp_event->prog = NULL;
7175 static inline void perf_tp_register(void)
7179 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7184 static void perf_event_free_filter(struct perf_event *event)
7188 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7193 static void perf_event_free_bpf_prog(struct perf_event *event)
7196 #endif /* CONFIG_EVENT_TRACING */
7198 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7199 void perf_bp_event(struct perf_event *bp, void *data)
7201 struct perf_sample_data sample;
7202 struct pt_regs *regs = data;
7204 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7206 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7207 perf_swevent_event(bp, 1, &sample, regs);
7212 * hrtimer based swevent callback
7215 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7217 enum hrtimer_restart ret = HRTIMER_RESTART;
7218 struct perf_sample_data data;
7219 struct pt_regs *regs;
7220 struct perf_event *event;
7223 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7225 if (event->state != PERF_EVENT_STATE_ACTIVE)
7226 return HRTIMER_NORESTART;
7228 event->pmu->read(event);
7230 perf_sample_data_init(&data, 0, event->hw.last_period);
7231 regs = get_irq_regs();
7233 if (regs && !perf_exclude_event(event, regs)) {
7234 if (!(event->attr.exclude_idle && is_idle_task(current)))
7235 if (__perf_event_overflow(event, 1, &data, regs))
7236 ret = HRTIMER_NORESTART;
7239 period = max_t(u64, 10000, event->hw.sample_period);
7240 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7245 static void perf_swevent_start_hrtimer(struct perf_event *event)
7247 struct hw_perf_event *hwc = &event->hw;
7250 if (!is_sampling_event(event))
7253 period = local64_read(&hwc->period_left);
7258 local64_set(&hwc->period_left, 0);
7260 period = max_t(u64, 10000, hwc->sample_period);
7262 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7263 HRTIMER_MODE_REL_PINNED);
7266 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7268 struct hw_perf_event *hwc = &event->hw;
7270 if (is_sampling_event(event)) {
7271 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7272 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7274 hrtimer_cancel(&hwc->hrtimer);
7278 static void perf_swevent_init_hrtimer(struct perf_event *event)
7280 struct hw_perf_event *hwc = &event->hw;
7282 if (!is_sampling_event(event))
7285 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7286 hwc->hrtimer.function = perf_swevent_hrtimer;
7289 * Since hrtimers have a fixed rate, we can do a static freq->period
7290 * mapping and avoid the whole period adjust feedback stuff.
7292 if (event->attr.freq) {
7293 long freq = event->attr.sample_freq;
7295 event->attr.sample_period = NSEC_PER_SEC / freq;
7296 hwc->sample_period = event->attr.sample_period;
7297 local64_set(&hwc->period_left, hwc->sample_period);
7298 hwc->last_period = hwc->sample_period;
7299 event->attr.freq = 0;
7304 * Software event: cpu wall time clock
7307 static void cpu_clock_event_update(struct perf_event *event)
7312 now = local_clock();
7313 prev = local64_xchg(&event->hw.prev_count, now);
7314 local64_add(now - prev, &event->count);
7317 static void cpu_clock_event_start(struct perf_event *event, int flags)
7319 local64_set(&event->hw.prev_count, local_clock());
7320 perf_swevent_start_hrtimer(event);
7323 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7325 perf_swevent_cancel_hrtimer(event);
7326 cpu_clock_event_update(event);
7329 static int cpu_clock_event_add(struct perf_event *event, int flags)
7331 if (flags & PERF_EF_START)
7332 cpu_clock_event_start(event, flags);
7333 perf_event_update_userpage(event);
7338 static void cpu_clock_event_del(struct perf_event *event, int flags)
7340 cpu_clock_event_stop(event, flags);
7343 static void cpu_clock_event_read(struct perf_event *event)
7345 cpu_clock_event_update(event);
7348 static int cpu_clock_event_init(struct perf_event *event)
7350 if (event->attr.type != PERF_TYPE_SOFTWARE)
7353 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7357 * no branch sampling for software events
7359 if (has_branch_stack(event))
7362 perf_swevent_init_hrtimer(event);
7367 static struct pmu perf_cpu_clock = {
7368 .task_ctx_nr = perf_sw_context,
7370 .capabilities = PERF_PMU_CAP_NO_NMI,
7372 .event_init = cpu_clock_event_init,
7373 .add = cpu_clock_event_add,
7374 .del = cpu_clock_event_del,
7375 .start = cpu_clock_event_start,
7376 .stop = cpu_clock_event_stop,
7377 .read = cpu_clock_event_read,
7381 * Software event: task time clock
7384 static void task_clock_event_update(struct perf_event *event, u64 now)
7389 prev = local64_xchg(&event->hw.prev_count, now);
7391 local64_add(delta, &event->count);
7394 static void task_clock_event_start(struct perf_event *event, int flags)
7396 local64_set(&event->hw.prev_count, event->ctx->time);
7397 perf_swevent_start_hrtimer(event);
7400 static void task_clock_event_stop(struct perf_event *event, int flags)
7402 perf_swevent_cancel_hrtimer(event);
7403 task_clock_event_update(event, event->ctx->time);
7406 static int task_clock_event_add(struct perf_event *event, int flags)
7408 if (flags & PERF_EF_START)
7409 task_clock_event_start(event, flags);
7410 perf_event_update_userpage(event);
7415 static void task_clock_event_del(struct perf_event *event, int flags)
7417 task_clock_event_stop(event, PERF_EF_UPDATE);
7420 static void task_clock_event_read(struct perf_event *event)
7422 u64 now = perf_clock();
7423 u64 delta = now - event->ctx->timestamp;
7424 u64 time = event->ctx->time + delta;
7426 task_clock_event_update(event, time);
7429 static int task_clock_event_init(struct perf_event *event)
7431 if (event->attr.type != PERF_TYPE_SOFTWARE)
7434 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7438 * no branch sampling for software events
7440 if (has_branch_stack(event))
7443 perf_swevent_init_hrtimer(event);
7448 static struct pmu perf_task_clock = {
7449 .task_ctx_nr = perf_sw_context,
7451 .capabilities = PERF_PMU_CAP_NO_NMI,
7453 .event_init = task_clock_event_init,
7454 .add = task_clock_event_add,
7455 .del = task_clock_event_del,
7456 .start = task_clock_event_start,
7457 .stop = task_clock_event_stop,
7458 .read = task_clock_event_read,
7461 static void perf_pmu_nop_void(struct pmu *pmu)
7465 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7469 static int perf_pmu_nop_int(struct pmu *pmu)
7474 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7476 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7478 __this_cpu_write(nop_txn_flags, flags);
7480 if (flags & ~PERF_PMU_TXN_ADD)
7483 perf_pmu_disable(pmu);
7486 static int perf_pmu_commit_txn(struct pmu *pmu)
7488 unsigned int flags = __this_cpu_read(nop_txn_flags);
7490 __this_cpu_write(nop_txn_flags, 0);
7492 if (flags & ~PERF_PMU_TXN_ADD)
7495 perf_pmu_enable(pmu);
7499 static void perf_pmu_cancel_txn(struct pmu *pmu)
7501 unsigned int flags = __this_cpu_read(nop_txn_flags);
7503 __this_cpu_write(nop_txn_flags, 0);
7505 if (flags & ~PERF_PMU_TXN_ADD)
7508 perf_pmu_enable(pmu);
7511 static int perf_event_idx_default(struct perf_event *event)
7517 * Ensures all contexts with the same task_ctx_nr have the same
7518 * pmu_cpu_context too.
7520 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7527 list_for_each_entry(pmu, &pmus, entry) {
7528 if (pmu->task_ctx_nr == ctxn)
7529 return pmu->pmu_cpu_context;
7535 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7539 for_each_possible_cpu(cpu) {
7540 struct perf_cpu_context *cpuctx;
7542 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7544 if (cpuctx->unique_pmu == old_pmu)
7545 cpuctx->unique_pmu = pmu;
7549 static void free_pmu_context(struct pmu *pmu)
7553 mutex_lock(&pmus_lock);
7555 * Like a real lame refcount.
7557 list_for_each_entry(i, &pmus, entry) {
7558 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7559 update_pmu_context(i, pmu);
7564 free_percpu(pmu->pmu_cpu_context);
7566 mutex_unlock(&pmus_lock);
7568 static struct idr pmu_idr;
7571 type_show(struct device *dev, struct device_attribute *attr, char *page)
7573 struct pmu *pmu = dev_get_drvdata(dev);
7575 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7577 static DEVICE_ATTR_RO(type);
7580 perf_event_mux_interval_ms_show(struct device *dev,
7581 struct device_attribute *attr,
7584 struct pmu *pmu = dev_get_drvdata(dev);
7586 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7589 static DEFINE_MUTEX(mux_interval_mutex);
7592 perf_event_mux_interval_ms_store(struct device *dev,
7593 struct device_attribute *attr,
7594 const char *buf, size_t count)
7596 struct pmu *pmu = dev_get_drvdata(dev);
7597 int timer, cpu, ret;
7599 ret = kstrtoint(buf, 0, &timer);
7606 /* same value, noting to do */
7607 if (timer == pmu->hrtimer_interval_ms)
7610 mutex_lock(&mux_interval_mutex);
7611 pmu->hrtimer_interval_ms = timer;
7613 /* update all cpuctx for this PMU */
7615 for_each_online_cpu(cpu) {
7616 struct perf_cpu_context *cpuctx;
7617 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7618 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7620 cpu_function_call(cpu,
7621 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7624 mutex_unlock(&mux_interval_mutex);
7628 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7630 static struct attribute *pmu_dev_attrs[] = {
7631 &dev_attr_type.attr,
7632 &dev_attr_perf_event_mux_interval_ms.attr,
7635 ATTRIBUTE_GROUPS(pmu_dev);
7637 static int pmu_bus_running;
7638 static struct bus_type pmu_bus = {
7639 .name = "event_source",
7640 .dev_groups = pmu_dev_groups,
7643 static void pmu_dev_release(struct device *dev)
7648 static int pmu_dev_alloc(struct pmu *pmu)
7652 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7656 pmu->dev->groups = pmu->attr_groups;
7657 device_initialize(pmu->dev);
7658 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7662 dev_set_drvdata(pmu->dev, pmu);
7663 pmu->dev->bus = &pmu_bus;
7664 pmu->dev->release = pmu_dev_release;
7665 ret = device_add(pmu->dev);
7673 put_device(pmu->dev);
7677 static struct lock_class_key cpuctx_mutex;
7678 static struct lock_class_key cpuctx_lock;
7680 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7684 mutex_lock(&pmus_lock);
7686 pmu->pmu_disable_count = alloc_percpu(int);
7687 if (!pmu->pmu_disable_count)
7696 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7704 if (pmu_bus_running) {
7705 ret = pmu_dev_alloc(pmu);
7711 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7712 if (pmu->pmu_cpu_context)
7713 goto got_cpu_context;
7716 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7717 if (!pmu->pmu_cpu_context)
7720 for_each_possible_cpu(cpu) {
7721 struct perf_cpu_context *cpuctx;
7723 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7724 __perf_event_init_context(&cpuctx->ctx);
7725 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7726 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7727 cpuctx->ctx.pmu = pmu;
7729 __perf_mux_hrtimer_init(cpuctx, cpu);
7731 cpuctx->unique_pmu = pmu;
7735 if (!pmu->start_txn) {
7736 if (pmu->pmu_enable) {
7738 * If we have pmu_enable/pmu_disable calls, install
7739 * transaction stubs that use that to try and batch
7740 * hardware accesses.
7742 pmu->start_txn = perf_pmu_start_txn;
7743 pmu->commit_txn = perf_pmu_commit_txn;
7744 pmu->cancel_txn = perf_pmu_cancel_txn;
7746 pmu->start_txn = perf_pmu_nop_txn;
7747 pmu->commit_txn = perf_pmu_nop_int;
7748 pmu->cancel_txn = perf_pmu_nop_void;
7752 if (!pmu->pmu_enable) {
7753 pmu->pmu_enable = perf_pmu_nop_void;
7754 pmu->pmu_disable = perf_pmu_nop_void;
7757 if (!pmu->event_idx)
7758 pmu->event_idx = perf_event_idx_default;
7760 list_add_rcu(&pmu->entry, &pmus);
7761 atomic_set(&pmu->exclusive_cnt, 0);
7764 mutex_unlock(&pmus_lock);
7769 device_del(pmu->dev);
7770 put_device(pmu->dev);
7773 if (pmu->type >= PERF_TYPE_MAX)
7774 idr_remove(&pmu_idr, pmu->type);
7777 free_percpu(pmu->pmu_disable_count);
7780 EXPORT_SYMBOL_GPL(perf_pmu_register);
7782 void perf_pmu_unregister(struct pmu *pmu)
7784 mutex_lock(&pmus_lock);
7785 list_del_rcu(&pmu->entry);
7786 mutex_unlock(&pmus_lock);
7789 * We dereference the pmu list under both SRCU and regular RCU, so
7790 * synchronize against both of those.
7792 synchronize_srcu(&pmus_srcu);
7795 free_percpu(pmu->pmu_disable_count);
7796 if (pmu->type >= PERF_TYPE_MAX)
7797 idr_remove(&pmu_idr, pmu->type);
7798 device_del(pmu->dev);
7799 put_device(pmu->dev);
7800 free_pmu_context(pmu);
7802 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7804 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7806 struct perf_event_context *ctx = NULL;
7809 if (!try_module_get(pmu->module))
7812 if (event->group_leader != event) {
7814 * This ctx->mutex can nest when we're called through
7815 * inheritance. See the perf_event_ctx_lock_nested() comment.
7817 ctx = perf_event_ctx_lock_nested(event->group_leader,
7818 SINGLE_DEPTH_NESTING);
7823 ret = pmu->event_init(event);
7826 perf_event_ctx_unlock(event->group_leader, ctx);
7829 module_put(pmu->module);
7834 static struct pmu *perf_init_event(struct perf_event *event)
7836 struct pmu *pmu = NULL;
7840 idx = srcu_read_lock(&pmus_srcu);
7843 pmu = idr_find(&pmu_idr, event->attr.type);
7846 ret = perf_try_init_event(pmu, event);
7852 list_for_each_entry_rcu(pmu, &pmus, entry) {
7853 ret = perf_try_init_event(pmu, event);
7857 if (ret != -ENOENT) {
7862 pmu = ERR_PTR(-ENOENT);
7864 srcu_read_unlock(&pmus_srcu, idx);
7869 static void account_event_cpu(struct perf_event *event, int cpu)
7874 if (is_cgroup_event(event))
7875 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7878 static void account_event(struct perf_event *event)
7883 if (event->attach_state & PERF_ATTACH_TASK)
7884 static_key_slow_inc(&perf_sched_events.key);
7885 if (event->attr.mmap || event->attr.mmap_data)
7886 atomic_inc(&nr_mmap_events);
7887 if (event->attr.comm)
7888 atomic_inc(&nr_comm_events);
7889 if (event->attr.task)
7890 atomic_inc(&nr_task_events);
7891 if (event->attr.freq) {
7892 if (atomic_inc_return(&nr_freq_events) == 1)
7893 tick_nohz_full_kick_all();
7895 if (event->attr.context_switch) {
7896 atomic_inc(&nr_switch_events);
7897 static_key_slow_inc(&perf_sched_events.key);
7899 if (has_branch_stack(event))
7900 static_key_slow_inc(&perf_sched_events.key);
7901 if (is_cgroup_event(event))
7902 static_key_slow_inc(&perf_sched_events.key);
7904 account_event_cpu(event, event->cpu);
7908 * Allocate and initialize a event structure
7910 static struct perf_event *
7911 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7912 struct task_struct *task,
7913 struct perf_event *group_leader,
7914 struct perf_event *parent_event,
7915 perf_overflow_handler_t overflow_handler,
7916 void *context, int cgroup_fd)
7919 struct perf_event *event;
7920 struct hw_perf_event *hwc;
7923 if ((unsigned)cpu >= nr_cpu_ids) {
7924 if (!task || cpu != -1)
7925 return ERR_PTR(-EINVAL);
7928 event = kzalloc(sizeof(*event), GFP_KERNEL);
7930 return ERR_PTR(-ENOMEM);
7933 * Single events are their own group leaders, with an
7934 * empty sibling list:
7937 group_leader = event;
7939 mutex_init(&event->child_mutex);
7940 INIT_LIST_HEAD(&event->child_list);
7942 INIT_LIST_HEAD(&event->group_entry);
7943 INIT_LIST_HEAD(&event->event_entry);
7944 INIT_LIST_HEAD(&event->sibling_list);
7945 INIT_LIST_HEAD(&event->rb_entry);
7946 INIT_LIST_HEAD(&event->active_entry);
7947 INIT_HLIST_NODE(&event->hlist_entry);
7950 init_waitqueue_head(&event->waitq);
7951 init_irq_work(&event->pending, perf_pending_event);
7953 mutex_init(&event->mmap_mutex);
7955 atomic_long_set(&event->refcount, 1);
7957 event->attr = *attr;
7958 event->group_leader = group_leader;
7962 event->parent = parent_event;
7964 event->ns = get_pid_ns(task_active_pid_ns(current));
7965 event->id = atomic64_inc_return(&perf_event_id);
7967 event->state = PERF_EVENT_STATE_INACTIVE;
7970 event->attach_state = PERF_ATTACH_TASK;
7972 * XXX pmu::event_init needs to know what task to account to
7973 * and we cannot use the ctx information because we need the
7974 * pmu before we get a ctx.
7976 event->hw.target = task;
7979 event->clock = &local_clock;
7981 event->clock = parent_event->clock;
7983 if (!overflow_handler && parent_event) {
7984 overflow_handler = parent_event->overflow_handler;
7985 context = parent_event->overflow_handler_context;
7988 event->overflow_handler = overflow_handler;
7989 event->overflow_handler_context = context;
7991 perf_event__state_init(event);
7996 hwc->sample_period = attr->sample_period;
7997 if (attr->freq && attr->sample_freq)
7998 hwc->sample_period = 1;
7999 hwc->last_period = hwc->sample_period;
8001 local64_set(&hwc->period_left, hwc->sample_period);
8004 * We currently do not support PERF_SAMPLE_READ on inherited events.
8005 * See perf_output_read().
8007 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
8010 if (!has_branch_stack(event))
8011 event->attr.branch_sample_type = 0;
8013 if (cgroup_fd != -1) {
8014 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8019 pmu = perf_init_event(event);
8022 else if (IS_ERR(pmu)) {
8027 err = exclusive_event_init(event);
8031 if (!event->parent) {
8032 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8033 err = get_callchain_buffers();
8039 /* symmetric to unaccount_event() in _free_event() */
8040 account_event(event);
8045 exclusive_event_destroy(event);
8049 event->destroy(event);
8050 module_put(pmu->module);
8052 if (is_cgroup_event(event))
8053 perf_detach_cgroup(event);
8055 put_pid_ns(event->ns);
8058 return ERR_PTR(err);
8061 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8062 struct perf_event_attr *attr)
8067 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8071 * zero the full structure, so that a short copy will be nice.
8073 memset(attr, 0, sizeof(*attr));
8075 ret = get_user(size, &uattr->size);
8079 if (size > PAGE_SIZE) /* silly large */
8082 if (!size) /* abi compat */
8083 size = PERF_ATTR_SIZE_VER0;
8085 if (size < PERF_ATTR_SIZE_VER0)
8089 * If we're handed a bigger struct than we know of,
8090 * ensure all the unknown bits are 0 - i.e. new
8091 * user-space does not rely on any kernel feature
8092 * extensions we dont know about yet.
8094 if (size > sizeof(*attr)) {
8095 unsigned char __user *addr;
8096 unsigned char __user *end;
8099 addr = (void __user *)uattr + sizeof(*attr);
8100 end = (void __user *)uattr + size;
8102 for (; addr < end; addr++) {
8103 ret = get_user(val, addr);
8109 size = sizeof(*attr);
8112 ret = copy_from_user(attr, uattr, size);
8116 if (attr->__reserved_1)
8119 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8122 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8125 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8126 u64 mask = attr->branch_sample_type;
8128 /* only using defined bits */
8129 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8132 /* at least one branch bit must be set */
8133 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8136 /* propagate priv level, when not set for branch */
8137 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8139 /* exclude_kernel checked on syscall entry */
8140 if (!attr->exclude_kernel)
8141 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8143 if (!attr->exclude_user)
8144 mask |= PERF_SAMPLE_BRANCH_USER;
8146 if (!attr->exclude_hv)
8147 mask |= PERF_SAMPLE_BRANCH_HV;
8149 * adjust user setting (for HW filter setup)
8151 attr->branch_sample_type = mask;
8153 /* privileged levels capture (kernel, hv): check permissions */
8154 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8155 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8159 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8160 ret = perf_reg_validate(attr->sample_regs_user);
8165 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8166 if (!arch_perf_have_user_stack_dump())
8170 * We have __u32 type for the size, but so far
8171 * we can only use __u16 as maximum due to the
8172 * __u16 sample size limit.
8174 if (attr->sample_stack_user >= USHRT_MAX)
8176 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8180 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8181 ret = perf_reg_validate(attr->sample_regs_intr);
8186 put_user(sizeof(*attr), &uattr->size);
8192 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8194 struct ring_buffer *rb = NULL;
8200 /* don't allow circular references */
8201 if (event == output_event)
8205 * Don't allow cross-cpu buffers
8207 if (output_event->cpu != event->cpu)
8211 * If its not a per-cpu rb, it must be the same task.
8213 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8217 * Mixing clocks in the same buffer is trouble you don't need.
8219 if (output_event->clock != event->clock)
8223 * If both events generate aux data, they must be on the same PMU
8225 if (has_aux(event) && has_aux(output_event) &&
8226 event->pmu != output_event->pmu)
8230 mutex_lock(&event->mmap_mutex);
8231 /* Can't redirect output if we've got an active mmap() */
8232 if (atomic_read(&event->mmap_count))
8236 /* get the rb we want to redirect to */
8237 rb = ring_buffer_get(output_event);
8242 ring_buffer_attach(event, rb);
8246 mutex_unlock(&event->mmap_mutex);
8252 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8258 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8261 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8263 bool nmi_safe = false;
8266 case CLOCK_MONOTONIC:
8267 event->clock = &ktime_get_mono_fast_ns;
8271 case CLOCK_MONOTONIC_RAW:
8272 event->clock = &ktime_get_raw_fast_ns;
8276 case CLOCK_REALTIME:
8277 event->clock = &ktime_get_real_ns;
8280 case CLOCK_BOOTTIME:
8281 event->clock = &ktime_get_boot_ns;
8285 event->clock = &ktime_get_tai_ns;
8292 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8299 * Variation on perf_event_ctx_lock_nested(), except we take two context
8302 static struct perf_event_context *
8303 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8304 struct perf_event_context *ctx)
8306 struct perf_event_context *gctx;
8310 gctx = READ_ONCE(group_leader->ctx);
8311 if (!atomic_inc_not_zero(&gctx->refcount)) {
8317 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8319 if (group_leader->ctx != gctx) {
8320 mutex_unlock(&ctx->mutex);
8321 mutex_unlock(&gctx->mutex);
8330 * sys_perf_event_open - open a performance event, associate it to a task/cpu
8332 * @attr_uptr: event_id type attributes for monitoring/sampling
8335 * @group_fd: group leader event fd
8337 SYSCALL_DEFINE5(perf_event_open,
8338 struct perf_event_attr __user *, attr_uptr,
8339 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8341 struct perf_event *group_leader = NULL, *output_event = NULL;
8342 struct perf_event *event, *sibling;
8343 struct perf_event_attr attr;
8344 struct perf_event_context *ctx, *uninitialized_var(gctx);
8345 struct file *event_file = NULL;
8346 struct fd group = {NULL, 0};
8347 struct task_struct *task = NULL;
8352 int f_flags = O_RDWR;
8355 /* for future expandability... */
8356 if (flags & ~PERF_FLAG_ALL)
8359 err = perf_copy_attr(attr_uptr, &attr);
8363 if (!attr.exclude_kernel) {
8364 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8369 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8372 if (attr.sample_period & (1ULL << 63))
8377 * In cgroup mode, the pid argument is used to pass the fd
8378 * opened to the cgroup directory in cgroupfs. The cpu argument
8379 * designates the cpu on which to monitor threads from that
8382 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8385 if (flags & PERF_FLAG_FD_CLOEXEC)
8386 f_flags |= O_CLOEXEC;
8388 event_fd = get_unused_fd_flags(f_flags);
8392 if (group_fd != -1) {
8393 err = perf_fget_light(group_fd, &group);
8396 group_leader = group.file->private_data;
8397 if (flags & PERF_FLAG_FD_OUTPUT)
8398 output_event = group_leader;
8399 if (flags & PERF_FLAG_FD_NO_GROUP)
8400 group_leader = NULL;
8403 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8404 task = find_lively_task_by_vpid(pid);
8406 err = PTR_ERR(task);
8411 if (task && group_leader &&
8412 group_leader->attr.inherit != attr.inherit) {
8420 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8425 * Reuse ptrace permission checks for now.
8427 * We must hold cred_guard_mutex across this and any potential
8428 * perf_install_in_context() call for this new event to
8429 * serialize against exec() altering our credentials (and the
8430 * perf_event_exit_task() that could imply).
8433 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8437 if (flags & PERF_FLAG_PID_CGROUP)
8440 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8441 NULL, NULL, cgroup_fd);
8442 if (IS_ERR(event)) {
8443 err = PTR_ERR(event);
8447 if (is_sampling_event(event)) {
8448 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8455 * Special case software events and allow them to be part of
8456 * any hardware group.
8460 if (attr.use_clockid) {
8461 err = perf_event_set_clock(event, attr.clockid);
8467 (is_software_event(event) != is_software_event(group_leader))) {
8468 if (is_software_event(event)) {
8470 * If event and group_leader are not both a software
8471 * event, and event is, then group leader is not.
8473 * Allow the addition of software events to !software
8474 * groups, this is safe because software events never
8477 pmu = group_leader->pmu;
8478 } else if (is_software_event(group_leader) &&
8479 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8481 * In case the group is a pure software group, and we
8482 * try to add a hardware event, move the whole group to
8483 * the hardware context.
8490 * Get the target context (task or percpu):
8492 ctx = find_get_context(pmu, task, event);
8498 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8504 * Look up the group leader (we will attach this event to it):
8510 * Do not allow a recursive hierarchy (this new sibling
8511 * becoming part of another group-sibling):
8513 if (group_leader->group_leader != group_leader)
8516 /* All events in a group should have the same clock */
8517 if (group_leader->clock != event->clock)
8521 * Make sure we're both events for the same CPU;
8522 * grouping events for different CPUs is broken; since
8523 * you can never concurrently schedule them anyhow.
8525 if (group_leader->cpu != event->cpu)
8529 * Make sure we're both on the same task, or both
8532 if (group_leader->ctx->task != ctx->task)
8536 * Do not allow to attach to a group in a different task
8537 * or CPU context. If we're moving SW events, we'll fix
8538 * this up later, so allow that.
8540 if (!move_group && group_leader->ctx != ctx)
8544 * Only a group leader can be exclusive or pinned
8546 if (attr.exclusive || attr.pinned)
8551 err = perf_event_set_output(event, output_event);
8556 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8558 if (IS_ERR(event_file)) {
8559 err = PTR_ERR(event_file);
8565 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8568 * Check if we raced against another sys_perf_event_open() call
8569 * moving the software group underneath us.
8571 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8573 * If someone moved the group out from under us, check
8574 * if this new event wound up on the same ctx, if so
8575 * its the regular !move_group case, otherwise fail.
8581 perf_event_ctx_unlock(group_leader, gctx);
8586 mutex_lock(&ctx->mutex);
8589 if (!perf_event_validate_size(event)) {
8595 * Must be under the same ctx::mutex as perf_install_in_context(),
8596 * because we need to serialize with concurrent event creation.
8598 if (!exclusive_event_installable(event, ctx)) {
8599 /* exclusive and group stuff are assumed mutually exclusive */
8600 WARN_ON_ONCE(move_group);
8606 WARN_ON_ONCE(ctx->parent_ctx);
8609 * This is the point on no return; we cannot fail hereafter. This is
8610 * where we start modifying current state.
8615 * See perf_event_ctx_lock() for comments on the details
8616 * of swizzling perf_event::ctx.
8618 perf_remove_from_context(group_leader, false);
8620 list_for_each_entry(sibling, &group_leader->sibling_list,
8622 perf_remove_from_context(sibling, false);
8627 * Wait for everybody to stop referencing the events through
8628 * the old lists, before installing it on new lists.
8633 * Install the group siblings before the group leader.
8635 * Because a group leader will try and install the entire group
8636 * (through the sibling list, which is still in-tact), we can
8637 * end up with siblings installed in the wrong context.
8639 * By installing siblings first we NO-OP because they're not
8640 * reachable through the group lists.
8642 list_for_each_entry(sibling, &group_leader->sibling_list,
8644 perf_event__state_init(sibling);
8645 perf_install_in_context(ctx, sibling, sibling->cpu);
8650 * Removing from the context ends up with disabled
8651 * event. What we want here is event in the initial
8652 * startup state, ready to be add into new context.
8654 perf_event__state_init(group_leader);
8655 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8659 * Now that all events are installed in @ctx, nothing
8660 * references @gctx anymore, so drop the last reference we have
8667 * Precalculate sample_data sizes; do while holding ctx::mutex such
8668 * that we're serialized against further additions and before
8669 * perf_install_in_context() which is the point the event is active and
8670 * can use these values.
8672 perf_event__header_size(event);
8673 perf_event__id_header_size(event);
8675 perf_install_in_context(ctx, event, event->cpu);
8676 perf_unpin_context(ctx);
8679 perf_event_ctx_unlock(group_leader, gctx);
8680 mutex_unlock(&ctx->mutex);
8683 mutex_unlock(&task->signal->cred_guard_mutex);
8684 put_task_struct(task);
8689 event->owner = current;
8691 mutex_lock(¤t->perf_event_mutex);
8692 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8693 mutex_unlock(¤t->perf_event_mutex);
8696 * Drop the reference on the group_event after placing the
8697 * new event on the sibling_list. This ensures destruction
8698 * of the group leader will find the pointer to itself in
8699 * perf_group_detach().
8702 fd_install(event_fd, event_file);
8707 perf_event_ctx_unlock(group_leader, gctx);
8708 mutex_unlock(&ctx->mutex);
8712 perf_unpin_context(ctx);
8716 * If event_file is set, the fput() above will have called ->release()
8717 * and that will take care of freeing the event.
8723 mutex_unlock(&task->signal->cred_guard_mutex);
8728 put_task_struct(task);
8732 put_unused_fd(event_fd);
8737 * perf_event_create_kernel_counter
8739 * @attr: attributes of the counter to create
8740 * @cpu: cpu in which the counter is bound
8741 * @task: task to profile (NULL for percpu)
8744 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8745 struct task_struct *task,
8746 perf_overflow_handler_t overflow_handler,
8749 struct perf_event_context *ctx;
8750 struct perf_event *event;
8754 * Get the target context (task or percpu):
8757 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8758 overflow_handler, context, -1);
8759 if (IS_ERR(event)) {
8760 err = PTR_ERR(event);
8764 /* Mark owner so we could distinguish it from user events. */
8765 event->owner = EVENT_OWNER_KERNEL;
8767 ctx = find_get_context(event->pmu, task, event);
8773 WARN_ON_ONCE(ctx->parent_ctx);
8774 mutex_lock(&ctx->mutex);
8775 if (!exclusive_event_installable(event, ctx)) {
8776 mutex_unlock(&ctx->mutex);
8777 perf_unpin_context(ctx);
8783 perf_install_in_context(ctx, event, event->cpu);
8784 perf_unpin_context(ctx);
8785 mutex_unlock(&ctx->mutex);
8792 return ERR_PTR(err);
8794 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8796 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8798 struct perf_event_context *src_ctx;
8799 struct perf_event_context *dst_ctx;
8800 struct perf_event *event, *tmp;
8803 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8804 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8807 * See perf_event_ctx_lock() for comments on the details
8808 * of swizzling perf_event::ctx.
8810 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8811 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8813 perf_remove_from_context(event, false);
8814 unaccount_event_cpu(event, src_cpu);
8816 list_add(&event->migrate_entry, &events);
8820 * Wait for the events to quiesce before re-instating them.
8825 * Re-instate events in 2 passes.
8827 * Skip over group leaders and only install siblings on this first
8828 * pass, siblings will not get enabled without a leader, however a
8829 * leader will enable its siblings, even if those are still on the old
8832 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8833 if (event->group_leader == event)
8836 list_del(&event->migrate_entry);
8837 if (event->state >= PERF_EVENT_STATE_OFF)
8838 event->state = PERF_EVENT_STATE_INACTIVE;
8839 account_event_cpu(event, dst_cpu);
8840 perf_install_in_context(dst_ctx, event, dst_cpu);
8845 * Once all the siblings are setup properly, install the group leaders
8848 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8849 list_del(&event->migrate_entry);
8850 if (event->state >= PERF_EVENT_STATE_OFF)
8851 event->state = PERF_EVENT_STATE_INACTIVE;
8852 account_event_cpu(event, dst_cpu);
8853 perf_install_in_context(dst_ctx, event, dst_cpu);
8856 mutex_unlock(&dst_ctx->mutex);
8857 mutex_unlock(&src_ctx->mutex);
8859 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8861 static void sync_child_event(struct perf_event *child_event,
8862 struct task_struct *child)
8864 struct perf_event *parent_event = child_event->parent;
8867 if (child_event->attr.inherit_stat)
8868 perf_event_read_event(child_event, child);
8870 child_val = perf_event_count(child_event);
8873 * Add back the child's count to the parent's count:
8875 atomic64_add(child_val, &parent_event->child_count);
8876 atomic64_add(child_event->total_time_enabled,
8877 &parent_event->child_total_time_enabled);
8878 atomic64_add(child_event->total_time_running,
8879 &parent_event->child_total_time_running);
8882 * Remove this event from the parent's list
8884 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8885 mutex_lock(&parent_event->child_mutex);
8886 list_del_init(&child_event->child_list);
8887 mutex_unlock(&parent_event->child_mutex);
8890 * Make sure user/parent get notified, that we just
8893 perf_event_wakeup(parent_event);
8896 * Release the parent event, if this was the last
8899 put_event(parent_event);
8903 __perf_event_exit_task(struct perf_event *child_event,
8904 struct perf_event_context *child_ctx,
8905 struct task_struct *child)
8908 * Do not destroy the 'original' grouping; because of the context
8909 * switch optimization the original events could've ended up in a
8910 * random child task.
8912 * If we were to destroy the original group, all group related
8913 * operations would cease to function properly after this random
8916 * Do destroy all inherited groups, we don't care about those
8917 * and being thorough is better.
8919 perf_remove_from_context(child_event, !!child_event->parent);
8922 * It can happen that the parent exits first, and has events
8923 * that are still around due to the child reference. These
8924 * events need to be zapped.
8926 if (child_event->parent) {
8927 sync_child_event(child_event, child);
8928 free_event(child_event);
8930 child_event->state = PERF_EVENT_STATE_EXIT;
8931 perf_event_wakeup(child_event);
8935 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8937 struct perf_event *child_event, *next;
8938 struct perf_event_context *child_ctx, *clone_ctx = NULL;
8939 unsigned long flags;
8941 if (likely(!child->perf_event_ctxp[ctxn]))
8944 local_irq_save(flags);
8946 * We can't reschedule here because interrupts are disabled,
8947 * and either child is current or it is a task that can't be
8948 * scheduled, so we are now safe from rescheduling changing
8951 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8954 * Take the context lock here so that if find_get_context is
8955 * reading child->perf_event_ctxp, we wait until it has
8956 * incremented the context's refcount before we do put_ctx below.
8958 raw_spin_lock(&child_ctx->lock);
8959 task_ctx_sched_out(child_ctx);
8960 child->perf_event_ctxp[ctxn] = NULL;
8963 * If this context is a clone; unclone it so it can't get
8964 * swapped to another process while we're removing all
8965 * the events from it.
8967 clone_ctx = unclone_ctx(child_ctx);
8968 update_context_time(child_ctx);
8969 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8975 * Report the task dead after unscheduling the events so that we
8976 * won't get any samples after PERF_RECORD_EXIT. We can however still
8977 * get a few PERF_RECORD_READ events.
8979 perf_event_task(child, child_ctx, 0);
8982 * We can recurse on the same lock type through:
8984 * __perf_event_exit_task()
8985 * sync_child_event()
8987 * mutex_lock(&ctx->mutex)
8989 * But since its the parent context it won't be the same instance.
8991 mutex_lock(&child_ctx->mutex);
8993 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8994 __perf_event_exit_task(child_event, child_ctx, child);
8996 mutex_unlock(&child_ctx->mutex);
9002 * When a child task exits, feed back event values to parent events.
9004 * Can be called with cred_guard_mutex held when called from
9005 * install_exec_creds().
9007 void perf_event_exit_task(struct task_struct *child)
9009 struct perf_event *event, *tmp;
9012 mutex_lock(&child->perf_event_mutex);
9013 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9015 list_del_init(&event->owner_entry);
9018 * Ensure the list deletion is visible before we clear
9019 * the owner, closes a race against perf_release() where
9020 * we need to serialize on the owner->perf_event_mutex.
9023 event->owner = NULL;
9025 mutex_unlock(&child->perf_event_mutex);
9027 for_each_task_context_nr(ctxn)
9028 perf_event_exit_task_context(child, ctxn);
9031 * The perf_event_exit_task_context calls perf_event_task
9032 * with child's task_ctx, which generates EXIT events for
9033 * child contexts and sets child->perf_event_ctxp[] to NULL.
9034 * At this point we need to send EXIT events to cpu contexts.
9036 perf_event_task(child, NULL, 0);
9039 static void perf_free_event(struct perf_event *event,
9040 struct perf_event_context *ctx)
9042 struct perf_event *parent = event->parent;
9044 if (WARN_ON_ONCE(!parent))
9047 mutex_lock(&parent->child_mutex);
9048 list_del_init(&event->child_list);
9049 mutex_unlock(&parent->child_mutex);
9053 raw_spin_lock_irq(&ctx->lock);
9054 perf_group_detach(event);
9055 list_del_event(event, ctx);
9056 raw_spin_unlock_irq(&ctx->lock);
9061 * Free an unexposed, unused context as created by inheritance by
9062 * perf_event_init_task below, used by fork() in case of fail.
9064 * Not all locks are strictly required, but take them anyway to be nice and
9065 * help out with the lockdep assertions.
9067 void perf_event_free_task(struct task_struct *task)
9069 struct perf_event_context *ctx;
9070 struct perf_event *event, *tmp;
9073 for_each_task_context_nr(ctxn) {
9074 ctx = task->perf_event_ctxp[ctxn];
9078 mutex_lock(&ctx->mutex);
9080 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9082 perf_free_event(event, ctx);
9084 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9086 perf_free_event(event, ctx);
9088 if (!list_empty(&ctx->pinned_groups) ||
9089 !list_empty(&ctx->flexible_groups))
9092 mutex_unlock(&ctx->mutex);
9098 void perf_event_delayed_put(struct task_struct *task)
9102 for_each_task_context_nr(ctxn)
9103 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9106 struct perf_event *perf_event_get(unsigned int fd)
9110 struct perf_event *event;
9112 err = perf_fget_light(fd, &f);
9114 return ERR_PTR(err);
9116 event = f.file->private_data;
9117 atomic_long_inc(&event->refcount);
9123 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9126 return ERR_PTR(-EINVAL);
9128 return &event->attr;
9132 * inherit a event from parent task to child task:
9134 static struct perf_event *
9135 inherit_event(struct perf_event *parent_event,
9136 struct task_struct *parent,
9137 struct perf_event_context *parent_ctx,
9138 struct task_struct *child,
9139 struct perf_event *group_leader,
9140 struct perf_event_context *child_ctx)
9142 enum perf_event_active_state parent_state = parent_event->state;
9143 struct perf_event *child_event;
9144 unsigned long flags;
9147 * Instead of creating recursive hierarchies of events,
9148 * we link inherited events back to the original parent,
9149 * which has a filp for sure, which we use as the reference
9152 if (parent_event->parent)
9153 parent_event = parent_event->parent;
9155 child_event = perf_event_alloc(&parent_event->attr,
9158 group_leader, parent_event,
9160 if (IS_ERR(child_event))
9163 if (is_orphaned_event(parent_event) ||
9164 !atomic_long_inc_not_zero(&parent_event->refcount)) {
9165 free_event(child_event);
9172 * Make the child state follow the state of the parent event,
9173 * not its attr.disabled bit. We hold the parent's mutex,
9174 * so we won't race with perf_event_{en, dis}able_family.
9176 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9177 child_event->state = PERF_EVENT_STATE_INACTIVE;
9179 child_event->state = PERF_EVENT_STATE_OFF;
9181 if (parent_event->attr.freq) {
9182 u64 sample_period = parent_event->hw.sample_period;
9183 struct hw_perf_event *hwc = &child_event->hw;
9185 hwc->sample_period = sample_period;
9186 hwc->last_period = sample_period;
9188 local64_set(&hwc->period_left, sample_period);
9191 child_event->ctx = child_ctx;
9192 child_event->overflow_handler = parent_event->overflow_handler;
9193 child_event->overflow_handler_context
9194 = parent_event->overflow_handler_context;
9197 * Precalculate sample_data sizes
9199 perf_event__header_size(child_event);
9200 perf_event__id_header_size(child_event);
9203 * Link it up in the child's context:
9205 raw_spin_lock_irqsave(&child_ctx->lock, flags);
9206 add_event_to_ctx(child_event, child_ctx);
9207 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9210 * Link this into the parent event's child list
9212 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9213 mutex_lock(&parent_event->child_mutex);
9214 list_add_tail(&child_event->child_list, &parent_event->child_list);
9215 mutex_unlock(&parent_event->child_mutex);
9220 static int inherit_group(struct perf_event *parent_event,
9221 struct task_struct *parent,
9222 struct perf_event_context *parent_ctx,
9223 struct task_struct *child,
9224 struct perf_event_context *child_ctx)
9226 struct perf_event *leader;
9227 struct perf_event *sub;
9228 struct perf_event *child_ctr;
9230 leader = inherit_event(parent_event, parent, parent_ctx,
9231 child, NULL, child_ctx);
9233 return PTR_ERR(leader);
9234 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9235 child_ctr = inherit_event(sub, parent, parent_ctx,
9236 child, leader, child_ctx);
9237 if (IS_ERR(child_ctr))
9238 return PTR_ERR(child_ctr);
9244 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9245 struct perf_event_context *parent_ctx,
9246 struct task_struct *child, int ctxn,
9250 struct perf_event_context *child_ctx;
9252 if (!event->attr.inherit) {
9257 child_ctx = child->perf_event_ctxp[ctxn];
9260 * This is executed from the parent task context, so
9261 * inherit events that have been marked for cloning.
9262 * First allocate and initialize a context for the
9266 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9270 child->perf_event_ctxp[ctxn] = child_ctx;
9273 ret = inherit_group(event, parent, parent_ctx,
9283 * Initialize the perf_event context in task_struct
9285 static int perf_event_init_context(struct task_struct *child, int ctxn)
9287 struct perf_event_context *child_ctx, *parent_ctx;
9288 struct perf_event_context *cloned_ctx;
9289 struct perf_event *event;
9290 struct task_struct *parent = current;
9291 int inherited_all = 1;
9292 unsigned long flags;
9295 if (likely(!parent->perf_event_ctxp[ctxn]))
9299 * If the parent's context is a clone, pin it so it won't get
9302 parent_ctx = perf_pin_task_context(parent, ctxn);
9307 * No need to check if parent_ctx != NULL here; since we saw
9308 * it non-NULL earlier, the only reason for it to become NULL
9309 * is if we exit, and since we're currently in the middle of
9310 * a fork we can't be exiting at the same time.
9314 * Lock the parent list. No need to lock the child - not PID
9315 * hashed yet and not running, so nobody can access it.
9317 mutex_lock(&parent_ctx->mutex);
9320 * We dont have to disable NMIs - we are only looking at
9321 * the list, not manipulating it:
9323 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9324 ret = inherit_task_group(event, parent, parent_ctx,
9325 child, ctxn, &inherited_all);
9331 * We can't hold ctx->lock when iterating the ->flexible_group list due
9332 * to allocations, but we need to prevent rotation because
9333 * rotate_ctx() will change the list from interrupt context.
9335 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9336 parent_ctx->rotate_disable = 1;
9337 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9339 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9340 ret = inherit_task_group(event, parent, parent_ctx,
9341 child, ctxn, &inherited_all);
9346 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9347 parent_ctx->rotate_disable = 0;
9349 child_ctx = child->perf_event_ctxp[ctxn];
9351 if (child_ctx && inherited_all) {
9353 * Mark the child context as a clone of the parent
9354 * context, or of whatever the parent is a clone of.
9356 * Note that if the parent is a clone, the holding of
9357 * parent_ctx->lock avoids it from being uncloned.
9359 cloned_ctx = parent_ctx->parent_ctx;
9361 child_ctx->parent_ctx = cloned_ctx;
9362 child_ctx->parent_gen = parent_ctx->parent_gen;
9364 child_ctx->parent_ctx = parent_ctx;
9365 child_ctx->parent_gen = parent_ctx->generation;
9367 get_ctx(child_ctx->parent_ctx);
9370 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9372 mutex_unlock(&parent_ctx->mutex);
9374 perf_unpin_context(parent_ctx);
9375 put_ctx(parent_ctx);
9381 * Initialize the perf_event context in task_struct
9383 int perf_event_init_task(struct task_struct *child)
9387 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9388 mutex_init(&child->perf_event_mutex);
9389 INIT_LIST_HEAD(&child->perf_event_list);
9391 for_each_task_context_nr(ctxn) {
9392 ret = perf_event_init_context(child, ctxn);
9394 perf_event_free_task(child);
9402 static void __init perf_event_init_all_cpus(void)
9404 struct swevent_htable *swhash;
9407 for_each_possible_cpu(cpu) {
9408 swhash = &per_cpu(swevent_htable, cpu);
9409 mutex_init(&swhash->hlist_mutex);
9410 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9414 static void perf_event_init_cpu(int cpu)
9416 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9418 mutex_lock(&swhash->hlist_mutex);
9419 if (swhash->hlist_refcount > 0) {
9420 struct swevent_hlist *hlist;
9422 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9424 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9426 mutex_unlock(&swhash->hlist_mutex);
9429 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9430 static void __perf_event_exit_context(void *__info)
9432 struct remove_event re = { .detach_group = true };
9433 struct perf_event_context *ctx = __info;
9436 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9437 __perf_remove_from_context(&re);
9441 static void perf_event_exit_cpu_context(int cpu)
9443 struct perf_event_context *ctx;
9447 idx = srcu_read_lock(&pmus_srcu);
9448 list_for_each_entry_rcu(pmu, &pmus, entry) {
9449 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9451 mutex_lock(&ctx->mutex);
9452 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9453 mutex_unlock(&ctx->mutex);
9455 srcu_read_unlock(&pmus_srcu, idx);
9458 static void perf_event_exit_cpu(int cpu)
9460 perf_event_exit_cpu_context(cpu);
9463 static inline void perf_event_exit_cpu(int cpu) { }
9467 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9471 for_each_online_cpu(cpu)
9472 perf_event_exit_cpu(cpu);
9478 * Run the perf reboot notifier at the very last possible moment so that
9479 * the generic watchdog code runs as long as possible.
9481 static struct notifier_block perf_reboot_notifier = {
9482 .notifier_call = perf_reboot,
9483 .priority = INT_MIN,
9487 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9489 unsigned int cpu = (long)hcpu;
9491 switch (action & ~CPU_TASKS_FROZEN) {
9493 case CPU_UP_PREPARE:
9494 case CPU_DOWN_FAILED:
9495 perf_event_init_cpu(cpu);
9498 case CPU_UP_CANCELED:
9499 case CPU_DOWN_PREPARE:
9500 perf_event_exit_cpu(cpu);
9509 void __init perf_event_init(void)
9515 perf_event_init_all_cpus();
9516 init_srcu_struct(&pmus_srcu);
9517 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9518 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9519 perf_pmu_register(&perf_task_clock, NULL, -1);
9521 perf_cpu_notifier(perf_cpu_notify);
9522 register_reboot_notifier(&perf_reboot_notifier);
9524 ret = init_hw_breakpoint();
9525 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9527 /* do not patch jump label more than once per second */
9528 jump_label_rate_limit(&perf_sched_events, HZ);
9531 * Build time assertion that we keep the data_head at the intended
9532 * location. IOW, validation we got the __reserved[] size right.
9534 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9538 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9541 struct perf_pmu_events_attr *pmu_attr =
9542 container_of(attr, struct perf_pmu_events_attr, attr);
9544 if (pmu_attr->event_str)
9545 return sprintf(page, "%s\n", pmu_attr->event_str);
9550 static int __init perf_event_sysfs_init(void)
9555 mutex_lock(&pmus_lock);
9557 ret = bus_register(&pmu_bus);
9561 list_for_each_entry(pmu, &pmus, entry) {
9562 if (!pmu->name || pmu->type < 0)
9565 ret = pmu_dev_alloc(pmu);
9566 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9568 pmu_bus_running = 1;
9572 mutex_unlock(&pmus_lock);
9576 device_initcall(perf_event_sysfs_init);
9578 #ifdef CONFIG_CGROUP_PERF
9579 static struct cgroup_subsys_state *
9580 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9582 struct perf_cgroup *jc;
9584 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9586 return ERR_PTR(-ENOMEM);
9588 jc->info = alloc_percpu(struct perf_cgroup_info);
9591 return ERR_PTR(-ENOMEM);
9597 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9599 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9601 free_percpu(jc->info);
9605 static int __perf_cgroup_move(void *info)
9607 struct task_struct *task = info;
9609 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9614 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9616 struct task_struct *task;
9617 struct cgroup_subsys_state *css;
9619 cgroup_taskset_for_each(task, css, tset)
9620 task_function_call(task, __perf_cgroup_move, task);
9623 struct cgroup_subsys perf_event_cgrp_subsys = {
9624 .css_alloc = perf_cgroup_css_alloc,
9625 .css_free = perf_cgroup_css_free,
9626 .attach = perf_cgroup_attach,
9628 #endif /* CONFIG_CGROUP_PERF */