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(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_out = cpuctx->cgrp;
424 __update_cgrp_time(cgrp_out);
427 static inline void update_cgrp_time_from_event(struct perf_event *event)
429 struct perf_cgroup *cgrp;
432 * ensure we access cgroup data only when needed and
433 * when we know the cgroup is pinned (css_get)
435 if (!is_cgroup_event(event))
438 cgrp = perf_cgroup_from_task(current, event->ctx);
440 * Do not update time when cgroup is not active
442 if (cgrp == event->cgrp)
443 __update_cgrp_time(event->cgrp);
447 perf_cgroup_set_timestamp(struct task_struct *task,
448 struct perf_event_context *ctx)
450 struct perf_cgroup *cgrp;
451 struct perf_cgroup_info *info;
454 * ctx->lock held by caller
455 * ensure we do not access cgroup data
456 * unless we have the cgroup pinned (css_get)
458 if (!task || !ctx->nr_cgroups)
461 cgrp = perf_cgroup_from_task(task, ctx);
462 info = this_cpu_ptr(cgrp->info);
463 info->timestamp = ctx->timestamp;
466 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
467 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
470 * reschedule events based on the cgroup constraint of task.
472 * mode SWOUT : schedule out everything
473 * mode SWIN : schedule in based on cgroup for next
475 static void perf_cgroup_switch(struct task_struct *task, int mode)
477 struct perf_cpu_context *cpuctx;
482 * disable interrupts to avoid geting nr_cgroup
483 * changes via __perf_event_disable(). Also
486 local_irq_save(flags);
489 * we reschedule only in the presence of cgroup
490 * constrained events.
493 list_for_each_entry_rcu(pmu, &pmus, entry) {
494 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
495 if (cpuctx->unique_pmu != pmu)
496 continue; /* ensure we process each cpuctx once */
499 * perf_cgroup_events says at least one
500 * context on this CPU has cgroup events.
502 * ctx->nr_cgroups reports the number of cgroup
503 * events for a context.
505 if (cpuctx->ctx.nr_cgroups > 0) {
506 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
507 perf_pmu_disable(cpuctx->ctx.pmu);
509 if (mode & PERF_CGROUP_SWOUT) {
510 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
512 * must not be done before ctxswout due
513 * to event_filter_match() in event_sched_out()
518 if (mode & PERF_CGROUP_SWIN) {
519 WARN_ON_ONCE(cpuctx->cgrp);
521 * set cgrp before ctxsw in to allow
522 * event_filter_match() to not have to pass
524 * we pass the cpuctx->ctx to perf_cgroup_from_task()
525 * because cgorup events are only per-cpu
527 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
528 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
530 perf_pmu_enable(cpuctx->ctx.pmu);
531 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
535 local_irq_restore(flags);
538 static inline void perf_cgroup_sched_out(struct task_struct *task,
539 struct task_struct *next)
541 struct perf_cgroup *cgrp1;
542 struct perf_cgroup *cgrp2 = NULL;
546 * we come here when we know perf_cgroup_events > 0
547 * we do not need to pass the ctx here because we know
548 * we are holding the rcu lock
550 cgrp1 = perf_cgroup_from_task(task, NULL);
553 * next is NULL when called from perf_event_enable_on_exec()
554 * that will systematically cause a cgroup_switch()
557 cgrp2 = perf_cgroup_from_task(next, NULL);
560 * only schedule out current cgroup events if we know
561 * that we are switching to a different cgroup. Otherwise,
562 * do no touch the cgroup events.
565 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
570 static inline void perf_cgroup_sched_in(struct task_struct *prev,
571 struct task_struct *task)
573 struct perf_cgroup *cgrp1;
574 struct perf_cgroup *cgrp2 = NULL;
578 * we come here when we know perf_cgroup_events > 0
579 * we do not need to pass the ctx here because we know
580 * we are holding the rcu lock
582 cgrp1 = perf_cgroup_from_task(task, NULL);
584 /* prev can never be NULL */
585 cgrp2 = perf_cgroup_from_task(prev, NULL);
588 * only need to schedule in cgroup events if we are changing
589 * cgroup during ctxsw. Cgroup events were not scheduled
590 * out of ctxsw out if that was not the case.
593 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
598 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
599 struct perf_event_attr *attr,
600 struct perf_event *group_leader)
602 struct perf_cgroup *cgrp;
603 struct cgroup_subsys_state *css;
604 struct fd f = fdget(fd);
610 css = css_tryget_online_from_dir(f.file->f_path.dentry,
611 &perf_event_cgrp_subsys);
617 cgrp = container_of(css, struct perf_cgroup, css);
621 * all events in a group must monitor
622 * the same cgroup because a task belongs
623 * to only one perf cgroup at a time
625 if (group_leader && group_leader->cgrp != cgrp) {
626 perf_detach_cgroup(event);
635 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
637 struct perf_cgroup_info *t;
638 t = per_cpu_ptr(event->cgrp->info, event->cpu);
639 event->shadow_ctx_time = now - t->timestamp;
643 perf_cgroup_defer_enabled(struct perf_event *event)
646 * when the current task's perf cgroup does not match
647 * the event's, we need to remember to call the
648 * perf_mark_enable() function the first time a task with
649 * a matching perf cgroup is scheduled in.
651 if (is_cgroup_event(event) && !perf_cgroup_match(event))
652 event->cgrp_defer_enabled = 1;
656 perf_cgroup_mark_enabled(struct perf_event *event,
657 struct perf_event_context *ctx)
659 struct perf_event *sub;
660 u64 tstamp = perf_event_time(event);
662 if (!event->cgrp_defer_enabled)
665 event->cgrp_defer_enabled = 0;
667 event->tstamp_enabled = tstamp - event->total_time_enabled;
668 list_for_each_entry(sub, &event->sibling_list, group_entry) {
669 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
670 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
671 sub->cgrp_defer_enabled = 0;
675 #else /* !CONFIG_CGROUP_PERF */
678 perf_cgroup_match(struct perf_event *event)
683 static inline void perf_detach_cgroup(struct perf_event *event)
686 static inline int is_cgroup_event(struct perf_event *event)
691 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
696 static inline void update_cgrp_time_from_event(struct perf_event *event)
700 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
704 static inline void perf_cgroup_sched_out(struct task_struct *task,
705 struct task_struct *next)
709 static inline void perf_cgroup_sched_in(struct task_struct *prev,
710 struct task_struct *task)
714 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
715 struct perf_event_attr *attr,
716 struct perf_event *group_leader)
722 perf_cgroup_set_timestamp(struct task_struct *task,
723 struct perf_event_context *ctx)
728 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
733 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
737 static inline u64 perf_cgroup_event_time(struct perf_event *event)
743 perf_cgroup_defer_enabled(struct perf_event *event)
748 perf_cgroup_mark_enabled(struct perf_event *event,
749 struct perf_event_context *ctx)
755 * set default to be dependent on timer tick just
758 #define PERF_CPU_HRTIMER (1000 / HZ)
760 * function must be called with interrupts disbled
762 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
764 struct perf_cpu_context *cpuctx;
767 WARN_ON(!irqs_disabled());
769 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
770 rotations = perf_rotate_context(cpuctx);
772 raw_spin_lock(&cpuctx->hrtimer_lock);
774 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
776 cpuctx->hrtimer_active = 0;
777 raw_spin_unlock(&cpuctx->hrtimer_lock);
779 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
782 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
784 struct hrtimer *timer = &cpuctx->hrtimer;
785 struct pmu *pmu = cpuctx->ctx.pmu;
788 /* no multiplexing needed for SW PMU */
789 if (pmu->task_ctx_nr == perf_sw_context)
793 * check default is sane, if not set then force to
794 * default interval (1/tick)
796 interval = pmu->hrtimer_interval_ms;
798 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
800 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
802 raw_spin_lock_init(&cpuctx->hrtimer_lock);
803 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
804 timer->function = perf_mux_hrtimer_handler;
807 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
809 struct hrtimer *timer = &cpuctx->hrtimer;
810 struct pmu *pmu = cpuctx->ctx.pmu;
814 if (pmu->task_ctx_nr == perf_sw_context)
817 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
818 if (!cpuctx->hrtimer_active) {
819 cpuctx->hrtimer_active = 1;
820 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
821 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
823 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
828 void perf_pmu_disable(struct pmu *pmu)
830 int *count = this_cpu_ptr(pmu->pmu_disable_count);
832 pmu->pmu_disable(pmu);
835 void perf_pmu_enable(struct pmu *pmu)
837 int *count = this_cpu_ptr(pmu->pmu_disable_count);
839 pmu->pmu_enable(pmu);
842 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
845 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
846 * perf_event_task_tick() are fully serialized because they're strictly cpu
847 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
848 * disabled, while perf_event_task_tick is called from IRQ context.
850 static void perf_event_ctx_activate(struct perf_event_context *ctx)
852 struct list_head *head = this_cpu_ptr(&active_ctx_list);
854 WARN_ON(!irqs_disabled());
856 WARN_ON(!list_empty(&ctx->active_ctx_list));
858 list_add(&ctx->active_ctx_list, head);
861 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
863 WARN_ON(!irqs_disabled());
865 WARN_ON(list_empty(&ctx->active_ctx_list));
867 list_del_init(&ctx->active_ctx_list);
870 static void get_ctx(struct perf_event_context *ctx)
872 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
875 static void free_ctx(struct rcu_head *head)
877 struct perf_event_context *ctx;
879 ctx = container_of(head, struct perf_event_context, rcu_head);
880 kfree(ctx->task_ctx_data);
884 static void put_ctx(struct perf_event_context *ctx)
886 if (atomic_dec_and_test(&ctx->refcount)) {
888 put_ctx(ctx->parent_ctx);
890 put_task_struct(ctx->task);
891 call_rcu(&ctx->rcu_head, free_ctx);
896 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
897 * perf_pmu_migrate_context() we need some magic.
899 * Those places that change perf_event::ctx will hold both
900 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
902 * Lock ordering is by mutex address. There are two other sites where
903 * perf_event_context::mutex nests and those are:
905 * - perf_event_exit_task_context() [ child , 0 ]
906 * __perf_event_exit_task()
908 * put_event() [ parent, 1 ]
910 * - perf_event_init_context() [ parent, 0 ]
911 * inherit_task_group()
916 * perf_try_init_event() [ child , 1 ]
918 * While it appears there is an obvious deadlock here -- the parent and child
919 * nesting levels are inverted between the two. This is in fact safe because
920 * life-time rules separate them. That is an exiting task cannot fork, and a
921 * spawning task cannot (yet) exit.
923 * But remember that that these are parent<->child context relations, and
924 * migration does not affect children, therefore these two orderings should not
927 * The change in perf_event::ctx does not affect children (as claimed above)
928 * because the sys_perf_event_open() case will install a new event and break
929 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
930 * concerned with cpuctx and that doesn't have children.
932 * The places that change perf_event::ctx will issue:
934 * perf_remove_from_context();
936 * perf_install_in_context();
938 * to affect the change. The remove_from_context() + synchronize_rcu() should
939 * quiesce the event, after which we can install it in the new location. This
940 * means that only external vectors (perf_fops, prctl) can perturb the event
941 * while in transit. Therefore all such accessors should also acquire
942 * perf_event_context::mutex to serialize against this.
944 * However; because event->ctx can change while we're waiting to acquire
945 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
950 * task_struct::perf_event_mutex
951 * perf_event_context::mutex
952 * perf_event_context::lock
953 * perf_event::child_mutex;
954 * perf_event::mmap_mutex
957 static struct perf_event_context *
958 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
960 struct perf_event_context *ctx;
964 ctx = ACCESS_ONCE(event->ctx);
965 if (!atomic_inc_not_zero(&ctx->refcount)) {
971 mutex_lock_nested(&ctx->mutex, nesting);
972 if (event->ctx != ctx) {
973 mutex_unlock(&ctx->mutex);
981 static inline struct perf_event_context *
982 perf_event_ctx_lock(struct perf_event *event)
984 return perf_event_ctx_lock_nested(event, 0);
987 static void perf_event_ctx_unlock(struct perf_event *event,
988 struct perf_event_context *ctx)
990 mutex_unlock(&ctx->mutex);
995 * This must be done under the ctx->lock, such as to serialize against
996 * context_equiv(), therefore we cannot call put_ctx() since that might end up
997 * calling scheduler related locks and ctx->lock nests inside those.
999 static __must_check struct perf_event_context *
1000 unclone_ctx(struct perf_event_context *ctx)
1002 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1004 lockdep_assert_held(&ctx->lock);
1007 ctx->parent_ctx = NULL;
1013 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1016 * only top level events have the pid namespace they were created in
1019 event = event->parent;
1021 return task_tgid_nr_ns(p, event->ns);
1024 static u32 perf_event_tid(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_pid_nr_ns(p, event->ns);
1036 * If we inherit events we want to return the parent event id
1039 static u64 primary_event_id(struct perf_event *event)
1044 id = event->parent->id;
1050 * Get the perf_event_context for a task and lock it.
1051 * This has to cope with with the fact that until it is locked,
1052 * the context could get moved to another task.
1054 static struct perf_event_context *
1055 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1057 struct perf_event_context *ctx;
1061 * One of the few rules of preemptible RCU is that one cannot do
1062 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1063 * part of the read side critical section was irqs-enabled -- see
1064 * rcu_read_unlock_special().
1066 * Since ctx->lock nests under rq->lock we must ensure the entire read
1067 * side critical section has interrupts disabled.
1069 local_irq_save(*flags);
1071 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1074 * If this context is a clone of another, it might
1075 * get swapped for another underneath us by
1076 * perf_event_task_sched_out, though the
1077 * rcu_read_lock() protects us from any context
1078 * getting freed. Lock the context and check if it
1079 * got swapped before we could get the lock, and retry
1080 * if so. If we locked the right context, then it
1081 * can't get swapped on us any more.
1083 raw_spin_lock(&ctx->lock);
1084 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1085 raw_spin_unlock(&ctx->lock);
1087 local_irq_restore(*flags);
1091 if (!atomic_inc_not_zero(&ctx->refcount)) {
1092 raw_spin_unlock(&ctx->lock);
1098 local_irq_restore(*flags);
1103 * Get the context for a task and increment its pin_count so it
1104 * can't get swapped to another task. This also increments its
1105 * reference count so that the context can't get freed.
1107 static struct perf_event_context *
1108 perf_pin_task_context(struct task_struct *task, int ctxn)
1110 struct perf_event_context *ctx;
1111 unsigned long flags;
1113 ctx = perf_lock_task_context(task, ctxn, &flags);
1116 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1121 static void perf_unpin_context(struct perf_event_context *ctx)
1123 unsigned long flags;
1125 raw_spin_lock_irqsave(&ctx->lock, flags);
1127 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1131 * Update the record of the current time in a context.
1133 static void update_context_time(struct perf_event_context *ctx)
1135 u64 now = perf_clock();
1137 ctx->time += now - ctx->timestamp;
1138 ctx->timestamp = now;
1141 static u64 perf_event_time(struct perf_event *event)
1143 struct perf_event_context *ctx = event->ctx;
1145 if (is_cgroup_event(event))
1146 return perf_cgroup_event_time(event);
1148 return ctx ? ctx->time : 0;
1152 * Update the total_time_enabled and total_time_running fields for a event.
1153 * The caller of this function needs to hold the ctx->lock.
1155 static void update_event_times(struct perf_event *event)
1157 struct perf_event_context *ctx = event->ctx;
1160 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1161 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1164 * in cgroup mode, time_enabled represents
1165 * the time the event was enabled AND active
1166 * tasks were in the monitored cgroup. This is
1167 * independent of the activity of the context as
1168 * there may be a mix of cgroup and non-cgroup events.
1170 * That is why we treat cgroup events differently
1173 if (is_cgroup_event(event))
1174 run_end = perf_cgroup_event_time(event);
1175 else if (ctx->is_active)
1176 run_end = ctx->time;
1178 run_end = event->tstamp_stopped;
1180 event->total_time_enabled = run_end - event->tstamp_enabled;
1182 if (event->state == PERF_EVENT_STATE_INACTIVE)
1183 run_end = event->tstamp_stopped;
1185 run_end = perf_event_time(event);
1187 event->total_time_running = run_end - event->tstamp_running;
1192 * Update total_time_enabled and total_time_running for all events in a group.
1194 static void update_group_times(struct perf_event *leader)
1196 struct perf_event *event;
1198 update_event_times(leader);
1199 list_for_each_entry(event, &leader->sibling_list, group_entry)
1200 update_event_times(event);
1203 static struct list_head *
1204 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1206 if (event->attr.pinned)
1207 return &ctx->pinned_groups;
1209 return &ctx->flexible_groups;
1213 * Add a event from the lists for its context.
1214 * Must be called with ctx->mutex and ctx->lock held.
1217 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1219 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1220 event->attach_state |= PERF_ATTACH_CONTEXT;
1223 * If we're a stand alone event or group leader, we go to the context
1224 * list, group events are kept attached to the group so that
1225 * perf_group_detach can, at all times, locate all siblings.
1227 if (event->group_leader == event) {
1228 struct list_head *list;
1230 if (is_software_event(event))
1231 event->group_flags |= PERF_GROUP_SOFTWARE;
1233 list = ctx_group_list(event, ctx);
1234 list_add_tail(&event->group_entry, list);
1237 if (is_cgroup_event(event))
1240 list_add_rcu(&event->event_entry, &ctx->event_list);
1242 if (event->attr.inherit_stat)
1249 * Initialize event state based on the perf_event_attr::disabled.
1251 static inline void perf_event__state_init(struct perf_event *event)
1253 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1254 PERF_EVENT_STATE_INACTIVE;
1257 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1259 int entry = sizeof(u64); /* value */
1263 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1264 size += sizeof(u64);
1266 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1267 size += sizeof(u64);
1269 if (event->attr.read_format & PERF_FORMAT_ID)
1270 entry += sizeof(u64);
1272 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1274 size += sizeof(u64);
1278 event->read_size = size;
1281 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1283 struct perf_sample_data *data;
1286 if (sample_type & PERF_SAMPLE_IP)
1287 size += sizeof(data->ip);
1289 if (sample_type & PERF_SAMPLE_ADDR)
1290 size += sizeof(data->addr);
1292 if (sample_type & PERF_SAMPLE_PERIOD)
1293 size += sizeof(data->period);
1295 if (sample_type & PERF_SAMPLE_WEIGHT)
1296 size += sizeof(data->weight);
1298 if (sample_type & PERF_SAMPLE_READ)
1299 size += event->read_size;
1301 if (sample_type & PERF_SAMPLE_DATA_SRC)
1302 size += sizeof(data->data_src.val);
1304 if (sample_type & PERF_SAMPLE_TRANSACTION)
1305 size += sizeof(data->txn);
1307 event->header_size = size;
1311 * Called at perf_event creation and when events are attached/detached from a
1314 static void perf_event__header_size(struct perf_event *event)
1316 __perf_event_read_size(event,
1317 event->group_leader->nr_siblings);
1318 __perf_event_header_size(event, event->attr.sample_type);
1321 static void perf_event__id_header_size(struct perf_event *event)
1323 struct perf_sample_data *data;
1324 u64 sample_type = event->attr.sample_type;
1327 if (sample_type & PERF_SAMPLE_TID)
1328 size += sizeof(data->tid_entry);
1330 if (sample_type & PERF_SAMPLE_TIME)
1331 size += sizeof(data->time);
1333 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1334 size += sizeof(data->id);
1336 if (sample_type & PERF_SAMPLE_ID)
1337 size += sizeof(data->id);
1339 if (sample_type & PERF_SAMPLE_STREAM_ID)
1340 size += sizeof(data->stream_id);
1342 if (sample_type & PERF_SAMPLE_CPU)
1343 size += sizeof(data->cpu_entry);
1345 event->id_header_size = size;
1348 static bool perf_event_validate_size(struct perf_event *event)
1351 * The values computed here will be over-written when we actually
1354 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1355 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1356 perf_event__id_header_size(event);
1359 * Sum the lot; should not exceed the 64k limit we have on records.
1360 * Conservative limit to allow for callchains and other variable fields.
1362 if (event->read_size + event->header_size +
1363 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1369 static void perf_group_attach(struct perf_event *event)
1371 struct perf_event *group_leader = event->group_leader, *pos;
1374 * We can have double attach due to group movement in perf_event_open.
1376 if (event->attach_state & PERF_ATTACH_GROUP)
1379 event->attach_state |= PERF_ATTACH_GROUP;
1381 if (group_leader == event)
1384 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1386 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1387 !is_software_event(event))
1388 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1390 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1391 group_leader->nr_siblings++;
1393 perf_event__header_size(group_leader);
1395 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1396 perf_event__header_size(pos);
1400 * Remove a event from the lists for its context.
1401 * Must be called with ctx->mutex and ctx->lock held.
1404 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1406 struct perf_cpu_context *cpuctx;
1408 WARN_ON_ONCE(event->ctx != ctx);
1409 lockdep_assert_held(&ctx->lock);
1412 * We can have double detach due to exit/hot-unplug + close.
1414 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1417 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1419 if (is_cgroup_event(event)) {
1421 cpuctx = __get_cpu_context(ctx);
1423 * if there are no more cgroup events
1424 * then cler cgrp to avoid stale pointer
1425 * in update_cgrp_time_from_cpuctx()
1427 if (!ctx->nr_cgroups)
1428 cpuctx->cgrp = NULL;
1432 if (event->attr.inherit_stat)
1435 list_del_rcu(&event->event_entry);
1437 if (event->group_leader == event)
1438 list_del_init(&event->group_entry);
1440 update_group_times(event);
1443 * If event was in error state, then keep it
1444 * that way, otherwise bogus counts will be
1445 * returned on read(). The only way to get out
1446 * of error state is by explicit re-enabling
1449 if (event->state > PERF_EVENT_STATE_OFF)
1450 event->state = PERF_EVENT_STATE_OFF;
1455 static void perf_group_detach(struct perf_event *event)
1457 struct perf_event *sibling, *tmp;
1458 struct list_head *list = NULL;
1461 * We can have double detach due to exit/hot-unplug + close.
1463 if (!(event->attach_state & PERF_ATTACH_GROUP))
1466 event->attach_state &= ~PERF_ATTACH_GROUP;
1469 * If this is a sibling, remove it from its group.
1471 if (event->group_leader != event) {
1472 list_del_init(&event->group_entry);
1473 event->group_leader->nr_siblings--;
1477 if (!list_empty(&event->group_entry))
1478 list = &event->group_entry;
1481 * If this was a group event with sibling events then
1482 * upgrade the siblings to singleton events by adding them
1483 * to whatever list we are on.
1485 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1487 list_move_tail(&sibling->group_entry, list);
1488 sibling->group_leader = sibling;
1490 /* Inherit group flags from the previous leader */
1491 sibling->group_flags = event->group_flags;
1493 WARN_ON_ONCE(sibling->ctx != event->ctx);
1497 perf_event__header_size(event->group_leader);
1499 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1500 perf_event__header_size(tmp);
1504 * User event without the task.
1506 static bool is_orphaned_event(struct perf_event *event)
1508 return event && !is_kernel_event(event) && !event->owner;
1512 * Event has a parent but parent's task finished and it's
1513 * alive only because of children holding refference.
1515 static bool is_orphaned_child(struct perf_event *event)
1517 return is_orphaned_event(event->parent);
1520 static void orphans_remove_work(struct work_struct *work);
1522 static void schedule_orphans_remove(struct perf_event_context *ctx)
1524 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1527 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1529 ctx->orphans_remove_sched = true;
1533 static int __init perf_workqueue_init(void)
1535 perf_wq = create_singlethread_workqueue("perf");
1536 WARN(!perf_wq, "failed to create perf workqueue\n");
1537 return perf_wq ? 0 : -1;
1540 core_initcall(perf_workqueue_init);
1542 static inline int __pmu_filter_match(struct perf_event *event)
1544 struct pmu *pmu = event->pmu;
1545 return pmu->filter_match ? pmu->filter_match(event) : 1;
1549 * Check whether we should attempt to schedule an event group based on
1550 * PMU-specific filtering. An event group can consist of HW and SW events,
1551 * potentially with a SW leader, so we must check all the filters, to
1552 * determine whether a group is schedulable:
1554 static inline int pmu_filter_match(struct perf_event *event)
1556 struct perf_event *child;
1558 if (!__pmu_filter_match(event))
1561 list_for_each_entry(child, &event->sibling_list, group_entry) {
1562 if (!__pmu_filter_match(child))
1570 event_filter_match(struct perf_event *event)
1572 return (event->cpu == -1 || event->cpu == smp_processor_id())
1573 && perf_cgroup_match(event) && pmu_filter_match(event);
1577 event_sched_out(struct perf_event *event,
1578 struct perf_cpu_context *cpuctx,
1579 struct perf_event_context *ctx)
1581 u64 tstamp = perf_event_time(event);
1584 WARN_ON_ONCE(event->ctx != ctx);
1585 lockdep_assert_held(&ctx->lock);
1588 * An event which could not be activated because of
1589 * filter mismatch still needs to have its timings
1590 * maintained, otherwise bogus information is return
1591 * via read() for time_enabled, time_running:
1593 if (event->state == PERF_EVENT_STATE_INACTIVE
1594 && !event_filter_match(event)) {
1595 delta = tstamp - event->tstamp_stopped;
1596 event->tstamp_running += delta;
1597 event->tstamp_stopped = tstamp;
1600 if (event->state != PERF_EVENT_STATE_ACTIVE)
1603 perf_pmu_disable(event->pmu);
1605 event->tstamp_stopped = tstamp;
1606 event->pmu->del(event, 0);
1608 event->state = PERF_EVENT_STATE_INACTIVE;
1609 if (event->pending_disable) {
1610 event->pending_disable = 0;
1611 event->state = PERF_EVENT_STATE_OFF;
1614 if (!is_software_event(event))
1615 cpuctx->active_oncpu--;
1616 if (!--ctx->nr_active)
1617 perf_event_ctx_deactivate(ctx);
1618 if (event->attr.freq && event->attr.sample_freq)
1620 if (event->attr.exclusive || !cpuctx->active_oncpu)
1621 cpuctx->exclusive = 0;
1623 if (is_orphaned_child(event))
1624 schedule_orphans_remove(ctx);
1626 perf_pmu_enable(event->pmu);
1630 group_sched_out(struct perf_event *group_event,
1631 struct perf_cpu_context *cpuctx,
1632 struct perf_event_context *ctx)
1634 struct perf_event *event;
1635 int state = group_event->state;
1637 event_sched_out(group_event, cpuctx, ctx);
1640 * Schedule out siblings (if any):
1642 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1643 event_sched_out(event, cpuctx, ctx);
1645 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1646 cpuctx->exclusive = 0;
1649 struct remove_event {
1650 struct perf_event *event;
1655 * Cross CPU call to remove a performance event
1657 * We disable the event on the hardware level first. After that we
1658 * remove it from the context list.
1660 static int __perf_remove_from_context(void *info)
1662 struct remove_event *re = info;
1663 struct perf_event *event = re->event;
1664 struct perf_event_context *ctx = event->ctx;
1665 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1667 raw_spin_lock(&ctx->lock);
1668 event_sched_out(event, cpuctx, ctx);
1669 if (re->detach_group)
1670 perf_group_detach(event);
1671 list_del_event(event, ctx);
1672 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1674 cpuctx->task_ctx = NULL;
1676 raw_spin_unlock(&ctx->lock);
1683 * Remove the event from a task's (or a CPU's) list of events.
1685 * CPU events are removed with a smp call. For task events we only
1686 * call when the task is on a CPU.
1688 * If event->ctx is a cloned context, callers must make sure that
1689 * every task struct that event->ctx->task could possibly point to
1690 * remains valid. This is OK when called from perf_release since
1691 * that only calls us on the top-level context, which can't be a clone.
1692 * When called from perf_event_exit_task, it's OK because the
1693 * context has been detached from its task.
1695 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1697 struct perf_event_context *ctx = event->ctx;
1698 struct task_struct *task = ctx->task;
1699 struct remove_event re = {
1701 .detach_group = detach_group,
1704 lockdep_assert_held(&ctx->mutex);
1708 * Per cpu events are removed via an smp call. The removal can
1709 * fail if the CPU is currently offline, but in that case we
1710 * already called __perf_remove_from_context from
1711 * perf_event_exit_cpu.
1713 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1718 if (!task_function_call(task, __perf_remove_from_context, &re))
1721 raw_spin_lock_irq(&ctx->lock);
1723 * If we failed to find a running task, but find the context active now
1724 * that we've acquired the ctx->lock, retry.
1726 if (ctx->is_active) {
1727 raw_spin_unlock_irq(&ctx->lock);
1729 * Reload the task pointer, it might have been changed by
1730 * a concurrent perf_event_context_sched_out().
1737 * Since the task isn't running, its safe to remove the event, us
1738 * holding the ctx->lock ensures the task won't get scheduled in.
1741 perf_group_detach(event);
1742 list_del_event(event, ctx);
1743 raw_spin_unlock_irq(&ctx->lock);
1747 * Cross CPU call to disable a performance event
1749 int __perf_event_disable(void *info)
1751 struct perf_event *event = info;
1752 struct perf_event_context *ctx = event->ctx;
1753 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1756 * If this is a per-task event, need to check whether this
1757 * event's task is the current task on this cpu.
1759 * Can trigger due to concurrent perf_event_context_sched_out()
1760 * flipping contexts around.
1762 if (ctx->task && cpuctx->task_ctx != ctx)
1765 raw_spin_lock(&ctx->lock);
1768 * If the event is on, turn it off.
1769 * If it is in error state, leave it in error state.
1771 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1772 update_context_time(ctx);
1773 update_cgrp_time_from_event(event);
1774 update_group_times(event);
1775 if (event == event->group_leader)
1776 group_sched_out(event, cpuctx, ctx);
1778 event_sched_out(event, cpuctx, ctx);
1779 event->state = PERF_EVENT_STATE_OFF;
1782 raw_spin_unlock(&ctx->lock);
1790 * If event->ctx is a cloned context, callers must make sure that
1791 * every task struct that event->ctx->task could possibly point to
1792 * remains valid. This condition is satisifed when called through
1793 * perf_event_for_each_child or perf_event_for_each because they
1794 * hold the top-level event's child_mutex, so any descendant that
1795 * goes to exit will block in sync_child_event.
1796 * When called from perf_pending_event it's OK because event->ctx
1797 * is the current context on this CPU and preemption is disabled,
1798 * hence we can't get into perf_event_task_sched_out for this context.
1800 static void _perf_event_disable(struct perf_event *event)
1802 struct perf_event_context *ctx = event->ctx;
1803 struct task_struct *task = ctx->task;
1807 * Disable the event on the cpu that it's on
1809 cpu_function_call(event->cpu, __perf_event_disable, event);
1814 if (!task_function_call(task, __perf_event_disable, event))
1817 raw_spin_lock_irq(&ctx->lock);
1819 * If the event is still active, we need to retry the cross-call.
1821 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1822 raw_spin_unlock_irq(&ctx->lock);
1824 * Reload the task pointer, it might have been changed by
1825 * a concurrent perf_event_context_sched_out().
1832 * Since we have the lock this context can't be scheduled
1833 * in, so we can change the state safely.
1835 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1836 update_group_times(event);
1837 event->state = PERF_EVENT_STATE_OFF;
1839 raw_spin_unlock_irq(&ctx->lock);
1843 * Strictly speaking kernel users cannot create groups and therefore this
1844 * interface does not need the perf_event_ctx_lock() magic.
1846 void perf_event_disable(struct perf_event *event)
1848 struct perf_event_context *ctx;
1850 ctx = perf_event_ctx_lock(event);
1851 _perf_event_disable(event);
1852 perf_event_ctx_unlock(event, ctx);
1854 EXPORT_SYMBOL_GPL(perf_event_disable);
1856 static void perf_set_shadow_time(struct perf_event *event,
1857 struct perf_event_context *ctx,
1861 * use the correct time source for the time snapshot
1863 * We could get by without this by leveraging the
1864 * fact that to get to this function, the caller
1865 * has most likely already called update_context_time()
1866 * and update_cgrp_time_xx() and thus both timestamp
1867 * are identical (or very close). Given that tstamp is,
1868 * already adjusted for cgroup, we could say that:
1869 * tstamp - ctx->timestamp
1871 * tstamp - cgrp->timestamp.
1873 * Then, in perf_output_read(), the calculation would
1874 * work with no changes because:
1875 * - event is guaranteed scheduled in
1876 * - no scheduled out in between
1877 * - thus the timestamp would be the same
1879 * But this is a bit hairy.
1881 * So instead, we have an explicit cgroup call to remain
1882 * within the time time source all along. We believe it
1883 * is cleaner and simpler to understand.
1885 if (is_cgroup_event(event))
1886 perf_cgroup_set_shadow_time(event, tstamp);
1888 event->shadow_ctx_time = tstamp - ctx->timestamp;
1891 #define MAX_INTERRUPTS (~0ULL)
1893 static void perf_log_throttle(struct perf_event *event, int enable);
1894 static void perf_log_itrace_start(struct perf_event *event);
1897 event_sched_in(struct perf_event *event,
1898 struct perf_cpu_context *cpuctx,
1899 struct perf_event_context *ctx)
1901 u64 tstamp = perf_event_time(event);
1904 lockdep_assert_held(&ctx->lock);
1906 if (event->state <= PERF_EVENT_STATE_OFF)
1909 event->state = PERF_EVENT_STATE_ACTIVE;
1910 event->oncpu = smp_processor_id();
1913 * Unthrottle events, since we scheduled we might have missed several
1914 * ticks already, also for a heavily scheduling task there is little
1915 * guarantee it'll get a tick in a timely manner.
1917 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1918 perf_log_throttle(event, 1);
1919 event->hw.interrupts = 0;
1923 * The new state must be visible before we turn it on in the hardware:
1927 perf_pmu_disable(event->pmu);
1929 perf_set_shadow_time(event, ctx, tstamp);
1931 perf_log_itrace_start(event);
1933 if (event->pmu->add(event, PERF_EF_START)) {
1934 event->state = PERF_EVENT_STATE_INACTIVE;
1940 event->tstamp_running += tstamp - event->tstamp_stopped;
1942 if (!is_software_event(event))
1943 cpuctx->active_oncpu++;
1944 if (!ctx->nr_active++)
1945 perf_event_ctx_activate(ctx);
1946 if (event->attr.freq && event->attr.sample_freq)
1949 if (event->attr.exclusive)
1950 cpuctx->exclusive = 1;
1952 if (is_orphaned_child(event))
1953 schedule_orphans_remove(ctx);
1956 perf_pmu_enable(event->pmu);
1962 group_sched_in(struct perf_event *group_event,
1963 struct perf_cpu_context *cpuctx,
1964 struct perf_event_context *ctx)
1966 struct perf_event *event, *partial_group = NULL;
1967 struct pmu *pmu = ctx->pmu;
1968 u64 now = ctx->time;
1969 bool simulate = false;
1971 if (group_event->state == PERF_EVENT_STATE_OFF)
1974 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
1976 if (event_sched_in(group_event, cpuctx, ctx)) {
1977 pmu->cancel_txn(pmu);
1978 perf_mux_hrtimer_restart(cpuctx);
1983 * Schedule in siblings as one group (if any):
1985 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1986 if (event_sched_in(event, cpuctx, ctx)) {
1987 partial_group = event;
1992 if (!pmu->commit_txn(pmu))
1997 * Groups can be scheduled in as one unit only, so undo any
1998 * partial group before returning:
1999 * The events up to the failed event are scheduled out normally,
2000 * tstamp_stopped will be updated.
2002 * The failed events and the remaining siblings need to have
2003 * their timings updated as if they had gone thru event_sched_in()
2004 * and event_sched_out(). This is required to get consistent timings
2005 * across the group. This also takes care of the case where the group
2006 * could never be scheduled by ensuring tstamp_stopped is set to mark
2007 * the time the event was actually stopped, such that time delta
2008 * calculation in update_event_times() is correct.
2010 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2011 if (event == partial_group)
2015 event->tstamp_running += now - event->tstamp_stopped;
2016 event->tstamp_stopped = now;
2018 event_sched_out(event, cpuctx, ctx);
2021 event_sched_out(group_event, cpuctx, ctx);
2023 pmu->cancel_txn(pmu);
2025 perf_mux_hrtimer_restart(cpuctx);
2031 * Work out whether we can put this event group on the CPU now.
2033 static int group_can_go_on(struct perf_event *event,
2034 struct perf_cpu_context *cpuctx,
2038 * Groups consisting entirely of software events can always go on.
2040 if (event->group_flags & PERF_GROUP_SOFTWARE)
2043 * If an exclusive group is already on, no other hardware
2046 if (cpuctx->exclusive)
2049 * If this group is exclusive and there are already
2050 * events on the CPU, it can't go on.
2052 if (event->attr.exclusive && cpuctx->active_oncpu)
2055 * Otherwise, try to add it if all previous groups were able
2061 static void add_event_to_ctx(struct perf_event *event,
2062 struct perf_event_context *ctx)
2064 u64 tstamp = perf_event_time(event);
2066 list_add_event(event, ctx);
2067 perf_group_attach(event);
2068 event->tstamp_enabled = tstamp;
2069 event->tstamp_running = tstamp;
2070 event->tstamp_stopped = tstamp;
2073 static void task_ctx_sched_out(struct perf_event_context *ctx);
2075 ctx_sched_in(struct perf_event_context *ctx,
2076 struct perf_cpu_context *cpuctx,
2077 enum event_type_t event_type,
2078 struct task_struct *task);
2080 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2081 struct perf_event_context *ctx,
2082 struct task_struct *task)
2084 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2086 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2087 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2089 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2093 * Cross CPU call to install and enable a performance event
2095 * Must be called with ctx->mutex held
2097 static int __perf_install_in_context(void *info)
2099 struct perf_event *event = info;
2100 struct perf_event_context *ctx = event->ctx;
2101 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2102 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2103 struct task_struct *task = current;
2105 perf_ctx_lock(cpuctx, task_ctx);
2106 perf_pmu_disable(cpuctx->ctx.pmu);
2109 * If there was an active task_ctx schedule it out.
2112 task_ctx_sched_out(task_ctx);
2115 * If the context we're installing events in is not the
2116 * active task_ctx, flip them.
2118 if (ctx->task && task_ctx != ctx) {
2120 raw_spin_unlock(&task_ctx->lock);
2121 raw_spin_lock(&ctx->lock);
2126 cpuctx->task_ctx = task_ctx;
2127 task = task_ctx->task;
2130 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2132 update_context_time(ctx);
2134 * update cgrp time only if current cgrp
2135 * matches event->cgrp. Must be done before
2136 * calling add_event_to_ctx()
2138 update_cgrp_time_from_event(event);
2140 add_event_to_ctx(event, ctx);
2143 * Schedule everything back in
2145 perf_event_sched_in(cpuctx, task_ctx, task);
2147 perf_pmu_enable(cpuctx->ctx.pmu);
2148 perf_ctx_unlock(cpuctx, task_ctx);
2154 * Attach a performance event to a context
2156 * First we add the event to the list with the hardware enable bit
2157 * in event->hw_config cleared.
2159 * If the event is attached to a task which is on a CPU we use a smp
2160 * call to enable it in the task context. The task might have been
2161 * scheduled away, but we check this in the smp call again.
2164 perf_install_in_context(struct perf_event_context *ctx,
2165 struct perf_event *event,
2168 struct task_struct *task = ctx->task;
2170 lockdep_assert_held(&ctx->mutex);
2173 if (event->cpu != -1)
2178 * Per cpu events are installed via an smp call and
2179 * the install is always successful.
2181 cpu_function_call(cpu, __perf_install_in_context, event);
2186 if (!task_function_call(task, __perf_install_in_context, event))
2189 raw_spin_lock_irq(&ctx->lock);
2191 * If we failed to find a running task, but find the context active now
2192 * that we've acquired the ctx->lock, retry.
2194 if (ctx->is_active) {
2195 raw_spin_unlock_irq(&ctx->lock);
2197 * Reload the task pointer, it might have been changed by
2198 * a concurrent perf_event_context_sched_out().
2205 * Since the task isn't running, its safe to add the event, us holding
2206 * the ctx->lock ensures the task won't get scheduled in.
2208 add_event_to_ctx(event, ctx);
2209 raw_spin_unlock_irq(&ctx->lock);
2213 * Put a event into inactive state and update time fields.
2214 * Enabling the leader of a group effectively enables all
2215 * the group members that aren't explicitly disabled, so we
2216 * have to update their ->tstamp_enabled also.
2217 * Note: this works for group members as well as group leaders
2218 * since the non-leader members' sibling_lists will be empty.
2220 static void __perf_event_mark_enabled(struct perf_event *event)
2222 struct perf_event *sub;
2223 u64 tstamp = perf_event_time(event);
2225 event->state = PERF_EVENT_STATE_INACTIVE;
2226 event->tstamp_enabled = tstamp - event->total_time_enabled;
2227 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2228 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2229 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2234 * Cross CPU call to enable a performance event
2236 static int __perf_event_enable(void *info)
2238 struct perf_event *event = info;
2239 struct perf_event_context *ctx = event->ctx;
2240 struct perf_event *leader = event->group_leader;
2241 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2245 * There's a time window between 'ctx->is_active' check
2246 * in perf_event_enable function and this place having:
2248 * - ctx->lock unlocked
2250 * where the task could be killed and 'ctx' deactivated
2251 * by perf_event_exit_task.
2253 if (!ctx->is_active)
2256 raw_spin_lock(&ctx->lock);
2257 update_context_time(ctx);
2259 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2263 * set current task's cgroup time reference point
2265 perf_cgroup_set_timestamp(current, ctx);
2267 __perf_event_mark_enabled(event);
2269 if (!event_filter_match(event)) {
2270 if (is_cgroup_event(event))
2271 perf_cgroup_defer_enabled(event);
2276 * If the event is in a group and isn't the group leader,
2277 * then don't put it on unless the group is on.
2279 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2282 if (!group_can_go_on(event, cpuctx, 1)) {
2285 if (event == leader)
2286 err = group_sched_in(event, cpuctx, ctx);
2288 err = event_sched_in(event, cpuctx, ctx);
2293 * If this event can't go on and it's part of a
2294 * group, then the whole group has to come off.
2296 if (leader != event) {
2297 group_sched_out(leader, cpuctx, ctx);
2298 perf_mux_hrtimer_restart(cpuctx);
2300 if (leader->attr.pinned) {
2301 update_group_times(leader);
2302 leader->state = PERF_EVENT_STATE_ERROR;
2307 raw_spin_unlock(&ctx->lock);
2315 * If event->ctx is a cloned context, callers must make sure that
2316 * every task struct that event->ctx->task could possibly point to
2317 * remains valid. This condition is satisfied when called through
2318 * perf_event_for_each_child or perf_event_for_each as described
2319 * for perf_event_disable.
2321 static void _perf_event_enable(struct perf_event *event)
2323 struct perf_event_context *ctx = event->ctx;
2324 struct task_struct *task = ctx->task;
2328 * Enable the event on the cpu that it's on
2330 cpu_function_call(event->cpu, __perf_event_enable, event);
2334 raw_spin_lock_irq(&ctx->lock);
2335 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2339 * If the event is in error state, clear that first.
2340 * That way, if we see the event in error state below, we
2341 * know that it has gone back into error state, as distinct
2342 * from the task having been scheduled away before the
2343 * cross-call arrived.
2345 if (event->state == PERF_EVENT_STATE_ERROR)
2346 event->state = PERF_EVENT_STATE_OFF;
2349 if (!ctx->is_active) {
2350 __perf_event_mark_enabled(event);
2354 raw_spin_unlock_irq(&ctx->lock);
2356 if (!task_function_call(task, __perf_event_enable, event))
2359 raw_spin_lock_irq(&ctx->lock);
2362 * If the context is active and the event is still off,
2363 * we need to retry the cross-call.
2365 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2367 * task could have been flipped by a concurrent
2368 * perf_event_context_sched_out()
2375 raw_spin_unlock_irq(&ctx->lock);
2379 * See perf_event_disable();
2381 void perf_event_enable(struct perf_event *event)
2383 struct perf_event_context *ctx;
2385 ctx = perf_event_ctx_lock(event);
2386 _perf_event_enable(event);
2387 perf_event_ctx_unlock(event, ctx);
2389 EXPORT_SYMBOL_GPL(perf_event_enable);
2391 static int _perf_event_refresh(struct perf_event *event, int refresh)
2394 * not supported on inherited events
2396 if (event->attr.inherit || !is_sampling_event(event))
2399 atomic_add(refresh, &event->event_limit);
2400 _perf_event_enable(event);
2406 * See perf_event_disable()
2408 int perf_event_refresh(struct perf_event *event, int refresh)
2410 struct perf_event_context *ctx;
2413 ctx = perf_event_ctx_lock(event);
2414 ret = _perf_event_refresh(event, refresh);
2415 perf_event_ctx_unlock(event, ctx);
2419 EXPORT_SYMBOL_GPL(perf_event_refresh);
2421 static void ctx_sched_out(struct perf_event_context *ctx,
2422 struct perf_cpu_context *cpuctx,
2423 enum event_type_t event_type)
2425 struct perf_event *event;
2426 int is_active = ctx->is_active;
2428 ctx->is_active &= ~event_type;
2429 if (likely(!ctx->nr_events))
2432 update_context_time(ctx);
2433 update_cgrp_time_from_cpuctx(cpuctx);
2434 if (!ctx->nr_active)
2437 perf_pmu_disable(ctx->pmu);
2438 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2439 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2440 group_sched_out(event, cpuctx, ctx);
2443 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2444 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2445 group_sched_out(event, cpuctx, ctx);
2447 perf_pmu_enable(ctx->pmu);
2451 * Test whether two contexts are equivalent, i.e. whether they have both been
2452 * cloned from the same version of the same context.
2454 * Equivalence is measured using a generation number in the context that is
2455 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2456 * and list_del_event().
2458 static int context_equiv(struct perf_event_context *ctx1,
2459 struct perf_event_context *ctx2)
2461 lockdep_assert_held(&ctx1->lock);
2462 lockdep_assert_held(&ctx2->lock);
2464 /* Pinning disables the swap optimization */
2465 if (ctx1->pin_count || ctx2->pin_count)
2468 /* If ctx1 is the parent of ctx2 */
2469 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2472 /* If ctx2 is the parent of ctx1 */
2473 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2477 * If ctx1 and ctx2 have the same parent; we flatten the parent
2478 * hierarchy, see perf_event_init_context().
2480 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2481 ctx1->parent_gen == ctx2->parent_gen)
2488 static void __perf_event_sync_stat(struct perf_event *event,
2489 struct perf_event *next_event)
2493 if (!event->attr.inherit_stat)
2497 * Update the event value, we cannot use perf_event_read()
2498 * because we're in the middle of a context switch and have IRQs
2499 * disabled, which upsets smp_call_function_single(), however
2500 * we know the event must be on the current CPU, therefore we
2501 * don't need to use it.
2503 switch (event->state) {
2504 case PERF_EVENT_STATE_ACTIVE:
2505 event->pmu->read(event);
2508 case PERF_EVENT_STATE_INACTIVE:
2509 update_event_times(event);
2517 * In order to keep per-task stats reliable we need to flip the event
2518 * values when we flip the contexts.
2520 value = local64_read(&next_event->count);
2521 value = local64_xchg(&event->count, value);
2522 local64_set(&next_event->count, value);
2524 swap(event->total_time_enabled, next_event->total_time_enabled);
2525 swap(event->total_time_running, next_event->total_time_running);
2528 * Since we swizzled the values, update the user visible data too.
2530 perf_event_update_userpage(event);
2531 perf_event_update_userpage(next_event);
2534 static void perf_event_sync_stat(struct perf_event_context *ctx,
2535 struct perf_event_context *next_ctx)
2537 struct perf_event *event, *next_event;
2542 update_context_time(ctx);
2544 event = list_first_entry(&ctx->event_list,
2545 struct perf_event, event_entry);
2547 next_event = list_first_entry(&next_ctx->event_list,
2548 struct perf_event, event_entry);
2550 while (&event->event_entry != &ctx->event_list &&
2551 &next_event->event_entry != &next_ctx->event_list) {
2553 __perf_event_sync_stat(event, next_event);
2555 event = list_next_entry(event, event_entry);
2556 next_event = list_next_entry(next_event, event_entry);
2560 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2561 struct task_struct *next)
2563 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2564 struct perf_event_context *next_ctx;
2565 struct perf_event_context *parent, *next_parent;
2566 struct perf_cpu_context *cpuctx;
2572 cpuctx = __get_cpu_context(ctx);
2573 if (!cpuctx->task_ctx)
2577 next_ctx = next->perf_event_ctxp[ctxn];
2581 parent = rcu_dereference(ctx->parent_ctx);
2582 next_parent = rcu_dereference(next_ctx->parent_ctx);
2584 /* If neither context have a parent context; they cannot be clones. */
2585 if (!parent && !next_parent)
2588 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2590 * Looks like the two contexts are clones, so we might be
2591 * able to optimize the context switch. We lock both
2592 * contexts and check that they are clones under the
2593 * lock (including re-checking that neither has been
2594 * uncloned in the meantime). It doesn't matter which
2595 * order we take the locks because no other cpu could
2596 * be trying to lock both of these tasks.
2598 raw_spin_lock(&ctx->lock);
2599 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2600 if (context_equiv(ctx, next_ctx)) {
2602 * XXX do we need a memory barrier of sorts
2603 * wrt to rcu_dereference() of perf_event_ctxp
2605 task->perf_event_ctxp[ctxn] = next_ctx;
2606 next->perf_event_ctxp[ctxn] = ctx;
2608 next_ctx->task = task;
2610 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2614 perf_event_sync_stat(ctx, next_ctx);
2616 raw_spin_unlock(&next_ctx->lock);
2617 raw_spin_unlock(&ctx->lock);
2623 raw_spin_lock(&ctx->lock);
2624 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2625 cpuctx->task_ctx = NULL;
2626 raw_spin_unlock(&ctx->lock);
2630 void perf_sched_cb_dec(struct pmu *pmu)
2632 this_cpu_dec(perf_sched_cb_usages);
2635 void perf_sched_cb_inc(struct pmu *pmu)
2637 this_cpu_inc(perf_sched_cb_usages);
2641 * This function provides the context switch callback to the lower code
2642 * layer. It is invoked ONLY when the context switch callback is enabled.
2644 static void perf_pmu_sched_task(struct task_struct *prev,
2645 struct task_struct *next,
2648 struct perf_cpu_context *cpuctx;
2650 unsigned long flags;
2655 local_irq_save(flags);
2659 list_for_each_entry_rcu(pmu, &pmus, entry) {
2660 if (pmu->sched_task) {
2661 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2663 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2665 perf_pmu_disable(pmu);
2667 pmu->sched_task(cpuctx->task_ctx, sched_in);
2669 perf_pmu_enable(pmu);
2671 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2677 local_irq_restore(flags);
2680 static void perf_event_switch(struct task_struct *task,
2681 struct task_struct *next_prev, bool sched_in);
2683 #define for_each_task_context_nr(ctxn) \
2684 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2687 * Called from scheduler to remove the events of the current task,
2688 * with interrupts disabled.
2690 * We stop each event and update the event value in event->count.
2692 * This does not protect us against NMI, but disable()
2693 * sets the disabled bit in the control field of event _before_
2694 * accessing the event control register. If a NMI hits, then it will
2695 * not restart the event.
2697 void __perf_event_task_sched_out(struct task_struct *task,
2698 struct task_struct *next)
2702 if (__this_cpu_read(perf_sched_cb_usages))
2703 perf_pmu_sched_task(task, next, false);
2705 if (atomic_read(&nr_switch_events))
2706 perf_event_switch(task, next, false);
2708 for_each_task_context_nr(ctxn)
2709 perf_event_context_sched_out(task, ctxn, next);
2712 * if cgroup events exist on this CPU, then we need
2713 * to check if we have to switch out PMU state.
2714 * cgroup event are system-wide mode only
2716 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2717 perf_cgroup_sched_out(task, next);
2720 static void task_ctx_sched_out(struct perf_event_context *ctx)
2722 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2724 if (!cpuctx->task_ctx)
2727 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2730 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2731 cpuctx->task_ctx = NULL;
2735 * Called with IRQs disabled
2737 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2738 enum event_type_t event_type)
2740 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2744 ctx_pinned_sched_in(struct perf_event_context *ctx,
2745 struct perf_cpu_context *cpuctx)
2747 struct perf_event *event;
2749 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2750 if (event->state <= PERF_EVENT_STATE_OFF)
2752 if (!event_filter_match(event))
2755 /* may need to reset tstamp_enabled */
2756 if (is_cgroup_event(event))
2757 perf_cgroup_mark_enabled(event, ctx);
2759 if (group_can_go_on(event, cpuctx, 1))
2760 group_sched_in(event, cpuctx, ctx);
2763 * If this pinned group hasn't been scheduled,
2764 * put it in error state.
2766 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2767 update_group_times(event);
2768 event->state = PERF_EVENT_STATE_ERROR;
2774 ctx_flexible_sched_in(struct perf_event_context *ctx,
2775 struct perf_cpu_context *cpuctx)
2777 struct perf_event *event;
2780 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2781 /* Ignore events in OFF or ERROR state */
2782 if (event->state <= PERF_EVENT_STATE_OFF)
2785 * Listen to the 'cpu' scheduling filter constraint
2788 if (!event_filter_match(event))
2791 /* may need to reset tstamp_enabled */
2792 if (is_cgroup_event(event))
2793 perf_cgroup_mark_enabled(event, ctx);
2795 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2796 if (group_sched_in(event, cpuctx, ctx))
2803 ctx_sched_in(struct perf_event_context *ctx,
2804 struct perf_cpu_context *cpuctx,
2805 enum event_type_t event_type,
2806 struct task_struct *task)
2809 int is_active = ctx->is_active;
2811 ctx->is_active |= event_type;
2812 if (likely(!ctx->nr_events))
2816 ctx->timestamp = now;
2817 perf_cgroup_set_timestamp(task, ctx);
2819 * First go through the list and put on any pinned groups
2820 * in order to give them the best chance of going on.
2822 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2823 ctx_pinned_sched_in(ctx, cpuctx);
2825 /* Then walk through the lower prio flexible groups */
2826 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2827 ctx_flexible_sched_in(ctx, cpuctx);
2830 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2831 enum event_type_t event_type,
2832 struct task_struct *task)
2834 struct perf_event_context *ctx = &cpuctx->ctx;
2836 ctx_sched_in(ctx, cpuctx, event_type, task);
2839 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2840 struct task_struct *task)
2842 struct perf_cpu_context *cpuctx;
2844 cpuctx = __get_cpu_context(ctx);
2845 if (cpuctx->task_ctx == ctx)
2848 perf_ctx_lock(cpuctx, ctx);
2849 perf_pmu_disable(ctx->pmu);
2851 * We want to keep the following priority order:
2852 * cpu pinned (that don't need to move), task pinned,
2853 * cpu flexible, task flexible.
2855 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2858 cpuctx->task_ctx = ctx;
2860 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2862 perf_pmu_enable(ctx->pmu);
2863 perf_ctx_unlock(cpuctx, ctx);
2867 * Called from scheduler to add the events of the current task
2868 * with interrupts disabled.
2870 * We restore the event value and then enable it.
2872 * This does not protect us against NMI, but enable()
2873 * sets the enabled bit in the control field of event _before_
2874 * accessing the event control register. If a NMI hits, then it will
2875 * keep the event running.
2877 void __perf_event_task_sched_in(struct task_struct *prev,
2878 struct task_struct *task)
2880 struct perf_event_context *ctx;
2883 for_each_task_context_nr(ctxn) {
2884 ctx = task->perf_event_ctxp[ctxn];
2888 perf_event_context_sched_in(ctx, task);
2891 * if cgroup events exist on this CPU, then we need
2892 * to check if we have to switch in PMU state.
2893 * cgroup event are system-wide mode only
2895 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2896 perf_cgroup_sched_in(prev, task);
2898 if (atomic_read(&nr_switch_events))
2899 perf_event_switch(task, prev, true);
2901 if (__this_cpu_read(perf_sched_cb_usages))
2902 perf_pmu_sched_task(prev, task, true);
2905 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2907 u64 frequency = event->attr.sample_freq;
2908 u64 sec = NSEC_PER_SEC;
2909 u64 divisor, dividend;
2911 int count_fls, nsec_fls, frequency_fls, sec_fls;
2913 count_fls = fls64(count);
2914 nsec_fls = fls64(nsec);
2915 frequency_fls = fls64(frequency);
2919 * We got @count in @nsec, with a target of sample_freq HZ
2920 * the target period becomes:
2923 * period = -------------------
2924 * @nsec * sample_freq
2929 * Reduce accuracy by one bit such that @a and @b converge
2930 * to a similar magnitude.
2932 #define REDUCE_FLS(a, b) \
2934 if (a##_fls > b##_fls) { \
2944 * Reduce accuracy until either term fits in a u64, then proceed with
2945 * the other, so that finally we can do a u64/u64 division.
2947 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2948 REDUCE_FLS(nsec, frequency);
2949 REDUCE_FLS(sec, count);
2952 if (count_fls + sec_fls > 64) {
2953 divisor = nsec * frequency;
2955 while (count_fls + sec_fls > 64) {
2956 REDUCE_FLS(count, sec);
2960 dividend = count * sec;
2962 dividend = count * sec;
2964 while (nsec_fls + frequency_fls > 64) {
2965 REDUCE_FLS(nsec, frequency);
2969 divisor = nsec * frequency;
2975 return div64_u64(dividend, divisor);
2978 static DEFINE_PER_CPU(int, perf_throttled_count);
2979 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2981 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2983 struct hw_perf_event *hwc = &event->hw;
2984 s64 period, sample_period;
2987 period = perf_calculate_period(event, nsec, count);
2989 delta = (s64)(period - hwc->sample_period);
2990 delta = (delta + 7) / 8; /* low pass filter */
2992 sample_period = hwc->sample_period + delta;
2997 hwc->sample_period = sample_period;
2999 if (local64_read(&hwc->period_left) > 8*sample_period) {
3001 event->pmu->stop(event, PERF_EF_UPDATE);
3003 local64_set(&hwc->period_left, 0);
3006 event->pmu->start(event, PERF_EF_RELOAD);
3011 * combine freq adjustment with unthrottling to avoid two passes over the
3012 * events. At the same time, make sure, having freq events does not change
3013 * the rate of unthrottling as that would introduce bias.
3015 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3018 struct perf_event *event;
3019 struct hw_perf_event *hwc;
3020 u64 now, period = TICK_NSEC;
3024 * only need to iterate over all events iff:
3025 * - context have events in frequency mode (needs freq adjust)
3026 * - there are events to unthrottle on this cpu
3028 if (!(ctx->nr_freq || needs_unthr))
3031 raw_spin_lock(&ctx->lock);
3032 perf_pmu_disable(ctx->pmu);
3034 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3035 if (event->state != PERF_EVENT_STATE_ACTIVE)
3038 if (!event_filter_match(event))
3041 perf_pmu_disable(event->pmu);
3045 if (hwc->interrupts == MAX_INTERRUPTS) {
3046 hwc->interrupts = 0;
3047 perf_log_throttle(event, 1);
3048 event->pmu->start(event, 0);
3051 if (!event->attr.freq || !event->attr.sample_freq)
3055 * stop the event and update event->count
3057 event->pmu->stop(event, PERF_EF_UPDATE);
3059 now = local64_read(&event->count);
3060 delta = now - hwc->freq_count_stamp;
3061 hwc->freq_count_stamp = now;
3065 * reload only if value has changed
3066 * we have stopped the event so tell that
3067 * to perf_adjust_period() to avoid stopping it
3071 perf_adjust_period(event, period, delta, false);
3073 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3075 perf_pmu_enable(event->pmu);
3078 perf_pmu_enable(ctx->pmu);
3079 raw_spin_unlock(&ctx->lock);
3083 * Round-robin a context's events:
3085 static void rotate_ctx(struct perf_event_context *ctx)
3088 * Rotate the first entry last of non-pinned groups. Rotation might be
3089 * disabled by the inheritance code.
3091 if (!ctx->rotate_disable)
3092 list_rotate_left(&ctx->flexible_groups);
3095 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3097 struct perf_event_context *ctx = NULL;
3100 if (cpuctx->ctx.nr_events) {
3101 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3105 ctx = cpuctx->task_ctx;
3106 if (ctx && ctx->nr_events) {
3107 if (ctx->nr_events != ctx->nr_active)
3114 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3115 perf_pmu_disable(cpuctx->ctx.pmu);
3117 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3119 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3121 rotate_ctx(&cpuctx->ctx);
3125 perf_event_sched_in(cpuctx, ctx, current);
3127 perf_pmu_enable(cpuctx->ctx.pmu);
3128 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3134 #ifdef CONFIG_NO_HZ_FULL
3135 bool perf_event_can_stop_tick(void)
3137 if (atomic_read(&nr_freq_events) ||
3138 __this_cpu_read(perf_throttled_count))
3145 void perf_event_task_tick(void)
3147 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3148 struct perf_event_context *ctx, *tmp;
3151 WARN_ON(!irqs_disabled());
3153 __this_cpu_inc(perf_throttled_seq);
3154 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3156 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3157 perf_adjust_freq_unthr_context(ctx, throttled);
3160 static int event_enable_on_exec(struct perf_event *event,
3161 struct perf_event_context *ctx)
3163 if (!event->attr.enable_on_exec)
3166 event->attr.enable_on_exec = 0;
3167 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3170 __perf_event_mark_enabled(event);
3176 * Enable all of a task's events that have been marked enable-on-exec.
3177 * This expects task == current.
3179 static void perf_event_enable_on_exec(int ctxn)
3181 struct perf_event_context *ctx, *clone_ctx = NULL;
3182 struct perf_event *event;
3183 unsigned long flags;
3187 local_irq_save(flags);
3188 ctx = current->perf_event_ctxp[ctxn];
3189 if (!ctx || !ctx->nr_events)
3193 * We must ctxsw out cgroup events to avoid conflict
3194 * when invoking perf_task_event_sched_in() later on
3195 * in this function. Otherwise we end up trying to
3196 * ctxswin cgroup events which are already scheduled
3199 perf_cgroup_sched_out(current, NULL);
3201 raw_spin_lock(&ctx->lock);
3202 task_ctx_sched_out(ctx);
3204 list_for_each_entry(event, &ctx->event_list, event_entry) {
3205 ret = event_enable_on_exec(event, ctx);
3211 * Unclone this context if we enabled any event.
3214 clone_ctx = unclone_ctx(ctx);
3216 raw_spin_unlock(&ctx->lock);
3219 * Also calls ctxswin for cgroup events, if any:
3221 perf_event_context_sched_in(ctx, ctx->task);
3223 local_irq_restore(flags);
3229 void perf_event_exec(void)
3234 for_each_task_context_nr(ctxn)
3235 perf_event_enable_on_exec(ctxn);
3239 struct perf_read_data {
3240 struct perf_event *event;
3246 * Cross CPU call to read the hardware event
3248 static void __perf_event_read(void *info)
3250 struct perf_read_data *data = info;
3251 struct perf_event *sub, *event = data->event;
3252 struct perf_event_context *ctx = event->ctx;
3253 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3254 struct pmu *pmu = event->pmu;
3257 * If this is a task context, we need to check whether it is
3258 * the current task context of this cpu. If not it has been
3259 * scheduled out before the smp call arrived. In that case
3260 * event->count would have been updated to a recent sample
3261 * when the event was scheduled out.
3263 if (ctx->task && cpuctx->task_ctx != ctx)
3266 raw_spin_lock(&ctx->lock);
3267 if (ctx->is_active) {
3268 update_context_time(ctx);
3269 update_cgrp_time_from_event(event);
3272 update_event_times(event);
3273 if (event->state != PERF_EVENT_STATE_ACTIVE)
3282 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3286 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3287 update_event_times(sub);
3288 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3290 * Use sibling's PMU rather than @event's since
3291 * sibling could be on different (eg: software) PMU.
3293 sub->pmu->read(sub);
3297 data->ret = pmu->commit_txn(pmu);
3300 raw_spin_unlock(&ctx->lock);
3303 static inline u64 perf_event_count(struct perf_event *event)
3305 if (event->pmu->count)
3306 return event->pmu->count(event);
3308 return __perf_event_count(event);
3312 * NMI-safe method to read a local event, that is an event that
3314 * - either for the current task, or for this CPU
3315 * - does not have inherit set, for inherited task events
3316 * will not be local and we cannot read them atomically
3317 * - must not have a pmu::count method
3319 u64 perf_event_read_local(struct perf_event *event)
3321 unsigned long flags;
3325 * Disabling interrupts avoids all counter scheduling (context
3326 * switches, timer based rotation and IPIs).
3328 local_irq_save(flags);
3330 /* If this is a per-task event, it must be for current */
3331 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3332 event->hw.target != current);
3334 /* If this is a per-CPU event, it must be for this CPU */
3335 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3336 event->cpu != smp_processor_id());
3339 * It must not be an event with inherit set, we cannot read
3340 * all child counters from atomic context.
3342 WARN_ON_ONCE(event->attr.inherit);
3345 * It must not have a pmu::count method, those are not
3348 WARN_ON_ONCE(event->pmu->count);
3351 * If the event is currently on this CPU, its either a per-task event,
3352 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3355 if (event->oncpu == smp_processor_id())
3356 event->pmu->read(event);
3358 val = local64_read(&event->count);
3359 local_irq_restore(flags);
3364 static int perf_event_read(struct perf_event *event, bool group)
3369 * If event is enabled and currently active on a CPU, update the
3370 * value in the event structure:
3372 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3373 struct perf_read_data data = {
3378 smp_call_function_single(event->oncpu,
3379 __perf_event_read, &data, 1);
3381 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3382 struct perf_event_context *ctx = event->ctx;
3383 unsigned long flags;
3385 raw_spin_lock_irqsave(&ctx->lock, flags);
3387 * may read while context is not active
3388 * (e.g., thread is blocked), in that case
3389 * we cannot update context time
3391 if (ctx->is_active) {
3392 update_context_time(ctx);
3393 update_cgrp_time_from_event(event);
3396 update_group_times(event);
3398 update_event_times(event);
3399 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3406 * Initialize the perf_event context in a task_struct:
3408 static void __perf_event_init_context(struct perf_event_context *ctx)
3410 raw_spin_lock_init(&ctx->lock);
3411 mutex_init(&ctx->mutex);
3412 INIT_LIST_HEAD(&ctx->active_ctx_list);
3413 INIT_LIST_HEAD(&ctx->pinned_groups);
3414 INIT_LIST_HEAD(&ctx->flexible_groups);
3415 INIT_LIST_HEAD(&ctx->event_list);
3416 atomic_set(&ctx->refcount, 1);
3417 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3420 static struct perf_event_context *
3421 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3423 struct perf_event_context *ctx;
3425 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3429 __perf_event_init_context(ctx);
3432 get_task_struct(task);
3439 static struct task_struct *
3440 find_lively_task_by_vpid(pid_t vpid)
3442 struct task_struct *task;
3448 task = find_task_by_vpid(vpid);
3450 get_task_struct(task);
3454 return ERR_PTR(-ESRCH);
3460 * Returns a matching context with refcount and pincount.
3462 static struct perf_event_context *
3463 find_get_context(struct pmu *pmu, struct task_struct *task,
3464 struct perf_event *event)
3466 struct perf_event_context *ctx, *clone_ctx = NULL;
3467 struct perf_cpu_context *cpuctx;
3468 void *task_ctx_data = NULL;
3469 unsigned long flags;
3471 int cpu = event->cpu;
3474 /* Must be root to operate on a CPU event: */
3475 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3476 return ERR_PTR(-EACCES);
3479 * We could be clever and allow to attach a event to an
3480 * offline CPU and activate it when the CPU comes up, but
3483 if (!cpu_online(cpu))
3484 return ERR_PTR(-ENODEV);
3486 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3495 ctxn = pmu->task_ctx_nr;
3499 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3500 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3501 if (!task_ctx_data) {
3508 ctx = perf_lock_task_context(task, ctxn, &flags);
3510 clone_ctx = unclone_ctx(ctx);
3513 if (task_ctx_data && !ctx->task_ctx_data) {
3514 ctx->task_ctx_data = task_ctx_data;
3515 task_ctx_data = NULL;
3517 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3522 ctx = alloc_perf_context(pmu, task);
3527 if (task_ctx_data) {
3528 ctx->task_ctx_data = task_ctx_data;
3529 task_ctx_data = NULL;
3533 mutex_lock(&task->perf_event_mutex);
3535 * If it has already passed perf_event_exit_task().
3536 * we must see PF_EXITING, it takes this mutex too.
3538 if (task->flags & PF_EXITING)
3540 else if (task->perf_event_ctxp[ctxn])
3545 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3547 mutex_unlock(&task->perf_event_mutex);
3549 if (unlikely(err)) {
3558 kfree(task_ctx_data);
3562 kfree(task_ctx_data);
3563 return ERR_PTR(err);
3566 static void perf_event_free_filter(struct perf_event *event);
3567 static void perf_event_free_bpf_prog(struct perf_event *event);
3569 static void free_event_rcu(struct rcu_head *head)
3571 struct perf_event *event;
3573 event = container_of(head, struct perf_event, rcu_head);
3575 put_pid_ns(event->ns);
3576 perf_event_free_filter(event);
3580 static void ring_buffer_attach(struct perf_event *event,
3581 struct ring_buffer *rb);
3583 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3588 if (is_cgroup_event(event))
3589 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3592 static void unaccount_event(struct perf_event *event)
3597 if (event->attach_state & PERF_ATTACH_TASK)
3598 static_key_slow_dec_deferred(&perf_sched_events);
3599 if (event->attr.mmap || event->attr.mmap_data)
3600 atomic_dec(&nr_mmap_events);
3601 if (event->attr.comm)
3602 atomic_dec(&nr_comm_events);
3603 if (event->attr.task)
3604 atomic_dec(&nr_task_events);
3605 if (event->attr.freq)
3606 atomic_dec(&nr_freq_events);
3607 if (event->attr.context_switch) {
3608 static_key_slow_dec_deferred(&perf_sched_events);
3609 atomic_dec(&nr_switch_events);
3611 if (is_cgroup_event(event))
3612 static_key_slow_dec_deferred(&perf_sched_events);
3613 if (has_branch_stack(event))
3614 static_key_slow_dec_deferred(&perf_sched_events);
3616 unaccount_event_cpu(event, event->cpu);
3620 * The following implement mutual exclusion of events on "exclusive" pmus
3621 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3622 * at a time, so we disallow creating events that might conflict, namely:
3624 * 1) cpu-wide events in the presence of per-task events,
3625 * 2) per-task events in the presence of cpu-wide events,
3626 * 3) two matching events on the same context.
3628 * The former two cases are handled in the allocation path (perf_event_alloc(),
3629 * __free_event()), the latter -- before the first perf_install_in_context().
3631 static int exclusive_event_init(struct perf_event *event)
3633 struct pmu *pmu = event->pmu;
3635 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3639 * Prevent co-existence of per-task and cpu-wide events on the
3640 * same exclusive pmu.
3642 * Negative pmu::exclusive_cnt means there are cpu-wide
3643 * events on this "exclusive" pmu, positive means there are
3646 * Since this is called in perf_event_alloc() path, event::ctx
3647 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3648 * to mean "per-task event", because unlike other attach states it
3649 * never gets cleared.
3651 if (event->attach_state & PERF_ATTACH_TASK) {
3652 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3655 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3662 static void exclusive_event_destroy(struct perf_event *event)
3664 struct pmu *pmu = event->pmu;
3666 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3669 /* see comment in exclusive_event_init() */
3670 if (event->attach_state & PERF_ATTACH_TASK)
3671 atomic_dec(&pmu->exclusive_cnt);
3673 atomic_inc(&pmu->exclusive_cnt);
3676 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3678 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3679 (e1->cpu == e2->cpu ||
3686 /* Called under the same ctx::mutex as perf_install_in_context() */
3687 static bool exclusive_event_installable(struct perf_event *event,
3688 struct perf_event_context *ctx)
3690 struct perf_event *iter_event;
3691 struct pmu *pmu = event->pmu;
3693 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3696 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3697 if (exclusive_event_match(iter_event, event))
3704 static void __free_event(struct perf_event *event)
3706 if (!event->parent) {
3707 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3708 put_callchain_buffers();
3711 perf_event_free_bpf_prog(event);
3714 event->destroy(event);
3717 put_ctx(event->ctx);
3720 exclusive_event_destroy(event);
3721 module_put(event->pmu->module);
3724 call_rcu(&event->rcu_head, free_event_rcu);
3727 static void _free_event(struct perf_event *event)
3729 irq_work_sync(&event->pending);
3731 unaccount_event(event);
3735 * Can happen when we close an event with re-directed output.
3737 * Since we have a 0 refcount, perf_mmap_close() will skip
3738 * over us; possibly making our ring_buffer_put() the last.
3740 mutex_lock(&event->mmap_mutex);
3741 ring_buffer_attach(event, NULL);
3742 mutex_unlock(&event->mmap_mutex);
3745 if (is_cgroup_event(event))
3746 perf_detach_cgroup(event);
3748 __free_event(event);
3752 * Used to free events which have a known refcount of 1, such as in error paths
3753 * where the event isn't exposed yet and inherited events.
3755 static void free_event(struct perf_event *event)
3757 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3758 "unexpected event refcount: %ld; ptr=%p\n",
3759 atomic_long_read(&event->refcount), event)) {
3760 /* leak to avoid use-after-free */
3768 * Remove user event from the owner task.
3770 static void perf_remove_from_owner(struct perf_event *event)
3772 struct task_struct *owner;
3775 owner = ACCESS_ONCE(event->owner);
3777 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3778 * !owner it means the list deletion is complete and we can indeed
3779 * free this event, otherwise we need to serialize on
3780 * owner->perf_event_mutex.
3782 smp_read_barrier_depends();
3785 * Since delayed_put_task_struct() also drops the last
3786 * task reference we can safely take a new reference
3787 * while holding the rcu_read_lock().
3789 get_task_struct(owner);
3795 * If we're here through perf_event_exit_task() we're already
3796 * holding ctx->mutex which would be an inversion wrt. the
3797 * normal lock order.
3799 * However we can safely take this lock because its the child
3802 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3805 * We have to re-check the event->owner field, if it is cleared
3806 * we raced with perf_event_exit_task(), acquiring the mutex
3807 * ensured they're done, and we can proceed with freeing the
3811 list_del_init(&event->owner_entry);
3812 mutex_unlock(&owner->perf_event_mutex);
3813 put_task_struct(owner);
3817 static void put_event(struct perf_event *event)
3819 struct perf_event_context *ctx;
3821 if (!atomic_long_dec_and_test(&event->refcount))
3824 if (!is_kernel_event(event))
3825 perf_remove_from_owner(event);
3828 * There are two ways this annotation is useful:
3830 * 1) there is a lock recursion from perf_event_exit_task
3831 * see the comment there.
3833 * 2) there is a lock-inversion with mmap_sem through
3834 * perf_read_group(), which takes faults while
3835 * holding ctx->mutex, however this is called after
3836 * the last filedesc died, so there is no possibility
3837 * to trigger the AB-BA case.
3839 ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3840 WARN_ON_ONCE(ctx->parent_ctx);
3841 perf_remove_from_context(event, true);
3842 perf_event_ctx_unlock(event, ctx);
3847 int perf_event_release_kernel(struct perf_event *event)
3852 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3855 * Called when the last reference to the file is gone.
3857 static int perf_release(struct inode *inode, struct file *file)
3859 put_event(file->private_data);
3864 * Remove all orphanes events from the context.
3866 static void orphans_remove_work(struct work_struct *work)
3868 struct perf_event_context *ctx;
3869 struct perf_event *event, *tmp;
3871 ctx = container_of(work, struct perf_event_context,
3872 orphans_remove.work);
3874 mutex_lock(&ctx->mutex);
3875 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3876 struct perf_event *parent_event = event->parent;
3878 if (!is_orphaned_child(event))
3881 perf_remove_from_context(event, true);
3883 mutex_lock(&parent_event->child_mutex);
3884 list_del_init(&event->child_list);
3885 mutex_unlock(&parent_event->child_mutex);
3888 put_event(parent_event);
3891 raw_spin_lock_irq(&ctx->lock);
3892 ctx->orphans_remove_sched = false;
3893 raw_spin_unlock_irq(&ctx->lock);
3894 mutex_unlock(&ctx->mutex);
3899 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3901 struct perf_event *child;
3907 mutex_lock(&event->child_mutex);
3909 (void)perf_event_read(event, false);
3910 total += perf_event_count(event);
3912 *enabled += event->total_time_enabled +
3913 atomic64_read(&event->child_total_time_enabled);
3914 *running += event->total_time_running +
3915 atomic64_read(&event->child_total_time_running);
3917 list_for_each_entry(child, &event->child_list, child_list) {
3918 (void)perf_event_read(child, false);
3919 total += perf_event_count(child);
3920 *enabled += child->total_time_enabled;
3921 *running += child->total_time_running;
3923 mutex_unlock(&event->child_mutex);
3927 EXPORT_SYMBOL_GPL(perf_event_read_value);
3929 static int __perf_read_group_add(struct perf_event *leader,
3930 u64 read_format, u64 *values)
3932 struct perf_event *sub;
3933 int n = 1; /* skip @nr */
3936 ret = perf_event_read(leader, true);
3941 * Since we co-schedule groups, {enabled,running} times of siblings
3942 * will be identical to those of the leader, so we only publish one
3945 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3946 values[n++] += leader->total_time_enabled +
3947 atomic64_read(&leader->child_total_time_enabled);
3950 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3951 values[n++] += leader->total_time_running +
3952 atomic64_read(&leader->child_total_time_running);
3956 * Write {count,id} tuples for every sibling.
3958 values[n++] += perf_event_count(leader);
3959 if (read_format & PERF_FORMAT_ID)
3960 values[n++] = primary_event_id(leader);
3962 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3963 values[n++] += perf_event_count(sub);
3964 if (read_format & PERF_FORMAT_ID)
3965 values[n++] = primary_event_id(sub);
3971 static int perf_read_group(struct perf_event *event,
3972 u64 read_format, char __user *buf)
3974 struct perf_event *leader = event->group_leader, *child;
3975 struct perf_event_context *ctx = leader->ctx;
3979 lockdep_assert_held(&ctx->mutex);
3981 values = kzalloc(event->read_size, GFP_KERNEL);
3985 values[0] = 1 + leader->nr_siblings;
3988 * By locking the child_mutex of the leader we effectively
3989 * lock the child list of all siblings.. XXX explain how.
3991 mutex_lock(&leader->child_mutex);
3993 ret = __perf_read_group_add(leader, read_format, values);
3997 list_for_each_entry(child, &leader->child_list, child_list) {
3998 ret = __perf_read_group_add(child, read_format, values);
4003 mutex_unlock(&leader->child_mutex);
4005 ret = event->read_size;
4006 if (copy_to_user(buf, values, event->read_size))
4011 mutex_unlock(&leader->child_mutex);
4017 static int perf_read_one(struct perf_event *event,
4018 u64 read_format, char __user *buf)
4020 u64 enabled, running;
4024 values[n++] = perf_event_read_value(event, &enabled, &running);
4025 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4026 values[n++] = enabled;
4027 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4028 values[n++] = running;
4029 if (read_format & PERF_FORMAT_ID)
4030 values[n++] = primary_event_id(event);
4032 if (copy_to_user(buf, values, n * sizeof(u64)))
4035 return n * sizeof(u64);
4038 static bool is_event_hup(struct perf_event *event)
4042 if (event->state != PERF_EVENT_STATE_EXIT)
4045 mutex_lock(&event->child_mutex);
4046 no_children = list_empty(&event->child_list);
4047 mutex_unlock(&event->child_mutex);
4052 * Read the performance event - simple non blocking version for now
4055 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4057 u64 read_format = event->attr.read_format;
4061 * Return end-of-file for a read on a event that is in
4062 * error state (i.e. because it was pinned but it couldn't be
4063 * scheduled on to the CPU at some point).
4065 if (event->state == PERF_EVENT_STATE_ERROR)
4068 if (count < event->read_size)
4071 WARN_ON_ONCE(event->ctx->parent_ctx);
4072 if (read_format & PERF_FORMAT_GROUP)
4073 ret = perf_read_group(event, read_format, buf);
4075 ret = perf_read_one(event, read_format, buf);
4081 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4083 struct perf_event *event = file->private_data;
4084 struct perf_event_context *ctx;
4087 ctx = perf_event_ctx_lock(event);
4088 ret = __perf_read(event, buf, count);
4089 perf_event_ctx_unlock(event, ctx);
4094 static unsigned int perf_poll(struct file *file, poll_table *wait)
4096 struct perf_event *event = file->private_data;
4097 struct ring_buffer *rb;
4098 unsigned int events = POLLHUP;
4100 poll_wait(file, &event->waitq, wait);
4102 if (is_event_hup(event))
4106 * Pin the event->rb by taking event->mmap_mutex; otherwise
4107 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4109 mutex_lock(&event->mmap_mutex);
4112 events = atomic_xchg(&rb->poll, 0);
4113 mutex_unlock(&event->mmap_mutex);
4117 static void _perf_event_reset(struct perf_event *event)
4119 (void)perf_event_read(event, false);
4120 local64_set(&event->count, 0);
4121 perf_event_update_userpage(event);
4125 * Holding the top-level event's child_mutex means that any
4126 * descendant process that has inherited this event will block
4127 * in sync_child_event if it goes to exit, thus satisfying the
4128 * task existence requirements of perf_event_enable/disable.
4130 static void perf_event_for_each_child(struct perf_event *event,
4131 void (*func)(struct perf_event *))
4133 struct perf_event *child;
4135 WARN_ON_ONCE(event->ctx->parent_ctx);
4137 mutex_lock(&event->child_mutex);
4139 list_for_each_entry(child, &event->child_list, child_list)
4141 mutex_unlock(&event->child_mutex);
4144 static void perf_event_for_each(struct perf_event *event,
4145 void (*func)(struct perf_event *))
4147 struct perf_event_context *ctx = event->ctx;
4148 struct perf_event *sibling;
4150 lockdep_assert_held(&ctx->mutex);
4152 event = event->group_leader;
4154 perf_event_for_each_child(event, func);
4155 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4156 perf_event_for_each_child(sibling, func);
4159 struct period_event {
4160 struct perf_event *event;
4164 static int __perf_event_period(void *info)
4166 struct period_event *pe = info;
4167 struct perf_event *event = pe->event;
4168 struct perf_event_context *ctx = event->ctx;
4169 u64 value = pe->value;
4172 raw_spin_lock(&ctx->lock);
4173 if (event->attr.freq) {
4174 event->attr.sample_freq = value;
4176 event->attr.sample_period = value;
4177 event->hw.sample_period = value;
4180 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4182 perf_pmu_disable(ctx->pmu);
4183 event->pmu->stop(event, PERF_EF_UPDATE);
4186 local64_set(&event->hw.period_left, 0);
4189 event->pmu->start(event, PERF_EF_RELOAD);
4190 perf_pmu_enable(ctx->pmu);
4192 raw_spin_unlock(&ctx->lock);
4197 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4199 struct period_event pe = { .event = event, };
4200 struct perf_event_context *ctx = event->ctx;
4201 struct task_struct *task;
4204 if (!is_sampling_event(event))
4207 if (copy_from_user(&value, arg, sizeof(value)))
4213 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4220 cpu_function_call(event->cpu, __perf_event_period, &pe);
4225 if (!task_function_call(task, __perf_event_period, &pe))
4228 raw_spin_lock_irq(&ctx->lock);
4229 if (ctx->is_active) {
4230 raw_spin_unlock_irq(&ctx->lock);
4235 if (event->attr.freq) {
4236 event->attr.sample_freq = value;
4238 event->attr.sample_period = value;
4239 event->hw.sample_period = value;
4242 local64_set(&event->hw.period_left, 0);
4243 raw_spin_unlock_irq(&ctx->lock);
4248 static const struct file_operations perf_fops;
4250 static inline int perf_fget_light(int fd, struct fd *p)
4252 struct fd f = fdget(fd);
4256 if (f.file->f_op != &perf_fops) {
4264 static int perf_event_set_output(struct perf_event *event,
4265 struct perf_event *output_event);
4266 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4267 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4269 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4271 void (*func)(struct perf_event *);
4275 case PERF_EVENT_IOC_ENABLE:
4276 func = _perf_event_enable;
4278 case PERF_EVENT_IOC_DISABLE:
4279 func = _perf_event_disable;
4281 case PERF_EVENT_IOC_RESET:
4282 func = _perf_event_reset;
4285 case PERF_EVENT_IOC_REFRESH:
4286 return _perf_event_refresh(event, arg);
4288 case PERF_EVENT_IOC_PERIOD:
4289 return perf_event_period(event, (u64 __user *)arg);
4291 case PERF_EVENT_IOC_ID:
4293 u64 id = primary_event_id(event);
4295 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4300 case PERF_EVENT_IOC_SET_OUTPUT:
4304 struct perf_event *output_event;
4306 ret = perf_fget_light(arg, &output);
4309 output_event = output.file->private_data;
4310 ret = perf_event_set_output(event, output_event);
4313 ret = perf_event_set_output(event, NULL);
4318 case PERF_EVENT_IOC_SET_FILTER:
4319 return perf_event_set_filter(event, (void __user *)arg);
4321 case PERF_EVENT_IOC_SET_BPF:
4322 return perf_event_set_bpf_prog(event, arg);
4328 if (flags & PERF_IOC_FLAG_GROUP)
4329 perf_event_for_each(event, func);
4331 perf_event_for_each_child(event, func);
4336 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4338 struct perf_event *event = file->private_data;
4339 struct perf_event_context *ctx;
4342 ctx = perf_event_ctx_lock(event);
4343 ret = _perf_ioctl(event, cmd, arg);
4344 perf_event_ctx_unlock(event, ctx);
4349 #ifdef CONFIG_COMPAT
4350 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4353 switch (_IOC_NR(cmd)) {
4354 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4355 case _IOC_NR(PERF_EVENT_IOC_ID):
4356 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4357 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4358 cmd &= ~IOCSIZE_MASK;
4359 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4363 return perf_ioctl(file, cmd, arg);
4366 # define perf_compat_ioctl NULL
4369 int perf_event_task_enable(void)
4371 struct perf_event_context *ctx;
4372 struct perf_event *event;
4374 mutex_lock(¤t->perf_event_mutex);
4375 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4376 ctx = perf_event_ctx_lock(event);
4377 perf_event_for_each_child(event, _perf_event_enable);
4378 perf_event_ctx_unlock(event, ctx);
4380 mutex_unlock(¤t->perf_event_mutex);
4385 int perf_event_task_disable(void)
4387 struct perf_event_context *ctx;
4388 struct perf_event *event;
4390 mutex_lock(¤t->perf_event_mutex);
4391 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4392 ctx = perf_event_ctx_lock(event);
4393 perf_event_for_each_child(event, _perf_event_disable);
4394 perf_event_ctx_unlock(event, ctx);
4396 mutex_unlock(¤t->perf_event_mutex);
4401 static int perf_event_index(struct perf_event *event)
4403 if (event->hw.state & PERF_HES_STOPPED)
4406 if (event->state != PERF_EVENT_STATE_ACTIVE)
4409 return event->pmu->event_idx(event);
4412 static void calc_timer_values(struct perf_event *event,
4419 *now = perf_clock();
4420 ctx_time = event->shadow_ctx_time + *now;
4421 *enabled = ctx_time - event->tstamp_enabled;
4422 *running = ctx_time - event->tstamp_running;
4425 static void perf_event_init_userpage(struct perf_event *event)
4427 struct perf_event_mmap_page *userpg;
4428 struct ring_buffer *rb;
4431 rb = rcu_dereference(event->rb);
4435 userpg = rb->user_page;
4437 /* Allow new userspace to detect that bit 0 is deprecated */
4438 userpg->cap_bit0_is_deprecated = 1;
4439 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4440 userpg->data_offset = PAGE_SIZE;
4441 userpg->data_size = perf_data_size(rb);
4447 void __weak arch_perf_update_userpage(
4448 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4453 * Callers need to ensure there can be no nesting of this function, otherwise
4454 * the seqlock logic goes bad. We can not serialize this because the arch
4455 * code calls this from NMI context.
4457 void perf_event_update_userpage(struct perf_event *event)
4459 struct perf_event_mmap_page *userpg;
4460 struct ring_buffer *rb;
4461 u64 enabled, running, now;
4464 rb = rcu_dereference(event->rb);
4469 * compute total_time_enabled, total_time_running
4470 * based on snapshot values taken when the event
4471 * was last scheduled in.
4473 * we cannot simply called update_context_time()
4474 * because of locking issue as we can be called in
4477 calc_timer_values(event, &now, &enabled, &running);
4479 userpg = rb->user_page;
4481 * Disable preemption so as to not let the corresponding user-space
4482 * spin too long if we get preempted.
4487 userpg->index = perf_event_index(event);
4488 userpg->offset = perf_event_count(event);
4490 userpg->offset -= local64_read(&event->hw.prev_count);
4492 userpg->time_enabled = enabled +
4493 atomic64_read(&event->child_total_time_enabled);
4495 userpg->time_running = running +
4496 atomic64_read(&event->child_total_time_running);
4498 arch_perf_update_userpage(event, userpg, now);
4507 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4509 struct perf_event *event = vma->vm_file->private_data;
4510 struct ring_buffer *rb;
4511 int ret = VM_FAULT_SIGBUS;
4513 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4514 if (vmf->pgoff == 0)
4520 rb = rcu_dereference(event->rb);
4524 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4527 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4531 get_page(vmf->page);
4532 vmf->page->mapping = vma->vm_file->f_mapping;
4533 vmf->page->index = vmf->pgoff;
4542 static void ring_buffer_attach(struct perf_event *event,
4543 struct ring_buffer *rb)
4545 struct ring_buffer *old_rb = NULL;
4546 unsigned long flags;
4550 * Should be impossible, we set this when removing
4551 * event->rb_entry and wait/clear when adding event->rb_entry.
4553 WARN_ON_ONCE(event->rcu_pending);
4556 spin_lock_irqsave(&old_rb->event_lock, flags);
4557 list_del_rcu(&event->rb_entry);
4558 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4560 event->rcu_batches = get_state_synchronize_rcu();
4561 event->rcu_pending = 1;
4565 if (event->rcu_pending) {
4566 cond_synchronize_rcu(event->rcu_batches);
4567 event->rcu_pending = 0;
4570 spin_lock_irqsave(&rb->event_lock, flags);
4571 list_add_rcu(&event->rb_entry, &rb->event_list);
4572 spin_unlock_irqrestore(&rb->event_lock, flags);
4575 rcu_assign_pointer(event->rb, rb);
4578 ring_buffer_put(old_rb);
4580 * Since we detached before setting the new rb, so that we
4581 * could attach the new rb, we could have missed a wakeup.
4584 wake_up_all(&event->waitq);
4588 static void ring_buffer_wakeup(struct perf_event *event)
4590 struct ring_buffer *rb;
4593 rb = rcu_dereference(event->rb);
4595 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4596 wake_up_all(&event->waitq);
4601 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4603 struct ring_buffer *rb;
4606 rb = rcu_dereference(event->rb);
4608 if (!atomic_inc_not_zero(&rb->refcount))
4616 void ring_buffer_put(struct ring_buffer *rb)
4618 if (!atomic_dec_and_test(&rb->refcount))
4621 WARN_ON_ONCE(!list_empty(&rb->event_list));
4623 call_rcu(&rb->rcu_head, rb_free_rcu);
4626 static void perf_mmap_open(struct vm_area_struct *vma)
4628 struct perf_event *event = vma->vm_file->private_data;
4630 atomic_inc(&event->mmap_count);
4631 atomic_inc(&event->rb->mmap_count);
4634 atomic_inc(&event->rb->aux_mmap_count);
4636 if (event->pmu->event_mapped)
4637 event->pmu->event_mapped(event);
4641 * A buffer can be mmap()ed multiple times; either directly through the same
4642 * event, or through other events by use of perf_event_set_output().
4644 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4645 * the buffer here, where we still have a VM context. This means we need
4646 * to detach all events redirecting to us.
4648 static void perf_mmap_close(struct vm_area_struct *vma)
4650 struct perf_event *event = vma->vm_file->private_data;
4652 struct ring_buffer *rb = ring_buffer_get(event);
4653 struct user_struct *mmap_user = rb->mmap_user;
4654 int mmap_locked = rb->mmap_locked;
4655 unsigned long size = perf_data_size(rb);
4657 if (event->pmu->event_unmapped)
4658 event->pmu->event_unmapped(event);
4661 * rb->aux_mmap_count will always drop before rb->mmap_count and
4662 * event->mmap_count, so it is ok to use event->mmap_mutex to
4663 * serialize with perf_mmap here.
4665 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4666 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4667 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4668 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4671 mutex_unlock(&event->mmap_mutex);
4674 atomic_dec(&rb->mmap_count);
4676 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4679 ring_buffer_attach(event, NULL);
4680 mutex_unlock(&event->mmap_mutex);
4682 /* If there's still other mmap()s of this buffer, we're done. */
4683 if (atomic_read(&rb->mmap_count))
4687 * No other mmap()s, detach from all other events that might redirect
4688 * into the now unreachable buffer. Somewhat complicated by the
4689 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4693 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4694 if (!atomic_long_inc_not_zero(&event->refcount)) {
4696 * This event is en-route to free_event() which will
4697 * detach it and remove it from the list.
4703 mutex_lock(&event->mmap_mutex);
4705 * Check we didn't race with perf_event_set_output() which can
4706 * swizzle the rb from under us while we were waiting to
4707 * acquire mmap_mutex.
4709 * If we find a different rb; ignore this event, a next
4710 * iteration will no longer find it on the list. We have to
4711 * still restart the iteration to make sure we're not now
4712 * iterating the wrong list.
4714 if (event->rb == rb)
4715 ring_buffer_attach(event, NULL);
4717 mutex_unlock(&event->mmap_mutex);
4721 * Restart the iteration; either we're on the wrong list or
4722 * destroyed its integrity by doing a deletion.
4729 * It could be there's still a few 0-ref events on the list; they'll
4730 * get cleaned up by free_event() -- they'll also still have their
4731 * ref on the rb and will free it whenever they are done with it.
4733 * Aside from that, this buffer is 'fully' detached and unmapped,
4734 * undo the VM accounting.
4737 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4738 vma->vm_mm->pinned_vm -= mmap_locked;
4739 free_uid(mmap_user);
4742 ring_buffer_put(rb); /* could be last */
4745 static const struct vm_operations_struct perf_mmap_vmops = {
4746 .open = perf_mmap_open,
4747 .close = perf_mmap_close, /* non mergable */
4748 .fault = perf_mmap_fault,
4749 .page_mkwrite = perf_mmap_fault,
4752 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4754 struct perf_event *event = file->private_data;
4755 unsigned long user_locked, user_lock_limit;
4756 struct user_struct *user = current_user();
4757 unsigned long locked, lock_limit;
4758 struct ring_buffer *rb = NULL;
4759 unsigned long vma_size;
4760 unsigned long nr_pages;
4761 long user_extra = 0, extra = 0;
4762 int ret = 0, flags = 0;
4765 * Don't allow mmap() of inherited per-task counters. This would
4766 * create a performance issue due to all children writing to the
4769 if (event->cpu == -1 && event->attr.inherit)
4772 if (!(vma->vm_flags & VM_SHARED))
4775 vma_size = vma->vm_end - vma->vm_start;
4777 if (vma->vm_pgoff == 0) {
4778 nr_pages = (vma_size / PAGE_SIZE) - 1;
4781 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4782 * mapped, all subsequent mappings should have the same size
4783 * and offset. Must be above the normal perf buffer.
4785 u64 aux_offset, aux_size;
4790 nr_pages = vma_size / PAGE_SIZE;
4792 mutex_lock(&event->mmap_mutex);
4799 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4800 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4802 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4805 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4808 /* already mapped with a different offset */
4809 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4812 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4815 /* already mapped with a different size */
4816 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4819 if (!is_power_of_2(nr_pages))
4822 if (!atomic_inc_not_zero(&rb->mmap_count))
4825 if (rb_has_aux(rb)) {
4826 atomic_inc(&rb->aux_mmap_count);
4831 atomic_set(&rb->aux_mmap_count, 1);
4832 user_extra = nr_pages;
4838 * If we have rb pages ensure they're a power-of-two number, so we
4839 * can do bitmasks instead of modulo.
4841 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4844 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4847 WARN_ON_ONCE(event->ctx->parent_ctx);
4849 mutex_lock(&event->mmap_mutex);
4851 if (event->rb->nr_pages != nr_pages) {
4856 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4858 * Raced against perf_mmap_close() through
4859 * perf_event_set_output(). Try again, hope for better
4862 mutex_unlock(&event->mmap_mutex);
4869 user_extra = nr_pages + 1;
4872 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4875 * Increase the limit linearly with more CPUs:
4877 user_lock_limit *= num_online_cpus();
4879 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4881 if (user_locked > user_lock_limit)
4882 extra = user_locked - user_lock_limit;
4884 lock_limit = rlimit(RLIMIT_MEMLOCK);
4885 lock_limit >>= PAGE_SHIFT;
4886 locked = vma->vm_mm->pinned_vm + extra;
4888 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4889 !capable(CAP_IPC_LOCK)) {
4894 WARN_ON(!rb && event->rb);
4896 if (vma->vm_flags & VM_WRITE)
4897 flags |= RING_BUFFER_WRITABLE;
4900 rb = rb_alloc(nr_pages,
4901 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4909 atomic_set(&rb->mmap_count, 1);
4910 rb->mmap_user = get_current_user();
4911 rb->mmap_locked = extra;
4913 ring_buffer_attach(event, rb);
4915 perf_event_init_userpage(event);
4916 perf_event_update_userpage(event);
4918 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4919 event->attr.aux_watermark, flags);
4921 rb->aux_mmap_locked = extra;
4926 atomic_long_add(user_extra, &user->locked_vm);
4927 vma->vm_mm->pinned_vm += extra;
4929 atomic_inc(&event->mmap_count);
4931 atomic_dec(&rb->mmap_count);
4934 mutex_unlock(&event->mmap_mutex);
4937 * Since pinned accounting is per vm we cannot allow fork() to copy our
4940 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4941 vma->vm_ops = &perf_mmap_vmops;
4943 if (event->pmu->event_mapped)
4944 event->pmu->event_mapped(event);
4949 static int perf_fasync(int fd, struct file *filp, int on)
4951 struct inode *inode = file_inode(filp);
4952 struct perf_event *event = filp->private_data;
4955 mutex_lock(&inode->i_mutex);
4956 retval = fasync_helper(fd, filp, on, &event->fasync);
4957 mutex_unlock(&inode->i_mutex);
4965 static const struct file_operations perf_fops = {
4966 .llseek = no_llseek,
4967 .release = perf_release,
4970 .unlocked_ioctl = perf_ioctl,
4971 .compat_ioctl = perf_compat_ioctl,
4973 .fasync = perf_fasync,
4979 * If there's data, ensure we set the poll() state and publish everything
4980 * to user-space before waking everybody up.
4983 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4985 /* only the parent has fasync state */
4987 event = event->parent;
4988 return &event->fasync;
4991 void perf_event_wakeup(struct perf_event *event)
4993 ring_buffer_wakeup(event);
4995 if (event->pending_kill) {
4996 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
4997 event->pending_kill = 0;
5001 static void perf_pending_event(struct irq_work *entry)
5003 struct perf_event *event = container_of(entry,
5004 struct perf_event, pending);
5007 rctx = perf_swevent_get_recursion_context();
5009 * If we 'fail' here, that's OK, it means recursion is already disabled
5010 * and we won't recurse 'further'.
5013 if (event->pending_disable) {
5014 event->pending_disable = 0;
5015 __perf_event_disable(event);
5018 if (event->pending_wakeup) {
5019 event->pending_wakeup = 0;
5020 perf_event_wakeup(event);
5024 perf_swevent_put_recursion_context(rctx);
5028 * We assume there is only KVM supporting the callbacks.
5029 * Later on, we might change it to a list if there is
5030 * another virtualization implementation supporting the callbacks.
5032 struct perf_guest_info_callbacks *perf_guest_cbs;
5034 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5036 perf_guest_cbs = cbs;
5039 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5041 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5043 perf_guest_cbs = NULL;
5046 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5049 perf_output_sample_regs(struct perf_output_handle *handle,
5050 struct pt_regs *regs, u64 mask)
5054 for_each_set_bit(bit, (const unsigned long *) &mask,
5055 sizeof(mask) * BITS_PER_BYTE) {
5058 val = perf_reg_value(regs, bit);
5059 perf_output_put(handle, val);
5063 static void perf_sample_regs_user(struct perf_regs *regs_user,
5064 struct pt_regs *regs,
5065 struct pt_regs *regs_user_copy)
5067 if (user_mode(regs)) {
5068 regs_user->abi = perf_reg_abi(current);
5069 regs_user->regs = regs;
5070 } else if (current->mm) {
5071 perf_get_regs_user(regs_user, regs, regs_user_copy);
5073 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5074 regs_user->regs = NULL;
5078 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5079 struct pt_regs *regs)
5081 regs_intr->regs = regs;
5082 regs_intr->abi = perf_reg_abi(current);
5087 * Get remaining task size from user stack pointer.
5089 * It'd be better to take stack vma map and limit this more
5090 * precisly, but there's no way to get it safely under interrupt,
5091 * so using TASK_SIZE as limit.
5093 static u64 perf_ustack_task_size(struct pt_regs *regs)
5095 unsigned long addr = perf_user_stack_pointer(regs);
5097 if (!addr || addr >= TASK_SIZE)
5100 return TASK_SIZE - addr;
5104 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5105 struct pt_regs *regs)
5109 /* No regs, no stack pointer, no dump. */
5114 * Check if we fit in with the requested stack size into the:
5116 * If we don't, we limit the size to the TASK_SIZE.
5118 * - remaining sample size
5119 * If we don't, we customize the stack size to
5120 * fit in to the remaining sample size.
5123 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5124 stack_size = min(stack_size, (u16) task_size);
5126 /* Current header size plus static size and dynamic size. */
5127 header_size += 2 * sizeof(u64);
5129 /* Do we fit in with the current stack dump size? */
5130 if ((u16) (header_size + stack_size) < header_size) {
5132 * If we overflow the maximum size for the sample,
5133 * we customize the stack dump size to fit in.
5135 stack_size = USHRT_MAX - header_size - sizeof(u64);
5136 stack_size = round_up(stack_size, sizeof(u64));
5143 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5144 struct pt_regs *regs)
5146 /* Case of a kernel thread, nothing to dump */
5149 perf_output_put(handle, size);
5158 * - the size requested by user or the best one we can fit
5159 * in to the sample max size
5161 * - user stack dump data
5163 * - the actual dumped size
5167 perf_output_put(handle, dump_size);
5170 sp = perf_user_stack_pointer(regs);
5171 rem = __output_copy_user(handle, (void *) sp, dump_size);
5172 dyn_size = dump_size - rem;
5174 perf_output_skip(handle, rem);
5177 perf_output_put(handle, dyn_size);
5181 static void __perf_event_header__init_id(struct perf_event_header *header,
5182 struct perf_sample_data *data,
5183 struct perf_event *event)
5185 u64 sample_type = event->attr.sample_type;
5187 data->type = sample_type;
5188 header->size += event->id_header_size;
5190 if (sample_type & PERF_SAMPLE_TID) {
5191 /* namespace issues */
5192 data->tid_entry.pid = perf_event_pid(event, current);
5193 data->tid_entry.tid = perf_event_tid(event, current);
5196 if (sample_type & PERF_SAMPLE_TIME)
5197 data->time = perf_event_clock(event);
5199 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5200 data->id = primary_event_id(event);
5202 if (sample_type & PERF_SAMPLE_STREAM_ID)
5203 data->stream_id = event->id;
5205 if (sample_type & PERF_SAMPLE_CPU) {
5206 data->cpu_entry.cpu = raw_smp_processor_id();
5207 data->cpu_entry.reserved = 0;
5211 void perf_event_header__init_id(struct perf_event_header *header,
5212 struct perf_sample_data *data,
5213 struct perf_event *event)
5215 if (event->attr.sample_id_all)
5216 __perf_event_header__init_id(header, data, event);
5219 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5220 struct perf_sample_data *data)
5222 u64 sample_type = data->type;
5224 if (sample_type & PERF_SAMPLE_TID)
5225 perf_output_put(handle, data->tid_entry);
5227 if (sample_type & PERF_SAMPLE_TIME)
5228 perf_output_put(handle, data->time);
5230 if (sample_type & PERF_SAMPLE_ID)
5231 perf_output_put(handle, data->id);
5233 if (sample_type & PERF_SAMPLE_STREAM_ID)
5234 perf_output_put(handle, data->stream_id);
5236 if (sample_type & PERF_SAMPLE_CPU)
5237 perf_output_put(handle, data->cpu_entry);
5239 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5240 perf_output_put(handle, data->id);
5243 void perf_event__output_id_sample(struct perf_event *event,
5244 struct perf_output_handle *handle,
5245 struct perf_sample_data *sample)
5247 if (event->attr.sample_id_all)
5248 __perf_event__output_id_sample(handle, sample);
5251 static void perf_output_read_one(struct perf_output_handle *handle,
5252 struct perf_event *event,
5253 u64 enabled, u64 running)
5255 u64 read_format = event->attr.read_format;
5259 values[n++] = perf_event_count(event);
5260 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5261 values[n++] = enabled +
5262 atomic64_read(&event->child_total_time_enabled);
5264 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5265 values[n++] = running +
5266 atomic64_read(&event->child_total_time_running);
5268 if (read_format & PERF_FORMAT_ID)
5269 values[n++] = primary_event_id(event);
5271 __output_copy(handle, values, n * sizeof(u64));
5275 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5277 static void perf_output_read_group(struct perf_output_handle *handle,
5278 struct perf_event *event,
5279 u64 enabled, u64 running)
5281 struct perf_event *leader = event->group_leader, *sub;
5282 u64 read_format = event->attr.read_format;
5286 values[n++] = 1 + leader->nr_siblings;
5288 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5289 values[n++] = enabled;
5291 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5292 values[n++] = running;
5294 if (leader != event)
5295 leader->pmu->read(leader);
5297 values[n++] = perf_event_count(leader);
5298 if (read_format & PERF_FORMAT_ID)
5299 values[n++] = primary_event_id(leader);
5301 __output_copy(handle, values, n * sizeof(u64));
5303 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5306 if ((sub != event) &&
5307 (sub->state == PERF_EVENT_STATE_ACTIVE))
5308 sub->pmu->read(sub);
5310 values[n++] = perf_event_count(sub);
5311 if (read_format & PERF_FORMAT_ID)
5312 values[n++] = primary_event_id(sub);
5314 __output_copy(handle, values, n * sizeof(u64));
5318 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5319 PERF_FORMAT_TOTAL_TIME_RUNNING)
5321 static void perf_output_read(struct perf_output_handle *handle,
5322 struct perf_event *event)
5324 u64 enabled = 0, running = 0, now;
5325 u64 read_format = event->attr.read_format;
5328 * compute total_time_enabled, total_time_running
5329 * based on snapshot values taken when the event
5330 * was last scheduled in.
5332 * we cannot simply called update_context_time()
5333 * because of locking issue as we are called in
5336 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5337 calc_timer_values(event, &now, &enabled, &running);
5339 if (event->attr.read_format & PERF_FORMAT_GROUP)
5340 perf_output_read_group(handle, event, enabled, running);
5342 perf_output_read_one(handle, event, enabled, running);
5345 void perf_output_sample(struct perf_output_handle *handle,
5346 struct perf_event_header *header,
5347 struct perf_sample_data *data,
5348 struct perf_event *event)
5350 u64 sample_type = data->type;
5352 perf_output_put(handle, *header);
5354 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5355 perf_output_put(handle, data->id);
5357 if (sample_type & PERF_SAMPLE_IP)
5358 perf_output_put(handle, data->ip);
5360 if (sample_type & PERF_SAMPLE_TID)
5361 perf_output_put(handle, data->tid_entry);
5363 if (sample_type & PERF_SAMPLE_TIME)
5364 perf_output_put(handle, data->time);
5366 if (sample_type & PERF_SAMPLE_ADDR)
5367 perf_output_put(handle, data->addr);
5369 if (sample_type & PERF_SAMPLE_ID)
5370 perf_output_put(handle, data->id);
5372 if (sample_type & PERF_SAMPLE_STREAM_ID)
5373 perf_output_put(handle, data->stream_id);
5375 if (sample_type & PERF_SAMPLE_CPU)
5376 perf_output_put(handle, data->cpu_entry);
5378 if (sample_type & PERF_SAMPLE_PERIOD)
5379 perf_output_put(handle, data->period);
5381 if (sample_type & PERF_SAMPLE_READ)
5382 perf_output_read(handle, event);
5384 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5385 if (data->callchain) {
5388 if (data->callchain)
5389 size += data->callchain->nr;
5391 size *= sizeof(u64);
5393 __output_copy(handle, data->callchain, size);
5396 perf_output_put(handle, nr);
5400 if (sample_type & PERF_SAMPLE_RAW) {
5402 u32 raw_size = data->raw->size;
5403 u32 real_size = round_up(raw_size + sizeof(u32),
5404 sizeof(u64)) - sizeof(u32);
5407 perf_output_put(handle, real_size);
5408 __output_copy(handle, data->raw->data, raw_size);
5409 if (real_size - raw_size)
5410 __output_copy(handle, &zero, real_size - raw_size);
5416 .size = sizeof(u32),
5419 perf_output_put(handle, raw);
5423 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5424 if (data->br_stack) {
5427 size = data->br_stack->nr
5428 * sizeof(struct perf_branch_entry);
5430 perf_output_put(handle, data->br_stack->nr);
5431 perf_output_copy(handle, data->br_stack->entries, size);
5434 * we always store at least the value of nr
5437 perf_output_put(handle, nr);
5441 if (sample_type & PERF_SAMPLE_REGS_USER) {
5442 u64 abi = data->regs_user.abi;
5445 * If there are no regs to dump, notice it through
5446 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5448 perf_output_put(handle, abi);
5451 u64 mask = event->attr.sample_regs_user;
5452 perf_output_sample_regs(handle,
5453 data->regs_user.regs,
5458 if (sample_type & PERF_SAMPLE_STACK_USER) {
5459 perf_output_sample_ustack(handle,
5460 data->stack_user_size,
5461 data->regs_user.regs);
5464 if (sample_type & PERF_SAMPLE_WEIGHT)
5465 perf_output_put(handle, data->weight);
5467 if (sample_type & PERF_SAMPLE_DATA_SRC)
5468 perf_output_put(handle, data->data_src.val);
5470 if (sample_type & PERF_SAMPLE_TRANSACTION)
5471 perf_output_put(handle, data->txn);
5473 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5474 u64 abi = data->regs_intr.abi;
5476 * If there are no regs to dump, notice it through
5477 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5479 perf_output_put(handle, abi);
5482 u64 mask = event->attr.sample_regs_intr;
5484 perf_output_sample_regs(handle,
5485 data->regs_intr.regs,
5490 if (!event->attr.watermark) {
5491 int wakeup_events = event->attr.wakeup_events;
5493 if (wakeup_events) {
5494 struct ring_buffer *rb = handle->rb;
5495 int events = local_inc_return(&rb->events);
5497 if (events >= wakeup_events) {
5498 local_sub(wakeup_events, &rb->events);
5499 local_inc(&rb->wakeup);
5505 void perf_prepare_sample(struct perf_event_header *header,
5506 struct perf_sample_data *data,
5507 struct perf_event *event,
5508 struct pt_regs *regs)
5510 u64 sample_type = event->attr.sample_type;
5512 header->type = PERF_RECORD_SAMPLE;
5513 header->size = sizeof(*header) + event->header_size;
5516 header->misc |= perf_misc_flags(regs);
5518 __perf_event_header__init_id(header, data, event);
5520 if (sample_type & PERF_SAMPLE_IP)
5521 data->ip = perf_instruction_pointer(regs);
5523 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5526 data->callchain = perf_callchain(event, regs);
5528 if (data->callchain)
5529 size += data->callchain->nr;
5531 header->size += size * sizeof(u64);
5534 if (sample_type & PERF_SAMPLE_RAW) {
5535 int size = sizeof(u32);
5538 size += data->raw->size;
5540 size += sizeof(u32);
5542 header->size += round_up(size, sizeof(u64));
5545 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5546 int size = sizeof(u64); /* nr */
5547 if (data->br_stack) {
5548 size += data->br_stack->nr
5549 * sizeof(struct perf_branch_entry);
5551 header->size += size;
5554 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5555 perf_sample_regs_user(&data->regs_user, regs,
5556 &data->regs_user_copy);
5558 if (sample_type & PERF_SAMPLE_REGS_USER) {
5559 /* regs dump ABI info */
5560 int size = sizeof(u64);
5562 if (data->regs_user.regs) {
5563 u64 mask = event->attr.sample_regs_user;
5564 size += hweight64(mask) * sizeof(u64);
5567 header->size += size;
5570 if (sample_type & PERF_SAMPLE_STACK_USER) {
5572 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5573 * processed as the last one or have additional check added
5574 * in case new sample type is added, because we could eat
5575 * up the rest of the sample size.
5577 u16 stack_size = event->attr.sample_stack_user;
5578 u16 size = sizeof(u64);
5580 stack_size = perf_sample_ustack_size(stack_size, header->size,
5581 data->regs_user.regs);
5584 * If there is something to dump, add space for the dump
5585 * itself and for the field that tells the dynamic size,
5586 * which is how many have been actually dumped.
5589 size += sizeof(u64) + stack_size;
5591 data->stack_user_size = stack_size;
5592 header->size += size;
5595 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5596 /* regs dump ABI info */
5597 int size = sizeof(u64);
5599 perf_sample_regs_intr(&data->regs_intr, regs);
5601 if (data->regs_intr.regs) {
5602 u64 mask = event->attr.sample_regs_intr;
5604 size += hweight64(mask) * sizeof(u64);
5607 header->size += size;
5611 void perf_event_output(struct perf_event *event,
5612 struct perf_sample_data *data,
5613 struct pt_regs *regs)
5615 struct perf_output_handle handle;
5616 struct perf_event_header header;
5618 /* protect the callchain buffers */
5621 perf_prepare_sample(&header, data, event, regs);
5623 if (perf_output_begin(&handle, event, header.size))
5626 perf_output_sample(&handle, &header, data, event);
5628 perf_output_end(&handle);
5638 struct perf_read_event {
5639 struct perf_event_header header;
5646 perf_event_read_event(struct perf_event *event,
5647 struct task_struct *task)
5649 struct perf_output_handle handle;
5650 struct perf_sample_data sample;
5651 struct perf_read_event read_event = {
5653 .type = PERF_RECORD_READ,
5655 .size = sizeof(read_event) + event->read_size,
5657 .pid = perf_event_pid(event, task),
5658 .tid = perf_event_tid(event, task),
5662 perf_event_header__init_id(&read_event.header, &sample, event);
5663 ret = perf_output_begin(&handle, event, read_event.header.size);
5667 perf_output_put(&handle, read_event);
5668 perf_output_read(&handle, event);
5669 perf_event__output_id_sample(event, &handle, &sample);
5671 perf_output_end(&handle);
5674 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5677 perf_event_aux_ctx(struct perf_event_context *ctx,
5678 perf_event_aux_output_cb output,
5681 struct perf_event *event;
5683 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5684 if (event->state < PERF_EVENT_STATE_INACTIVE)
5686 if (!event_filter_match(event))
5688 output(event, data);
5693 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5694 struct perf_event_context *task_ctx)
5698 perf_event_aux_ctx(task_ctx, output, data);
5704 perf_event_aux(perf_event_aux_output_cb output, void *data,
5705 struct perf_event_context *task_ctx)
5707 struct perf_cpu_context *cpuctx;
5708 struct perf_event_context *ctx;
5713 * If we have task_ctx != NULL we only notify
5714 * the task context itself. The task_ctx is set
5715 * only for EXIT events before releasing task
5719 perf_event_aux_task_ctx(output, data, task_ctx);
5724 list_for_each_entry_rcu(pmu, &pmus, entry) {
5725 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5726 if (cpuctx->unique_pmu != pmu)
5728 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5729 ctxn = pmu->task_ctx_nr;
5732 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5734 perf_event_aux_ctx(ctx, output, data);
5736 put_cpu_ptr(pmu->pmu_cpu_context);
5742 * task tracking -- fork/exit
5744 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5747 struct perf_task_event {
5748 struct task_struct *task;
5749 struct perf_event_context *task_ctx;
5752 struct perf_event_header header;
5762 static int perf_event_task_match(struct perf_event *event)
5764 return event->attr.comm || event->attr.mmap ||
5765 event->attr.mmap2 || event->attr.mmap_data ||
5769 static void perf_event_task_output(struct perf_event *event,
5772 struct perf_task_event *task_event = data;
5773 struct perf_output_handle handle;
5774 struct perf_sample_data sample;
5775 struct task_struct *task = task_event->task;
5776 int ret, size = task_event->event_id.header.size;
5778 if (!perf_event_task_match(event))
5781 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5783 ret = perf_output_begin(&handle, event,
5784 task_event->event_id.header.size);
5788 task_event->event_id.pid = perf_event_pid(event, task);
5789 task_event->event_id.ppid = perf_event_pid(event, current);
5791 task_event->event_id.tid = perf_event_tid(event, task);
5792 task_event->event_id.ptid = perf_event_tid(event, current);
5794 task_event->event_id.time = perf_event_clock(event);
5796 perf_output_put(&handle, task_event->event_id);
5798 perf_event__output_id_sample(event, &handle, &sample);
5800 perf_output_end(&handle);
5802 task_event->event_id.header.size = size;
5805 static void perf_event_task(struct task_struct *task,
5806 struct perf_event_context *task_ctx,
5809 struct perf_task_event task_event;
5811 if (!atomic_read(&nr_comm_events) &&
5812 !atomic_read(&nr_mmap_events) &&
5813 !atomic_read(&nr_task_events))
5816 task_event = (struct perf_task_event){
5818 .task_ctx = task_ctx,
5821 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5823 .size = sizeof(task_event.event_id),
5833 perf_event_aux(perf_event_task_output,
5838 void perf_event_fork(struct task_struct *task)
5840 perf_event_task(task, NULL, 1);
5847 struct perf_comm_event {
5848 struct task_struct *task;
5853 struct perf_event_header header;
5860 static int perf_event_comm_match(struct perf_event *event)
5862 return event->attr.comm;
5865 static void perf_event_comm_output(struct perf_event *event,
5868 struct perf_comm_event *comm_event = data;
5869 struct perf_output_handle handle;
5870 struct perf_sample_data sample;
5871 int size = comm_event->event_id.header.size;
5874 if (!perf_event_comm_match(event))
5877 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5878 ret = perf_output_begin(&handle, event,
5879 comm_event->event_id.header.size);
5884 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5885 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5887 perf_output_put(&handle, comm_event->event_id);
5888 __output_copy(&handle, comm_event->comm,
5889 comm_event->comm_size);
5891 perf_event__output_id_sample(event, &handle, &sample);
5893 perf_output_end(&handle);
5895 comm_event->event_id.header.size = size;
5898 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5900 char comm[TASK_COMM_LEN];
5903 memset(comm, 0, sizeof(comm));
5904 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5905 size = ALIGN(strlen(comm)+1, sizeof(u64));
5907 comm_event->comm = comm;
5908 comm_event->comm_size = size;
5910 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5912 perf_event_aux(perf_event_comm_output,
5917 void perf_event_comm(struct task_struct *task, bool exec)
5919 struct perf_comm_event comm_event;
5921 if (!atomic_read(&nr_comm_events))
5924 comm_event = (struct perf_comm_event){
5930 .type = PERF_RECORD_COMM,
5931 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5939 perf_event_comm_event(&comm_event);
5946 struct perf_mmap_event {
5947 struct vm_area_struct *vma;
5949 const char *file_name;
5957 struct perf_event_header header;
5967 static int perf_event_mmap_match(struct perf_event *event,
5970 struct perf_mmap_event *mmap_event = data;
5971 struct vm_area_struct *vma = mmap_event->vma;
5972 int executable = vma->vm_flags & VM_EXEC;
5974 return (!executable && event->attr.mmap_data) ||
5975 (executable && (event->attr.mmap || event->attr.mmap2));
5978 static void perf_event_mmap_output(struct perf_event *event,
5981 struct perf_mmap_event *mmap_event = data;
5982 struct perf_output_handle handle;
5983 struct perf_sample_data sample;
5984 int size = mmap_event->event_id.header.size;
5987 if (!perf_event_mmap_match(event, data))
5990 if (event->attr.mmap2) {
5991 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5992 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5993 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5994 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5995 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5996 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5997 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6000 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6001 ret = perf_output_begin(&handle, event,
6002 mmap_event->event_id.header.size);
6006 mmap_event->event_id.pid = perf_event_pid(event, current);
6007 mmap_event->event_id.tid = perf_event_tid(event, current);
6009 perf_output_put(&handle, mmap_event->event_id);
6011 if (event->attr.mmap2) {
6012 perf_output_put(&handle, mmap_event->maj);
6013 perf_output_put(&handle, mmap_event->min);
6014 perf_output_put(&handle, mmap_event->ino);
6015 perf_output_put(&handle, mmap_event->ino_generation);
6016 perf_output_put(&handle, mmap_event->prot);
6017 perf_output_put(&handle, mmap_event->flags);
6020 __output_copy(&handle, mmap_event->file_name,
6021 mmap_event->file_size);
6023 perf_event__output_id_sample(event, &handle, &sample);
6025 perf_output_end(&handle);
6027 mmap_event->event_id.header.size = size;
6030 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6032 struct vm_area_struct *vma = mmap_event->vma;
6033 struct file *file = vma->vm_file;
6034 int maj = 0, min = 0;
6035 u64 ino = 0, gen = 0;
6036 u32 prot = 0, flags = 0;
6042 if (vma->vm_flags & VM_READ)
6044 if (vma->vm_flags & VM_WRITE)
6046 if (vma->vm_flags & VM_EXEC)
6049 if (vma->vm_flags & VM_MAYSHARE)
6052 flags = MAP_PRIVATE;
6054 if (vma->vm_flags & VM_DENYWRITE)
6055 flags |= MAP_DENYWRITE;
6056 if (vma->vm_flags & VM_MAYEXEC)
6057 flags |= MAP_EXECUTABLE;
6058 if (vma->vm_flags & VM_LOCKED)
6059 flags |= MAP_LOCKED;
6060 if (vma->vm_flags & VM_HUGETLB)
6061 flags |= MAP_HUGETLB;
6064 struct inode *inode;
6067 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6073 * d_path() works from the end of the rb backwards, so we
6074 * need to add enough zero bytes after the string to handle
6075 * the 64bit alignment we do later.
6077 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6082 inode = file_inode(vma->vm_file);
6083 dev = inode->i_sb->s_dev;
6085 gen = inode->i_generation;
6091 if (vma->vm_ops && vma->vm_ops->name) {
6092 name = (char *) vma->vm_ops->name(vma);
6097 name = (char *)arch_vma_name(vma);
6101 if (vma->vm_start <= vma->vm_mm->start_brk &&
6102 vma->vm_end >= vma->vm_mm->brk) {
6106 if (vma->vm_start <= vma->vm_mm->start_stack &&
6107 vma->vm_end >= vma->vm_mm->start_stack) {
6117 strlcpy(tmp, name, sizeof(tmp));
6121 * Since our buffer works in 8 byte units we need to align our string
6122 * size to a multiple of 8. However, we must guarantee the tail end is
6123 * zero'd out to avoid leaking random bits to userspace.
6125 size = strlen(name)+1;
6126 while (!IS_ALIGNED(size, sizeof(u64)))
6127 name[size++] = '\0';
6129 mmap_event->file_name = name;
6130 mmap_event->file_size = size;
6131 mmap_event->maj = maj;
6132 mmap_event->min = min;
6133 mmap_event->ino = ino;
6134 mmap_event->ino_generation = gen;
6135 mmap_event->prot = prot;
6136 mmap_event->flags = flags;
6138 if (!(vma->vm_flags & VM_EXEC))
6139 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6141 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6143 perf_event_aux(perf_event_mmap_output,
6150 void perf_event_mmap(struct vm_area_struct *vma)
6152 struct perf_mmap_event mmap_event;
6154 if (!atomic_read(&nr_mmap_events))
6157 mmap_event = (struct perf_mmap_event){
6163 .type = PERF_RECORD_MMAP,
6164 .misc = PERF_RECORD_MISC_USER,
6169 .start = vma->vm_start,
6170 .len = vma->vm_end - vma->vm_start,
6171 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6173 /* .maj (attr_mmap2 only) */
6174 /* .min (attr_mmap2 only) */
6175 /* .ino (attr_mmap2 only) */
6176 /* .ino_generation (attr_mmap2 only) */
6177 /* .prot (attr_mmap2 only) */
6178 /* .flags (attr_mmap2 only) */
6181 perf_event_mmap_event(&mmap_event);
6184 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6185 unsigned long size, u64 flags)
6187 struct perf_output_handle handle;
6188 struct perf_sample_data sample;
6189 struct perf_aux_event {
6190 struct perf_event_header header;
6196 .type = PERF_RECORD_AUX,
6198 .size = sizeof(rec),
6206 perf_event_header__init_id(&rec.header, &sample, event);
6207 ret = perf_output_begin(&handle, event, rec.header.size);
6212 perf_output_put(&handle, rec);
6213 perf_event__output_id_sample(event, &handle, &sample);
6215 perf_output_end(&handle);
6219 * Lost/dropped samples logging
6221 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6223 struct perf_output_handle handle;
6224 struct perf_sample_data sample;
6228 struct perf_event_header header;
6230 } lost_samples_event = {
6232 .type = PERF_RECORD_LOST_SAMPLES,
6234 .size = sizeof(lost_samples_event),
6239 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6241 ret = perf_output_begin(&handle, event,
6242 lost_samples_event.header.size);
6246 perf_output_put(&handle, lost_samples_event);
6247 perf_event__output_id_sample(event, &handle, &sample);
6248 perf_output_end(&handle);
6252 * context_switch tracking
6255 struct perf_switch_event {
6256 struct task_struct *task;
6257 struct task_struct *next_prev;
6260 struct perf_event_header header;
6266 static int perf_event_switch_match(struct perf_event *event)
6268 return event->attr.context_switch;
6271 static void perf_event_switch_output(struct perf_event *event, void *data)
6273 struct perf_switch_event *se = data;
6274 struct perf_output_handle handle;
6275 struct perf_sample_data sample;
6278 if (!perf_event_switch_match(event))
6281 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6282 if (event->ctx->task) {
6283 se->event_id.header.type = PERF_RECORD_SWITCH;
6284 se->event_id.header.size = sizeof(se->event_id.header);
6286 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6287 se->event_id.header.size = sizeof(se->event_id);
6288 se->event_id.next_prev_pid =
6289 perf_event_pid(event, se->next_prev);
6290 se->event_id.next_prev_tid =
6291 perf_event_tid(event, se->next_prev);
6294 perf_event_header__init_id(&se->event_id.header, &sample, event);
6296 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6300 if (event->ctx->task)
6301 perf_output_put(&handle, se->event_id.header);
6303 perf_output_put(&handle, se->event_id);
6305 perf_event__output_id_sample(event, &handle, &sample);
6307 perf_output_end(&handle);
6310 static void perf_event_switch(struct task_struct *task,
6311 struct task_struct *next_prev, bool sched_in)
6313 struct perf_switch_event switch_event;
6315 /* N.B. caller checks nr_switch_events != 0 */
6317 switch_event = (struct perf_switch_event){
6319 .next_prev = next_prev,
6323 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6326 /* .next_prev_pid */
6327 /* .next_prev_tid */
6331 perf_event_aux(perf_event_switch_output,
6337 * IRQ throttle logging
6340 static void perf_log_throttle(struct perf_event *event, int enable)
6342 struct perf_output_handle handle;
6343 struct perf_sample_data sample;
6347 struct perf_event_header header;
6351 } throttle_event = {
6353 .type = PERF_RECORD_THROTTLE,
6355 .size = sizeof(throttle_event),
6357 .time = perf_event_clock(event),
6358 .id = primary_event_id(event),
6359 .stream_id = event->id,
6363 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6365 perf_event_header__init_id(&throttle_event.header, &sample, event);
6367 ret = perf_output_begin(&handle, event,
6368 throttle_event.header.size);
6372 perf_output_put(&handle, throttle_event);
6373 perf_event__output_id_sample(event, &handle, &sample);
6374 perf_output_end(&handle);
6377 static void perf_log_itrace_start(struct perf_event *event)
6379 struct perf_output_handle handle;
6380 struct perf_sample_data sample;
6381 struct perf_aux_event {
6382 struct perf_event_header header;
6389 event = event->parent;
6391 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6392 event->hw.itrace_started)
6395 rec.header.type = PERF_RECORD_ITRACE_START;
6396 rec.header.misc = 0;
6397 rec.header.size = sizeof(rec);
6398 rec.pid = perf_event_pid(event, current);
6399 rec.tid = perf_event_tid(event, current);
6401 perf_event_header__init_id(&rec.header, &sample, event);
6402 ret = perf_output_begin(&handle, event, rec.header.size);
6407 perf_output_put(&handle, rec);
6408 perf_event__output_id_sample(event, &handle, &sample);
6410 perf_output_end(&handle);
6414 * Generic event overflow handling, sampling.
6417 static int __perf_event_overflow(struct perf_event *event,
6418 int throttle, struct perf_sample_data *data,
6419 struct pt_regs *regs)
6421 int events = atomic_read(&event->event_limit);
6422 struct hw_perf_event *hwc = &event->hw;
6427 * Non-sampling counters might still use the PMI to fold short
6428 * hardware counters, ignore those.
6430 if (unlikely(!is_sampling_event(event)))
6433 seq = __this_cpu_read(perf_throttled_seq);
6434 if (seq != hwc->interrupts_seq) {
6435 hwc->interrupts_seq = seq;
6436 hwc->interrupts = 1;
6439 if (unlikely(throttle
6440 && hwc->interrupts >= max_samples_per_tick)) {
6441 __this_cpu_inc(perf_throttled_count);
6442 hwc->interrupts = MAX_INTERRUPTS;
6443 perf_log_throttle(event, 0);
6444 tick_nohz_full_kick();
6449 if (event->attr.freq) {
6450 u64 now = perf_clock();
6451 s64 delta = now - hwc->freq_time_stamp;
6453 hwc->freq_time_stamp = now;
6455 if (delta > 0 && delta < 2*TICK_NSEC)
6456 perf_adjust_period(event, delta, hwc->last_period, true);
6460 * XXX event_limit might not quite work as expected on inherited
6464 event->pending_kill = POLL_IN;
6465 if (events && atomic_dec_and_test(&event->event_limit)) {
6467 event->pending_kill = POLL_HUP;
6468 event->pending_disable = 1;
6469 irq_work_queue(&event->pending);
6472 if (event->overflow_handler)
6473 event->overflow_handler(event, data, regs);
6475 perf_event_output(event, data, regs);
6477 if (*perf_event_fasync(event) && event->pending_kill) {
6478 event->pending_wakeup = 1;
6479 irq_work_queue(&event->pending);
6485 int perf_event_overflow(struct perf_event *event,
6486 struct perf_sample_data *data,
6487 struct pt_regs *regs)
6489 return __perf_event_overflow(event, 1, data, regs);
6493 * Generic software event infrastructure
6496 struct swevent_htable {
6497 struct swevent_hlist *swevent_hlist;
6498 struct mutex hlist_mutex;
6501 /* Recursion avoidance in each contexts */
6502 int recursion[PERF_NR_CONTEXTS];
6505 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6508 * We directly increment event->count and keep a second value in
6509 * event->hw.period_left to count intervals. This period event
6510 * is kept in the range [-sample_period, 0] so that we can use the
6514 u64 perf_swevent_set_period(struct perf_event *event)
6516 struct hw_perf_event *hwc = &event->hw;
6517 u64 period = hwc->last_period;
6521 hwc->last_period = hwc->sample_period;
6524 old = val = local64_read(&hwc->period_left);
6528 nr = div64_u64(period + val, period);
6529 offset = nr * period;
6531 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6537 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6538 struct perf_sample_data *data,
6539 struct pt_regs *regs)
6541 struct hw_perf_event *hwc = &event->hw;
6545 overflow = perf_swevent_set_period(event);
6547 if (hwc->interrupts == MAX_INTERRUPTS)
6550 for (; overflow; overflow--) {
6551 if (__perf_event_overflow(event, throttle,
6554 * We inhibit the overflow from happening when
6555 * hwc->interrupts == MAX_INTERRUPTS.
6563 static void perf_swevent_event(struct perf_event *event, u64 nr,
6564 struct perf_sample_data *data,
6565 struct pt_regs *regs)
6567 struct hw_perf_event *hwc = &event->hw;
6569 local64_add(nr, &event->count);
6574 if (!is_sampling_event(event))
6577 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6579 return perf_swevent_overflow(event, 1, data, regs);
6581 data->period = event->hw.last_period;
6583 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6584 return perf_swevent_overflow(event, 1, data, regs);
6586 if (local64_add_negative(nr, &hwc->period_left))
6589 perf_swevent_overflow(event, 0, data, regs);
6592 static int perf_exclude_event(struct perf_event *event,
6593 struct pt_regs *regs)
6595 if (event->hw.state & PERF_HES_STOPPED)
6599 if (event->attr.exclude_user && user_mode(regs))
6602 if (event->attr.exclude_kernel && !user_mode(regs))
6609 static int perf_swevent_match(struct perf_event *event,
6610 enum perf_type_id type,
6612 struct perf_sample_data *data,
6613 struct pt_regs *regs)
6615 if (event->attr.type != type)
6618 if (event->attr.config != event_id)
6621 if (perf_exclude_event(event, regs))
6627 static inline u64 swevent_hash(u64 type, u32 event_id)
6629 u64 val = event_id | (type << 32);
6631 return hash_64(val, SWEVENT_HLIST_BITS);
6634 static inline struct hlist_head *
6635 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6637 u64 hash = swevent_hash(type, event_id);
6639 return &hlist->heads[hash];
6642 /* For the read side: events when they trigger */
6643 static inline struct hlist_head *
6644 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6646 struct swevent_hlist *hlist;
6648 hlist = rcu_dereference(swhash->swevent_hlist);
6652 return __find_swevent_head(hlist, type, event_id);
6655 /* For the event head insertion and removal in the hlist */
6656 static inline struct hlist_head *
6657 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6659 struct swevent_hlist *hlist;
6660 u32 event_id = event->attr.config;
6661 u64 type = event->attr.type;
6664 * Event scheduling is always serialized against hlist allocation
6665 * and release. Which makes the protected version suitable here.
6666 * The context lock guarantees that.
6668 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6669 lockdep_is_held(&event->ctx->lock));
6673 return __find_swevent_head(hlist, type, event_id);
6676 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6678 struct perf_sample_data *data,
6679 struct pt_regs *regs)
6681 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6682 struct perf_event *event;
6683 struct hlist_head *head;
6686 head = find_swevent_head_rcu(swhash, type, event_id);
6690 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6691 if (perf_swevent_match(event, type, event_id, data, regs))
6692 perf_swevent_event(event, nr, data, regs);
6698 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6700 int perf_swevent_get_recursion_context(void)
6702 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6704 return get_recursion_context(swhash->recursion);
6706 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6708 inline void perf_swevent_put_recursion_context(int rctx)
6710 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6712 put_recursion_context(swhash->recursion, rctx);
6715 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6717 struct perf_sample_data data;
6719 if (WARN_ON_ONCE(!regs))
6722 perf_sample_data_init(&data, addr, 0);
6723 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6726 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6730 preempt_disable_notrace();
6731 rctx = perf_swevent_get_recursion_context();
6732 if (unlikely(rctx < 0))
6735 ___perf_sw_event(event_id, nr, regs, addr);
6737 perf_swevent_put_recursion_context(rctx);
6739 preempt_enable_notrace();
6742 static void perf_swevent_read(struct perf_event *event)
6746 static int perf_swevent_add(struct perf_event *event, int flags)
6748 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6749 struct hw_perf_event *hwc = &event->hw;
6750 struct hlist_head *head;
6752 if (is_sampling_event(event)) {
6753 hwc->last_period = hwc->sample_period;
6754 perf_swevent_set_period(event);
6757 hwc->state = !(flags & PERF_EF_START);
6759 head = find_swevent_head(swhash, event);
6760 if (WARN_ON_ONCE(!head))
6763 hlist_add_head_rcu(&event->hlist_entry, head);
6764 perf_event_update_userpage(event);
6769 static void perf_swevent_del(struct perf_event *event, int flags)
6771 hlist_del_rcu(&event->hlist_entry);
6774 static void perf_swevent_start(struct perf_event *event, int flags)
6776 event->hw.state = 0;
6779 static void perf_swevent_stop(struct perf_event *event, int flags)
6781 event->hw.state = PERF_HES_STOPPED;
6784 /* Deref the hlist from the update side */
6785 static inline struct swevent_hlist *
6786 swevent_hlist_deref(struct swevent_htable *swhash)
6788 return rcu_dereference_protected(swhash->swevent_hlist,
6789 lockdep_is_held(&swhash->hlist_mutex));
6792 static void swevent_hlist_release(struct swevent_htable *swhash)
6794 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6799 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6800 kfree_rcu(hlist, rcu_head);
6803 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6805 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6807 mutex_lock(&swhash->hlist_mutex);
6809 if (!--swhash->hlist_refcount)
6810 swevent_hlist_release(swhash);
6812 mutex_unlock(&swhash->hlist_mutex);
6815 static void swevent_hlist_put(struct perf_event *event)
6819 for_each_possible_cpu(cpu)
6820 swevent_hlist_put_cpu(event, cpu);
6823 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6825 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6828 mutex_lock(&swhash->hlist_mutex);
6829 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6830 struct swevent_hlist *hlist;
6832 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6837 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6839 swhash->hlist_refcount++;
6841 mutex_unlock(&swhash->hlist_mutex);
6846 static int swevent_hlist_get(struct perf_event *event)
6849 int cpu, failed_cpu;
6852 for_each_possible_cpu(cpu) {
6853 err = swevent_hlist_get_cpu(event, cpu);
6863 for_each_possible_cpu(cpu) {
6864 if (cpu == failed_cpu)
6866 swevent_hlist_put_cpu(event, cpu);
6873 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6875 static void sw_perf_event_destroy(struct perf_event *event)
6877 u64 event_id = event->attr.config;
6879 WARN_ON(event->parent);
6881 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6882 swevent_hlist_put(event);
6885 static int perf_swevent_init(struct perf_event *event)
6887 u64 event_id = event->attr.config;
6889 if (event->attr.type != PERF_TYPE_SOFTWARE)
6893 * no branch sampling for software events
6895 if (has_branch_stack(event))
6899 case PERF_COUNT_SW_CPU_CLOCK:
6900 case PERF_COUNT_SW_TASK_CLOCK:
6907 if (event_id >= PERF_COUNT_SW_MAX)
6910 if (!event->parent) {
6913 err = swevent_hlist_get(event);
6917 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6918 event->destroy = sw_perf_event_destroy;
6924 static struct pmu perf_swevent = {
6925 .task_ctx_nr = perf_sw_context,
6927 .capabilities = PERF_PMU_CAP_NO_NMI,
6929 .event_init = perf_swevent_init,
6930 .add = perf_swevent_add,
6931 .del = perf_swevent_del,
6932 .start = perf_swevent_start,
6933 .stop = perf_swevent_stop,
6934 .read = perf_swevent_read,
6937 #ifdef CONFIG_EVENT_TRACING
6939 static int perf_tp_filter_match(struct perf_event *event,
6940 struct perf_sample_data *data)
6942 void *record = data->raw->data;
6944 /* only top level events have filters set */
6946 event = event->parent;
6948 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6953 static int perf_tp_event_match(struct perf_event *event,
6954 struct perf_sample_data *data,
6955 struct pt_regs *regs)
6957 if (event->hw.state & PERF_HES_STOPPED)
6960 * All tracepoints are from kernel-space.
6962 if (event->attr.exclude_kernel)
6965 if (!perf_tp_filter_match(event, data))
6971 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6972 struct pt_regs *regs, struct hlist_head *head, int rctx,
6973 struct task_struct *task)
6975 struct perf_sample_data data;
6976 struct perf_event *event;
6978 struct perf_raw_record raw = {
6983 perf_sample_data_init(&data, addr, 0);
6986 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6987 if (perf_tp_event_match(event, &data, regs))
6988 perf_swevent_event(event, count, &data, regs);
6992 * If we got specified a target task, also iterate its context and
6993 * deliver this event there too.
6995 if (task && task != current) {
6996 struct perf_event_context *ctx;
6997 struct trace_entry *entry = record;
7000 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7004 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7005 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7007 if (event->attr.config != entry->type)
7009 if (perf_tp_event_match(event, &data, regs))
7010 perf_swevent_event(event, count, &data, regs);
7016 perf_swevent_put_recursion_context(rctx);
7018 EXPORT_SYMBOL_GPL(perf_tp_event);
7020 static void tp_perf_event_destroy(struct perf_event *event)
7022 perf_trace_destroy(event);
7025 static int perf_tp_event_init(struct perf_event *event)
7029 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7033 * no branch sampling for tracepoint events
7035 if (has_branch_stack(event))
7038 err = perf_trace_init(event);
7042 event->destroy = tp_perf_event_destroy;
7047 static struct pmu perf_tracepoint = {
7048 .task_ctx_nr = perf_sw_context,
7050 .event_init = perf_tp_event_init,
7051 .add = perf_trace_add,
7052 .del = perf_trace_del,
7053 .start = perf_swevent_start,
7054 .stop = perf_swevent_stop,
7055 .read = perf_swevent_read,
7058 static inline void perf_tp_register(void)
7060 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7063 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7068 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7071 filter_str = strndup_user(arg, PAGE_SIZE);
7072 if (IS_ERR(filter_str))
7073 return PTR_ERR(filter_str);
7075 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7081 static void perf_event_free_filter(struct perf_event *event)
7083 ftrace_profile_free_filter(event);
7086 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7088 struct bpf_prog *prog;
7090 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7093 if (event->tp_event->prog)
7096 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7097 /* bpf programs can only be attached to u/kprobes */
7100 prog = bpf_prog_get(prog_fd);
7102 return PTR_ERR(prog);
7104 if (prog->type != BPF_PROG_TYPE_KPROBE) {
7105 /* valid fd, but invalid bpf program type */
7110 event->tp_event->prog = prog;
7115 static void perf_event_free_bpf_prog(struct perf_event *event)
7117 struct bpf_prog *prog;
7119 if (!event->tp_event)
7122 prog = event->tp_event->prog;
7124 event->tp_event->prog = NULL;
7125 bpf_prog_put_rcu(prog);
7131 static inline void perf_tp_register(void)
7135 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7140 static void perf_event_free_filter(struct perf_event *event)
7144 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7149 static void perf_event_free_bpf_prog(struct perf_event *event)
7152 #endif /* CONFIG_EVENT_TRACING */
7154 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7155 void perf_bp_event(struct perf_event *bp, void *data)
7157 struct perf_sample_data sample;
7158 struct pt_regs *regs = data;
7160 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7162 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7163 perf_swevent_event(bp, 1, &sample, regs);
7168 * hrtimer based swevent callback
7171 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7173 enum hrtimer_restart ret = HRTIMER_RESTART;
7174 struct perf_sample_data data;
7175 struct pt_regs *regs;
7176 struct perf_event *event;
7179 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7181 if (event->state != PERF_EVENT_STATE_ACTIVE)
7182 return HRTIMER_NORESTART;
7184 event->pmu->read(event);
7186 perf_sample_data_init(&data, 0, event->hw.last_period);
7187 regs = get_irq_regs();
7189 if (regs && !perf_exclude_event(event, regs)) {
7190 if (!(event->attr.exclude_idle && is_idle_task(current)))
7191 if (__perf_event_overflow(event, 1, &data, regs))
7192 ret = HRTIMER_NORESTART;
7195 period = max_t(u64, 10000, event->hw.sample_period);
7196 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7201 static void perf_swevent_start_hrtimer(struct perf_event *event)
7203 struct hw_perf_event *hwc = &event->hw;
7206 if (!is_sampling_event(event))
7209 period = local64_read(&hwc->period_left);
7214 local64_set(&hwc->period_left, 0);
7216 period = max_t(u64, 10000, hwc->sample_period);
7218 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7219 HRTIMER_MODE_REL_PINNED);
7222 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7224 struct hw_perf_event *hwc = &event->hw;
7226 if (is_sampling_event(event)) {
7227 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7228 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7230 hrtimer_cancel(&hwc->hrtimer);
7234 static void perf_swevent_init_hrtimer(struct perf_event *event)
7236 struct hw_perf_event *hwc = &event->hw;
7238 if (!is_sampling_event(event))
7241 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7242 hwc->hrtimer.function = perf_swevent_hrtimer;
7245 * Since hrtimers have a fixed rate, we can do a static freq->period
7246 * mapping and avoid the whole period adjust feedback stuff.
7248 if (event->attr.freq) {
7249 long freq = event->attr.sample_freq;
7251 event->attr.sample_period = NSEC_PER_SEC / freq;
7252 hwc->sample_period = event->attr.sample_period;
7253 local64_set(&hwc->period_left, hwc->sample_period);
7254 hwc->last_period = hwc->sample_period;
7255 event->attr.freq = 0;
7260 * Software event: cpu wall time clock
7263 static void cpu_clock_event_update(struct perf_event *event)
7268 now = local_clock();
7269 prev = local64_xchg(&event->hw.prev_count, now);
7270 local64_add(now - prev, &event->count);
7273 static void cpu_clock_event_start(struct perf_event *event, int flags)
7275 local64_set(&event->hw.prev_count, local_clock());
7276 perf_swevent_start_hrtimer(event);
7279 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7281 perf_swevent_cancel_hrtimer(event);
7282 cpu_clock_event_update(event);
7285 static int cpu_clock_event_add(struct perf_event *event, int flags)
7287 if (flags & PERF_EF_START)
7288 cpu_clock_event_start(event, flags);
7289 perf_event_update_userpage(event);
7294 static void cpu_clock_event_del(struct perf_event *event, int flags)
7296 cpu_clock_event_stop(event, flags);
7299 static void cpu_clock_event_read(struct perf_event *event)
7301 cpu_clock_event_update(event);
7304 static int cpu_clock_event_init(struct perf_event *event)
7306 if (event->attr.type != PERF_TYPE_SOFTWARE)
7309 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7313 * no branch sampling for software events
7315 if (has_branch_stack(event))
7318 perf_swevent_init_hrtimer(event);
7323 static struct pmu perf_cpu_clock = {
7324 .task_ctx_nr = perf_sw_context,
7326 .capabilities = PERF_PMU_CAP_NO_NMI,
7328 .event_init = cpu_clock_event_init,
7329 .add = cpu_clock_event_add,
7330 .del = cpu_clock_event_del,
7331 .start = cpu_clock_event_start,
7332 .stop = cpu_clock_event_stop,
7333 .read = cpu_clock_event_read,
7337 * Software event: task time clock
7340 static void task_clock_event_update(struct perf_event *event, u64 now)
7345 prev = local64_xchg(&event->hw.prev_count, now);
7347 local64_add(delta, &event->count);
7350 static void task_clock_event_start(struct perf_event *event, int flags)
7352 local64_set(&event->hw.prev_count, event->ctx->time);
7353 perf_swevent_start_hrtimer(event);
7356 static void task_clock_event_stop(struct perf_event *event, int flags)
7358 perf_swevent_cancel_hrtimer(event);
7359 task_clock_event_update(event, event->ctx->time);
7362 static int task_clock_event_add(struct perf_event *event, int flags)
7364 if (flags & PERF_EF_START)
7365 task_clock_event_start(event, flags);
7366 perf_event_update_userpage(event);
7371 static void task_clock_event_del(struct perf_event *event, int flags)
7373 task_clock_event_stop(event, PERF_EF_UPDATE);
7376 static void task_clock_event_read(struct perf_event *event)
7378 u64 now = perf_clock();
7379 u64 delta = now - event->ctx->timestamp;
7380 u64 time = event->ctx->time + delta;
7382 task_clock_event_update(event, time);
7385 static int task_clock_event_init(struct perf_event *event)
7387 if (event->attr.type != PERF_TYPE_SOFTWARE)
7390 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7394 * no branch sampling for software events
7396 if (has_branch_stack(event))
7399 perf_swevent_init_hrtimer(event);
7404 static struct pmu perf_task_clock = {
7405 .task_ctx_nr = perf_sw_context,
7407 .capabilities = PERF_PMU_CAP_NO_NMI,
7409 .event_init = task_clock_event_init,
7410 .add = task_clock_event_add,
7411 .del = task_clock_event_del,
7412 .start = task_clock_event_start,
7413 .stop = task_clock_event_stop,
7414 .read = task_clock_event_read,
7417 static void perf_pmu_nop_void(struct pmu *pmu)
7421 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7425 static int perf_pmu_nop_int(struct pmu *pmu)
7430 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7432 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7434 __this_cpu_write(nop_txn_flags, flags);
7436 if (flags & ~PERF_PMU_TXN_ADD)
7439 perf_pmu_disable(pmu);
7442 static int perf_pmu_commit_txn(struct pmu *pmu)
7444 unsigned int flags = __this_cpu_read(nop_txn_flags);
7446 __this_cpu_write(nop_txn_flags, 0);
7448 if (flags & ~PERF_PMU_TXN_ADD)
7451 perf_pmu_enable(pmu);
7455 static void perf_pmu_cancel_txn(struct pmu *pmu)
7457 unsigned int flags = __this_cpu_read(nop_txn_flags);
7459 __this_cpu_write(nop_txn_flags, 0);
7461 if (flags & ~PERF_PMU_TXN_ADD)
7464 perf_pmu_enable(pmu);
7467 static int perf_event_idx_default(struct perf_event *event)
7473 * Ensures all contexts with the same task_ctx_nr have the same
7474 * pmu_cpu_context too.
7476 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7483 list_for_each_entry(pmu, &pmus, entry) {
7484 if (pmu->task_ctx_nr == ctxn)
7485 return pmu->pmu_cpu_context;
7491 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7495 for_each_possible_cpu(cpu) {
7496 struct perf_cpu_context *cpuctx;
7498 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7500 if (cpuctx->unique_pmu == old_pmu)
7501 cpuctx->unique_pmu = pmu;
7505 static void free_pmu_context(struct pmu *pmu)
7509 mutex_lock(&pmus_lock);
7511 * Like a real lame refcount.
7513 list_for_each_entry(i, &pmus, entry) {
7514 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7515 update_pmu_context(i, pmu);
7520 free_percpu(pmu->pmu_cpu_context);
7522 mutex_unlock(&pmus_lock);
7524 static struct idr pmu_idr;
7527 type_show(struct device *dev, struct device_attribute *attr, char *page)
7529 struct pmu *pmu = dev_get_drvdata(dev);
7531 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7533 static DEVICE_ATTR_RO(type);
7536 perf_event_mux_interval_ms_show(struct device *dev,
7537 struct device_attribute *attr,
7540 struct pmu *pmu = dev_get_drvdata(dev);
7542 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7545 static DEFINE_MUTEX(mux_interval_mutex);
7548 perf_event_mux_interval_ms_store(struct device *dev,
7549 struct device_attribute *attr,
7550 const char *buf, size_t count)
7552 struct pmu *pmu = dev_get_drvdata(dev);
7553 int timer, cpu, ret;
7555 ret = kstrtoint(buf, 0, &timer);
7562 /* same value, noting to do */
7563 if (timer == pmu->hrtimer_interval_ms)
7566 mutex_lock(&mux_interval_mutex);
7567 pmu->hrtimer_interval_ms = timer;
7569 /* update all cpuctx for this PMU */
7571 for_each_online_cpu(cpu) {
7572 struct perf_cpu_context *cpuctx;
7573 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7574 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7576 cpu_function_call(cpu,
7577 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7580 mutex_unlock(&mux_interval_mutex);
7584 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7586 static struct attribute *pmu_dev_attrs[] = {
7587 &dev_attr_type.attr,
7588 &dev_attr_perf_event_mux_interval_ms.attr,
7591 ATTRIBUTE_GROUPS(pmu_dev);
7593 static int pmu_bus_running;
7594 static struct bus_type pmu_bus = {
7595 .name = "event_source",
7596 .dev_groups = pmu_dev_groups,
7599 static void pmu_dev_release(struct device *dev)
7604 static int pmu_dev_alloc(struct pmu *pmu)
7608 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7612 pmu->dev->groups = pmu->attr_groups;
7613 device_initialize(pmu->dev);
7614 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7618 dev_set_drvdata(pmu->dev, pmu);
7619 pmu->dev->bus = &pmu_bus;
7620 pmu->dev->release = pmu_dev_release;
7621 ret = device_add(pmu->dev);
7629 put_device(pmu->dev);
7633 static struct lock_class_key cpuctx_mutex;
7634 static struct lock_class_key cpuctx_lock;
7636 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7640 mutex_lock(&pmus_lock);
7642 pmu->pmu_disable_count = alloc_percpu(int);
7643 if (!pmu->pmu_disable_count)
7652 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7660 if (pmu_bus_running) {
7661 ret = pmu_dev_alloc(pmu);
7667 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7668 if (pmu->pmu_cpu_context)
7669 goto got_cpu_context;
7672 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7673 if (!pmu->pmu_cpu_context)
7676 for_each_possible_cpu(cpu) {
7677 struct perf_cpu_context *cpuctx;
7679 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7680 __perf_event_init_context(&cpuctx->ctx);
7681 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7682 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7683 cpuctx->ctx.pmu = pmu;
7685 __perf_mux_hrtimer_init(cpuctx, cpu);
7687 cpuctx->unique_pmu = pmu;
7691 if (!pmu->start_txn) {
7692 if (pmu->pmu_enable) {
7694 * If we have pmu_enable/pmu_disable calls, install
7695 * transaction stubs that use that to try and batch
7696 * hardware accesses.
7698 pmu->start_txn = perf_pmu_start_txn;
7699 pmu->commit_txn = perf_pmu_commit_txn;
7700 pmu->cancel_txn = perf_pmu_cancel_txn;
7702 pmu->start_txn = perf_pmu_nop_txn;
7703 pmu->commit_txn = perf_pmu_nop_int;
7704 pmu->cancel_txn = perf_pmu_nop_void;
7708 if (!pmu->pmu_enable) {
7709 pmu->pmu_enable = perf_pmu_nop_void;
7710 pmu->pmu_disable = perf_pmu_nop_void;
7713 if (!pmu->event_idx)
7714 pmu->event_idx = perf_event_idx_default;
7716 list_add_rcu(&pmu->entry, &pmus);
7717 atomic_set(&pmu->exclusive_cnt, 0);
7720 mutex_unlock(&pmus_lock);
7725 device_del(pmu->dev);
7726 put_device(pmu->dev);
7729 if (pmu->type >= PERF_TYPE_MAX)
7730 idr_remove(&pmu_idr, pmu->type);
7733 free_percpu(pmu->pmu_disable_count);
7736 EXPORT_SYMBOL_GPL(perf_pmu_register);
7738 void perf_pmu_unregister(struct pmu *pmu)
7740 mutex_lock(&pmus_lock);
7741 list_del_rcu(&pmu->entry);
7742 mutex_unlock(&pmus_lock);
7745 * We dereference the pmu list under both SRCU and regular RCU, so
7746 * synchronize against both of those.
7748 synchronize_srcu(&pmus_srcu);
7751 free_percpu(pmu->pmu_disable_count);
7752 if (pmu->type >= PERF_TYPE_MAX)
7753 idr_remove(&pmu_idr, pmu->type);
7754 device_del(pmu->dev);
7755 put_device(pmu->dev);
7756 free_pmu_context(pmu);
7758 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7760 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7762 struct perf_event_context *ctx = NULL;
7765 if (!try_module_get(pmu->module))
7768 if (event->group_leader != event) {
7770 * This ctx->mutex can nest when we're called through
7771 * inheritance. See the perf_event_ctx_lock_nested() comment.
7773 ctx = perf_event_ctx_lock_nested(event->group_leader,
7774 SINGLE_DEPTH_NESTING);
7779 ret = pmu->event_init(event);
7782 perf_event_ctx_unlock(event->group_leader, ctx);
7785 module_put(pmu->module);
7790 static struct pmu *perf_init_event(struct perf_event *event)
7792 struct pmu *pmu = NULL;
7796 idx = srcu_read_lock(&pmus_srcu);
7799 pmu = idr_find(&pmu_idr, event->attr.type);
7802 ret = perf_try_init_event(pmu, event);
7808 list_for_each_entry_rcu(pmu, &pmus, entry) {
7809 ret = perf_try_init_event(pmu, event);
7813 if (ret != -ENOENT) {
7818 pmu = ERR_PTR(-ENOENT);
7820 srcu_read_unlock(&pmus_srcu, idx);
7825 static void account_event_cpu(struct perf_event *event, int cpu)
7830 if (is_cgroup_event(event))
7831 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7834 static void account_event(struct perf_event *event)
7839 if (event->attach_state & PERF_ATTACH_TASK)
7840 static_key_slow_inc(&perf_sched_events.key);
7841 if (event->attr.mmap || event->attr.mmap_data)
7842 atomic_inc(&nr_mmap_events);
7843 if (event->attr.comm)
7844 atomic_inc(&nr_comm_events);
7845 if (event->attr.task)
7846 atomic_inc(&nr_task_events);
7847 if (event->attr.freq) {
7848 if (atomic_inc_return(&nr_freq_events) == 1)
7849 tick_nohz_full_kick_all();
7851 if (event->attr.context_switch) {
7852 atomic_inc(&nr_switch_events);
7853 static_key_slow_inc(&perf_sched_events.key);
7855 if (has_branch_stack(event))
7856 static_key_slow_inc(&perf_sched_events.key);
7857 if (is_cgroup_event(event))
7858 static_key_slow_inc(&perf_sched_events.key);
7860 account_event_cpu(event, event->cpu);
7864 * Allocate and initialize a event structure
7866 static struct perf_event *
7867 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7868 struct task_struct *task,
7869 struct perf_event *group_leader,
7870 struct perf_event *parent_event,
7871 perf_overflow_handler_t overflow_handler,
7872 void *context, int cgroup_fd)
7875 struct perf_event *event;
7876 struct hw_perf_event *hwc;
7879 if ((unsigned)cpu >= nr_cpu_ids) {
7880 if (!task || cpu != -1)
7881 return ERR_PTR(-EINVAL);
7884 event = kzalloc(sizeof(*event), GFP_KERNEL);
7886 return ERR_PTR(-ENOMEM);
7889 * Single events are their own group leaders, with an
7890 * empty sibling list:
7893 group_leader = event;
7895 mutex_init(&event->child_mutex);
7896 INIT_LIST_HEAD(&event->child_list);
7898 INIT_LIST_HEAD(&event->group_entry);
7899 INIT_LIST_HEAD(&event->event_entry);
7900 INIT_LIST_HEAD(&event->sibling_list);
7901 INIT_LIST_HEAD(&event->rb_entry);
7902 INIT_LIST_HEAD(&event->active_entry);
7903 INIT_HLIST_NODE(&event->hlist_entry);
7906 init_waitqueue_head(&event->waitq);
7907 init_irq_work(&event->pending, perf_pending_event);
7909 mutex_init(&event->mmap_mutex);
7911 atomic_long_set(&event->refcount, 1);
7913 event->attr = *attr;
7914 event->group_leader = group_leader;
7918 event->parent = parent_event;
7920 event->ns = get_pid_ns(task_active_pid_ns(current));
7921 event->id = atomic64_inc_return(&perf_event_id);
7923 event->state = PERF_EVENT_STATE_INACTIVE;
7926 event->attach_state = PERF_ATTACH_TASK;
7928 * XXX pmu::event_init needs to know what task to account to
7929 * and we cannot use the ctx information because we need the
7930 * pmu before we get a ctx.
7932 event->hw.target = task;
7935 event->clock = &local_clock;
7937 event->clock = parent_event->clock;
7939 if (!overflow_handler && parent_event) {
7940 overflow_handler = parent_event->overflow_handler;
7941 context = parent_event->overflow_handler_context;
7944 event->overflow_handler = overflow_handler;
7945 event->overflow_handler_context = context;
7947 perf_event__state_init(event);
7952 hwc->sample_period = attr->sample_period;
7953 if (attr->freq && attr->sample_freq)
7954 hwc->sample_period = 1;
7955 hwc->last_period = hwc->sample_period;
7957 local64_set(&hwc->period_left, hwc->sample_period);
7960 * we currently do not support PERF_FORMAT_GROUP on inherited events
7962 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7965 if (!has_branch_stack(event))
7966 event->attr.branch_sample_type = 0;
7968 if (cgroup_fd != -1) {
7969 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7974 pmu = perf_init_event(event);
7977 else if (IS_ERR(pmu)) {
7982 err = exclusive_event_init(event);
7986 if (!event->parent) {
7987 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7988 err = get_callchain_buffers();
7994 /* symmetric to unaccount_event() in _free_event() */
7995 account_event(event);
8000 exclusive_event_destroy(event);
8004 event->destroy(event);
8005 module_put(pmu->module);
8007 if (is_cgroup_event(event))
8008 perf_detach_cgroup(event);
8010 put_pid_ns(event->ns);
8013 return ERR_PTR(err);
8016 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8017 struct perf_event_attr *attr)
8022 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8026 * zero the full structure, so that a short copy will be nice.
8028 memset(attr, 0, sizeof(*attr));
8030 ret = get_user(size, &uattr->size);
8034 if (size > PAGE_SIZE) /* silly large */
8037 if (!size) /* abi compat */
8038 size = PERF_ATTR_SIZE_VER0;
8040 if (size < PERF_ATTR_SIZE_VER0)
8044 * If we're handed a bigger struct than we know of,
8045 * ensure all the unknown bits are 0 - i.e. new
8046 * user-space does not rely on any kernel feature
8047 * extensions we dont know about yet.
8049 if (size > sizeof(*attr)) {
8050 unsigned char __user *addr;
8051 unsigned char __user *end;
8054 addr = (void __user *)uattr + sizeof(*attr);
8055 end = (void __user *)uattr + size;
8057 for (; addr < end; addr++) {
8058 ret = get_user(val, addr);
8064 size = sizeof(*attr);
8067 ret = copy_from_user(attr, uattr, size);
8071 if (attr->__reserved_1)
8074 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8077 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8080 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8081 u64 mask = attr->branch_sample_type;
8083 /* only using defined bits */
8084 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8087 /* at least one branch bit must be set */
8088 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8091 /* propagate priv level, when not set for branch */
8092 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8094 /* exclude_kernel checked on syscall entry */
8095 if (!attr->exclude_kernel)
8096 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8098 if (!attr->exclude_user)
8099 mask |= PERF_SAMPLE_BRANCH_USER;
8101 if (!attr->exclude_hv)
8102 mask |= PERF_SAMPLE_BRANCH_HV;
8104 * adjust user setting (for HW filter setup)
8106 attr->branch_sample_type = mask;
8108 /* privileged levels capture (kernel, hv): check permissions */
8109 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8110 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8114 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8115 ret = perf_reg_validate(attr->sample_regs_user);
8120 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8121 if (!arch_perf_have_user_stack_dump())
8125 * We have __u32 type for the size, but so far
8126 * we can only use __u16 as maximum due to the
8127 * __u16 sample size limit.
8129 if (attr->sample_stack_user >= USHRT_MAX)
8131 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8135 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8136 ret = perf_reg_validate(attr->sample_regs_intr);
8141 put_user(sizeof(*attr), &uattr->size);
8147 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8149 struct ring_buffer *rb = NULL;
8155 /* don't allow circular references */
8156 if (event == output_event)
8160 * Don't allow cross-cpu buffers
8162 if (output_event->cpu != event->cpu)
8166 * If its not a per-cpu rb, it must be the same task.
8168 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8172 * Mixing clocks in the same buffer is trouble you don't need.
8174 if (output_event->clock != event->clock)
8178 * If both events generate aux data, they must be on the same PMU
8180 if (has_aux(event) && has_aux(output_event) &&
8181 event->pmu != output_event->pmu)
8185 mutex_lock(&event->mmap_mutex);
8186 /* Can't redirect output if we've got an active mmap() */
8187 if (atomic_read(&event->mmap_count))
8191 /* get the rb we want to redirect to */
8192 rb = ring_buffer_get(output_event);
8197 ring_buffer_attach(event, rb);
8201 mutex_unlock(&event->mmap_mutex);
8207 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8213 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8216 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8218 bool nmi_safe = false;
8221 case CLOCK_MONOTONIC:
8222 event->clock = &ktime_get_mono_fast_ns;
8226 case CLOCK_MONOTONIC_RAW:
8227 event->clock = &ktime_get_raw_fast_ns;
8231 case CLOCK_REALTIME:
8232 event->clock = &ktime_get_real_ns;
8235 case CLOCK_BOOTTIME:
8236 event->clock = &ktime_get_boot_ns;
8240 event->clock = &ktime_get_tai_ns;
8247 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8254 * sys_perf_event_open - open a performance event, associate it to a task/cpu
8256 * @attr_uptr: event_id type attributes for monitoring/sampling
8259 * @group_fd: group leader event fd
8261 SYSCALL_DEFINE5(perf_event_open,
8262 struct perf_event_attr __user *, attr_uptr,
8263 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8265 struct perf_event *group_leader = NULL, *output_event = NULL;
8266 struct perf_event *event, *sibling;
8267 struct perf_event_attr attr;
8268 struct perf_event_context *ctx, *uninitialized_var(gctx);
8269 struct file *event_file = NULL;
8270 struct fd group = {NULL, 0};
8271 struct task_struct *task = NULL;
8276 int f_flags = O_RDWR;
8279 /* for future expandability... */
8280 if (flags & ~PERF_FLAG_ALL)
8283 err = perf_copy_attr(attr_uptr, &attr);
8287 if (!attr.exclude_kernel) {
8288 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8293 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8296 if (attr.sample_period & (1ULL << 63))
8301 * In cgroup mode, the pid argument is used to pass the fd
8302 * opened to the cgroup directory in cgroupfs. The cpu argument
8303 * designates the cpu on which to monitor threads from that
8306 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8309 if (flags & PERF_FLAG_FD_CLOEXEC)
8310 f_flags |= O_CLOEXEC;
8312 event_fd = get_unused_fd_flags(f_flags);
8316 if (group_fd != -1) {
8317 err = perf_fget_light(group_fd, &group);
8320 group_leader = group.file->private_data;
8321 if (flags & PERF_FLAG_FD_OUTPUT)
8322 output_event = group_leader;
8323 if (flags & PERF_FLAG_FD_NO_GROUP)
8324 group_leader = NULL;
8327 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8328 task = find_lively_task_by_vpid(pid);
8330 err = PTR_ERR(task);
8335 if (task && group_leader &&
8336 group_leader->attr.inherit != attr.inherit) {
8344 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8349 * Reuse ptrace permission checks for now.
8351 * We must hold cred_guard_mutex across this and any potential
8352 * perf_install_in_context() call for this new event to
8353 * serialize against exec() altering our credentials (and the
8354 * perf_event_exit_task() that could imply).
8357 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8361 if (flags & PERF_FLAG_PID_CGROUP)
8364 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8365 NULL, NULL, cgroup_fd);
8366 if (IS_ERR(event)) {
8367 err = PTR_ERR(event);
8371 if (is_sampling_event(event)) {
8372 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8379 * Special case software events and allow them to be part of
8380 * any hardware group.
8384 if (attr.use_clockid) {
8385 err = perf_event_set_clock(event, attr.clockid);
8391 (is_software_event(event) != is_software_event(group_leader))) {
8392 if (is_software_event(event)) {
8394 * If event and group_leader are not both a software
8395 * event, and event is, then group leader is not.
8397 * Allow the addition of software events to !software
8398 * groups, this is safe because software events never
8401 pmu = group_leader->pmu;
8402 } else if (is_software_event(group_leader) &&
8403 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8405 * In case the group is a pure software group, and we
8406 * try to add a hardware event, move the whole group to
8407 * the hardware context.
8414 * Get the target context (task or percpu):
8416 ctx = find_get_context(pmu, task, event);
8422 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8428 * Look up the group leader (we will attach this event to it):
8434 * Do not allow a recursive hierarchy (this new sibling
8435 * becoming part of another group-sibling):
8437 if (group_leader->group_leader != group_leader)
8440 /* All events in a group should have the same clock */
8441 if (group_leader->clock != event->clock)
8445 * Do not allow to attach to a group in a different
8446 * task or CPU context:
8450 * Make sure we're both on the same task, or both
8453 if (group_leader->ctx->task != ctx->task)
8457 * Make sure we're both events for the same CPU;
8458 * grouping events for different CPUs is broken; since
8459 * you can never concurrently schedule them anyhow.
8461 if (group_leader->cpu != event->cpu)
8464 if (group_leader->ctx != ctx)
8469 * Only a group leader can be exclusive or pinned
8471 if (attr.exclusive || attr.pinned)
8476 err = perf_event_set_output(event, output_event);
8481 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8483 if (IS_ERR(event_file)) {
8484 err = PTR_ERR(event_file);
8489 gctx = group_leader->ctx;
8490 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8492 mutex_lock(&ctx->mutex);
8495 if (!perf_event_validate_size(event)) {
8501 * Must be under the same ctx::mutex as perf_install_in_context(),
8502 * because we need to serialize with concurrent event creation.
8504 if (!exclusive_event_installable(event, ctx)) {
8505 /* exclusive and group stuff are assumed mutually exclusive */
8506 WARN_ON_ONCE(move_group);
8512 WARN_ON_ONCE(ctx->parent_ctx);
8515 * This is the point on no return; we cannot fail hereafter. This is
8516 * where we start modifying current state.
8521 * See perf_event_ctx_lock() for comments on the details
8522 * of swizzling perf_event::ctx.
8524 perf_remove_from_context(group_leader, false);
8526 list_for_each_entry(sibling, &group_leader->sibling_list,
8528 perf_remove_from_context(sibling, false);
8533 * Wait for everybody to stop referencing the events through
8534 * the old lists, before installing it on new lists.
8539 * Install the group siblings before the group leader.
8541 * Because a group leader will try and install the entire group
8542 * (through the sibling list, which is still in-tact), we can
8543 * end up with siblings installed in the wrong context.
8545 * By installing siblings first we NO-OP because they're not
8546 * reachable through the group lists.
8548 list_for_each_entry(sibling, &group_leader->sibling_list,
8550 perf_event__state_init(sibling);
8551 perf_install_in_context(ctx, sibling, sibling->cpu);
8556 * Removing from the context ends up with disabled
8557 * event. What we want here is event in the initial
8558 * startup state, ready to be add into new context.
8560 perf_event__state_init(group_leader);
8561 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8565 * Now that all events are installed in @ctx, nothing
8566 * references @gctx anymore, so drop the last reference we have
8573 * Precalculate sample_data sizes; do while holding ctx::mutex such
8574 * that we're serialized against further additions and before
8575 * perf_install_in_context() which is the point the event is active and
8576 * can use these values.
8578 perf_event__header_size(event);
8579 perf_event__id_header_size(event);
8581 perf_install_in_context(ctx, event, event->cpu);
8582 perf_unpin_context(ctx);
8585 mutex_unlock(&gctx->mutex);
8586 mutex_unlock(&ctx->mutex);
8589 mutex_unlock(&task->signal->cred_guard_mutex);
8590 put_task_struct(task);
8595 event->owner = current;
8597 mutex_lock(¤t->perf_event_mutex);
8598 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8599 mutex_unlock(¤t->perf_event_mutex);
8602 * Drop the reference on the group_event after placing the
8603 * new event on the sibling_list. This ensures destruction
8604 * of the group leader will find the pointer to itself in
8605 * perf_group_detach().
8608 fd_install(event_fd, event_file);
8613 mutex_unlock(&gctx->mutex);
8614 mutex_unlock(&ctx->mutex);
8618 perf_unpin_context(ctx);
8622 * If event_file is set, the fput() above will have called ->release()
8623 * and that will take care of freeing the event.
8629 mutex_unlock(&task->signal->cred_guard_mutex);
8634 put_task_struct(task);
8638 put_unused_fd(event_fd);
8643 * perf_event_create_kernel_counter
8645 * @attr: attributes of the counter to create
8646 * @cpu: cpu in which the counter is bound
8647 * @task: task to profile (NULL for percpu)
8650 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8651 struct task_struct *task,
8652 perf_overflow_handler_t overflow_handler,
8655 struct perf_event_context *ctx;
8656 struct perf_event *event;
8660 * Get the target context (task or percpu):
8663 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8664 overflow_handler, context, -1);
8665 if (IS_ERR(event)) {
8666 err = PTR_ERR(event);
8670 /* Mark owner so we could distinguish it from user events. */
8671 event->owner = EVENT_OWNER_KERNEL;
8673 ctx = find_get_context(event->pmu, task, event);
8679 WARN_ON_ONCE(ctx->parent_ctx);
8680 mutex_lock(&ctx->mutex);
8681 if (!exclusive_event_installable(event, ctx)) {
8682 mutex_unlock(&ctx->mutex);
8683 perf_unpin_context(ctx);
8689 perf_install_in_context(ctx, event, cpu);
8690 perf_unpin_context(ctx);
8691 mutex_unlock(&ctx->mutex);
8698 return ERR_PTR(err);
8700 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8702 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8704 struct perf_event_context *src_ctx;
8705 struct perf_event_context *dst_ctx;
8706 struct perf_event *event, *tmp;
8709 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8710 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8713 * See perf_event_ctx_lock() for comments on the details
8714 * of swizzling perf_event::ctx.
8716 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8717 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8719 perf_remove_from_context(event, false);
8720 unaccount_event_cpu(event, src_cpu);
8722 list_add(&event->migrate_entry, &events);
8726 * Wait for the events to quiesce before re-instating them.
8731 * Re-instate events in 2 passes.
8733 * Skip over group leaders and only install siblings on this first
8734 * pass, siblings will not get enabled without a leader, however a
8735 * leader will enable its siblings, even if those are still on the old
8738 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8739 if (event->group_leader == event)
8742 list_del(&event->migrate_entry);
8743 if (event->state >= PERF_EVENT_STATE_OFF)
8744 event->state = PERF_EVENT_STATE_INACTIVE;
8745 account_event_cpu(event, dst_cpu);
8746 perf_install_in_context(dst_ctx, event, dst_cpu);
8751 * Once all the siblings are setup properly, install the group leaders
8754 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8755 list_del(&event->migrate_entry);
8756 if (event->state >= PERF_EVENT_STATE_OFF)
8757 event->state = PERF_EVENT_STATE_INACTIVE;
8758 account_event_cpu(event, dst_cpu);
8759 perf_install_in_context(dst_ctx, event, dst_cpu);
8762 mutex_unlock(&dst_ctx->mutex);
8763 mutex_unlock(&src_ctx->mutex);
8765 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8767 static void sync_child_event(struct perf_event *child_event,
8768 struct task_struct *child)
8770 struct perf_event *parent_event = child_event->parent;
8773 if (child_event->attr.inherit_stat)
8774 perf_event_read_event(child_event, child);
8776 child_val = perf_event_count(child_event);
8779 * Add back the child's count to the parent's count:
8781 atomic64_add(child_val, &parent_event->child_count);
8782 atomic64_add(child_event->total_time_enabled,
8783 &parent_event->child_total_time_enabled);
8784 atomic64_add(child_event->total_time_running,
8785 &parent_event->child_total_time_running);
8788 * Remove this event from the parent's list
8790 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8791 mutex_lock(&parent_event->child_mutex);
8792 list_del_init(&child_event->child_list);
8793 mutex_unlock(&parent_event->child_mutex);
8796 * Make sure user/parent get notified, that we just
8799 perf_event_wakeup(parent_event);
8802 * Release the parent event, if this was the last
8805 put_event(parent_event);
8809 __perf_event_exit_task(struct perf_event *child_event,
8810 struct perf_event_context *child_ctx,
8811 struct task_struct *child)
8814 * Do not destroy the 'original' grouping; because of the context
8815 * switch optimization the original events could've ended up in a
8816 * random child task.
8818 * If we were to destroy the original group, all group related
8819 * operations would cease to function properly after this random
8822 * Do destroy all inherited groups, we don't care about those
8823 * and being thorough is better.
8825 perf_remove_from_context(child_event, !!child_event->parent);
8828 * It can happen that the parent exits first, and has events
8829 * that are still around due to the child reference. These
8830 * events need to be zapped.
8832 if (child_event->parent) {
8833 sync_child_event(child_event, child);
8834 free_event(child_event);
8836 child_event->state = PERF_EVENT_STATE_EXIT;
8837 perf_event_wakeup(child_event);
8841 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8843 struct perf_event *child_event, *next;
8844 struct perf_event_context *child_ctx, *clone_ctx = NULL;
8845 unsigned long flags;
8847 if (likely(!child->perf_event_ctxp[ctxn]))
8850 local_irq_save(flags);
8852 * We can't reschedule here because interrupts are disabled,
8853 * and either child is current or it is a task that can't be
8854 * scheduled, so we are now safe from rescheduling changing
8857 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8860 * Take the context lock here so that if find_get_context is
8861 * reading child->perf_event_ctxp, we wait until it has
8862 * incremented the context's refcount before we do put_ctx below.
8864 raw_spin_lock(&child_ctx->lock);
8865 task_ctx_sched_out(child_ctx);
8866 child->perf_event_ctxp[ctxn] = NULL;
8869 * If this context is a clone; unclone it so it can't get
8870 * swapped to another process while we're removing all
8871 * the events from it.
8873 clone_ctx = unclone_ctx(child_ctx);
8874 update_context_time(child_ctx);
8875 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8881 * Report the task dead after unscheduling the events so that we
8882 * won't get any samples after PERF_RECORD_EXIT. We can however still
8883 * get a few PERF_RECORD_READ events.
8885 perf_event_task(child, child_ctx, 0);
8888 * We can recurse on the same lock type through:
8890 * __perf_event_exit_task()
8891 * sync_child_event()
8893 * mutex_lock(&ctx->mutex)
8895 * But since its the parent context it won't be the same instance.
8897 mutex_lock(&child_ctx->mutex);
8899 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8900 __perf_event_exit_task(child_event, child_ctx, child);
8902 mutex_unlock(&child_ctx->mutex);
8908 * When a child task exits, feed back event values to parent events.
8910 * Can be called with cred_guard_mutex held when called from
8911 * install_exec_creds().
8913 void perf_event_exit_task(struct task_struct *child)
8915 struct perf_event *event, *tmp;
8918 mutex_lock(&child->perf_event_mutex);
8919 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8921 list_del_init(&event->owner_entry);
8924 * Ensure the list deletion is visible before we clear
8925 * the owner, closes a race against perf_release() where
8926 * we need to serialize on the owner->perf_event_mutex.
8929 event->owner = NULL;
8931 mutex_unlock(&child->perf_event_mutex);
8933 for_each_task_context_nr(ctxn)
8934 perf_event_exit_task_context(child, ctxn);
8937 * The perf_event_exit_task_context calls perf_event_task
8938 * with child's task_ctx, which generates EXIT events for
8939 * child contexts and sets child->perf_event_ctxp[] to NULL.
8940 * At this point we need to send EXIT events to cpu contexts.
8942 perf_event_task(child, NULL, 0);
8945 static void perf_free_event(struct perf_event *event,
8946 struct perf_event_context *ctx)
8948 struct perf_event *parent = event->parent;
8950 if (WARN_ON_ONCE(!parent))
8953 mutex_lock(&parent->child_mutex);
8954 list_del_init(&event->child_list);
8955 mutex_unlock(&parent->child_mutex);
8959 raw_spin_lock_irq(&ctx->lock);
8960 perf_group_detach(event);
8961 list_del_event(event, ctx);
8962 raw_spin_unlock_irq(&ctx->lock);
8967 * Free an unexposed, unused context as created by inheritance by
8968 * perf_event_init_task below, used by fork() in case of fail.
8970 * Not all locks are strictly required, but take them anyway to be nice and
8971 * help out with the lockdep assertions.
8973 void perf_event_free_task(struct task_struct *task)
8975 struct perf_event_context *ctx;
8976 struct perf_event *event, *tmp;
8979 for_each_task_context_nr(ctxn) {
8980 ctx = task->perf_event_ctxp[ctxn];
8984 mutex_lock(&ctx->mutex);
8986 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8988 perf_free_event(event, ctx);
8990 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8992 perf_free_event(event, ctx);
8994 if (!list_empty(&ctx->pinned_groups) ||
8995 !list_empty(&ctx->flexible_groups))
8998 mutex_unlock(&ctx->mutex);
9004 void perf_event_delayed_put(struct task_struct *task)
9008 for_each_task_context_nr(ctxn)
9009 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9012 struct perf_event *perf_event_get(unsigned int fd)
9016 struct perf_event *event;
9018 err = perf_fget_light(fd, &f);
9020 return ERR_PTR(err);
9022 event = f.file->private_data;
9023 atomic_long_inc(&event->refcount);
9029 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9032 return ERR_PTR(-EINVAL);
9034 return &event->attr;
9038 * inherit a event from parent task to child task:
9040 static struct perf_event *
9041 inherit_event(struct perf_event *parent_event,
9042 struct task_struct *parent,
9043 struct perf_event_context *parent_ctx,
9044 struct task_struct *child,
9045 struct perf_event *group_leader,
9046 struct perf_event_context *child_ctx)
9048 enum perf_event_active_state parent_state = parent_event->state;
9049 struct perf_event *child_event;
9050 unsigned long flags;
9053 * Instead of creating recursive hierarchies of events,
9054 * we link inherited events back to the original parent,
9055 * which has a filp for sure, which we use as the reference
9058 if (parent_event->parent)
9059 parent_event = parent_event->parent;
9061 child_event = perf_event_alloc(&parent_event->attr,
9064 group_leader, parent_event,
9066 if (IS_ERR(child_event))
9069 if (is_orphaned_event(parent_event) ||
9070 !atomic_long_inc_not_zero(&parent_event->refcount)) {
9071 free_event(child_event);
9078 * Make the child state follow the state of the parent event,
9079 * not its attr.disabled bit. We hold the parent's mutex,
9080 * so we won't race with perf_event_{en, dis}able_family.
9082 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9083 child_event->state = PERF_EVENT_STATE_INACTIVE;
9085 child_event->state = PERF_EVENT_STATE_OFF;
9087 if (parent_event->attr.freq) {
9088 u64 sample_period = parent_event->hw.sample_period;
9089 struct hw_perf_event *hwc = &child_event->hw;
9091 hwc->sample_period = sample_period;
9092 hwc->last_period = sample_period;
9094 local64_set(&hwc->period_left, sample_period);
9097 child_event->ctx = child_ctx;
9098 child_event->overflow_handler = parent_event->overflow_handler;
9099 child_event->overflow_handler_context
9100 = parent_event->overflow_handler_context;
9103 * Precalculate sample_data sizes
9105 perf_event__header_size(child_event);
9106 perf_event__id_header_size(child_event);
9109 * Link it up in the child's context:
9111 raw_spin_lock_irqsave(&child_ctx->lock, flags);
9112 add_event_to_ctx(child_event, child_ctx);
9113 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9116 * Link this into the parent event's child list
9118 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9119 mutex_lock(&parent_event->child_mutex);
9120 list_add_tail(&child_event->child_list, &parent_event->child_list);
9121 mutex_unlock(&parent_event->child_mutex);
9126 static int inherit_group(struct perf_event *parent_event,
9127 struct task_struct *parent,
9128 struct perf_event_context *parent_ctx,
9129 struct task_struct *child,
9130 struct perf_event_context *child_ctx)
9132 struct perf_event *leader;
9133 struct perf_event *sub;
9134 struct perf_event *child_ctr;
9136 leader = inherit_event(parent_event, parent, parent_ctx,
9137 child, NULL, child_ctx);
9139 return PTR_ERR(leader);
9140 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9141 child_ctr = inherit_event(sub, parent, parent_ctx,
9142 child, leader, child_ctx);
9143 if (IS_ERR(child_ctr))
9144 return PTR_ERR(child_ctr);
9150 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9151 struct perf_event_context *parent_ctx,
9152 struct task_struct *child, int ctxn,
9156 struct perf_event_context *child_ctx;
9158 if (!event->attr.inherit) {
9163 child_ctx = child->perf_event_ctxp[ctxn];
9166 * This is executed from the parent task context, so
9167 * inherit events that have been marked for cloning.
9168 * First allocate and initialize a context for the
9172 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9176 child->perf_event_ctxp[ctxn] = child_ctx;
9179 ret = inherit_group(event, parent, parent_ctx,
9189 * Initialize the perf_event context in task_struct
9191 static int perf_event_init_context(struct task_struct *child, int ctxn)
9193 struct perf_event_context *child_ctx, *parent_ctx;
9194 struct perf_event_context *cloned_ctx;
9195 struct perf_event *event;
9196 struct task_struct *parent = current;
9197 int inherited_all = 1;
9198 unsigned long flags;
9201 if (likely(!parent->perf_event_ctxp[ctxn]))
9205 * If the parent's context is a clone, pin it so it won't get
9208 parent_ctx = perf_pin_task_context(parent, ctxn);
9213 * No need to check if parent_ctx != NULL here; since we saw
9214 * it non-NULL earlier, the only reason for it to become NULL
9215 * is if we exit, and since we're currently in the middle of
9216 * a fork we can't be exiting at the same time.
9220 * Lock the parent list. No need to lock the child - not PID
9221 * hashed yet and not running, so nobody can access it.
9223 mutex_lock(&parent_ctx->mutex);
9226 * We dont have to disable NMIs - we are only looking at
9227 * the list, not manipulating it:
9229 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9230 ret = inherit_task_group(event, parent, parent_ctx,
9231 child, ctxn, &inherited_all);
9237 * We can't hold ctx->lock when iterating the ->flexible_group list due
9238 * to allocations, but we need to prevent rotation because
9239 * rotate_ctx() will change the list from interrupt context.
9241 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9242 parent_ctx->rotate_disable = 1;
9243 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9245 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9246 ret = inherit_task_group(event, parent, parent_ctx,
9247 child, ctxn, &inherited_all);
9252 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9253 parent_ctx->rotate_disable = 0;
9255 child_ctx = child->perf_event_ctxp[ctxn];
9257 if (child_ctx && inherited_all) {
9259 * Mark the child context as a clone of the parent
9260 * context, or of whatever the parent is a clone of.
9262 * Note that if the parent is a clone, the holding of
9263 * parent_ctx->lock avoids it from being uncloned.
9265 cloned_ctx = parent_ctx->parent_ctx;
9267 child_ctx->parent_ctx = cloned_ctx;
9268 child_ctx->parent_gen = parent_ctx->parent_gen;
9270 child_ctx->parent_ctx = parent_ctx;
9271 child_ctx->parent_gen = parent_ctx->generation;
9273 get_ctx(child_ctx->parent_ctx);
9276 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9277 mutex_unlock(&parent_ctx->mutex);
9279 perf_unpin_context(parent_ctx);
9280 put_ctx(parent_ctx);
9286 * Initialize the perf_event context in task_struct
9288 int perf_event_init_task(struct task_struct *child)
9292 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9293 mutex_init(&child->perf_event_mutex);
9294 INIT_LIST_HEAD(&child->perf_event_list);
9296 for_each_task_context_nr(ctxn) {
9297 ret = perf_event_init_context(child, ctxn);
9299 perf_event_free_task(child);
9307 static void __init perf_event_init_all_cpus(void)
9309 struct swevent_htable *swhash;
9312 for_each_possible_cpu(cpu) {
9313 swhash = &per_cpu(swevent_htable, cpu);
9314 mutex_init(&swhash->hlist_mutex);
9315 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9319 static void perf_event_init_cpu(int cpu)
9321 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9323 mutex_lock(&swhash->hlist_mutex);
9324 if (swhash->hlist_refcount > 0) {
9325 struct swevent_hlist *hlist;
9327 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9329 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9331 mutex_unlock(&swhash->hlist_mutex);
9334 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9335 static void __perf_event_exit_context(void *__info)
9337 struct remove_event re = { .detach_group = true };
9338 struct perf_event_context *ctx = __info;
9341 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9342 __perf_remove_from_context(&re);
9346 static void perf_event_exit_cpu_context(int cpu)
9348 struct perf_event_context *ctx;
9352 idx = srcu_read_lock(&pmus_srcu);
9353 list_for_each_entry_rcu(pmu, &pmus, entry) {
9354 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9356 mutex_lock(&ctx->mutex);
9357 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9358 mutex_unlock(&ctx->mutex);
9360 srcu_read_unlock(&pmus_srcu, idx);
9363 static void perf_event_exit_cpu(int cpu)
9365 perf_event_exit_cpu_context(cpu);
9368 static inline void perf_event_exit_cpu(int cpu) { }
9372 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9376 for_each_online_cpu(cpu)
9377 perf_event_exit_cpu(cpu);
9383 * Run the perf reboot notifier at the very last possible moment so that
9384 * the generic watchdog code runs as long as possible.
9386 static struct notifier_block perf_reboot_notifier = {
9387 .notifier_call = perf_reboot,
9388 .priority = INT_MIN,
9392 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9394 unsigned int cpu = (long)hcpu;
9396 switch (action & ~CPU_TASKS_FROZEN) {
9398 case CPU_UP_PREPARE:
9399 case CPU_DOWN_FAILED:
9400 perf_event_init_cpu(cpu);
9403 case CPU_UP_CANCELED:
9404 case CPU_DOWN_PREPARE:
9405 perf_event_exit_cpu(cpu);
9414 void __init perf_event_init(void)
9420 perf_event_init_all_cpus();
9421 init_srcu_struct(&pmus_srcu);
9422 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9423 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9424 perf_pmu_register(&perf_task_clock, NULL, -1);
9426 perf_cpu_notifier(perf_cpu_notify);
9427 register_reboot_notifier(&perf_reboot_notifier);
9429 ret = init_hw_breakpoint();
9430 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9432 /* do not patch jump label more than once per second */
9433 jump_label_rate_limit(&perf_sched_events, HZ);
9436 * Build time assertion that we keep the data_head at the intended
9437 * location. IOW, validation we got the __reserved[] size right.
9439 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9443 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9446 struct perf_pmu_events_attr *pmu_attr =
9447 container_of(attr, struct perf_pmu_events_attr, attr);
9449 if (pmu_attr->event_str)
9450 return sprintf(page, "%s\n", pmu_attr->event_str);
9455 static int __init perf_event_sysfs_init(void)
9460 mutex_lock(&pmus_lock);
9462 ret = bus_register(&pmu_bus);
9466 list_for_each_entry(pmu, &pmus, entry) {
9467 if (!pmu->name || pmu->type < 0)
9470 ret = pmu_dev_alloc(pmu);
9471 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9473 pmu_bus_running = 1;
9477 mutex_unlock(&pmus_lock);
9481 device_initcall(perf_event_sysfs_init);
9483 #ifdef CONFIG_CGROUP_PERF
9484 static struct cgroup_subsys_state *
9485 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9487 struct perf_cgroup *jc;
9489 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9491 return ERR_PTR(-ENOMEM);
9493 jc->info = alloc_percpu(struct perf_cgroup_info);
9496 return ERR_PTR(-ENOMEM);
9502 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9504 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9506 free_percpu(jc->info);
9510 static int __perf_cgroup_move(void *info)
9512 struct task_struct *task = info;
9514 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9519 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9521 struct task_struct *task;
9522 struct cgroup_subsys_state *css;
9524 cgroup_taskset_for_each(task, css, tset)
9525 task_function_call(task, __perf_cgroup_move, task);
9528 struct cgroup_subsys perf_event_cgrp_subsys = {
9529 .css_alloc = perf_cgroup_css_alloc,
9530 .css_free = perf_cgroup_css_free,
9531 .attach = perf_cgroup_attach,
9533 #endif /* CONFIG_CGROUP_PERF */