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 <pzijlstr@redhat.com>
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/ftrace_event.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;
167 static LIST_HEAD(pmus);
168 static DEFINE_MUTEX(pmus_lock);
169 static struct srcu_struct pmus_srcu;
172 * perf event paranoia level:
173 * -1 - not paranoid at all
174 * 0 - disallow raw tracepoint access for unpriv
175 * 1 - disallow cpu events for unpriv
176 * 2 - disallow kernel profiling for unpriv
178 int sysctl_perf_event_paranoid __read_mostly = 1;
180 /* Minimum for 512 kiB + 1 user control page */
181 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
184 * max perf event sample rate
186 #define DEFAULT_MAX_SAMPLE_RATE 100000
187 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
188 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
190 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
192 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
193 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
195 static int perf_sample_allowed_ns __read_mostly =
196 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
198 void update_perf_cpu_limits(void)
200 u64 tmp = perf_sample_period_ns;
202 tmp *= sysctl_perf_cpu_time_max_percent;
204 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
207 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
209 int perf_proc_update_handler(struct ctl_table *table, int write,
210 void __user *buffer, size_t *lenp,
213 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
218 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
219 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
220 update_perf_cpu_limits();
225 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
227 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
228 void __user *buffer, size_t *lenp,
231 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
236 update_perf_cpu_limits();
242 * perf samples are done in some very critical code paths (NMIs).
243 * If they take too much CPU time, the system can lock up and not
244 * get any real work done. This will drop the sample rate when
245 * we detect that events are taking too long.
247 #define NR_ACCUMULATED_SAMPLES 128
248 static DEFINE_PER_CPU(u64, running_sample_length);
250 static void perf_duration_warn(struct irq_work *w)
252 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
253 u64 avg_local_sample_len;
254 u64 local_samples_len;
256 local_samples_len = __this_cpu_read(running_sample_length);
257 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
259 printk_ratelimited(KERN_WARNING
260 "perf interrupt took too long (%lld > %lld), lowering "
261 "kernel.perf_event_max_sample_rate to %d\n",
262 avg_local_sample_len, allowed_ns >> 1,
263 sysctl_perf_event_sample_rate);
266 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
268 void perf_sample_event_took(u64 sample_len_ns)
270 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
271 u64 avg_local_sample_len;
272 u64 local_samples_len;
277 /* decay the counter by 1 average sample */
278 local_samples_len = __this_cpu_read(running_sample_length);
279 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
280 local_samples_len += sample_len_ns;
281 __this_cpu_write(running_sample_length, local_samples_len);
284 * note: this will be biased artifically low until we have
285 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
286 * from having to maintain a count.
288 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
290 if (avg_local_sample_len <= allowed_ns)
293 if (max_samples_per_tick <= 1)
296 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
297 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
298 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
300 update_perf_cpu_limits();
302 if (!irq_work_queue(&perf_duration_work)) {
303 early_printk("perf interrupt took too long (%lld > %lld), lowering "
304 "kernel.perf_event_max_sample_rate to %d\n",
305 avg_local_sample_len, allowed_ns >> 1,
306 sysctl_perf_event_sample_rate);
310 static atomic64_t perf_event_id;
312 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
313 enum event_type_t event_type);
315 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
316 enum event_type_t event_type,
317 struct task_struct *task);
319 static void update_context_time(struct perf_event_context *ctx);
320 static u64 perf_event_time(struct perf_event *event);
322 void __weak perf_event_print_debug(void) { }
324 extern __weak const char *perf_pmu_name(void)
329 static inline u64 perf_clock(void)
331 return local_clock();
334 static inline u64 perf_event_clock(struct perf_event *event)
336 return event->clock();
339 static inline struct perf_cpu_context *
340 __get_cpu_context(struct perf_event_context *ctx)
342 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
345 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
346 struct perf_event_context *ctx)
348 raw_spin_lock(&cpuctx->ctx.lock);
350 raw_spin_lock(&ctx->lock);
353 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
354 struct perf_event_context *ctx)
357 raw_spin_unlock(&ctx->lock);
358 raw_spin_unlock(&cpuctx->ctx.lock);
361 #ifdef CONFIG_CGROUP_PERF
364 perf_cgroup_match(struct perf_event *event)
366 struct perf_event_context *ctx = event->ctx;
367 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
369 /* @event doesn't care about cgroup */
373 /* wants specific cgroup scope but @cpuctx isn't associated with any */
378 * Cgroup scoping is recursive. An event enabled for a cgroup is
379 * also enabled for all its descendant cgroups. If @cpuctx's
380 * cgroup is a descendant of @event's (the test covers identity
381 * case), it's a match.
383 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
384 event->cgrp->css.cgroup);
387 static inline void perf_detach_cgroup(struct perf_event *event)
389 css_put(&event->cgrp->css);
393 static inline int is_cgroup_event(struct perf_event *event)
395 return event->cgrp != NULL;
398 static inline u64 perf_cgroup_event_time(struct perf_event *event)
400 struct perf_cgroup_info *t;
402 t = per_cpu_ptr(event->cgrp->info, event->cpu);
406 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
408 struct perf_cgroup_info *info;
413 info = this_cpu_ptr(cgrp->info);
415 info->time += now - info->timestamp;
416 info->timestamp = now;
419 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
421 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
423 __update_cgrp_time(cgrp_out);
426 static inline void update_cgrp_time_from_event(struct perf_event *event)
428 struct perf_cgroup *cgrp;
431 * ensure we access cgroup data only when needed and
432 * when we know the cgroup is pinned (css_get)
434 if (!is_cgroup_event(event))
437 cgrp = perf_cgroup_from_task(current);
439 * Do not update time when cgroup is not active
441 if (cgrp == event->cgrp)
442 __update_cgrp_time(event->cgrp);
446 perf_cgroup_set_timestamp(struct task_struct *task,
447 struct perf_event_context *ctx)
449 struct perf_cgroup *cgrp;
450 struct perf_cgroup_info *info;
453 * ctx->lock held by caller
454 * ensure we do not access cgroup data
455 * unless we have the cgroup pinned (css_get)
457 if (!task || !ctx->nr_cgroups)
460 cgrp = perf_cgroup_from_task(task);
461 info = this_cpu_ptr(cgrp->info);
462 info->timestamp = ctx->timestamp;
465 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
466 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
469 * reschedule events based on the cgroup constraint of task.
471 * mode SWOUT : schedule out everything
472 * mode SWIN : schedule in based on cgroup for next
474 void perf_cgroup_switch(struct task_struct *task, int mode)
476 struct perf_cpu_context *cpuctx;
481 * disable interrupts to avoid geting nr_cgroup
482 * changes via __perf_event_disable(). Also
485 local_irq_save(flags);
488 * we reschedule only in the presence of cgroup
489 * 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
525 cpuctx->cgrp = perf_cgroup_from_task(task);
526 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
528 perf_pmu_enable(cpuctx->ctx.pmu);
529 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;
545 * we come here when we know perf_cgroup_events > 0
547 cgrp1 = perf_cgroup_from_task(task);
550 * next is NULL when called from perf_event_enable_on_exec()
551 * that will systematically cause a cgroup_switch()
554 cgrp2 = perf_cgroup_from_task(next);
557 * only schedule out current cgroup events if we know
558 * that we are switching to a different cgroup. Otherwise,
559 * do no touch the cgroup events.
562 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
565 static inline void perf_cgroup_sched_in(struct task_struct *prev,
566 struct task_struct *task)
568 struct perf_cgroup *cgrp1;
569 struct perf_cgroup *cgrp2 = NULL;
572 * we come here when we know perf_cgroup_events > 0
574 cgrp1 = perf_cgroup_from_task(task);
576 /* prev can never be NULL */
577 cgrp2 = perf_cgroup_from_task(prev);
580 * only need to schedule in cgroup events if we are changing
581 * cgroup during ctxsw. Cgroup events were not scheduled
582 * out of ctxsw out if that was not the case.
585 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
588 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
589 struct perf_event_attr *attr,
590 struct perf_event *group_leader)
592 struct perf_cgroup *cgrp;
593 struct cgroup_subsys_state *css;
594 struct fd f = fdget(fd);
600 css = css_tryget_online_from_dir(f.file->f_path.dentry,
601 &perf_event_cgrp_subsys);
607 cgrp = container_of(css, struct perf_cgroup, css);
611 * all events in a group must monitor
612 * the same cgroup because a task belongs
613 * to only one perf cgroup at a time
615 if (group_leader && group_leader->cgrp != cgrp) {
616 perf_detach_cgroup(event);
625 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
627 struct perf_cgroup_info *t;
628 t = per_cpu_ptr(event->cgrp->info, event->cpu);
629 event->shadow_ctx_time = now - t->timestamp;
633 perf_cgroup_defer_enabled(struct perf_event *event)
636 * when the current task's perf cgroup does not match
637 * the event's, we need to remember to call the
638 * perf_mark_enable() function the first time a task with
639 * a matching perf cgroup is scheduled in.
641 if (is_cgroup_event(event) && !perf_cgroup_match(event))
642 event->cgrp_defer_enabled = 1;
646 perf_cgroup_mark_enabled(struct perf_event *event,
647 struct perf_event_context *ctx)
649 struct perf_event *sub;
650 u64 tstamp = perf_event_time(event);
652 if (!event->cgrp_defer_enabled)
655 event->cgrp_defer_enabled = 0;
657 event->tstamp_enabled = tstamp - event->total_time_enabled;
658 list_for_each_entry(sub, &event->sibling_list, group_entry) {
659 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
660 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
661 sub->cgrp_defer_enabled = 0;
665 #else /* !CONFIG_CGROUP_PERF */
668 perf_cgroup_match(struct perf_event *event)
673 static inline void perf_detach_cgroup(struct perf_event *event)
676 static inline int is_cgroup_event(struct perf_event *event)
681 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
686 static inline void update_cgrp_time_from_event(struct perf_event *event)
690 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
694 static inline void perf_cgroup_sched_out(struct task_struct *task,
695 struct task_struct *next)
699 static inline void perf_cgroup_sched_in(struct task_struct *prev,
700 struct task_struct *task)
704 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
705 struct perf_event_attr *attr,
706 struct perf_event *group_leader)
712 perf_cgroup_set_timestamp(struct task_struct *task,
713 struct perf_event_context *ctx)
718 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
723 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
727 static inline u64 perf_cgroup_event_time(struct perf_event *event)
733 perf_cgroup_defer_enabled(struct perf_event *event)
738 perf_cgroup_mark_enabled(struct perf_event *event,
739 struct perf_event_context *ctx)
745 * set default to be dependent on timer tick just
748 #define PERF_CPU_HRTIMER (1000 / HZ)
750 * function must be called with interrupts disbled
752 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
754 struct perf_cpu_context *cpuctx;
757 WARN_ON(!irqs_disabled());
759 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
760 rotations = perf_rotate_context(cpuctx);
762 raw_spin_lock(&cpuctx->hrtimer_lock);
764 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
766 cpuctx->hrtimer_active = 0;
767 raw_spin_unlock(&cpuctx->hrtimer_lock);
769 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
772 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
774 struct hrtimer *timer = &cpuctx->hrtimer;
775 struct pmu *pmu = cpuctx->ctx.pmu;
778 /* no multiplexing needed for SW PMU */
779 if (pmu->task_ctx_nr == perf_sw_context)
783 * check default is sane, if not set then force to
784 * default interval (1/tick)
786 interval = pmu->hrtimer_interval_ms;
788 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
790 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
792 raw_spin_lock_init(&cpuctx->hrtimer_lock);
793 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
794 timer->function = perf_mux_hrtimer_handler;
797 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
799 struct hrtimer *timer = &cpuctx->hrtimer;
800 struct pmu *pmu = cpuctx->ctx.pmu;
804 if (pmu->task_ctx_nr == perf_sw_context)
807 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
808 if (!cpuctx->hrtimer_active) {
809 cpuctx->hrtimer_active = 1;
810 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
811 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
813 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
818 void perf_pmu_disable(struct pmu *pmu)
820 int *count = this_cpu_ptr(pmu->pmu_disable_count);
822 pmu->pmu_disable(pmu);
825 void perf_pmu_enable(struct pmu *pmu)
827 int *count = this_cpu_ptr(pmu->pmu_disable_count);
829 pmu->pmu_enable(pmu);
832 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
835 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
836 * perf_event_task_tick() are fully serialized because they're strictly cpu
837 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
838 * disabled, while perf_event_task_tick is called from IRQ context.
840 static void perf_event_ctx_activate(struct perf_event_context *ctx)
842 struct list_head *head = this_cpu_ptr(&active_ctx_list);
844 WARN_ON(!irqs_disabled());
846 WARN_ON(!list_empty(&ctx->active_ctx_list));
848 list_add(&ctx->active_ctx_list, head);
851 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
853 WARN_ON(!irqs_disabled());
855 WARN_ON(list_empty(&ctx->active_ctx_list));
857 list_del_init(&ctx->active_ctx_list);
860 static void get_ctx(struct perf_event_context *ctx)
862 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
865 static void free_ctx(struct rcu_head *head)
867 struct perf_event_context *ctx;
869 ctx = container_of(head, struct perf_event_context, rcu_head);
870 kfree(ctx->task_ctx_data);
874 static void put_ctx(struct perf_event_context *ctx)
876 if (atomic_dec_and_test(&ctx->refcount)) {
878 put_ctx(ctx->parent_ctx);
880 put_task_struct(ctx->task);
881 call_rcu(&ctx->rcu_head, free_ctx);
886 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
887 * perf_pmu_migrate_context() we need some magic.
889 * Those places that change perf_event::ctx will hold both
890 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
892 * Lock ordering is by mutex address. There are two other sites where
893 * perf_event_context::mutex nests and those are:
895 * - perf_event_exit_task_context() [ child , 0 ]
896 * __perf_event_exit_task()
898 * put_event() [ parent, 1 ]
900 * - perf_event_init_context() [ parent, 0 ]
901 * inherit_task_group()
906 * perf_try_init_event() [ child , 1 ]
908 * While it appears there is an obvious deadlock here -- the parent and child
909 * nesting levels are inverted between the two. This is in fact safe because
910 * life-time rules separate them. That is an exiting task cannot fork, and a
911 * spawning task cannot (yet) exit.
913 * But remember that that these are parent<->child context relations, and
914 * migration does not affect children, therefore these two orderings should not
917 * The change in perf_event::ctx does not affect children (as claimed above)
918 * because the sys_perf_event_open() case will install a new event and break
919 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
920 * concerned with cpuctx and that doesn't have children.
922 * The places that change perf_event::ctx will issue:
924 * perf_remove_from_context();
926 * perf_install_in_context();
928 * to affect the change. The remove_from_context() + synchronize_rcu() should
929 * quiesce the event, after which we can install it in the new location. This
930 * means that only external vectors (perf_fops, prctl) can perturb the event
931 * while in transit. Therefore all such accessors should also acquire
932 * perf_event_context::mutex to serialize against this.
934 * However; because event->ctx can change while we're waiting to acquire
935 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
939 * task_struct::perf_event_mutex
940 * perf_event_context::mutex
941 * perf_event_context::lock
942 * perf_event::child_mutex;
943 * perf_event::mmap_mutex
946 static struct perf_event_context *
947 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
949 struct perf_event_context *ctx;
953 ctx = ACCESS_ONCE(event->ctx);
954 if (!atomic_inc_not_zero(&ctx->refcount)) {
960 mutex_lock_nested(&ctx->mutex, nesting);
961 if (event->ctx != ctx) {
962 mutex_unlock(&ctx->mutex);
970 static inline struct perf_event_context *
971 perf_event_ctx_lock(struct perf_event *event)
973 return perf_event_ctx_lock_nested(event, 0);
976 static void perf_event_ctx_unlock(struct perf_event *event,
977 struct perf_event_context *ctx)
979 mutex_unlock(&ctx->mutex);
984 * This must be done under the ctx->lock, such as to serialize against
985 * context_equiv(), therefore we cannot call put_ctx() since that might end up
986 * calling scheduler related locks and ctx->lock nests inside those.
988 static __must_check struct perf_event_context *
989 unclone_ctx(struct perf_event_context *ctx)
991 struct perf_event_context *parent_ctx = ctx->parent_ctx;
993 lockdep_assert_held(&ctx->lock);
996 ctx->parent_ctx = NULL;
1002 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1005 * only top level events have the pid namespace they were created in
1008 event = event->parent;
1010 return task_tgid_nr_ns(p, event->ns);
1013 static u32 perf_event_tid(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_pid_nr_ns(p, event->ns);
1025 * If we inherit events we want to return the parent event id
1028 static u64 primary_event_id(struct perf_event *event)
1033 id = event->parent->id;
1039 * Get the perf_event_context for a task and lock it.
1040 * This has to cope with with the fact that until it is locked,
1041 * the context could get moved to another task.
1043 static struct perf_event_context *
1044 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1046 struct perf_event_context *ctx;
1050 * One of the few rules of preemptible RCU is that one cannot do
1051 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1052 * part of the read side critical section was preemptible -- see
1053 * rcu_read_unlock_special().
1055 * Since ctx->lock nests under rq->lock we must ensure the entire read
1056 * side critical section is non-preemptible.
1060 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1063 * If this context is a clone of another, it might
1064 * get swapped for another underneath us by
1065 * perf_event_task_sched_out, though the
1066 * rcu_read_lock() protects us from any context
1067 * getting freed. Lock the context and check if it
1068 * got swapped before we could get the lock, and retry
1069 * if so. If we locked the right context, then it
1070 * can't get swapped on us any more.
1072 raw_spin_lock_irqsave(&ctx->lock, *flags);
1073 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1074 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1080 if (!atomic_inc_not_zero(&ctx->refcount)) {
1081 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1091 * Get the context for a task and increment its pin_count so it
1092 * can't get swapped to another task. This also increments its
1093 * reference count so that the context can't get freed.
1095 static struct perf_event_context *
1096 perf_pin_task_context(struct task_struct *task, int ctxn)
1098 struct perf_event_context *ctx;
1099 unsigned long flags;
1101 ctx = perf_lock_task_context(task, ctxn, &flags);
1104 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1109 static void perf_unpin_context(struct perf_event_context *ctx)
1111 unsigned long flags;
1113 raw_spin_lock_irqsave(&ctx->lock, flags);
1115 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1119 * Update the record of the current time in a context.
1121 static void update_context_time(struct perf_event_context *ctx)
1123 u64 now = perf_clock();
1125 ctx->time += now - ctx->timestamp;
1126 ctx->timestamp = now;
1129 static u64 perf_event_time(struct perf_event *event)
1131 struct perf_event_context *ctx = event->ctx;
1133 if (is_cgroup_event(event))
1134 return perf_cgroup_event_time(event);
1136 return ctx ? ctx->time : 0;
1140 * Update the total_time_enabled and total_time_running fields for a event.
1141 * The caller of this function needs to hold the ctx->lock.
1143 static void update_event_times(struct perf_event *event)
1145 struct perf_event_context *ctx = event->ctx;
1148 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1149 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1152 * in cgroup mode, time_enabled represents
1153 * the time the event was enabled AND active
1154 * tasks were in the monitored cgroup. This is
1155 * independent of the activity of the context as
1156 * there may be a mix of cgroup and non-cgroup events.
1158 * That is why we treat cgroup events differently
1161 if (is_cgroup_event(event))
1162 run_end = perf_cgroup_event_time(event);
1163 else if (ctx->is_active)
1164 run_end = ctx->time;
1166 run_end = event->tstamp_stopped;
1168 event->total_time_enabled = run_end - event->tstamp_enabled;
1170 if (event->state == PERF_EVENT_STATE_INACTIVE)
1171 run_end = event->tstamp_stopped;
1173 run_end = perf_event_time(event);
1175 event->total_time_running = run_end - event->tstamp_running;
1180 * Update total_time_enabled and total_time_running for all events in a group.
1182 static void update_group_times(struct perf_event *leader)
1184 struct perf_event *event;
1186 update_event_times(leader);
1187 list_for_each_entry(event, &leader->sibling_list, group_entry)
1188 update_event_times(event);
1191 static struct list_head *
1192 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1194 if (event->attr.pinned)
1195 return &ctx->pinned_groups;
1197 return &ctx->flexible_groups;
1201 * Add a event from the lists for its context.
1202 * Must be called with ctx->mutex and ctx->lock held.
1205 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1207 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1208 event->attach_state |= PERF_ATTACH_CONTEXT;
1211 * If we're a stand alone event or group leader, we go to the context
1212 * list, group events are kept attached to the group so that
1213 * perf_group_detach can, at all times, locate all siblings.
1215 if (event->group_leader == event) {
1216 struct list_head *list;
1218 if (is_software_event(event))
1219 event->group_flags |= PERF_GROUP_SOFTWARE;
1221 list = ctx_group_list(event, ctx);
1222 list_add_tail(&event->group_entry, list);
1225 if (is_cgroup_event(event))
1228 list_add_rcu(&event->event_entry, &ctx->event_list);
1230 if (event->attr.inherit_stat)
1237 * Initialize event state based on the perf_event_attr::disabled.
1239 static inline void perf_event__state_init(struct perf_event *event)
1241 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1242 PERF_EVENT_STATE_INACTIVE;
1246 * Called at perf_event creation and when events are attached/detached from a
1249 static void perf_event__read_size(struct perf_event *event)
1251 int entry = sizeof(u64); /* value */
1255 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1256 size += sizeof(u64);
1258 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1259 size += sizeof(u64);
1261 if (event->attr.read_format & PERF_FORMAT_ID)
1262 entry += sizeof(u64);
1264 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1265 nr += event->group_leader->nr_siblings;
1266 size += sizeof(u64);
1270 event->read_size = size;
1273 static void perf_event__header_size(struct perf_event *event)
1275 struct perf_sample_data *data;
1276 u64 sample_type = event->attr.sample_type;
1279 perf_event__read_size(event);
1281 if (sample_type & PERF_SAMPLE_IP)
1282 size += sizeof(data->ip);
1284 if (sample_type & PERF_SAMPLE_ADDR)
1285 size += sizeof(data->addr);
1287 if (sample_type & PERF_SAMPLE_PERIOD)
1288 size += sizeof(data->period);
1290 if (sample_type & PERF_SAMPLE_WEIGHT)
1291 size += sizeof(data->weight);
1293 if (sample_type & PERF_SAMPLE_READ)
1294 size += event->read_size;
1296 if (sample_type & PERF_SAMPLE_DATA_SRC)
1297 size += sizeof(data->data_src.val);
1299 if (sample_type & PERF_SAMPLE_TRANSACTION)
1300 size += sizeof(data->txn);
1302 event->header_size = size;
1305 static void perf_event__id_header_size(struct perf_event *event)
1307 struct perf_sample_data *data;
1308 u64 sample_type = event->attr.sample_type;
1311 if (sample_type & PERF_SAMPLE_TID)
1312 size += sizeof(data->tid_entry);
1314 if (sample_type & PERF_SAMPLE_TIME)
1315 size += sizeof(data->time);
1317 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1318 size += sizeof(data->id);
1320 if (sample_type & PERF_SAMPLE_ID)
1321 size += sizeof(data->id);
1323 if (sample_type & PERF_SAMPLE_STREAM_ID)
1324 size += sizeof(data->stream_id);
1326 if (sample_type & PERF_SAMPLE_CPU)
1327 size += sizeof(data->cpu_entry);
1329 event->id_header_size = size;
1332 static void perf_group_attach(struct perf_event *event)
1334 struct perf_event *group_leader = event->group_leader, *pos;
1337 * We can have double attach due to group movement in perf_event_open.
1339 if (event->attach_state & PERF_ATTACH_GROUP)
1342 event->attach_state |= PERF_ATTACH_GROUP;
1344 if (group_leader == event)
1347 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1349 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1350 !is_software_event(event))
1351 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1353 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1354 group_leader->nr_siblings++;
1356 perf_event__header_size(group_leader);
1358 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1359 perf_event__header_size(pos);
1363 * Remove a event from the lists for its context.
1364 * Must be called with ctx->mutex and ctx->lock held.
1367 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1369 struct perf_cpu_context *cpuctx;
1371 WARN_ON_ONCE(event->ctx != ctx);
1372 lockdep_assert_held(&ctx->lock);
1375 * We can have double detach due to exit/hot-unplug + close.
1377 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1380 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1382 if (is_cgroup_event(event)) {
1384 cpuctx = __get_cpu_context(ctx);
1386 * if there are no more cgroup events
1387 * then cler cgrp to avoid stale pointer
1388 * in update_cgrp_time_from_cpuctx()
1390 if (!ctx->nr_cgroups)
1391 cpuctx->cgrp = NULL;
1395 if (event->attr.inherit_stat)
1398 list_del_rcu(&event->event_entry);
1400 if (event->group_leader == event)
1401 list_del_init(&event->group_entry);
1403 update_group_times(event);
1406 * If event was in error state, then keep it
1407 * that way, otherwise bogus counts will be
1408 * returned on read(). The only way to get out
1409 * of error state is by explicit re-enabling
1412 if (event->state > PERF_EVENT_STATE_OFF)
1413 event->state = PERF_EVENT_STATE_OFF;
1418 static void perf_group_detach(struct perf_event *event)
1420 struct perf_event *sibling, *tmp;
1421 struct list_head *list = NULL;
1424 * We can have double detach due to exit/hot-unplug + close.
1426 if (!(event->attach_state & PERF_ATTACH_GROUP))
1429 event->attach_state &= ~PERF_ATTACH_GROUP;
1432 * If this is a sibling, remove it from its group.
1434 if (event->group_leader != event) {
1435 list_del_init(&event->group_entry);
1436 event->group_leader->nr_siblings--;
1440 if (!list_empty(&event->group_entry))
1441 list = &event->group_entry;
1444 * If this was a group event with sibling events then
1445 * upgrade the siblings to singleton events by adding them
1446 * to whatever list we are on.
1448 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1450 list_move_tail(&sibling->group_entry, list);
1451 sibling->group_leader = sibling;
1453 /* Inherit group flags from the previous leader */
1454 sibling->group_flags = event->group_flags;
1456 WARN_ON_ONCE(sibling->ctx != event->ctx);
1460 perf_event__header_size(event->group_leader);
1462 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1463 perf_event__header_size(tmp);
1467 * User event without the task.
1469 static bool is_orphaned_event(struct perf_event *event)
1471 return event && !is_kernel_event(event) && !event->owner;
1475 * Event has a parent but parent's task finished and it's
1476 * alive only because of children holding refference.
1478 static bool is_orphaned_child(struct perf_event *event)
1480 return is_orphaned_event(event->parent);
1483 static void orphans_remove_work(struct work_struct *work);
1485 static void schedule_orphans_remove(struct perf_event_context *ctx)
1487 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1490 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1492 ctx->orphans_remove_sched = true;
1496 static int __init perf_workqueue_init(void)
1498 perf_wq = create_singlethread_workqueue("perf");
1499 WARN(!perf_wq, "failed to create perf workqueue\n");
1500 return perf_wq ? 0 : -1;
1503 core_initcall(perf_workqueue_init);
1506 event_filter_match(struct perf_event *event)
1508 return (event->cpu == -1 || event->cpu == smp_processor_id())
1509 && perf_cgroup_match(event);
1513 event_sched_out(struct perf_event *event,
1514 struct perf_cpu_context *cpuctx,
1515 struct perf_event_context *ctx)
1517 u64 tstamp = perf_event_time(event);
1520 WARN_ON_ONCE(event->ctx != ctx);
1521 lockdep_assert_held(&ctx->lock);
1524 * An event which could not be activated because of
1525 * filter mismatch still needs to have its timings
1526 * maintained, otherwise bogus information is return
1527 * via read() for time_enabled, time_running:
1529 if (event->state == PERF_EVENT_STATE_INACTIVE
1530 && !event_filter_match(event)) {
1531 delta = tstamp - event->tstamp_stopped;
1532 event->tstamp_running += delta;
1533 event->tstamp_stopped = tstamp;
1536 if (event->state != PERF_EVENT_STATE_ACTIVE)
1539 perf_pmu_disable(event->pmu);
1541 event->state = PERF_EVENT_STATE_INACTIVE;
1542 if (event->pending_disable) {
1543 event->pending_disable = 0;
1544 event->state = PERF_EVENT_STATE_OFF;
1546 event->tstamp_stopped = tstamp;
1547 event->pmu->del(event, 0);
1550 if (!is_software_event(event))
1551 cpuctx->active_oncpu--;
1552 if (!--ctx->nr_active)
1553 perf_event_ctx_deactivate(ctx);
1554 if (event->attr.freq && event->attr.sample_freq)
1556 if (event->attr.exclusive || !cpuctx->active_oncpu)
1557 cpuctx->exclusive = 0;
1559 if (is_orphaned_child(event))
1560 schedule_orphans_remove(ctx);
1562 perf_pmu_enable(event->pmu);
1566 group_sched_out(struct perf_event *group_event,
1567 struct perf_cpu_context *cpuctx,
1568 struct perf_event_context *ctx)
1570 struct perf_event *event;
1571 int state = group_event->state;
1573 event_sched_out(group_event, cpuctx, ctx);
1576 * Schedule out siblings (if any):
1578 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1579 event_sched_out(event, cpuctx, ctx);
1581 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1582 cpuctx->exclusive = 0;
1585 struct remove_event {
1586 struct perf_event *event;
1591 * Cross CPU call to remove a performance event
1593 * We disable the event on the hardware level first. After that we
1594 * remove it from the context list.
1596 static int __perf_remove_from_context(void *info)
1598 struct remove_event *re = info;
1599 struct perf_event *event = re->event;
1600 struct perf_event_context *ctx = event->ctx;
1601 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1603 raw_spin_lock(&ctx->lock);
1604 event_sched_out(event, cpuctx, ctx);
1605 if (re->detach_group)
1606 perf_group_detach(event);
1607 list_del_event(event, ctx);
1608 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1610 cpuctx->task_ctx = NULL;
1612 raw_spin_unlock(&ctx->lock);
1619 * Remove the event from a task's (or a CPU's) list of events.
1621 * CPU events are removed with a smp call. For task events we only
1622 * call when the task is on a CPU.
1624 * If event->ctx is a cloned context, callers must make sure that
1625 * every task struct that event->ctx->task could possibly point to
1626 * remains valid. This is OK when called from perf_release since
1627 * that only calls us on the top-level context, which can't be a clone.
1628 * When called from perf_event_exit_task, it's OK because the
1629 * context has been detached from its task.
1631 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1633 struct perf_event_context *ctx = event->ctx;
1634 struct task_struct *task = ctx->task;
1635 struct remove_event re = {
1637 .detach_group = detach_group,
1640 lockdep_assert_held(&ctx->mutex);
1644 * Per cpu events are removed via an smp call. The removal can
1645 * fail if the CPU is currently offline, but in that case we
1646 * already called __perf_remove_from_context from
1647 * perf_event_exit_cpu.
1649 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1654 if (!task_function_call(task, __perf_remove_from_context, &re))
1657 raw_spin_lock_irq(&ctx->lock);
1659 * If we failed to find a running task, but find the context active now
1660 * that we've acquired the ctx->lock, retry.
1662 if (ctx->is_active) {
1663 raw_spin_unlock_irq(&ctx->lock);
1665 * Reload the task pointer, it might have been changed by
1666 * a concurrent perf_event_context_sched_out().
1673 * Since the task isn't running, its safe to remove the event, us
1674 * holding the ctx->lock ensures the task won't get scheduled in.
1677 perf_group_detach(event);
1678 list_del_event(event, ctx);
1679 raw_spin_unlock_irq(&ctx->lock);
1683 * Cross CPU call to disable a performance event
1685 int __perf_event_disable(void *info)
1687 struct perf_event *event = info;
1688 struct perf_event_context *ctx = event->ctx;
1689 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1692 * If this is a per-task event, need to check whether this
1693 * event's task is the current task on this cpu.
1695 * Can trigger due to concurrent perf_event_context_sched_out()
1696 * flipping contexts around.
1698 if (ctx->task && cpuctx->task_ctx != ctx)
1701 raw_spin_lock(&ctx->lock);
1704 * If the event is on, turn it off.
1705 * If it is in error state, leave it in error state.
1707 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1708 update_context_time(ctx);
1709 update_cgrp_time_from_event(event);
1710 update_group_times(event);
1711 if (event == event->group_leader)
1712 group_sched_out(event, cpuctx, ctx);
1714 event_sched_out(event, cpuctx, ctx);
1715 event->state = PERF_EVENT_STATE_OFF;
1718 raw_spin_unlock(&ctx->lock);
1726 * If event->ctx is a cloned context, callers must make sure that
1727 * every task struct that event->ctx->task could possibly point to
1728 * remains valid. This condition is satisifed when called through
1729 * perf_event_for_each_child or perf_event_for_each because they
1730 * hold the top-level event's child_mutex, so any descendant that
1731 * goes to exit will block in sync_child_event.
1732 * When called from perf_pending_event it's OK because event->ctx
1733 * is the current context on this CPU and preemption is disabled,
1734 * hence we can't get into perf_event_task_sched_out for this context.
1736 static void _perf_event_disable(struct perf_event *event)
1738 struct perf_event_context *ctx = event->ctx;
1739 struct task_struct *task = ctx->task;
1743 * Disable the event on the cpu that it's on
1745 cpu_function_call(event->cpu, __perf_event_disable, event);
1750 if (!task_function_call(task, __perf_event_disable, event))
1753 raw_spin_lock_irq(&ctx->lock);
1755 * If the event is still active, we need to retry the cross-call.
1757 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1758 raw_spin_unlock_irq(&ctx->lock);
1760 * Reload the task pointer, it might have been changed by
1761 * a concurrent perf_event_context_sched_out().
1768 * Since we have the lock this context can't be scheduled
1769 * in, so we can change the state safely.
1771 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1772 update_group_times(event);
1773 event->state = PERF_EVENT_STATE_OFF;
1775 raw_spin_unlock_irq(&ctx->lock);
1779 * Strictly speaking kernel users cannot create groups and therefore this
1780 * interface does not need the perf_event_ctx_lock() magic.
1782 void perf_event_disable(struct perf_event *event)
1784 struct perf_event_context *ctx;
1786 ctx = perf_event_ctx_lock(event);
1787 _perf_event_disable(event);
1788 perf_event_ctx_unlock(event, ctx);
1790 EXPORT_SYMBOL_GPL(perf_event_disable);
1792 static void perf_set_shadow_time(struct perf_event *event,
1793 struct perf_event_context *ctx,
1797 * use the correct time source for the time snapshot
1799 * We could get by without this by leveraging the
1800 * fact that to get to this function, the caller
1801 * has most likely already called update_context_time()
1802 * and update_cgrp_time_xx() and thus both timestamp
1803 * are identical (or very close). Given that tstamp is,
1804 * already adjusted for cgroup, we could say that:
1805 * tstamp - ctx->timestamp
1807 * tstamp - cgrp->timestamp.
1809 * Then, in perf_output_read(), the calculation would
1810 * work with no changes because:
1811 * - event is guaranteed scheduled in
1812 * - no scheduled out in between
1813 * - thus the timestamp would be the same
1815 * But this is a bit hairy.
1817 * So instead, we have an explicit cgroup call to remain
1818 * within the time time source all along. We believe it
1819 * is cleaner and simpler to understand.
1821 if (is_cgroup_event(event))
1822 perf_cgroup_set_shadow_time(event, tstamp);
1824 event->shadow_ctx_time = tstamp - ctx->timestamp;
1827 #define MAX_INTERRUPTS (~0ULL)
1829 static void perf_log_throttle(struct perf_event *event, int enable);
1830 static void perf_log_itrace_start(struct perf_event *event);
1833 event_sched_in(struct perf_event *event,
1834 struct perf_cpu_context *cpuctx,
1835 struct perf_event_context *ctx)
1837 u64 tstamp = perf_event_time(event);
1840 lockdep_assert_held(&ctx->lock);
1842 if (event->state <= PERF_EVENT_STATE_OFF)
1845 event->state = PERF_EVENT_STATE_ACTIVE;
1846 event->oncpu = smp_processor_id();
1849 * Unthrottle events, since we scheduled we might have missed several
1850 * ticks already, also for a heavily scheduling task there is little
1851 * guarantee it'll get a tick in a timely manner.
1853 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1854 perf_log_throttle(event, 1);
1855 event->hw.interrupts = 0;
1859 * The new state must be visible before we turn it on in the hardware:
1863 perf_pmu_disable(event->pmu);
1865 event->tstamp_running += tstamp - event->tstamp_stopped;
1867 perf_set_shadow_time(event, ctx, tstamp);
1869 perf_log_itrace_start(event);
1871 if (event->pmu->add(event, PERF_EF_START)) {
1872 event->state = PERF_EVENT_STATE_INACTIVE;
1878 if (!is_software_event(event))
1879 cpuctx->active_oncpu++;
1880 if (!ctx->nr_active++)
1881 perf_event_ctx_activate(ctx);
1882 if (event->attr.freq && event->attr.sample_freq)
1885 if (event->attr.exclusive)
1886 cpuctx->exclusive = 1;
1888 if (is_orphaned_child(event))
1889 schedule_orphans_remove(ctx);
1892 perf_pmu_enable(event->pmu);
1898 group_sched_in(struct perf_event *group_event,
1899 struct perf_cpu_context *cpuctx,
1900 struct perf_event_context *ctx)
1902 struct perf_event *event, *partial_group = NULL;
1903 struct pmu *pmu = ctx->pmu;
1904 u64 now = ctx->time;
1905 bool simulate = false;
1907 if (group_event->state == PERF_EVENT_STATE_OFF)
1910 pmu->start_txn(pmu);
1912 if (event_sched_in(group_event, cpuctx, ctx)) {
1913 pmu->cancel_txn(pmu);
1914 perf_mux_hrtimer_restart(cpuctx);
1919 * Schedule in siblings as one group (if any):
1921 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1922 if (event_sched_in(event, cpuctx, ctx)) {
1923 partial_group = event;
1928 if (!pmu->commit_txn(pmu))
1933 * Groups can be scheduled in as one unit only, so undo any
1934 * partial group before returning:
1935 * The events up to the failed event are scheduled out normally,
1936 * tstamp_stopped will be updated.
1938 * The failed events and the remaining siblings need to have
1939 * their timings updated as if they had gone thru event_sched_in()
1940 * and event_sched_out(). This is required to get consistent timings
1941 * across the group. This also takes care of the case where the group
1942 * could never be scheduled by ensuring tstamp_stopped is set to mark
1943 * the time the event was actually stopped, such that time delta
1944 * calculation in update_event_times() is correct.
1946 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1947 if (event == partial_group)
1951 event->tstamp_running += now - event->tstamp_stopped;
1952 event->tstamp_stopped = now;
1954 event_sched_out(event, cpuctx, ctx);
1957 event_sched_out(group_event, cpuctx, ctx);
1959 pmu->cancel_txn(pmu);
1961 perf_mux_hrtimer_restart(cpuctx);
1967 * Work out whether we can put this event group on the CPU now.
1969 static int group_can_go_on(struct perf_event *event,
1970 struct perf_cpu_context *cpuctx,
1974 * Groups consisting entirely of software events can always go on.
1976 if (event->group_flags & PERF_GROUP_SOFTWARE)
1979 * If an exclusive group is already on, no other hardware
1982 if (cpuctx->exclusive)
1985 * If this group is exclusive and there are already
1986 * events on the CPU, it can't go on.
1988 if (event->attr.exclusive && cpuctx->active_oncpu)
1991 * Otherwise, try to add it if all previous groups were able
1997 static void add_event_to_ctx(struct perf_event *event,
1998 struct perf_event_context *ctx)
2000 u64 tstamp = perf_event_time(event);
2002 list_add_event(event, ctx);
2003 perf_group_attach(event);
2004 event->tstamp_enabled = tstamp;
2005 event->tstamp_running = tstamp;
2006 event->tstamp_stopped = tstamp;
2009 static void task_ctx_sched_out(struct perf_event_context *ctx);
2011 ctx_sched_in(struct perf_event_context *ctx,
2012 struct perf_cpu_context *cpuctx,
2013 enum event_type_t event_type,
2014 struct task_struct *task);
2016 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2017 struct perf_event_context *ctx,
2018 struct task_struct *task)
2020 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2022 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2023 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2025 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2029 * Cross CPU call to install and enable a performance event
2031 * Must be called with ctx->mutex held
2033 static int __perf_install_in_context(void *info)
2035 struct perf_event *event = info;
2036 struct perf_event_context *ctx = event->ctx;
2037 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2038 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2039 struct task_struct *task = current;
2041 perf_ctx_lock(cpuctx, task_ctx);
2042 perf_pmu_disable(cpuctx->ctx.pmu);
2045 * If there was an active task_ctx schedule it out.
2048 task_ctx_sched_out(task_ctx);
2051 * If the context we're installing events in is not the
2052 * active task_ctx, flip them.
2054 if (ctx->task && task_ctx != ctx) {
2056 raw_spin_unlock(&task_ctx->lock);
2057 raw_spin_lock(&ctx->lock);
2062 cpuctx->task_ctx = task_ctx;
2063 task = task_ctx->task;
2066 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2068 update_context_time(ctx);
2070 * update cgrp time only if current cgrp
2071 * matches event->cgrp. Must be done before
2072 * calling add_event_to_ctx()
2074 update_cgrp_time_from_event(event);
2076 add_event_to_ctx(event, ctx);
2079 * Schedule everything back in
2081 perf_event_sched_in(cpuctx, task_ctx, task);
2083 perf_pmu_enable(cpuctx->ctx.pmu);
2084 perf_ctx_unlock(cpuctx, task_ctx);
2090 * Attach a performance event to a context
2092 * First we add the event to the list with the hardware enable bit
2093 * in event->hw_config cleared.
2095 * If the event is attached to a task which is on a CPU we use a smp
2096 * call to enable it in the task context. The task might have been
2097 * scheduled away, but we check this in the smp call again.
2100 perf_install_in_context(struct perf_event_context *ctx,
2101 struct perf_event *event,
2104 struct task_struct *task = ctx->task;
2106 lockdep_assert_held(&ctx->mutex);
2109 if (event->cpu != -1)
2114 * Per cpu events are installed via an smp call and
2115 * the install is always successful.
2117 cpu_function_call(cpu, __perf_install_in_context, event);
2122 if (!task_function_call(task, __perf_install_in_context, event))
2125 raw_spin_lock_irq(&ctx->lock);
2127 * If we failed to find a running task, but find the context active now
2128 * that we've acquired the ctx->lock, retry.
2130 if (ctx->is_active) {
2131 raw_spin_unlock_irq(&ctx->lock);
2133 * Reload the task pointer, it might have been changed by
2134 * a concurrent perf_event_context_sched_out().
2141 * Since the task isn't running, its safe to add the event, us holding
2142 * the ctx->lock ensures the task won't get scheduled in.
2144 add_event_to_ctx(event, ctx);
2145 raw_spin_unlock_irq(&ctx->lock);
2149 * Put a event into inactive state and update time fields.
2150 * Enabling the leader of a group effectively enables all
2151 * the group members that aren't explicitly disabled, so we
2152 * have to update their ->tstamp_enabled also.
2153 * Note: this works for group members as well as group leaders
2154 * since the non-leader members' sibling_lists will be empty.
2156 static void __perf_event_mark_enabled(struct perf_event *event)
2158 struct perf_event *sub;
2159 u64 tstamp = perf_event_time(event);
2161 event->state = PERF_EVENT_STATE_INACTIVE;
2162 event->tstamp_enabled = tstamp - event->total_time_enabled;
2163 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2164 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2165 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2170 * Cross CPU call to enable a performance event
2172 static int __perf_event_enable(void *info)
2174 struct perf_event *event = info;
2175 struct perf_event_context *ctx = event->ctx;
2176 struct perf_event *leader = event->group_leader;
2177 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2181 * There's a time window between 'ctx->is_active' check
2182 * in perf_event_enable function and this place having:
2184 * - ctx->lock unlocked
2186 * where the task could be killed and 'ctx' deactivated
2187 * by perf_event_exit_task.
2189 if (!ctx->is_active)
2192 raw_spin_lock(&ctx->lock);
2193 update_context_time(ctx);
2195 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2199 * set current task's cgroup time reference point
2201 perf_cgroup_set_timestamp(current, ctx);
2203 __perf_event_mark_enabled(event);
2205 if (!event_filter_match(event)) {
2206 if (is_cgroup_event(event))
2207 perf_cgroup_defer_enabled(event);
2212 * If the event is in a group and isn't the group leader,
2213 * then don't put it on unless the group is on.
2215 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2218 if (!group_can_go_on(event, cpuctx, 1)) {
2221 if (event == leader)
2222 err = group_sched_in(event, cpuctx, ctx);
2224 err = event_sched_in(event, cpuctx, ctx);
2229 * If this event can't go on and it's part of a
2230 * group, then the whole group has to come off.
2232 if (leader != event) {
2233 group_sched_out(leader, cpuctx, ctx);
2234 perf_mux_hrtimer_restart(cpuctx);
2236 if (leader->attr.pinned) {
2237 update_group_times(leader);
2238 leader->state = PERF_EVENT_STATE_ERROR;
2243 raw_spin_unlock(&ctx->lock);
2251 * If event->ctx is a cloned context, callers must make sure that
2252 * every task struct that event->ctx->task could possibly point to
2253 * remains valid. This condition is satisfied when called through
2254 * perf_event_for_each_child or perf_event_for_each as described
2255 * for perf_event_disable.
2257 static void _perf_event_enable(struct perf_event *event)
2259 struct perf_event_context *ctx = event->ctx;
2260 struct task_struct *task = ctx->task;
2264 * Enable the event on the cpu that it's on
2266 cpu_function_call(event->cpu, __perf_event_enable, event);
2270 raw_spin_lock_irq(&ctx->lock);
2271 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2275 * If the event is in error state, clear that first.
2276 * That way, if we see the event in error state below, we
2277 * know that it has gone back into error state, as distinct
2278 * from the task having been scheduled away before the
2279 * cross-call arrived.
2281 if (event->state == PERF_EVENT_STATE_ERROR)
2282 event->state = PERF_EVENT_STATE_OFF;
2285 if (!ctx->is_active) {
2286 __perf_event_mark_enabled(event);
2290 raw_spin_unlock_irq(&ctx->lock);
2292 if (!task_function_call(task, __perf_event_enable, event))
2295 raw_spin_lock_irq(&ctx->lock);
2298 * If the context is active and the event is still off,
2299 * we need to retry the cross-call.
2301 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2303 * task could have been flipped by a concurrent
2304 * perf_event_context_sched_out()
2311 raw_spin_unlock_irq(&ctx->lock);
2315 * See perf_event_disable();
2317 void perf_event_enable(struct perf_event *event)
2319 struct perf_event_context *ctx;
2321 ctx = perf_event_ctx_lock(event);
2322 _perf_event_enable(event);
2323 perf_event_ctx_unlock(event, ctx);
2325 EXPORT_SYMBOL_GPL(perf_event_enable);
2327 static int _perf_event_refresh(struct perf_event *event, int refresh)
2330 * not supported on inherited events
2332 if (event->attr.inherit || !is_sampling_event(event))
2335 atomic_add(refresh, &event->event_limit);
2336 _perf_event_enable(event);
2342 * See perf_event_disable()
2344 int perf_event_refresh(struct perf_event *event, int refresh)
2346 struct perf_event_context *ctx;
2349 ctx = perf_event_ctx_lock(event);
2350 ret = _perf_event_refresh(event, refresh);
2351 perf_event_ctx_unlock(event, ctx);
2355 EXPORT_SYMBOL_GPL(perf_event_refresh);
2357 static void ctx_sched_out(struct perf_event_context *ctx,
2358 struct perf_cpu_context *cpuctx,
2359 enum event_type_t event_type)
2361 struct perf_event *event;
2362 int is_active = ctx->is_active;
2364 ctx->is_active &= ~event_type;
2365 if (likely(!ctx->nr_events))
2368 update_context_time(ctx);
2369 update_cgrp_time_from_cpuctx(cpuctx);
2370 if (!ctx->nr_active)
2373 perf_pmu_disable(ctx->pmu);
2374 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2375 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2376 group_sched_out(event, cpuctx, ctx);
2379 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2380 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2381 group_sched_out(event, cpuctx, ctx);
2383 perf_pmu_enable(ctx->pmu);
2387 * Test whether two contexts are equivalent, i.e. whether they have both been
2388 * cloned from the same version of the same context.
2390 * Equivalence is measured using a generation number in the context that is
2391 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2392 * and list_del_event().
2394 static int context_equiv(struct perf_event_context *ctx1,
2395 struct perf_event_context *ctx2)
2397 lockdep_assert_held(&ctx1->lock);
2398 lockdep_assert_held(&ctx2->lock);
2400 /* Pinning disables the swap optimization */
2401 if (ctx1->pin_count || ctx2->pin_count)
2404 /* If ctx1 is the parent of ctx2 */
2405 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2408 /* If ctx2 is the parent of ctx1 */
2409 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2413 * If ctx1 and ctx2 have the same parent; we flatten the parent
2414 * hierarchy, see perf_event_init_context().
2416 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2417 ctx1->parent_gen == ctx2->parent_gen)
2424 static void __perf_event_sync_stat(struct perf_event *event,
2425 struct perf_event *next_event)
2429 if (!event->attr.inherit_stat)
2433 * Update the event value, we cannot use perf_event_read()
2434 * because we're in the middle of a context switch and have IRQs
2435 * disabled, which upsets smp_call_function_single(), however
2436 * we know the event must be on the current CPU, therefore we
2437 * don't need to use it.
2439 switch (event->state) {
2440 case PERF_EVENT_STATE_ACTIVE:
2441 event->pmu->read(event);
2444 case PERF_EVENT_STATE_INACTIVE:
2445 update_event_times(event);
2453 * In order to keep per-task stats reliable we need to flip the event
2454 * values when we flip the contexts.
2456 value = local64_read(&next_event->count);
2457 value = local64_xchg(&event->count, value);
2458 local64_set(&next_event->count, value);
2460 swap(event->total_time_enabled, next_event->total_time_enabled);
2461 swap(event->total_time_running, next_event->total_time_running);
2464 * Since we swizzled the values, update the user visible data too.
2466 perf_event_update_userpage(event);
2467 perf_event_update_userpage(next_event);
2470 static void perf_event_sync_stat(struct perf_event_context *ctx,
2471 struct perf_event_context *next_ctx)
2473 struct perf_event *event, *next_event;
2478 update_context_time(ctx);
2480 event = list_first_entry(&ctx->event_list,
2481 struct perf_event, event_entry);
2483 next_event = list_first_entry(&next_ctx->event_list,
2484 struct perf_event, event_entry);
2486 while (&event->event_entry != &ctx->event_list &&
2487 &next_event->event_entry != &next_ctx->event_list) {
2489 __perf_event_sync_stat(event, next_event);
2491 event = list_next_entry(event, event_entry);
2492 next_event = list_next_entry(next_event, event_entry);
2496 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2497 struct task_struct *next)
2499 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2500 struct perf_event_context *next_ctx;
2501 struct perf_event_context *parent, *next_parent;
2502 struct perf_cpu_context *cpuctx;
2508 cpuctx = __get_cpu_context(ctx);
2509 if (!cpuctx->task_ctx)
2513 next_ctx = next->perf_event_ctxp[ctxn];
2517 parent = rcu_dereference(ctx->parent_ctx);
2518 next_parent = rcu_dereference(next_ctx->parent_ctx);
2520 /* If neither context have a parent context; they cannot be clones. */
2521 if (!parent && !next_parent)
2524 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2526 * Looks like the two contexts are clones, so we might be
2527 * able to optimize the context switch. We lock both
2528 * contexts and check that they are clones under the
2529 * lock (including re-checking that neither has been
2530 * uncloned in the meantime). It doesn't matter which
2531 * order we take the locks because no other cpu could
2532 * be trying to lock both of these tasks.
2534 raw_spin_lock(&ctx->lock);
2535 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2536 if (context_equiv(ctx, next_ctx)) {
2538 * XXX do we need a memory barrier of sorts
2539 * wrt to rcu_dereference() of perf_event_ctxp
2541 task->perf_event_ctxp[ctxn] = next_ctx;
2542 next->perf_event_ctxp[ctxn] = ctx;
2544 next_ctx->task = task;
2546 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2550 perf_event_sync_stat(ctx, next_ctx);
2552 raw_spin_unlock(&next_ctx->lock);
2553 raw_spin_unlock(&ctx->lock);
2559 raw_spin_lock(&ctx->lock);
2560 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2561 cpuctx->task_ctx = NULL;
2562 raw_spin_unlock(&ctx->lock);
2566 void perf_sched_cb_dec(struct pmu *pmu)
2568 this_cpu_dec(perf_sched_cb_usages);
2571 void perf_sched_cb_inc(struct pmu *pmu)
2573 this_cpu_inc(perf_sched_cb_usages);
2577 * This function provides the context switch callback to the lower code
2578 * layer. It is invoked ONLY when the context switch callback is enabled.
2580 static void perf_pmu_sched_task(struct task_struct *prev,
2581 struct task_struct *next,
2584 struct perf_cpu_context *cpuctx;
2586 unsigned long flags;
2591 local_irq_save(flags);
2595 list_for_each_entry_rcu(pmu, &pmus, entry) {
2596 if (pmu->sched_task) {
2597 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2599 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2601 perf_pmu_disable(pmu);
2603 pmu->sched_task(cpuctx->task_ctx, sched_in);
2605 perf_pmu_enable(pmu);
2607 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2613 local_irq_restore(flags);
2616 #define for_each_task_context_nr(ctxn) \
2617 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2620 * Called from scheduler to remove the events of the current task,
2621 * with interrupts disabled.
2623 * We stop each event and update the event value in event->count.
2625 * This does not protect us against NMI, but disable()
2626 * sets the disabled bit in the control field of event _before_
2627 * accessing the event control register. If a NMI hits, then it will
2628 * not restart the event.
2630 void __perf_event_task_sched_out(struct task_struct *task,
2631 struct task_struct *next)
2635 if (__this_cpu_read(perf_sched_cb_usages))
2636 perf_pmu_sched_task(task, next, false);
2638 for_each_task_context_nr(ctxn)
2639 perf_event_context_sched_out(task, ctxn, next);
2642 * if cgroup events exist on this CPU, then we need
2643 * to check if we have to switch out PMU state.
2644 * cgroup event are system-wide mode only
2646 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2647 perf_cgroup_sched_out(task, next);
2650 static void task_ctx_sched_out(struct perf_event_context *ctx)
2652 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2654 if (!cpuctx->task_ctx)
2657 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2660 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2661 cpuctx->task_ctx = NULL;
2665 * Called with IRQs disabled
2667 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2668 enum event_type_t event_type)
2670 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2674 ctx_pinned_sched_in(struct perf_event_context *ctx,
2675 struct perf_cpu_context *cpuctx)
2677 struct perf_event *event;
2679 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2680 if (event->state <= PERF_EVENT_STATE_OFF)
2682 if (!event_filter_match(event))
2685 /* may need to reset tstamp_enabled */
2686 if (is_cgroup_event(event))
2687 perf_cgroup_mark_enabled(event, ctx);
2689 if (group_can_go_on(event, cpuctx, 1))
2690 group_sched_in(event, cpuctx, ctx);
2693 * If this pinned group hasn't been scheduled,
2694 * put it in error state.
2696 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2697 update_group_times(event);
2698 event->state = PERF_EVENT_STATE_ERROR;
2704 ctx_flexible_sched_in(struct perf_event_context *ctx,
2705 struct perf_cpu_context *cpuctx)
2707 struct perf_event *event;
2710 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2711 /* Ignore events in OFF or ERROR state */
2712 if (event->state <= PERF_EVENT_STATE_OFF)
2715 * Listen to the 'cpu' scheduling filter constraint
2718 if (!event_filter_match(event))
2721 /* may need to reset tstamp_enabled */
2722 if (is_cgroup_event(event))
2723 perf_cgroup_mark_enabled(event, ctx);
2725 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2726 if (group_sched_in(event, cpuctx, ctx))
2733 ctx_sched_in(struct perf_event_context *ctx,
2734 struct perf_cpu_context *cpuctx,
2735 enum event_type_t event_type,
2736 struct task_struct *task)
2739 int is_active = ctx->is_active;
2741 ctx->is_active |= event_type;
2742 if (likely(!ctx->nr_events))
2746 ctx->timestamp = now;
2747 perf_cgroup_set_timestamp(task, ctx);
2749 * First go through the list and put on any pinned groups
2750 * in order to give them the best chance of going on.
2752 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2753 ctx_pinned_sched_in(ctx, cpuctx);
2755 /* Then walk through the lower prio flexible groups */
2756 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2757 ctx_flexible_sched_in(ctx, cpuctx);
2760 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2761 enum event_type_t event_type,
2762 struct task_struct *task)
2764 struct perf_event_context *ctx = &cpuctx->ctx;
2766 ctx_sched_in(ctx, cpuctx, event_type, task);
2769 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2770 struct task_struct *task)
2772 struct perf_cpu_context *cpuctx;
2774 cpuctx = __get_cpu_context(ctx);
2775 if (cpuctx->task_ctx == ctx)
2778 perf_ctx_lock(cpuctx, ctx);
2779 perf_pmu_disable(ctx->pmu);
2781 * We want to keep the following priority order:
2782 * cpu pinned (that don't need to move), task pinned,
2783 * cpu flexible, task flexible.
2785 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2788 cpuctx->task_ctx = ctx;
2790 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2792 perf_pmu_enable(ctx->pmu);
2793 perf_ctx_unlock(cpuctx, ctx);
2797 * Called from scheduler to add the events of the current task
2798 * with interrupts disabled.
2800 * We restore the event value and then enable it.
2802 * This does not protect us against NMI, but enable()
2803 * sets the enabled bit in the control field of event _before_
2804 * accessing the event control register. If a NMI hits, then it will
2805 * keep the event running.
2807 void __perf_event_task_sched_in(struct task_struct *prev,
2808 struct task_struct *task)
2810 struct perf_event_context *ctx;
2813 for_each_task_context_nr(ctxn) {
2814 ctx = task->perf_event_ctxp[ctxn];
2818 perf_event_context_sched_in(ctx, task);
2821 * if cgroup events exist on this CPU, then we need
2822 * to check if we have to switch in PMU state.
2823 * cgroup event are system-wide mode only
2825 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2826 perf_cgroup_sched_in(prev, task);
2828 if (__this_cpu_read(perf_sched_cb_usages))
2829 perf_pmu_sched_task(prev, task, true);
2832 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2834 u64 frequency = event->attr.sample_freq;
2835 u64 sec = NSEC_PER_SEC;
2836 u64 divisor, dividend;
2838 int count_fls, nsec_fls, frequency_fls, sec_fls;
2840 count_fls = fls64(count);
2841 nsec_fls = fls64(nsec);
2842 frequency_fls = fls64(frequency);
2846 * We got @count in @nsec, with a target of sample_freq HZ
2847 * the target period becomes:
2850 * period = -------------------
2851 * @nsec * sample_freq
2856 * Reduce accuracy by one bit such that @a and @b converge
2857 * to a similar magnitude.
2859 #define REDUCE_FLS(a, b) \
2861 if (a##_fls > b##_fls) { \
2871 * Reduce accuracy until either term fits in a u64, then proceed with
2872 * the other, so that finally we can do a u64/u64 division.
2874 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2875 REDUCE_FLS(nsec, frequency);
2876 REDUCE_FLS(sec, count);
2879 if (count_fls + sec_fls > 64) {
2880 divisor = nsec * frequency;
2882 while (count_fls + sec_fls > 64) {
2883 REDUCE_FLS(count, sec);
2887 dividend = count * sec;
2889 dividend = count * sec;
2891 while (nsec_fls + frequency_fls > 64) {
2892 REDUCE_FLS(nsec, frequency);
2896 divisor = nsec * frequency;
2902 return div64_u64(dividend, divisor);
2905 static DEFINE_PER_CPU(int, perf_throttled_count);
2906 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2908 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2910 struct hw_perf_event *hwc = &event->hw;
2911 s64 period, sample_period;
2914 period = perf_calculate_period(event, nsec, count);
2916 delta = (s64)(period - hwc->sample_period);
2917 delta = (delta + 7) / 8; /* low pass filter */
2919 sample_period = hwc->sample_period + delta;
2924 hwc->sample_period = sample_period;
2926 if (local64_read(&hwc->period_left) > 8*sample_period) {
2928 event->pmu->stop(event, PERF_EF_UPDATE);
2930 local64_set(&hwc->period_left, 0);
2933 event->pmu->start(event, PERF_EF_RELOAD);
2938 * combine freq adjustment with unthrottling to avoid two passes over the
2939 * events. At the same time, make sure, having freq events does not change
2940 * the rate of unthrottling as that would introduce bias.
2942 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2945 struct perf_event *event;
2946 struct hw_perf_event *hwc;
2947 u64 now, period = TICK_NSEC;
2951 * only need to iterate over all events iff:
2952 * - context have events in frequency mode (needs freq adjust)
2953 * - there are events to unthrottle on this cpu
2955 if (!(ctx->nr_freq || needs_unthr))
2958 raw_spin_lock(&ctx->lock);
2959 perf_pmu_disable(ctx->pmu);
2961 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2962 if (event->state != PERF_EVENT_STATE_ACTIVE)
2965 if (!event_filter_match(event))
2968 perf_pmu_disable(event->pmu);
2972 if (hwc->interrupts == MAX_INTERRUPTS) {
2973 hwc->interrupts = 0;
2974 perf_log_throttle(event, 1);
2975 event->pmu->start(event, 0);
2978 if (!event->attr.freq || !event->attr.sample_freq)
2982 * stop the event and update event->count
2984 event->pmu->stop(event, PERF_EF_UPDATE);
2986 now = local64_read(&event->count);
2987 delta = now - hwc->freq_count_stamp;
2988 hwc->freq_count_stamp = now;
2992 * reload only if value has changed
2993 * we have stopped the event so tell that
2994 * to perf_adjust_period() to avoid stopping it
2998 perf_adjust_period(event, period, delta, false);
3000 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3002 perf_pmu_enable(event->pmu);
3005 perf_pmu_enable(ctx->pmu);
3006 raw_spin_unlock(&ctx->lock);
3010 * Round-robin a context's events:
3012 static void rotate_ctx(struct perf_event_context *ctx)
3015 * Rotate the first entry last of non-pinned groups. Rotation might be
3016 * disabled by the inheritance code.
3018 if (!ctx->rotate_disable)
3019 list_rotate_left(&ctx->flexible_groups);
3022 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3024 struct perf_event_context *ctx = NULL;
3027 if (cpuctx->ctx.nr_events) {
3028 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3032 ctx = cpuctx->task_ctx;
3033 if (ctx && ctx->nr_events) {
3034 if (ctx->nr_events != ctx->nr_active)
3041 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3042 perf_pmu_disable(cpuctx->ctx.pmu);
3044 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3046 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3048 rotate_ctx(&cpuctx->ctx);
3052 perf_event_sched_in(cpuctx, ctx, current);
3054 perf_pmu_enable(cpuctx->ctx.pmu);
3055 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3061 #ifdef CONFIG_NO_HZ_FULL
3062 bool perf_event_can_stop_tick(void)
3064 if (atomic_read(&nr_freq_events) ||
3065 __this_cpu_read(perf_throttled_count))
3072 void perf_event_task_tick(void)
3074 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3075 struct perf_event_context *ctx, *tmp;
3078 WARN_ON(!irqs_disabled());
3080 __this_cpu_inc(perf_throttled_seq);
3081 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3083 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3084 perf_adjust_freq_unthr_context(ctx, throttled);
3087 static int event_enable_on_exec(struct perf_event *event,
3088 struct perf_event_context *ctx)
3090 if (!event->attr.enable_on_exec)
3093 event->attr.enable_on_exec = 0;
3094 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3097 __perf_event_mark_enabled(event);
3103 * Enable all of a task's events that have been marked enable-on-exec.
3104 * This expects task == current.
3106 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
3108 struct perf_event_context *clone_ctx = NULL;
3109 struct perf_event *event;
3110 unsigned long flags;
3114 local_irq_save(flags);
3115 if (!ctx || !ctx->nr_events)
3119 * We must ctxsw out cgroup events to avoid conflict
3120 * when invoking perf_task_event_sched_in() later on
3121 * in this function. Otherwise we end up trying to
3122 * ctxswin cgroup events which are already scheduled
3125 perf_cgroup_sched_out(current, NULL);
3127 raw_spin_lock(&ctx->lock);
3128 task_ctx_sched_out(ctx);
3130 list_for_each_entry(event, &ctx->event_list, event_entry) {
3131 ret = event_enable_on_exec(event, ctx);
3137 * Unclone this context if we enabled any event.
3140 clone_ctx = unclone_ctx(ctx);
3142 raw_spin_unlock(&ctx->lock);
3145 * Also calls ctxswin for cgroup events, if any:
3147 perf_event_context_sched_in(ctx, ctx->task);
3149 local_irq_restore(flags);
3155 void perf_event_exec(void)
3157 struct perf_event_context *ctx;
3161 for_each_task_context_nr(ctxn) {
3162 ctx = current->perf_event_ctxp[ctxn];
3166 perf_event_enable_on_exec(ctx);
3172 * Cross CPU call to read the hardware event
3174 static void __perf_event_read(void *info)
3176 struct perf_event *event = info;
3177 struct perf_event_context *ctx = event->ctx;
3178 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3181 * If this is a task context, we need to check whether it is
3182 * the current task context of this cpu. If not it has been
3183 * scheduled out before the smp call arrived. In that case
3184 * event->count would have been updated to a recent sample
3185 * when the event was scheduled out.
3187 if (ctx->task && cpuctx->task_ctx != ctx)
3190 raw_spin_lock(&ctx->lock);
3191 if (ctx->is_active) {
3192 update_context_time(ctx);
3193 update_cgrp_time_from_event(event);
3195 update_event_times(event);
3196 if (event->state == PERF_EVENT_STATE_ACTIVE)
3197 event->pmu->read(event);
3198 raw_spin_unlock(&ctx->lock);
3201 static inline u64 perf_event_count(struct perf_event *event)
3203 if (event->pmu->count)
3204 return event->pmu->count(event);
3206 return __perf_event_count(event);
3209 static u64 perf_event_read(struct perf_event *event)
3212 * If event is enabled and currently active on a CPU, update the
3213 * value in the event structure:
3215 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3216 smp_call_function_single(event->oncpu,
3217 __perf_event_read, event, 1);
3218 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3219 struct perf_event_context *ctx = event->ctx;
3220 unsigned long flags;
3222 raw_spin_lock_irqsave(&ctx->lock, flags);
3224 * may read while context is not active
3225 * (e.g., thread is blocked), in that case
3226 * we cannot update context time
3228 if (ctx->is_active) {
3229 update_context_time(ctx);
3230 update_cgrp_time_from_event(event);
3232 update_event_times(event);
3233 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3236 return perf_event_count(event);
3240 * Initialize the perf_event context in a task_struct:
3242 static void __perf_event_init_context(struct perf_event_context *ctx)
3244 raw_spin_lock_init(&ctx->lock);
3245 mutex_init(&ctx->mutex);
3246 INIT_LIST_HEAD(&ctx->active_ctx_list);
3247 INIT_LIST_HEAD(&ctx->pinned_groups);
3248 INIT_LIST_HEAD(&ctx->flexible_groups);
3249 INIT_LIST_HEAD(&ctx->event_list);
3250 atomic_set(&ctx->refcount, 1);
3251 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3254 static struct perf_event_context *
3255 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3257 struct perf_event_context *ctx;
3259 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3263 __perf_event_init_context(ctx);
3266 get_task_struct(task);
3273 static struct task_struct *
3274 find_lively_task_by_vpid(pid_t vpid)
3276 struct task_struct *task;
3283 task = find_task_by_vpid(vpid);
3285 get_task_struct(task);
3289 return ERR_PTR(-ESRCH);
3291 /* Reuse ptrace permission checks for now. */
3293 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3298 put_task_struct(task);
3299 return ERR_PTR(err);
3304 * Returns a matching context with refcount and pincount.
3306 static struct perf_event_context *
3307 find_get_context(struct pmu *pmu, struct task_struct *task,
3308 struct perf_event *event)
3310 struct perf_event_context *ctx, *clone_ctx = NULL;
3311 struct perf_cpu_context *cpuctx;
3312 void *task_ctx_data = NULL;
3313 unsigned long flags;
3315 int cpu = event->cpu;
3318 /* Must be root to operate on a CPU event: */
3319 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3320 return ERR_PTR(-EACCES);
3323 * We could be clever and allow to attach a event to an
3324 * offline CPU and activate it when the CPU comes up, but
3327 if (!cpu_online(cpu))
3328 return ERR_PTR(-ENODEV);
3330 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3339 ctxn = pmu->task_ctx_nr;
3343 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3344 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3345 if (!task_ctx_data) {
3352 ctx = perf_lock_task_context(task, ctxn, &flags);
3354 clone_ctx = unclone_ctx(ctx);
3357 if (task_ctx_data && !ctx->task_ctx_data) {
3358 ctx->task_ctx_data = task_ctx_data;
3359 task_ctx_data = NULL;
3361 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3366 ctx = alloc_perf_context(pmu, task);
3371 if (task_ctx_data) {
3372 ctx->task_ctx_data = task_ctx_data;
3373 task_ctx_data = NULL;
3377 mutex_lock(&task->perf_event_mutex);
3379 * If it has already passed perf_event_exit_task().
3380 * we must see PF_EXITING, it takes this mutex too.
3382 if (task->flags & PF_EXITING)
3384 else if (task->perf_event_ctxp[ctxn])
3389 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3391 mutex_unlock(&task->perf_event_mutex);
3393 if (unlikely(err)) {
3402 kfree(task_ctx_data);
3406 kfree(task_ctx_data);
3407 return ERR_PTR(err);
3410 static void perf_event_free_filter(struct perf_event *event);
3411 static void perf_event_free_bpf_prog(struct perf_event *event);
3413 static void free_event_rcu(struct rcu_head *head)
3415 struct perf_event *event;
3417 event = container_of(head, struct perf_event, rcu_head);
3419 put_pid_ns(event->ns);
3420 perf_event_free_filter(event);
3421 perf_event_free_bpf_prog(event);
3425 static void ring_buffer_attach(struct perf_event *event,
3426 struct ring_buffer *rb);
3428 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3433 if (is_cgroup_event(event))
3434 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3437 static void unaccount_event(struct perf_event *event)
3442 if (event->attach_state & PERF_ATTACH_TASK)
3443 static_key_slow_dec_deferred(&perf_sched_events);
3444 if (event->attr.mmap || event->attr.mmap_data)
3445 atomic_dec(&nr_mmap_events);
3446 if (event->attr.comm)
3447 atomic_dec(&nr_comm_events);
3448 if (event->attr.task)
3449 atomic_dec(&nr_task_events);
3450 if (event->attr.freq)
3451 atomic_dec(&nr_freq_events);
3452 if (is_cgroup_event(event))
3453 static_key_slow_dec_deferred(&perf_sched_events);
3454 if (has_branch_stack(event))
3455 static_key_slow_dec_deferred(&perf_sched_events);
3457 unaccount_event_cpu(event, event->cpu);
3461 * The following implement mutual exclusion of events on "exclusive" pmus
3462 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3463 * at a time, so we disallow creating events that might conflict, namely:
3465 * 1) cpu-wide events in the presence of per-task events,
3466 * 2) per-task events in the presence of cpu-wide events,
3467 * 3) two matching events on the same context.
3469 * The former two cases are handled in the allocation path (perf_event_alloc(),
3470 * __free_event()), the latter -- before the first perf_install_in_context().
3472 static int exclusive_event_init(struct perf_event *event)
3474 struct pmu *pmu = event->pmu;
3476 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3480 * Prevent co-existence of per-task and cpu-wide events on the
3481 * same exclusive pmu.
3483 * Negative pmu::exclusive_cnt means there are cpu-wide
3484 * events on this "exclusive" pmu, positive means there are
3487 * Since this is called in perf_event_alloc() path, event::ctx
3488 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3489 * to mean "per-task event", because unlike other attach states it
3490 * never gets cleared.
3492 if (event->attach_state & PERF_ATTACH_TASK) {
3493 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3496 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3503 static void exclusive_event_destroy(struct perf_event *event)
3505 struct pmu *pmu = event->pmu;
3507 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3510 /* see comment in exclusive_event_init() */
3511 if (event->attach_state & PERF_ATTACH_TASK)
3512 atomic_dec(&pmu->exclusive_cnt);
3514 atomic_inc(&pmu->exclusive_cnt);
3517 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3519 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3520 (e1->cpu == e2->cpu ||
3527 /* Called under the same ctx::mutex as perf_install_in_context() */
3528 static bool exclusive_event_installable(struct perf_event *event,
3529 struct perf_event_context *ctx)
3531 struct perf_event *iter_event;
3532 struct pmu *pmu = event->pmu;
3534 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3537 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3538 if (exclusive_event_match(iter_event, event))
3545 static void __free_event(struct perf_event *event)
3547 if (!event->parent) {
3548 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3549 put_callchain_buffers();
3553 event->destroy(event);
3556 put_ctx(event->ctx);
3559 exclusive_event_destroy(event);
3560 module_put(event->pmu->module);
3563 call_rcu(&event->rcu_head, free_event_rcu);
3566 static void _free_event(struct perf_event *event)
3568 irq_work_sync(&event->pending);
3570 unaccount_event(event);
3574 * Can happen when we close an event with re-directed output.
3576 * Since we have a 0 refcount, perf_mmap_close() will skip
3577 * over us; possibly making our ring_buffer_put() the last.
3579 mutex_lock(&event->mmap_mutex);
3580 ring_buffer_attach(event, NULL);
3581 mutex_unlock(&event->mmap_mutex);
3584 if (is_cgroup_event(event))
3585 perf_detach_cgroup(event);
3587 __free_event(event);
3591 * Used to free events which have a known refcount of 1, such as in error paths
3592 * where the event isn't exposed yet and inherited events.
3594 static void free_event(struct perf_event *event)
3596 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3597 "unexpected event refcount: %ld; ptr=%p\n",
3598 atomic_long_read(&event->refcount), event)) {
3599 /* leak to avoid use-after-free */
3607 * Remove user event from the owner task.
3609 static void perf_remove_from_owner(struct perf_event *event)
3611 struct task_struct *owner;
3614 owner = ACCESS_ONCE(event->owner);
3616 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3617 * !owner it means the list deletion is complete and we can indeed
3618 * free this event, otherwise we need to serialize on
3619 * owner->perf_event_mutex.
3621 smp_read_barrier_depends();
3624 * Since delayed_put_task_struct() also drops the last
3625 * task reference we can safely take a new reference
3626 * while holding the rcu_read_lock().
3628 get_task_struct(owner);
3634 * If we're here through perf_event_exit_task() we're already
3635 * holding ctx->mutex which would be an inversion wrt. the
3636 * normal lock order.
3638 * However we can safely take this lock because its the child
3641 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3644 * We have to re-check the event->owner field, if it is cleared
3645 * we raced with perf_event_exit_task(), acquiring the mutex
3646 * ensured they're done, and we can proceed with freeing the
3650 list_del_init(&event->owner_entry);
3651 mutex_unlock(&owner->perf_event_mutex);
3652 put_task_struct(owner);
3656 static void put_event(struct perf_event *event)
3658 struct perf_event_context *ctx;
3660 if (!atomic_long_dec_and_test(&event->refcount))
3663 if (!is_kernel_event(event))
3664 perf_remove_from_owner(event);
3667 * There are two ways this annotation is useful:
3669 * 1) there is a lock recursion from perf_event_exit_task
3670 * see the comment there.
3672 * 2) there is a lock-inversion with mmap_sem through
3673 * perf_event_read_group(), which takes faults while
3674 * holding ctx->mutex, however this is called after
3675 * the last filedesc died, so there is no possibility
3676 * to trigger the AB-BA case.
3678 ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3679 WARN_ON_ONCE(ctx->parent_ctx);
3680 perf_remove_from_context(event, true);
3681 perf_event_ctx_unlock(event, ctx);
3686 int perf_event_release_kernel(struct perf_event *event)
3691 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3694 * Called when the last reference to the file is gone.
3696 static int perf_release(struct inode *inode, struct file *file)
3698 put_event(file->private_data);
3703 * Remove all orphanes events from the context.
3705 static void orphans_remove_work(struct work_struct *work)
3707 struct perf_event_context *ctx;
3708 struct perf_event *event, *tmp;
3710 ctx = container_of(work, struct perf_event_context,
3711 orphans_remove.work);
3713 mutex_lock(&ctx->mutex);
3714 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3715 struct perf_event *parent_event = event->parent;
3717 if (!is_orphaned_child(event))
3720 perf_remove_from_context(event, true);
3722 mutex_lock(&parent_event->child_mutex);
3723 list_del_init(&event->child_list);
3724 mutex_unlock(&parent_event->child_mutex);
3727 put_event(parent_event);
3730 raw_spin_lock_irq(&ctx->lock);
3731 ctx->orphans_remove_sched = false;
3732 raw_spin_unlock_irq(&ctx->lock);
3733 mutex_unlock(&ctx->mutex);
3738 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3740 struct perf_event *child;
3746 mutex_lock(&event->child_mutex);
3747 total += perf_event_read(event);
3748 *enabled += event->total_time_enabled +
3749 atomic64_read(&event->child_total_time_enabled);
3750 *running += event->total_time_running +
3751 atomic64_read(&event->child_total_time_running);
3753 list_for_each_entry(child, &event->child_list, child_list) {
3754 total += perf_event_read(child);
3755 *enabled += child->total_time_enabled;
3756 *running += child->total_time_running;
3758 mutex_unlock(&event->child_mutex);
3762 EXPORT_SYMBOL_GPL(perf_event_read_value);
3764 static int perf_event_read_group(struct perf_event *event,
3765 u64 read_format, char __user *buf)
3767 struct perf_event *leader = event->group_leader, *sub;
3768 struct perf_event_context *ctx = leader->ctx;
3769 int n = 0, size = 0, ret;
3770 u64 count, enabled, running;
3773 lockdep_assert_held(&ctx->mutex);
3775 count = perf_event_read_value(leader, &enabled, &running);
3777 values[n++] = 1 + leader->nr_siblings;
3778 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3779 values[n++] = enabled;
3780 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3781 values[n++] = running;
3782 values[n++] = count;
3783 if (read_format & PERF_FORMAT_ID)
3784 values[n++] = primary_event_id(leader);
3786 size = n * sizeof(u64);
3788 if (copy_to_user(buf, values, size))
3793 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3796 values[n++] = perf_event_read_value(sub, &enabled, &running);
3797 if (read_format & PERF_FORMAT_ID)
3798 values[n++] = primary_event_id(sub);
3800 size = n * sizeof(u64);
3802 if (copy_to_user(buf + ret, values, size)) {
3812 static int perf_event_read_one(struct perf_event *event,
3813 u64 read_format, char __user *buf)
3815 u64 enabled, running;
3819 values[n++] = perf_event_read_value(event, &enabled, &running);
3820 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3821 values[n++] = enabled;
3822 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3823 values[n++] = running;
3824 if (read_format & PERF_FORMAT_ID)
3825 values[n++] = primary_event_id(event);
3827 if (copy_to_user(buf, values, n * sizeof(u64)))
3830 return n * sizeof(u64);
3833 static bool is_event_hup(struct perf_event *event)
3837 if (event->state != PERF_EVENT_STATE_EXIT)
3840 mutex_lock(&event->child_mutex);
3841 no_children = list_empty(&event->child_list);
3842 mutex_unlock(&event->child_mutex);
3847 * Read the performance event - simple non blocking version for now
3850 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3852 u64 read_format = event->attr.read_format;
3856 * Return end-of-file for a read on a event that is in
3857 * error state (i.e. because it was pinned but it couldn't be
3858 * scheduled on to the CPU at some point).
3860 if (event->state == PERF_EVENT_STATE_ERROR)
3863 if (count < event->read_size)
3866 WARN_ON_ONCE(event->ctx->parent_ctx);
3867 if (read_format & PERF_FORMAT_GROUP)
3868 ret = perf_event_read_group(event, read_format, buf);
3870 ret = perf_event_read_one(event, read_format, buf);
3876 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3878 struct perf_event *event = file->private_data;
3879 struct perf_event_context *ctx;
3882 ctx = perf_event_ctx_lock(event);
3883 ret = perf_read_hw(event, buf, count);
3884 perf_event_ctx_unlock(event, ctx);
3889 static unsigned int perf_poll(struct file *file, poll_table *wait)
3891 struct perf_event *event = file->private_data;
3892 struct ring_buffer *rb;
3893 unsigned int events = POLLHUP;
3895 poll_wait(file, &event->waitq, wait);
3897 if (is_event_hup(event))
3901 * Pin the event->rb by taking event->mmap_mutex; otherwise
3902 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3904 mutex_lock(&event->mmap_mutex);
3907 events = atomic_xchg(&rb->poll, 0);
3908 mutex_unlock(&event->mmap_mutex);
3912 static void _perf_event_reset(struct perf_event *event)
3914 (void)perf_event_read(event);
3915 local64_set(&event->count, 0);
3916 perf_event_update_userpage(event);
3920 * Holding the top-level event's child_mutex means that any
3921 * descendant process that has inherited this event will block
3922 * in sync_child_event if it goes to exit, thus satisfying the
3923 * task existence requirements of perf_event_enable/disable.
3925 static void perf_event_for_each_child(struct perf_event *event,
3926 void (*func)(struct perf_event *))
3928 struct perf_event *child;
3930 WARN_ON_ONCE(event->ctx->parent_ctx);
3932 mutex_lock(&event->child_mutex);
3934 list_for_each_entry(child, &event->child_list, child_list)
3936 mutex_unlock(&event->child_mutex);
3939 static void perf_event_for_each(struct perf_event *event,
3940 void (*func)(struct perf_event *))
3942 struct perf_event_context *ctx = event->ctx;
3943 struct perf_event *sibling;
3945 lockdep_assert_held(&ctx->mutex);
3947 event = event->group_leader;
3949 perf_event_for_each_child(event, func);
3950 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3951 perf_event_for_each_child(sibling, func);
3954 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3956 struct perf_event_context *ctx = event->ctx;
3957 int ret = 0, active;
3960 if (!is_sampling_event(event))
3963 if (copy_from_user(&value, arg, sizeof(value)))
3969 raw_spin_lock_irq(&ctx->lock);
3970 if (event->attr.freq) {
3971 if (value > sysctl_perf_event_sample_rate) {
3976 event->attr.sample_freq = value;
3978 event->attr.sample_period = value;
3979 event->hw.sample_period = value;
3982 active = (event->state == PERF_EVENT_STATE_ACTIVE);
3984 perf_pmu_disable(ctx->pmu);
3985 event->pmu->stop(event, PERF_EF_UPDATE);
3988 local64_set(&event->hw.period_left, 0);
3991 event->pmu->start(event, PERF_EF_RELOAD);
3992 perf_pmu_enable(ctx->pmu);
3996 raw_spin_unlock_irq(&ctx->lock);
4001 static const struct file_operations perf_fops;
4003 static inline int perf_fget_light(int fd, struct fd *p)
4005 struct fd f = fdget(fd);
4009 if (f.file->f_op != &perf_fops) {
4017 static int perf_event_set_output(struct perf_event *event,
4018 struct perf_event *output_event);
4019 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4020 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4022 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4024 void (*func)(struct perf_event *);
4028 case PERF_EVENT_IOC_ENABLE:
4029 func = _perf_event_enable;
4031 case PERF_EVENT_IOC_DISABLE:
4032 func = _perf_event_disable;
4034 case PERF_EVENT_IOC_RESET:
4035 func = _perf_event_reset;
4038 case PERF_EVENT_IOC_REFRESH:
4039 return _perf_event_refresh(event, arg);
4041 case PERF_EVENT_IOC_PERIOD:
4042 return perf_event_period(event, (u64 __user *)arg);
4044 case PERF_EVENT_IOC_ID:
4046 u64 id = primary_event_id(event);
4048 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4053 case PERF_EVENT_IOC_SET_OUTPUT:
4057 struct perf_event *output_event;
4059 ret = perf_fget_light(arg, &output);
4062 output_event = output.file->private_data;
4063 ret = perf_event_set_output(event, output_event);
4066 ret = perf_event_set_output(event, NULL);
4071 case PERF_EVENT_IOC_SET_FILTER:
4072 return perf_event_set_filter(event, (void __user *)arg);
4074 case PERF_EVENT_IOC_SET_BPF:
4075 return perf_event_set_bpf_prog(event, arg);
4081 if (flags & PERF_IOC_FLAG_GROUP)
4082 perf_event_for_each(event, func);
4084 perf_event_for_each_child(event, func);
4089 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4091 struct perf_event *event = file->private_data;
4092 struct perf_event_context *ctx;
4095 ctx = perf_event_ctx_lock(event);
4096 ret = _perf_ioctl(event, cmd, arg);
4097 perf_event_ctx_unlock(event, ctx);
4102 #ifdef CONFIG_COMPAT
4103 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4106 switch (_IOC_NR(cmd)) {
4107 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4108 case _IOC_NR(PERF_EVENT_IOC_ID):
4109 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4110 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4111 cmd &= ~IOCSIZE_MASK;
4112 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4116 return perf_ioctl(file, cmd, arg);
4119 # define perf_compat_ioctl NULL
4122 int perf_event_task_enable(void)
4124 struct perf_event_context *ctx;
4125 struct perf_event *event;
4127 mutex_lock(¤t->perf_event_mutex);
4128 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4129 ctx = perf_event_ctx_lock(event);
4130 perf_event_for_each_child(event, _perf_event_enable);
4131 perf_event_ctx_unlock(event, ctx);
4133 mutex_unlock(¤t->perf_event_mutex);
4138 int perf_event_task_disable(void)
4140 struct perf_event_context *ctx;
4141 struct perf_event *event;
4143 mutex_lock(¤t->perf_event_mutex);
4144 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4145 ctx = perf_event_ctx_lock(event);
4146 perf_event_for_each_child(event, _perf_event_disable);
4147 perf_event_ctx_unlock(event, ctx);
4149 mutex_unlock(¤t->perf_event_mutex);
4154 static int perf_event_index(struct perf_event *event)
4156 if (event->hw.state & PERF_HES_STOPPED)
4159 if (event->state != PERF_EVENT_STATE_ACTIVE)
4162 return event->pmu->event_idx(event);
4165 static void calc_timer_values(struct perf_event *event,
4172 *now = perf_clock();
4173 ctx_time = event->shadow_ctx_time + *now;
4174 *enabled = ctx_time - event->tstamp_enabled;
4175 *running = ctx_time - event->tstamp_running;
4178 static void perf_event_init_userpage(struct perf_event *event)
4180 struct perf_event_mmap_page *userpg;
4181 struct ring_buffer *rb;
4184 rb = rcu_dereference(event->rb);
4188 userpg = rb->user_page;
4190 /* Allow new userspace to detect that bit 0 is deprecated */
4191 userpg->cap_bit0_is_deprecated = 1;
4192 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4193 userpg->data_offset = PAGE_SIZE;
4194 userpg->data_size = perf_data_size(rb);
4200 void __weak arch_perf_update_userpage(
4201 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4206 * Callers need to ensure there can be no nesting of this function, otherwise
4207 * the seqlock logic goes bad. We can not serialize this because the arch
4208 * code calls this from NMI context.
4210 void perf_event_update_userpage(struct perf_event *event)
4212 struct perf_event_mmap_page *userpg;
4213 struct ring_buffer *rb;
4214 u64 enabled, running, now;
4217 rb = rcu_dereference(event->rb);
4222 * compute total_time_enabled, total_time_running
4223 * based on snapshot values taken when the event
4224 * was last scheduled in.
4226 * we cannot simply called update_context_time()
4227 * because of locking issue as we can be called in
4230 calc_timer_values(event, &now, &enabled, &running);
4232 userpg = rb->user_page;
4234 * Disable preemption so as to not let the corresponding user-space
4235 * spin too long if we get preempted.
4240 userpg->index = perf_event_index(event);
4241 userpg->offset = perf_event_count(event);
4243 userpg->offset -= local64_read(&event->hw.prev_count);
4245 userpg->time_enabled = enabled +
4246 atomic64_read(&event->child_total_time_enabled);
4248 userpg->time_running = running +
4249 atomic64_read(&event->child_total_time_running);
4251 arch_perf_update_userpage(event, userpg, now);
4260 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4262 struct perf_event *event = vma->vm_file->private_data;
4263 struct ring_buffer *rb;
4264 int ret = VM_FAULT_SIGBUS;
4266 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4267 if (vmf->pgoff == 0)
4273 rb = rcu_dereference(event->rb);
4277 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4280 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4284 get_page(vmf->page);
4285 vmf->page->mapping = vma->vm_file->f_mapping;
4286 vmf->page->index = vmf->pgoff;
4295 static void ring_buffer_attach(struct perf_event *event,
4296 struct ring_buffer *rb)
4298 struct ring_buffer *old_rb = NULL;
4299 unsigned long flags;
4303 * Should be impossible, we set this when removing
4304 * event->rb_entry and wait/clear when adding event->rb_entry.
4306 WARN_ON_ONCE(event->rcu_pending);
4309 event->rcu_batches = get_state_synchronize_rcu();
4310 event->rcu_pending = 1;
4312 spin_lock_irqsave(&old_rb->event_lock, flags);
4313 list_del_rcu(&event->rb_entry);
4314 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4317 if (event->rcu_pending && rb) {
4318 cond_synchronize_rcu(event->rcu_batches);
4319 event->rcu_pending = 0;
4323 spin_lock_irqsave(&rb->event_lock, flags);
4324 list_add_rcu(&event->rb_entry, &rb->event_list);
4325 spin_unlock_irqrestore(&rb->event_lock, flags);
4328 rcu_assign_pointer(event->rb, rb);
4331 ring_buffer_put(old_rb);
4333 * Since we detached before setting the new rb, so that we
4334 * could attach the new rb, we could have missed a wakeup.
4337 wake_up_all(&event->waitq);
4341 static void ring_buffer_wakeup(struct perf_event *event)
4343 struct ring_buffer *rb;
4346 rb = rcu_dereference(event->rb);
4348 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4349 wake_up_all(&event->waitq);
4354 static void rb_free_rcu(struct rcu_head *rcu_head)
4356 struct ring_buffer *rb;
4358 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
4362 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4364 struct ring_buffer *rb;
4367 rb = rcu_dereference(event->rb);
4369 if (!atomic_inc_not_zero(&rb->refcount))
4377 void ring_buffer_put(struct ring_buffer *rb)
4379 if (!atomic_dec_and_test(&rb->refcount))
4382 WARN_ON_ONCE(!list_empty(&rb->event_list));
4384 call_rcu(&rb->rcu_head, rb_free_rcu);
4387 static void perf_mmap_open(struct vm_area_struct *vma)
4389 struct perf_event *event = vma->vm_file->private_data;
4391 atomic_inc(&event->mmap_count);
4392 atomic_inc(&event->rb->mmap_count);
4395 atomic_inc(&event->rb->aux_mmap_count);
4397 if (event->pmu->event_mapped)
4398 event->pmu->event_mapped(event);
4402 * A buffer can be mmap()ed multiple times; either directly through the same
4403 * event, or through other events by use of perf_event_set_output().
4405 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4406 * the buffer here, where we still have a VM context. This means we need
4407 * to detach all events redirecting to us.
4409 static void perf_mmap_close(struct vm_area_struct *vma)
4411 struct perf_event *event = vma->vm_file->private_data;
4413 struct ring_buffer *rb = ring_buffer_get(event);
4414 struct user_struct *mmap_user = rb->mmap_user;
4415 int mmap_locked = rb->mmap_locked;
4416 unsigned long size = perf_data_size(rb);
4418 if (event->pmu->event_unmapped)
4419 event->pmu->event_unmapped(event);
4422 * rb->aux_mmap_count will always drop before rb->mmap_count and
4423 * event->mmap_count, so it is ok to use event->mmap_mutex to
4424 * serialize with perf_mmap here.
4426 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4427 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4428 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4429 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4432 mutex_unlock(&event->mmap_mutex);
4435 atomic_dec(&rb->mmap_count);
4437 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4440 ring_buffer_attach(event, NULL);
4441 mutex_unlock(&event->mmap_mutex);
4443 /* If there's still other mmap()s of this buffer, we're done. */
4444 if (atomic_read(&rb->mmap_count))
4448 * No other mmap()s, detach from all other events that might redirect
4449 * into the now unreachable buffer. Somewhat complicated by the
4450 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4454 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4455 if (!atomic_long_inc_not_zero(&event->refcount)) {
4457 * This event is en-route to free_event() which will
4458 * detach it and remove it from the list.
4464 mutex_lock(&event->mmap_mutex);
4466 * Check we didn't race with perf_event_set_output() which can
4467 * swizzle the rb from under us while we were waiting to
4468 * acquire mmap_mutex.
4470 * If we find a different rb; ignore this event, a next
4471 * iteration will no longer find it on the list. We have to
4472 * still restart the iteration to make sure we're not now
4473 * iterating the wrong list.
4475 if (event->rb == rb)
4476 ring_buffer_attach(event, NULL);
4478 mutex_unlock(&event->mmap_mutex);
4482 * Restart the iteration; either we're on the wrong list or
4483 * destroyed its integrity by doing a deletion.
4490 * It could be there's still a few 0-ref events on the list; they'll
4491 * get cleaned up by free_event() -- they'll also still have their
4492 * ref on the rb and will free it whenever they are done with it.
4494 * Aside from that, this buffer is 'fully' detached and unmapped,
4495 * undo the VM accounting.
4498 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4499 vma->vm_mm->pinned_vm -= mmap_locked;
4500 free_uid(mmap_user);
4503 ring_buffer_put(rb); /* could be last */
4506 static const struct vm_operations_struct perf_mmap_vmops = {
4507 .open = perf_mmap_open,
4508 .close = perf_mmap_close, /* non mergable */
4509 .fault = perf_mmap_fault,
4510 .page_mkwrite = perf_mmap_fault,
4513 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4515 struct perf_event *event = file->private_data;
4516 unsigned long user_locked, user_lock_limit;
4517 struct user_struct *user = current_user();
4518 unsigned long locked, lock_limit;
4519 struct ring_buffer *rb = NULL;
4520 unsigned long vma_size;
4521 unsigned long nr_pages;
4522 long user_extra = 0, extra = 0;
4523 int ret = 0, flags = 0;
4526 * Don't allow mmap() of inherited per-task counters. This would
4527 * create a performance issue due to all children writing to the
4530 if (event->cpu == -1 && event->attr.inherit)
4533 if (!(vma->vm_flags & VM_SHARED))
4536 vma_size = vma->vm_end - vma->vm_start;
4538 if (vma->vm_pgoff == 0) {
4539 nr_pages = (vma_size / PAGE_SIZE) - 1;
4542 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4543 * mapped, all subsequent mappings should have the same size
4544 * and offset. Must be above the normal perf buffer.
4546 u64 aux_offset, aux_size;
4551 nr_pages = vma_size / PAGE_SIZE;
4553 mutex_lock(&event->mmap_mutex);
4560 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4561 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4563 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4566 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4569 /* already mapped with a different offset */
4570 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4573 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4576 /* already mapped with a different size */
4577 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4580 if (!is_power_of_2(nr_pages))
4583 if (!atomic_inc_not_zero(&rb->mmap_count))
4586 if (rb_has_aux(rb)) {
4587 atomic_inc(&rb->aux_mmap_count);
4592 atomic_set(&rb->aux_mmap_count, 1);
4593 user_extra = nr_pages;
4599 * If we have rb pages ensure they're a power-of-two number, so we
4600 * can do bitmasks instead of modulo.
4602 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4605 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4608 WARN_ON_ONCE(event->ctx->parent_ctx);
4610 mutex_lock(&event->mmap_mutex);
4612 if (event->rb->nr_pages != nr_pages) {
4617 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4619 * Raced against perf_mmap_close() through
4620 * perf_event_set_output(). Try again, hope for better
4623 mutex_unlock(&event->mmap_mutex);
4630 user_extra = nr_pages + 1;
4633 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4636 * Increase the limit linearly with more CPUs:
4638 user_lock_limit *= num_online_cpus();
4640 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4642 if (user_locked > user_lock_limit)
4643 extra = user_locked - user_lock_limit;
4645 lock_limit = rlimit(RLIMIT_MEMLOCK);
4646 lock_limit >>= PAGE_SHIFT;
4647 locked = vma->vm_mm->pinned_vm + extra;
4649 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4650 !capable(CAP_IPC_LOCK)) {
4655 WARN_ON(!rb && event->rb);
4657 if (vma->vm_flags & VM_WRITE)
4658 flags |= RING_BUFFER_WRITABLE;
4661 rb = rb_alloc(nr_pages,
4662 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4670 atomic_set(&rb->mmap_count, 1);
4671 rb->mmap_user = get_current_user();
4672 rb->mmap_locked = extra;
4674 ring_buffer_attach(event, rb);
4676 perf_event_init_userpage(event);
4677 perf_event_update_userpage(event);
4679 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4680 event->attr.aux_watermark, flags);
4682 rb->aux_mmap_locked = extra;
4687 atomic_long_add(user_extra, &user->locked_vm);
4688 vma->vm_mm->pinned_vm += extra;
4690 atomic_inc(&event->mmap_count);
4692 atomic_dec(&rb->mmap_count);
4695 mutex_unlock(&event->mmap_mutex);
4698 * Since pinned accounting is per vm we cannot allow fork() to copy our
4701 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4702 vma->vm_ops = &perf_mmap_vmops;
4704 if (event->pmu->event_mapped)
4705 event->pmu->event_mapped(event);
4710 static int perf_fasync(int fd, struct file *filp, int on)
4712 struct inode *inode = file_inode(filp);
4713 struct perf_event *event = filp->private_data;
4716 mutex_lock(&inode->i_mutex);
4717 retval = fasync_helper(fd, filp, on, &event->fasync);
4718 mutex_unlock(&inode->i_mutex);
4726 static const struct file_operations perf_fops = {
4727 .llseek = no_llseek,
4728 .release = perf_release,
4731 .unlocked_ioctl = perf_ioctl,
4732 .compat_ioctl = perf_compat_ioctl,
4734 .fasync = perf_fasync,
4740 * If there's data, ensure we set the poll() state and publish everything
4741 * to user-space before waking everybody up.
4744 void perf_event_wakeup(struct perf_event *event)
4746 ring_buffer_wakeup(event);
4748 if (event->pending_kill) {
4749 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4750 event->pending_kill = 0;
4754 static void perf_pending_event(struct irq_work *entry)
4756 struct perf_event *event = container_of(entry,
4757 struct perf_event, pending);
4760 rctx = perf_swevent_get_recursion_context();
4762 * If we 'fail' here, that's OK, it means recursion is already disabled
4763 * and we won't recurse 'further'.
4766 if (event->pending_disable) {
4767 event->pending_disable = 0;
4768 __perf_event_disable(event);
4771 if (event->pending_wakeup) {
4772 event->pending_wakeup = 0;
4773 perf_event_wakeup(event);
4777 perf_swevent_put_recursion_context(rctx);
4781 * We assume there is only KVM supporting the callbacks.
4782 * Later on, we might change it to a list if there is
4783 * another virtualization implementation supporting the callbacks.
4785 struct perf_guest_info_callbacks *perf_guest_cbs;
4787 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4789 perf_guest_cbs = cbs;
4792 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4794 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4796 perf_guest_cbs = NULL;
4799 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4802 perf_output_sample_regs(struct perf_output_handle *handle,
4803 struct pt_regs *regs, u64 mask)
4807 for_each_set_bit(bit, (const unsigned long *) &mask,
4808 sizeof(mask) * BITS_PER_BYTE) {
4811 val = perf_reg_value(regs, bit);
4812 perf_output_put(handle, val);
4816 static void perf_sample_regs_user(struct perf_regs *regs_user,
4817 struct pt_regs *regs,
4818 struct pt_regs *regs_user_copy)
4820 if (user_mode(regs)) {
4821 regs_user->abi = perf_reg_abi(current);
4822 regs_user->regs = regs;
4823 } else if (current->mm) {
4824 perf_get_regs_user(regs_user, regs, regs_user_copy);
4826 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
4827 regs_user->regs = NULL;
4831 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
4832 struct pt_regs *regs)
4834 regs_intr->regs = regs;
4835 regs_intr->abi = perf_reg_abi(current);
4840 * Get remaining task size from user stack pointer.
4842 * It'd be better to take stack vma map and limit this more
4843 * precisly, but there's no way to get it safely under interrupt,
4844 * so using TASK_SIZE as limit.
4846 static u64 perf_ustack_task_size(struct pt_regs *regs)
4848 unsigned long addr = perf_user_stack_pointer(regs);
4850 if (!addr || addr >= TASK_SIZE)
4853 return TASK_SIZE - addr;
4857 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4858 struct pt_regs *regs)
4862 /* No regs, no stack pointer, no dump. */
4867 * Check if we fit in with the requested stack size into the:
4869 * If we don't, we limit the size to the TASK_SIZE.
4871 * - remaining sample size
4872 * If we don't, we customize the stack size to
4873 * fit in to the remaining sample size.
4876 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4877 stack_size = min(stack_size, (u16) task_size);
4879 /* Current header size plus static size and dynamic size. */
4880 header_size += 2 * sizeof(u64);
4882 /* Do we fit in with the current stack dump size? */
4883 if ((u16) (header_size + stack_size) < header_size) {
4885 * If we overflow the maximum size for the sample,
4886 * we customize the stack dump size to fit in.
4888 stack_size = USHRT_MAX - header_size - sizeof(u64);
4889 stack_size = round_up(stack_size, sizeof(u64));
4896 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4897 struct pt_regs *regs)
4899 /* Case of a kernel thread, nothing to dump */
4902 perf_output_put(handle, size);
4911 * - the size requested by user or the best one we can fit
4912 * in to the sample max size
4914 * - user stack dump data
4916 * - the actual dumped size
4920 perf_output_put(handle, dump_size);
4923 sp = perf_user_stack_pointer(regs);
4924 rem = __output_copy_user(handle, (void *) sp, dump_size);
4925 dyn_size = dump_size - rem;
4927 perf_output_skip(handle, rem);
4930 perf_output_put(handle, dyn_size);
4934 static void __perf_event_header__init_id(struct perf_event_header *header,
4935 struct perf_sample_data *data,
4936 struct perf_event *event)
4938 u64 sample_type = event->attr.sample_type;
4940 data->type = sample_type;
4941 header->size += event->id_header_size;
4943 if (sample_type & PERF_SAMPLE_TID) {
4944 /* namespace issues */
4945 data->tid_entry.pid = perf_event_pid(event, current);
4946 data->tid_entry.tid = perf_event_tid(event, current);
4949 if (sample_type & PERF_SAMPLE_TIME)
4950 data->time = perf_event_clock(event);
4952 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4953 data->id = primary_event_id(event);
4955 if (sample_type & PERF_SAMPLE_STREAM_ID)
4956 data->stream_id = event->id;
4958 if (sample_type & PERF_SAMPLE_CPU) {
4959 data->cpu_entry.cpu = raw_smp_processor_id();
4960 data->cpu_entry.reserved = 0;
4964 void perf_event_header__init_id(struct perf_event_header *header,
4965 struct perf_sample_data *data,
4966 struct perf_event *event)
4968 if (event->attr.sample_id_all)
4969 __perf_event_header__init_id(header, data, event);
4972 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4973 struct perf_sample_data *data)
4975 u64 sample_type = data->type;
4977 if (sample_type & PERF_SAMPLE_TID)
4978 perf_output_put(handle, data->tid_entry);
4980 if (sample_type & PERF_SAMPLE_TIME)
4981 perf_output_put(handle, data->time);
4983 if (sample_type & PERF_SAMPLE_ID)
4984 perf_output_put(handle, data->id);
4986 if (sample_type & PERF_SAMPLE_STREAM_ID)
4987 perf_output_put(handle, data->stream_id);
4989 if (sample_type & PERF_SAMPLE_CPU)
4990 perf_output_put(handle, data->cpu_entry);
4992 if (sample_type & PERF_SAMPLE_IDENTIFIER)
4993 perf_output_put(handle, data->id);
4996 void perf_event__output_id_sample(struct perf_event *event,
4997 struct perf_output_handle *handle,
4998 struct perf_sample_data *sample)
5000 if (event->attr.sample_id_all)
5001 __perf_event__output_id_sample(handle, sample);
5004 static void perf_output_read_one(struct perf_output_handle *handle,
5005 struct perf_event *event,
5006 u64 enabled, u64 running)
5008 u64 read_format = event->attr.read_format;
5012 values[n++] = perf_event_count(event);
5013 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5014 values[n++] = enabled +
5015 atomic64_read(&event->child_total_time_enabled);
5017 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5018 values[n++] = running +
5019 atomic64_read(&event->child_total_time_running);
5021 if (read_format & PERF_FORMAT_ID)
5022 values[n++] = primary_event_id(event);
5024 __output_copy(handle, values, n * sizeof(u64));
5028 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5030 static void perf_output_read_group(struct perf_output_handle *handle,
5031 struct perf_event *event,
5032 u64 enabled, u64 running)
5034 struct perf_event *leader = event->group_leader, *sub;
5035 u64 read_format = event->attr.read_format;
5039 values[n++] = 1 + leader->nr_siblings;
5041 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5042 values[n++] = enabled;
5044 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5045 values[n++] = running;
5047 if (leader != event)
5048 leader->pmu->read(leader);
5050 values[n++] = perf_event_count(leader);
5051 if (read_format & PERF_FORMAT_ID)
5052 values[n++] = primary_event_id(leader);
5054 __output_copy(handle, values, n * sizeof(u64));
5056 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5059 if ((sub != event) &&
5060 (sub->state == PERF_EVENT_STATE_ACTIVE))
5061 sub->pmu->read(sub);
5063 values[n++] = perf_event_count(sub);
5064 if (read_format & PERF_FORMAT_ID)
5065 values[n++] = primary_event_id(sub);
5067 __output_copy(handle, values, n * sizeof(u64));
5071 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5072 PERF_FORMAT_TOTAL_TIME_RUNNING)
5074 static void perf_output_read(struct perf_output_handle *handle,
5075 struct perf_event *event)
5077 u64 enabled = 0, running = 0, now;
5078 u64 read_format = event->attr.read_format;
5081 * compute total_time_enabled, total_time_running
5082 * based on snapshot values taken when the event
5083 * was last scheduled in.
5085 * we cannot simply called update_context_time()
5086 * because of locking issue as we are called in
5089 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5090 calc_timer_values(event, &now, &enabled, &running);
5092 if (event->attr.read_format & PERF_FORMAT_GROUP)
5093 perf_output_read_group(handle, event, enabled, running);
5095 perf_output_read_one(handle, event, enabled, running);
5098 void perf_output_sample(struct perf_output_handle *handle,
5099 struct perf_event_header *header,
5100 struct perf_sample_data *data,
5101 struct perf_event *event)
5103 u64 sample_type = data->type;
5105 perf_output_put(handle, *header);
5107 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5108 perf_output_put(handle, data->id);
5110 if (sample_type & PERF_SAMPLE_IP)
5111 perf_output_put(handle, data->ip);
5113 if (sample_type & PERF_SAMPLE_TID)
5114 perf_output_put(handle, data->tid_entry);
5116 if (sample_type & PERF_SAMPLE_TIME)
5117 perf_output_put(handle, data->time);
5119 if (sample_type & PERF_SAMPLE_ADDR)
5120 perf_output_put(handle, data->addr);
5122 if (sample_type & PERF_SAMPLE_ID)
5123 perf_output_put(handle, data->id);
5125 if (sample_type & PERF_SAMPLE_STREAM_ID)
5126 perf_output_put(handle, data->stream_id);
5128 if (sample_type & PERF_SAMPLE_CPU)
5129 perf_output_put(handle, data->cpu_entry);
5131 if (sample_type & PERF_SAMPLE_PERIOD)
5132 perf_output_put(handle, data->period);
5134 if (sample_type & PERF_SAMPLE_READ)
5135 perf_output_read(handle, event);
5137 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5138 if (data->callchain) {
5141 if (data->callchain)
5142 size += data->callchain->nr;
5144 size *= sizeof(u64);
5146 __output_copy(handle, data->callchain, size);
5149 perf_output_put(handle, nr);
5153 if (sample_type & PERF_SAMPLE_RAW) {
5155 perf_output_put(handle, data->raw->size);
5156 __output_copy(handle, data->raw->data,
5163 .size = sizeof(u32),
5166 perf_output_put(handle, raw);
5170 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5171 if (data->br_stack) {
5174 size = data->br_stack->nr
5175 * sizeof(struct perf_branch_entry);
5177 perf_output_put(handle, data->br_stack->nr);
5178 perf_output_copy(handle, data->br_stack->entries, size);
5181 * we always store at least the value of nr
5184 perf_output_put(handle, nr);
5188 if (sample_type & PERF_SAMPLE_REGS_USER) {
5189 u64 abi = data->regs_user.abi;
5192 * If there are no regs to dump, notice it through
5193 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5195 perf_output_put(handle, abi);
5198 u64 mask = event->attr.sample_regs_user;
5199 perf_output_sample_regs(handle,
5200 data->regs_user.regs,
5205 if (sample_type & PERF_SAMPLE_STACK_USER) {
5206 perf_output_sample_ustack(handle,
5207 data->stack_user_size,
5208 data->regs_user.regs);
5211 if (sample_type & PERF_SAMPLE_WEIGHT)
5212 perf_output_put(handle, data->weight);
5214 if (sample_type & PERF_SAMPLE_DATA_SRC)
5215 perf_output_put(handle, data->data_src.val);
5217 if (sample_type & PERF_SAMPLE_TRANSACTION)
5218 perf_output_put(handle, data->txn);
5220 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5221 u64 abi = data->regs_intr.abi;
5223 * If there are no regs to dump, notice it through
5224 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5226 perf_output_put(handle, abi);
5229 u64 mask = event->attr.sample_regs_intr;
5231 perf_output_sample_regs(handle,
5232 data->regs_intr.regs,
5237 if (!event->attr.watermark) {
5238 int wakeup_events = event->attr.wakeup_events;
5240 if (wakeup_events) {
5241 struct ring_buffer *rb = handle->rb;
5242 int events = local_inc_return(&rb->events);
5244 if (events >= wakeup_events) {
5245 local_sub(wakeup_events, &rb->events);
5246 local_inc(&rb->wakeup);
5252 void perf_prepare_sample(struct perf_event_header *header,
5253 struct perf_sample_data *data,
5254 struct perf_event *event,
5255 struct pt_regs *regs)
5257 u64 sample_type = event->attr.sample_type;
5259 header->type = PERF_RECORD_SAMPLE;
5260 header->size = sizeof(*header) + event->header_size;
5263 header->misc |= perf_misc_flags(regs);
5265 __perf_event_header__init_id(header, data, event);
5267 if (sample_type & PERF_SAMPLE_IP)
5268 data->ip = perf_instruction_pointer(regs);
5270 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5273 data->callchain = perf_callchain(event, regs);
5275 if (data->callchain)
5276 size += data->callchain->nr;
5278 header->size += size * sizeof(u64);
5281 if (sample_type & PERF_SAMPLE_RAW) {
5282 int size = sizeof(u32);
5285 size += data->raw->size;
5287 size += sizeof(u32);
5289 WARN_ON_ONCE(size & (sizeof(u64)-1));
5290 header->size += size;
5293 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5294 int size = sizeof(u64); /* nr */
5295 if (data->br_stack) {
5296 size += data->br_stack->nr
5297 * sizeof(struct perf_branch_entry);
5299 header->size += size;
5302 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5303 perf_sample_regs_user(&data->regs_user, regs,
5304 &data->regs_user_copy);
5306 if (sample_type & PERF_SAMPLE_REGS_USER) {
5307 /* regs dump ABI info */
5308 int size = sizeof(u64);
5310 if (data->regs_user.regs) {
5311 u64 mask = event->attr.sample_regs_user;
5312 size += hweight64(mask) * sizeof(u64);
5315 header->size += size;
5318 if (sample_type & PERF_SAMPLE_STACK_USER) {
5320 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5321 * processed as the last one or have additional check added
5322 * in case new sample type is added, because we could eat
5323 * up the rest of the sample size.
5325 u16 stack_size = event->attr.sample_stack_user;
5326 u16 size = sizeof(u64);
5328 stack_size = perf_sample_ustack_size(stack_size, header->size,
5329 data->regs_user.regs);
5332 * If there is something to dump, add space for the dump
5333 * itself and for the field that tells the dynamic size,
5334 * which is how many have been actually dumped.
5337 size += sizeof(u64) + stack_size;
5339 data->stack_user_size = stack_size;
5340 header->size += size;
5343 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5344 /* regs dump ABI info */
5345 int size = sizeof(u64);
5347 perf_sample_regs_intr(&data->regs_intr, regs);
5349 if (data->regs_intr.regs) {
5350 u64 mask = event->attr.sample_regs_intr;
5352 size += hweight64(mask) * sizeof(u64);
5355 header->size += size;
5359 static void perf_event_output(struct perf_event *event,
5360 struct perf_sample_data *data,
5361 struct pt_regs *regs)
5363 struct perf_output_handle handle;
5364 struct perf_event_header header;
5366 /* protect the callchain buffers */
5369 perf_prepare_sample(&header, data, event, regs);
5371 if (perf_output_begin(&handle, event, header.size))
5374 perf_output_sample(&handle, &header, data, event);
5376 perf_output_end(&handle);
5386 struct perf_read_event {
5387 struct perf_event_header header;
5394 perf_event_read_event(struct perf_event *event,
5395 struct task_struct *task)
5397 struct perf_output_handle handle;
5398 struct perf_sample_data sample;
5399 struct perf_read_event read_event = {
5401 .type = PERF_RECORD_READ,
5403 .size = sizeof(read_event) + event->read_size,
5405 .pid = perf_event_pid(event, task),
5406 .tid = perf_event_tid(event, task),
5410 perf_event_header__init_id(&read_event.header, &sample, event);
5411 ret = perf_output_begin(&handle, event, read_event.header.size);
5415 perf_output_put(&handle, read_event);
5416 perf_output_read(&handle, event);
5417 perf_event__output_id_sample(event, &handle, &sample);
5419 perf_output_end(&handle);
5422 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5425 perf_event_aux_ctx(struct perf_event_context *ctx,
5426 perf_event_aux_output_cb output,
5429 struct perf_event *event;
5431 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5432 if (event->state < PERF_EVENT_STATE_INACTIVE)
5434 if (!event_filter_match(event))
5436 output(event, data);
5441 perf_event_aux(perf_event_aux_output_cb output, void *data,
5442 struct perf_event_context *task_ctx)
5444 struct perf_cpu_context *cpuctx;
5445 struct perf_event_context *ctx;
5450 list_for_each_entry_rcu(pmu, &pmus, entry) {
5451 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5452 if (cpuctx->unique_pmu != pmu)
5454 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5457 ctxn = pmu->task_ctx_nr;
5460 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5462 perf_event_aux_ctx(ctx, output, data);
5464 put_cpu_ptr(pmu->pmu_cpu_context);
5469 perf_event_aux_ctx(task_ctx, output, data);
5476 * task tracking -- fork/exit
5478 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5481 struct perf_task_event {
5482 struct task_struct *task;
5483 struct perf_event_context *task_ctx;
5486 struct perf_event_header header;
5496 static int perf_event_task_match(struct perf_event *event)
5498 return event->attr.comm || event->attr.mmap ||
5499 event->attr.mmap2 || event->attr.mmap_data ||
5503 static void perf_event_task_output(struct perf_event *event,
5506 struct perf_task_event *task_event = data;
5507 struct perf_output_handle handle;
5508 struct perf_sample_data sample;
5509 struct task_struct *task = task_event->task;
5510 int ret, size = task_event->event_id.header.size;
5512 if (!perf_event_task_match(event))
5515 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5517 ret = perf_output_begin(&handle, event,
5518 task_event->event_id.header.size);
5522 task_event->event_id.pid = perf_event_pid(event, task);
5523 task_event->event_id.ppid = perf_event_pid(event, current);
5525 task_event->event_id.tid = perf_event_tid(event, task);
5526 task_event->event_id.ptid = perf_event_tid(event, current);
5528 task_event->event_id.time = perf_event_clock(event);
5530 perf_output_put(&handle, task_event->event_id);
5532 perf_event__output_id_sample(event, &handle, &sample);
5534 perf_output_end(&handle);
5536 task_event->event_id.header.size = size;
5539 static void perf_event_task(struct task_struct *task,
5540 struct perf_event_context *task_ctx,
5543 struct perf_task_event task_event;
5545 if (!atomic_read(&nr_comm_events) &&
5546 !atomic_read(&nr_mmap_events) &&
5547 !atomic_read(&nr_task_events))
5550 task_event = (struct perf_task_event){
5552 .task_ctx = task_ctx,
5555 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5557 .size = sizeof(task_event.event_id),
5567 perf_event_aux(perf_event_task_output,
5572 void perf_event_fork(struct task_struct *task)
5574 perf_event_task(task, NULL, 1);
5581 struct perf_comm_event {
5582 struct task_struct *task;
5587 struct perf_event_header header;
5594 static int perf_event_comm_match(struct perf_event *event)
5596 return event->attr.comm;
5599 static void perf_event_comm_output(struct perf_event *event,
5602 struct perf_comm_event *comm_event = data;
5603 struct perf_output_handle handle;
5604 struct perf_sample_data sample;
5605 int size = comm_event->event_id.header.size;
5608 if (!perf_event_comm_match(event))
5611 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5612 ret = perf_output_begin(&handle, event,
5613 comm_event->event_id.header.size);
5618 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5619 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5621 perf_output_put(&handle, comm_event->event_id);
5622 __output_copy(&handle, comm_event->comm,
5623 comm_event->comm_size);
5625 perf_event__output_id_sample(event, &handle, &sample);
5627 perf_output_end(&handle);
5629 comm_event->event_id.header.size = size;
5632 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5634 char comm[TASK_COMM_LEN];
5637 memset(comm, 0, sizeof(comm));
5638 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5639 size = ALIGN(strlen(comm)+1, sizeof(u64));
5641 comm_event->comm = comm;
5642 comm_event->comm_size = size;
5644 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5646 perf_event_aux(perf_event_comm_output,
5651 void perf_event_comm(struct task_struct *task, bool exec)
5653 struct perf_comm_event comm_event;
5655 if (!atomic_read(&nr_comm_events))
5658 comm_event = (struct perf_comm_event){
5664 .type = PERF_RECORD_COMM,
5665 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5673 perf_event_comm_event(&comm_event);
5680 struct perf_mmap_event {
5681 struct vm_area_struct *vma;
5683 const char *file_name;
5691 struct perf_event_header header;
5701 static int perf_event_mmap_match(struct perf_event *event,
5704 struct perf_mmap_event *mmap_event = data;
5705 struct vm_area_struct *vma = mmap_event->vma;
5706 int executable = vma->vm_flags & VM_EXEC;
5708 return (!executable && event->attr.mmap_data) ||
5709 (executable && (event->attr.mmap || event->attr.mmap2));
5712 static void perf_event_mmap_output(struct perf_event *event,
5715 struct perf_mmap_event *mmap_event = data;
5716 struct perf_output_handle handle;
5717 struct perf_sample_data sample;
5718 int size = mmap_event->event_id.header.size;
5721 if (!perf_event_mmap_match(event, data))
5724 if (event->attr.mmap2) {
5725 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5726 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5727 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5728 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5729 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5730 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5731 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5734 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5735 ret = perf_output_begin(&handle, event,
5736 mmap_event->event_id.header.size);
5740 mmap_event->event_id.pid = perf_event_pid(event, current);
5741 mmap_event->event_id.tid = perf_event_tid(event, current);
5743 perf_output_put(&handle, mmap_event->event_id);
5745 if (event->attr.mmap2) {
5746 perf_output_put(&handle, mmap_event->maj);
5747 perf_output_put(&handle, mmap_event->min);
5748 perf_output_put(&handle, mmap_event->ino);
5749 perf_output_put(&handle, mmap_event->ino_generation);
5750 perf_output_put(&handle, mmap_event->prot);
5751 perf_output_put(&handle, mmap_event->flags);
5754 __output_copy(&handle, mmap_event->file_name,
5755 mmap_event->file_size);
5757 perf_event__output_id_sample(event, &handle, &sample);
5759 perf_output_end(&handle);
5761 mmap_event->event_id.header.size = size;
5764 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5766 struct vm_area_struct *vma = mmap_event->vma;
5767 struct file *file = vma->vm_file;
5768 int maj = 0, min = 0;
5769 u64 ino = 0, gen = 0;
5770 u32 prot = 0, flags = 0;
5777 struct inode *inode;
5780 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5786 * d_path() works from the end of the rb backwards, so we
5787 * need to add enough zero bytes after the string to handle
5788 * the 64bit alignment we do later.
5790 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5795 inode = file_inode(vma->vm_file);
5796 dev = inode->i_sb->s_dev;
5798 gen = inode->i_generation;
5802 if (vma->vm_flags & VM_READ)
5804 if (vma->vm_flags & VM_WRITE)
5806 if (vma->vm_flags & VM_EXEC)
5809 if (vma->vm_flags & VM_MAYSHARE)
5812 flags = MAP_PRIVATE;
5814 if (vma->vm_flags & VM_DENYWRITE)
5815 flags |= MAP_DENYWRITE;
5816 if (vma->vm_flags & VM_MAYEXEC)
5817 flags |= MAP_EXECUTABLE;
5818 if (vma->vm_flags & VM_LOCKED)
5819 flags |= MAP_LOCKED;
5820 if (vma->vm_flags & VM_HUGETLB)
5821 flags |= MAP_HUGETLB;
5825 if (vma->vm_ops && vma->vm_ops->name) {
5826 name = (char *) vma->vm_ops->name(vma);
5831 name = (char *)arch_vma_name(vma);
5835 if (vma->vm_start <= vma->vm_mm->start_brk &&
5836 vma->vm_end >= vma->vm_mm->brk) {
5840 if (vma->vm_start <= vma->vm_mm->start_stack &&
5841 vma->vm_end >= vma->vm_mm->start_stack) {
5851 strlcpy(tmp, name, sizeof(tmp));
5855 * Since our buffer works in 8 byte units we need to align our string
5856 * size to a multiple of 8. However, we must guarantee the tail end is
5857 * zero'd out to avoid leaking random bits to userspace.
5859 size = strlen(name)+1;
5860 while (!IS_ALIGNED(size, sizeof(u64)))
5861 name[size++] = '\0';
5863 mmap_event->file_name = name;
5864 mmap_event->file_size = size;
5865 mmap_event->maj = maj;
5866 mmap_event->min = min;
5867 mmap_event->ino = ino;
5868 mmap_event->ino_generation = gen;
5869 mmap_event->prot = prot;
5870 mmap_event->flags = flags;
5872 if (!(vma->vm_flags & VM_EXEC))
5873 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5875 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5877 perf_event_aux(perf_event_mmap_output,
5884 void perf_event_mmap(struct vm_area_struct *vma)
5886 struct perf_mmap_event mmap_event;
5888 if (!atomic_read(&nr_mmap_events))
5891 mmap_event = (struct perf_mmap_event){
5897 .type = PERF_RECORD_MMAP,
5898 .misc = PERF_RECORD_MISC_USER,
5903 .start = vma->vm_start,
5904 .len = vma->vm_end - vma->vm_start,
5905 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5907 /* .maj (attr_mmap2 only) */
5908 /* .min (attr_mmap2 only) */
5909 /* .ino (attr_mmap2 only) */
5910 /* .ino_generation (attr_mmap2 only) */
5911 /* .prot (attr_mmap2 only) */
5912 /* .flags (attr_mmap2 only) */
5915 perf_event_mmap_event(&mmap_event);
5918 void perf_event_aux_event(struct perf_event *event, unsigned long head,
5919 unsigned long size, u64 flags)
5921 struct perf_output_handle handle;
5922 struct perf_sample_data sample;
5923 struct perf_aux_event {
5924 struct perf_event_header header;
5930 .type = PERF_RECORD_AUX,
5932 .size = sizeof(rec),
5940 perf_event_header__init_id(&rec.header, &sample, event);
5941 ret = perf_output_begin(&handle, event, rec.header.size);
5946 perf_output_put(&handle, rec);
5947 perf_event__output_id_sample(event, &handle, &sample);
5949 perf_output_end(&handle);
5953 * IRQ throttle logging
5956 static void perf_log_throttle(struct perf_event *event, int enable)
5958 struct perf_output_handle handle;
5959 struct perf_sample_data sample;
5963 struct perf_event_header header;
5967 } throttle_event = {
5969 .type = PERF_RECORD_THROTTLE,
5971 .size = sizeof(throttle_event),
5973 .time = perf_event_clock(event),
5974 .id = primary_event_id(event),
5975 .stream_id = event->id,
5979 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5981 perf_event_header__init_id(&throttle_event.header, &sample, event);
5983 ret = perf_output_begin(&handle, event,
5984 throttle_event.header.size);
5988 perf_output_put(&handle, throttle_event);
5989 perf_event__output_id_sample(event, &handle, &sample);
5990 perf_output_end(&handle);
5993 static void perf_log_itrace_start(struct perf_event *event)
5995 struct perf_output_handle handle;
5996 struct perf_sample_data sample;
5997 struct perf_aux_event {
5998 struct perf_event_header header;
6005 event = event->parent;
6007 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6008 event->hw.itrace_started)
6011 event->hw.itrace_started = 1;
6013 rec.header.type = PERF_RECORD_ITRACE_START;
6014 rec.header.misc = 0;
6015 rec.header.size = sizeof(rec);
6016 rec.pid = perf_event_pid(event, current);
6017 rec.tid = perf_event_tid(event, current);
6019 perf_event_header__init_id(&rec.header, &sample, event);
6020 ret = perf_output_begin(&handle, event, rec.header.size);
6025 perf_output_put(&handle, rec);
6026 perf_event__output_id_sample(event, &handle, &sample);
6028 perf_output_end(&handle);
6032 * Generic event overflow handling, sampling.
6035 static int __perf_event_overflow(struct perf_event *event,
6036 int throttle, struct perf_sample_data *data,
6037 struct pt_regs *regs)
6039 int events = atomic_read(&event->event_limit);
6040 struct hw_perf_event *hwc = &event->hw;
6045 * Non-sampling counters might still use the PMI to fold short
6046 * hardware counters, ignore those.
6048 if (unlikely(!is_sampling_event(event)))
6051 seq = __this_cpu_read(perf_throttled_seq);
6052 if (seq != hwc->interrupts_seq) {
6053 hwc->interrupts_seq = seq;
6054 hwc->interrupts = 1;
6057 if (unlikely(throttle
6058 && hwc->interrupts >= max_samples_per_tick)) {
6059 __this_cpu_inc(perf_throttled_count);
6060 hwc->interrupts = MAX_INTERRUPTS;
6061 perf_log_throttle(event, 0);
6062 tick_nohz_full_kick();
6067 if (event->attr.freq) {
6068 u64 now = perf_clock();
6069 s64 delta = now - hwc->freq_time_stamp;
6071 hwc->freq_time_stamp = now;
6073 if (delta > 0 && delta < 2*TICK_NSEC)
6074 perf_adjust_period(event, delta, hwc->last_period, true);
6078 * XXX event_limit might not quite work as expected on inherited
6082 event->pending_kill = POLL_IN;
6083 if (events && atomic_dec_and_test(&event->event_limit)) {
6085 event->pending_kill = POLL_HUP;
6086 event->pending_disable = 1;
6087 irq_work_queue(&event->pending);
6090 if (event->overflow_handler)
6091 event->overflow_handler(event, data, regs);
6093 perf_event_output(event, data, regs);
6095 if (event->fasync && event->pending_kill) {
6096 event->pending_wakeup = 1;
6097 irq_work_queue(&event->pending);
6103 int perf_event_overflow(struct perf_event *event,
6104 struct perf_sample_data *data,
6105 struct pt_regs *regs)
6107 return __perf_event_overflow(event, 1, data, regs);
6111 * Generic software event infrastructure
6114 struct swevent_htable {
6115 struct swevent_hlist *swevent_hlist;
6116 struct mutex hlist_mutex;
6119 /* Recursion avoidance in each contexts */
6120 int recursion[PERF_NR_CONTEXTS];
6122 /* Keeps track of cpu being initialized/exited */
6126 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6129 * We directly increment event->count and keep a second value in
6130 * event->hw.period_left to count intervals. This period event
6131 * is kept in the range [-sample_period, 0] so that we can use the
6135 u64 perf_swevent_set_period(struct perf_event *event)
6137 struct hw_perf_event *hwc = &event->hw;
6138 u64 period = hwc->last_period;
6142 hwc->last_period = hwc->sample_period;
6145 old = val = local64_read(&hwc->period_left);
6149 nr = div64_u64(period + val, period);
6150 offset = nr * period;
6152 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6158 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6159 struct perf_sample_data *data,
6160 struct pt_regs *regs)
6162 struct hw_perf_event *hwc = &event->hw;
6166 overflow = perf_swevent_set_period(event);
6168 if (hwc->interrupts == MAX_INTERRUPTS)
6171 for (; overflow; overflow--) {
6172 if (__perf_event_overflow(event, throttle,
6175 * We inhibit the overflow from happening when
6176 * hwc->interrupts == MAX_INTERRUPTS.
6184 static void perf_swevent_event(struct perf_event *event, u64 nr,
6185 struct perf_sample_data *data,
6186 struct pt_regs *regs)
6188 struct hw_perf_event *hwc = &event->hw;
6190 local64_add(nr, &event->count);
6195 if (!is_sampling_event(event))
6198 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6200 return perf_swevent_overflow(event, 1, data, regs);
6202 data->period = event->hw.last_period;
6204 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6205 return perf_swevent_overflow(event, 1, data, regs);
6207 if (local64_add_negative(nr, &hwc->period_left))
6210 perf_swevent_overflow(event, 0, data, regs);
6213 static int perf_exclude_event(struct perf_event *event,
6214 struct pt_regs *regs)
6216 if (event->hw.state & PERF_HES_STOPPED)
6220 if (event->attr.exclude_user && user_mode(regs))
6223 if (event->attr.exclude_kernel && !user_mode(regs))
6230 static int perf_swevent_match(struct perf_event *event,
6231 enum perf_type_id type,
6233 struct perf_sample_data *data,
6234 struct pt_regs *regs)
6236 if (event->attr.type != type)
6239 if (event->attr.config != event_id)
6242 if (perf_exclude_event(event, regs))
6248 static inline u64 swevent_hash(u64 type, u32 event_id)
6250 u64 val = event_id | (type << 32);
6252 return hash_64(val, SWEVENT_HLIST_BITS);
6255 static inline struct hlist_head *
6256 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6258 u64 hash = swevent_hash(type, event_id);
6260 return &hlist->heads[hash];
6263 /* For the read side: events when they trigger */
6264 static inline struct hlist_head *
6265 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6267 struct swevent_hlist *hlist;
6269 hlist = rcu_dereference(swhash->swevent_hlist);
6273 return __find_swevent_head(hlist, type, event_id);
6276 /* For the event head insertion and removal in the hlist */
6277 static inline struct hlist_head *
6278 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6280 struct swevent_hlist *hlist;
6281 u32 event_id = event->attr.config;
6282 u64 type = event->attr.type;
6285 * Event scheduling is always serialized against hlist allocation
6286 * and release. Which makes the protected version suitable here.
6287 * The context lock guarantees that.
6289 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6290 lockdep_is_held(&event->ctx->lock));
6294 return __find_swevent_head(hlist, type, event_id);
6297 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6299 struct perf_sample_data *data,
6300 struct pt_regs *regs)
6302 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6303 struct perf_event *event;
6304 struct hlist_head *head;
6307 head = find_swevent_head_rcu(swhash, type, event_id);
6311 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6312 if (perf_swevent_match(event, type, event_id, data, regs))
6313 perf_swevent_event(event, nr, data, regs);
6319 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6321 int perf_swevent_get_recursion_context(void)
6323 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6325 return get_recursion_context(swhash->recursion);
6327 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6329 inline void perf_swevent_put_recursion_context(int rctx)
6331 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6333 put_recursion_context(swhash->recursion, rctx);
6336 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6338 struct perf_sample_data data;
6340 if (WARN_ON_ONCE(!regs))
6343 perf_sample_data_init(&data, addr, 0);
6344 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6347 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6351 preempt_disable_notrace();
6352 rctx = perf_swevent_get_recursion_context();
6353 if (unlikely(rctx < 0))
6356 ___perf_sw_event(event_id, nr, regs, addr);
6358 perf_swevent_put_recursion_context(rctx);
6360 preempt_enable_notrace();
6363 static void perf_swevent_read(struct perf_event *event)
6367 static int perf_swevent_add(struct perf_event *event, int flags)
6369 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6370 struct hw_perf_event *hwc = &event->hw;
6371 struct hlist_head *head;
6373 if (is_sampling_event(event)) {
6374 hwc->last_period = hwc->sample_period;
6375 perf_swevent_set_period(event);
6378 hwc->state = !(flags & PERF_EF_START);
6380 head = find_swevent_head(swhash, event);
6383 * We can race with cpu hotplug code. Do not
6384 * WARN if the cpu just got unplugged.
6386 WARN_ON_ONCE(swhash->online);
6390 hlist_add_head_rcu(&event->hlist_entry, head);
6391 perf_event_update_userpage(event);
6396 static void perf_swevent_del(struct perf_event *event, int flags)
6398 hlist_del_rcu(&event->hlist_entry);
6401 static void perf_swevent_start(struct perf_event *event, int flags)
6403 event->hw.state = 0;
6406 static void perf_swevent_stop(struct perf_event *event, int flags)
6408 event->hw.state = PERF_HES_STOPPED;
6411 /* Deref the hlist from the update side */
6412 static inline struct swevent_hlist *
6413 swevent_hlist_deref(struct swevent_htable *swhash)
6415 return rcu_dereference_protected(swhash->swevent_hlist,
6416 lockdep_is_held(&swhash->hlist_mutex));
6419 static void swevent_hlist_release(struct swevent_htable *swhash)
6421 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6426 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6427 kfree_rcu(hlist, rcu_head);
6430 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6432 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6434 mutex_lock(&swhash->hlist_mutex);
6436 if (!--swhash->hlist_refcount)
6437 swevent_hlist_release(swhash);
6439 mutex_unlock(&swhash->hlist_mutex);
6442 static void swevent_hlist_put(struct perf_event *event)
6446 for_each_possible_cpu(cpu)
6447 swevent_hlist_put_cpu(event, cpu);
6450 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6452 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6455 mutex_lock(&swhash->hlist_mutex);
6457 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6458 struct swevent_hlist *hlist;
6460 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6465 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6467 swhash->hlist_refcount++;
6469 mutex_unlock(&swhash->hlist_mutex);
6474 static int swevent_hlist_get(struct perf_event *event)
6477 int cpu, failed_cpu;
6480 for_each_possible_cpu(cpu) {
6481 err = swevent_hlist_get_cpu(event, cpu);
6491 for_each_possible_cpu(cpu) {
6492 if (cpu == failed_cpu)
6494 swevent_hlist_put_cpu(event, cpu);
6501 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6503 static void sw_perf_event_destroy(struct perf_event *event)
6505 u64 event_id = event->attr.config;
6507 WARN_ON(event->parent);
6509 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6510 swevent_hlist_put(event);
6513 static int perf_swevent_init(struct perf_event *event)
6515 u64 event_id = event->attr.config;
6517 if (event->attr.type != PERF_TYPE_SOFTWARE)
6521 * no branch sampling for software events
6523 if (has_branch_stack(event))
6527 case PERF_COUNT_SW_CPU_CLOCK:
6528 case PERF_COUNT_SW_TASK_CLOCK:
6535 if (event_id >= PERF_COUNT_SW_MAX)
6538 if (!event->parent) {
6541 err = swevent_hlist_get(event);
6545 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6546 event->destroy = sw_perf_event_destroy;
6552 static struct pmu perf_swevent = {
6553 .task_ctx_nr = perf_sw_context,
6555 .capabilities = PERF_PMU_CAP_NO_NMI,
6557 .event_init = perf_swevent_init,
6558 .add = perf_swevent_add,
6559 .del = perf_swevent_del,
6560 .start = perf_swevent_start,
6561 .stop = perf_swevent_stop,
6562 .read = perf_swevent_read,
6565 #ifdef CONFIG_EVENT_TRACING
6567 static int perf_tp_filter_match(struct perf_event *event,
6568 struct perf_sample_data *data)
6570 void *record = data->raw->data;
6572 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6577 static int perf_tp_event_match(struct perf_event *event,
6578 struct perf_sample_data *data,
6579 struct pt_regs *regs)
6581 if (event->hw.state & PERF_HES_STOPPED)
6584 * All tracepoints are from kernel-space.
6586 if (event->attr.exclude_kernel)
6589 if (!perf_tp_filter_match(event, data))
6595 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6596 struct pt_regs *regs, struct hlist_head *head, int rctx,
6597 struct task_struct *task)
6599 struct perf_sample_data data;
6600 struct perf_event *event;
6602 struct perf_raw_record raw = {
6607 perf_sample_data_init(&data, addr, 0);
6610 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6611 if (perf_tp_event_match(event, &data, regs))
6612 perf_swevent_event(event, count, &data, regs);
6616 * If we got specified a target task, also iterate its context and
6617 * deliver this event there too.
6619 if (task && task != current) {
6620 struct perf_event_context *ctx;
6621 struct trace_entry *entry = record;
6624 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6628 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6629 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6631 if (event->attr.config != entry->type)
6633 if (perf_tp_event_match(event, &data, regs))
6634 perf_swevent_event(event, count, &data, regs);
6640 perf_swevent_put_recursion_context(rctx);
6642 EXPORT_SYMBOL_GPL(perf_tp_event);
6644 static void tp_perf_event_destroy(struct perf_event *event)
6646 perf_trace_destroy(event);
6649 static int perf_tp_event_init(struct perf_event *event)
6653 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6657 * no branch sampling for tracepoint events
6659 if (has_branch_stack(event))
6662 err = perf_trace_init(event);
6666 event->destroy = tp_perf_event_destroy;
6671 static struct pmu perf_tracepoint = {
6672 .task_ctx_nr = perf_sw_context,
6674 .event_init = perf_tp_event_init,
6675 .add = perf_trace_add,
6676 .del = perf_trace_del,
6677 .start = perf_swevent_start,
6678 .stop = perf_swevent_stop,
6679 .read = perf_swevent_read,
6682 static inline void perf_tp_register(void)
6684 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6687 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6692 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6695 filter_str = strndup_user(arg, PAGE_SIZE);
6696 if (IS_ERR(filter_str))
6697 return PTR_ERR(filter_str);
6699 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6705 static void perf_event_free_filter(struct perf_event *event)
6707 ftrace_profile_free_filter(event);
6710 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
6712 struct bpf_prog *prog;
6714 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6717 if (event->tp_event->prog)
6720 if (!(event->tp_event->flags & TRACE_EVENT_FL_KPROBE))
6721 /* bpf programs can only be attached to kprobes */
6724 prog = bpf_prog_get(prog_fd);
6726 return PTR_ERR(prog);
6728 if (prog->type != BPF_PROG_TYPE_KPROBE) {
6729 /* valid fd, but invalid bpf program type */
6734 event->tp_event->prog = prog;
6739 static void perf_event_free_bpf_prog(struct perf_event *event)
6741 struct bpf_prog *prog;
6743 if (!event->tp_event)
6746 prog = event->tp_event->prog;
6748 event->tp_event->prog = NULL;
6755 static inline void perf_tp_register(void)
6759 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6764 static void perf_event_free_filter(struct perf_event *event)
6768 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
6773 static void perf_event_free_bpf_prog(struct perf_event *event)
6776 #endif /* CONFIG_EVENT_TRACING */
6778 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6779 void perf_bp_event(struct perf_event *bp, void *data)
6781 struct perf_sample_data sample;
6782 struct pt_regs *regs = data;
6784 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6786 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6787 perf_swevent_event(bp, 1, &sample, regs);
6792 * hrtimer based swevent callback
6795 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6797 enum hrtimer_restart ret = HRTIMER_RESTART;
6798 struct perf_sample_data data;
6799 struct pt_regs *regs;
6800 struct perf_event *event;
6803 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6805 if (event->state != PERF_EVENT_STATE_ACTIVE)
6806 return HRTIMER_NORESTART;
6808 event->pmu->read(event);
6810 perf_sample_data_init(&data, 0, event->hw.last_period);
6811 regs = get_irq_regs();
6813 if (regs && !perf_exclude_event(event, regs)) {
6814 if (!(event->attr.exclude_idle && is_idle_task(current)))
6815 if (__perf_event_overflow(event, 1, &data, regs))
6816 ret = HRTIMER_NORESTART;
6819 period = max_t(u64, 10000, event->hw.sample_period);
6820 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6825 static void perf_swevent_start_hrtimer(struct perf_event *event)
6827 struct hw_perf_event *hwc = &event->hw;
6830 if (!is_sampling_event(event))
6833 period = local64_read(&hwc->period_left);
6838 local64_set(&hwc->period_left, 0);
6840 period = max_t(u64, 10000, hwc->sample_period);
6842 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
6843 HRTIMER_MODE_REL_PINNED);
6846 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6848 struct hw_perf_event *hwc = &event->hw;
6850 if (is_sampling_event(event)) {
6851 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6852 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6854 hrtimer_cancel(&hwc->hrtimer);
6858 static void perf_swevent_init_hrtimer(struct perf_event *event)
6860 struct hw_perf_event *hwc = &event->hw;
6862 if (!is_sampling_event(event))
6865 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6866 hwc->hrtimer.function = perf_swevent_hrtimer;
6869 * Since hrtimers have a fixed rate, we can do a static freq->period
6870 * mapping and avoid the whole period adjust feedback stuff.
6872 if (event->attr.freq) {
6873 long freq = event->attr.sample_freq;
6875 event->attr.sample_period = NSEC_PER_SEC / freq;
6876 hwc->sample_period = event->attr.sample_period;
6877 local64_set(&hwc->period_left, hwc->sample_period);
6878 hwc->last_period = hwc->sample_period;
6879 event->attr.freq = 0;
6884 * Software event: cpu wall time clock
6887 static void cpu_clock_event_update(struct perf_event *event)
6892 now = local_clock();
6893 prev = local64_xchg(&event->hw.prev_count, now);
6894 local64_add(now - prev, &event->count);
6897 static void cpu_clock_event_start(struct perf_event *event, int flags)
6899 local64_set(&event->hw.prev_count, local_clock());
6900 perf_swevent_start_hrtimer(event);
6903 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6905 perf_swevent_cancel_hrtimer(event);
6906 cpu_clock_event_update(event);
6909 static int cpu_clock_event_add(struct perf_event *event, int flags)
6911 if (flags & PERF_EF_START)
6912 cpu_clock_event_start(event, flags);
6913 perf_event_update_userpage(event);
6918 static void cpu_clock_event_del(struct perf_event *event, int flags)
6920 cpu_clock_event_stop(event, flags);
6923 static void cpu_clock_event_read(struct perf_event *event)
6925 cpu_clock_event_update(event);
6928 static int cpu_clock_event_init(struct perf_event *event)
6930 if (event->attr.type != PERF_TYPE_SOFTWARE)
6933 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6937 * no branch sampling for software events
6939 if (has_branch_stack(event))
6942 perf_swevent_init_hrtimer(event);
6947 static struct pmu perf_cpu_clock = {
6948 .task_ctx_nr = perf_sw_context,
6950 .capabilities = PERF_PMU_CAP_NO_NMI,
6952 .event_init = cpu_clock_event_init,
6953 .add = cpu_clock_event_add,
6954 .del = cpu_clock_event_del,
6955 .start = cpu_clock_event_start,
6956 .stop = cpu_clock_event_stop,
6957 .read = cpu_clock_event_read,
6961 * Software event: task time clock
6964 static void task_clock_event_update(struct perf_event *event, u64 now)
6969 prev = local64_xchg(&event->hw.prev_count, now);
6971 local64_add(delta, &event->count);
6974 static void task_clock_event_start(struct perf_event *event, int flags)
6976 local64_set(&event->hw.prev_count, event->ctx->time);
6977 perf_swevent_start_hrtimer(event);
6980 static void task_clock_event_stop(struct perf_event *event, int flags)
6982 perf_swevent_cancel_hrtimer(event);
6983 task_clock_event_update(event, event->ctx->time);
6986 static int task_clock_event_add(struct perf_event *event, int flags)
6988 if (flags & PERF_EF_START)
6989 task_clock_event_start(event, flags);
6990 perf_event_update_userpage(event);
6995 static void task_clock_event_del(struct perf_event *event, int flags)
6997 task_clock_event_stop(event, PERF_EF_UPDATE);
7000 static void task_clock_event_read(struct perf_event *event)
7002 u64 now = perf_clock();
7003 u64 delta = now - event->ctx->timestamp;
7004 u64 time = event->ctx->time + delta;
7006 task_clock_event_update(event, time);
7009 static int task_clock_event_init(struct perf_event *event)
7011 if (event->attr.type != PERF_TYPE_SOFTWARE)
7014 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7018 * no branch sampling for software events
7020 if (has_branch_stack(event))
7023 perf_swevent_init_hrtimer(event);
7028 static struct pmu perf_task_clock = {
7029 .task_ctx_nr = perf_sw_context,
7031 .capabilities = PERF_PMU_CAP_NO_NMI,
7033 .event_init = task_clock_event_init,
7034 .add = task_clock_event_add,
7035 .del = task_clock_event_del,
7036 .start = task_clock_event_start,
7037 .stop = task_clock_event_stop,
7038 .read = task_clock_event_read,
7041 static void perf_pmu_nop_void(struct pmu *pmu)
7045 static int perf_pmu_nop_int(struct pmu *pmu)
7050 static void perf_pmu_start_txn(struct pmu *pmu)
7052 perf_pmu_disable(pmu);
7055 static int perf_pmu_commit_txn(struct pmu *pmu)
7057 perf_pmu_enable(pmu);
7061 static void perf_pmu_cancel_txn(struct pmu *pmu)
7063 perf_pmu_enable(pmu);
7066 static int perf_event_idx_default(struct perf_event *event)
7072 * Ensures all contexts with the same task_ctx_nr have the same
7073 * pmu_cpu_context too.
7075 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7082 list_for_each_entry(pmu, &pmus, entry) {
7083 if (pmu->task_ctx_nr == ctxn)
7084 return pmu->pmu_cpu_context;
7090 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7094 for_each_possible_cpu(cpu) {
7095 struct perf_cpu_context *cpuctx;
7097 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7099 if (cpuctx->unique_pmu == old_pmu)
7100 cpuctx->unique_pmu = pmu;
7104 static void free_pmu_context(struct pmu *pmu)
7108 mutex_lock(&pmus_lock);
7110 * Like a real lame refcount.
7112 list_for_each_entry(i, &pmus, entry) {
7113 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7114 update_pmu_context(i, pmu);
7119 free_percpu(pmu->pmu_cpu_context);
7121 mutex_unlock(&pmus_lock);
7123 static struct idr pmu_idr;
7126 type_show(struct device *dev, struct device_attribute *attr, char *page)
7128 struct pmu *pmu = dev_get_drvdata(dev);
7130 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7132 static DEVICE_ATTR_RO(type);
7135 perf_event_mux_interval_ms_show(struct device *dev,
7136 struct device_attribute *attr,
7139 struct pmu *pmu = dev_get_drvdata(dev);
7141 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7144 static DEFINE_MUTEX(mux_interval_mutex);
7147 perf_event_mux_interval_ms_store(struct device *dev,
7148 struct device_attribute *attr,
7149 const char *buf, size_t count)
7151 struct pmu *pmu = dev_get_drvdata(dev);
7152 int timer, cpu, ret;
7154 ret = kstrtoint(buf, 0, &timer);
7161 /* same value, noting to do */
7162 if (timer == pmu->hrtimer_interval_ms)
7165 mutex_lock(&mux_interval_mutex);
7166 pmu->hrtimer_interval_ms = timer;
7168 /* update all cpuctx for this PMU */
7170 for_each_online_cpu(cpu) {
7171 struct perf_cpu_context *cpuctx;
7172 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7173 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7175 cpu_function_call(cpu,
7176 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7179 mutex_unlock(&mux_interval_mutex);
7183 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7185 static struct attribute *pmu_dev_attrs[] = {
7186 &dev_attr_type.attr,
7187 &dev_attr_perf_event_mux_interval_ms.attr,
7190 ATTRIBUTE_GROUPS(pmu_dev);
7192 static int pmu_bus_running;
7193 static struct bus_type pmu_bus = {
7194 .name = "event_source",
7195 .dev_groups = pmu_dev_groups,
7198 static void pmu_dev_release(struct device *dev)
7203 static int pmu_dev_alloc(struct pmu *pmu)
7207 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7211 pmu->dev->groups = pmu->attr_groups;
7212 device_initialize(pmu->dev);
7213 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7217 dev_set_drvdata(pmu->dev, pmu);
7218 pmu->dev->bus = &pmu_bus;
7219 pmu->dev->release = pmu_dev_release;
7220 ret = device_add(pmu->dev);
7228 put_device(pmu->dev);
7232 static struct lock_class_key cpuctx_mutex;
7233 static struct lock_class_key cpuctx_lock;
7235 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7239 mutex_lock(&pmus_lock);
7241 pmu->pmu_disable_count = alloc_percpu(int);
7242 if (!pmu->pmu_disable_count)
7251 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7259 if (pmu_bus_running) {
7260 ret = pmu_dev_alloc(pmu);
7266 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7267 if (pmu->pmu_cpu_context)
7268 goto got_cpu_context;
7271 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7272 if (!pmu->pmu_cpu_context)
7275 for_each_possible_cpu(cpu) {
7276 struct perf_cpu_context *cpuctx;
7278 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7279 __perf_event_init_context(&cpuctx->ctx);
7280 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7281 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7282 cpuctx->ctx.pmu = pmu;
7284 __perf_mux_hrtimer_init(cpuctx, cpu);
7286 cpuctx->unique_pmu = pmu;
7290 if (!pmu->start_txn) {
7291 if (pmu->pmu_enable) {
7293 * If we have pmu_enable/pmu_disable calls, install
7294 * transaction stubs that use that to try and batch
7295 * hardware accesses.
7297 pmu->start_txn = perf_pmu_start_txn;
7298 pmu->commit_txn = perf_pmu_commit_txn;
7299 pmu->cancel_txn = perf_pmu_cancel_txn;
7301 pmu->start_txn = perf_pmu_nop_void;
7302 pmu->commit_txn = perf_pmu_nop_int;
7303 pmu->cancel_txn = perf_pmu_nop_void;
7307 if (!pmu->pmu_enable) {
7308 pmu->pmu_enable = perf_pmu_nop_void;
7309 pmu->pmu_disable = perf_pmu_nop_void;
7312 if (!pmu->event_idx)
7313 pmu->event_idx = perf_event_idx_default;
7315 list_add_rcu(&pmu->entry, &pmus);
7316 atomic_set(&pmu->exclusive_cnt, 0);
7319 mutex_unlock(&pmus_lock);
7324 device_del(pmu->dev);
7325 put_device(pmu->dev);
7328 if (pmu->type >= PERF_TYPE_MAX)
7329 idr_remove(&pmu_idr, pmu->type);
7332 free_percpu(pmu->pmu_disable_count);
7335 EXPORT_SYMBOL_GPL(perf_pmu_register);
7337 void perf_pmu_unregister(struct pmu *pmu)
7339 mutex_lock(&pmus_lock);
7340 list_del_rcu(&pmu->entry);
7341 mutex_unlock(&pmus_lock);
7344 * We dereference the pmu list under both SRCU and regular RCU, so
7345 * synchronize against both of those.
7347 synchronize_srcu(&pmus_srcu);
7350 free_percpu(pmu->pmu_disable_count);
7351 if (pmu->type >= PERF_TYPE_MAX)
7352 idr_remove(&pmu_idr, pmu->type);
7353 device_del(pmu->dev);
7354 put_device(pmu->dev);
7355 free_pmu_context(pmu);
7357 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7359 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7361 struct perf_event_context *ctx = NULL;
7364 if (!try_module_get(pmu->module))
7367 if (event->group_leader != event) {
7369 * This ctx->mutex can nest when we're called through
7370 * inheritance. See the perf_event_ctx_lock_nested() comment.
7372 ctx = perf_event_ctx_lock_nested(event->group_leader,
7373 SINGLE_DEPTH_NESTING);
7378 ret = pmu->event_init(event);
7381 perf_event_ctx_unlock(event->group_leader, ctx);
7384 module_put(pmu->module);
7389 struct pmu *perf_init_event(struct perf_event *event)
7391 struct pmu *pmu = NULL;
7395 idx = srcu_read_lock(&pmus_srcu);
7398 pmu = idr_find(&pmu_idr, event->attr.type);
7401 ret = perf_try_init_event(pmu, event);
7407 list_for_each_entry_rcu(pmu, &pmus, entry) {
7408 ret = perf_try_init_event(pmu, event);
7412 if (ret != -ENOENT) {
7417 pmu = ERR_PTR(-ENOENT);
7419 srcu_read_unlock(&pmus_srcu, idx);
7424 static void account_event_cpu(struct perf_event *event, int cpu)
7429 if (is_cgroup_event(event))
7430 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7433 static void account_event(struct perf_event *event)
7438 if (event->attach_state & PERF_ATTACH_TASK)
7439 static_key_slow_inc(&perf_sched_events.key);
7440 if (event->attr.mmap || event->attr.mmap_data)
7441 atomic_inc(&nr_mmap_events);
7442 if (event->attr.comm)
7443 atomic_inc(&nr_comm_events);
7444 if (event->attr.task)
7445 atomic_inc(&nr_task_events);
7446 if (event->attr.freq) {
7447 if (atomic_inc_return(&nr_freq_events) == 1)
7448 tick_nohz_full_kick_all();
7450 if (has_branch_stack(event))
7451 static_key_slow_inc(&perf_sched_events.key);
7452 if (is_cgroup_event(event))
7453 static_key_slow_inc(&perf_sched_events.key);
7455 account_event_cpu(event, event->cpu);
7459 * Allocate and initialize a event structure
7461 static struct perf_event *
7462 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7463 struct task_struct *task,
7464 struct perf_event *group_leader,
7465 struct perf_event *parent_event,
7466 perf_overflow_handler_t overflow_handler,
7467 void *context, int cgroup_fd)
7470 struct perf_event *event;
7471 struct hw_perf_event *hwc;
7474 if ((unsigned)cpu >= nr_cpu_ids) {
7475 if (!task || cpu != -1)
7476 return ERR_PTR(-EINVAL);
7479 event = kzalloc(sizeof(*event), GFP_KERNEL);
7481 return ERR_PTR(-ENOMEM);
7484 * Single events are their own group leaders, with an
7485 * empty sibling list:
7488 group_leader = event;
7490 mutex_init(&event->child_mutex);
7491 INIT_LIST_HEAD(&event->child_list);
7493 INIT_LIST_HEAD(&event->group_entry);
7494 INIT_LIST_HEAD(&event->event_entry);
7495 INIT_LIST_HEAD(&event->sibling_list);
7496 INIT_LIST_HEAD(&event->rb_entry);
7497 INIT_LIST_HEAD(&event->active_entry);
7498 INIT_HLIST_NODE(&event->hlist_entry);
7501 init_waitqueue_head(&event->waitq);
7502 init_irq_work(&event->pending, perf_pending_event);
7504 mutex_init(&event->mmap_mutex);
7506 atomic_long_set(&event->refcount, 1);
7508 event->attr = *attr;
7509 event->group_leader = group_leader;
7513 event->parent = parent_event;
7515 event->ns = get_pid_ns(task_active_pid_ns(current));
7516 event->id = atomic64_inc_return(&perf_event_id);
7518 event->state = PERF_EVENT_STATE_INACTIVE;
7521 event->attach_state = PERF_ATTACH_TASK;
7523 * XXX pmu::event_init needs to know what task to account to
7524 * and we cannot use the ctx information because we need the
7525 * pmu before we get a ctx.
7527 event->hw.target = task;
7530 event->clock = &local_clock;
7532 event->clock = parent_event->clock;
7534 if (!overflow_handler && parent_event) {
7535 overflow_handler = parent_event->overflow_handler;
7536 context = parent_event->overflow_handler_context;
7539 event->overflow_handler = overflow_handler;
7540 event->overflow_handler_context = context;
7542 perf_event__state_init(event);
7547 hwc->sample_period = attr->sample_period;
7548 if (attr->freq && attr->sample_freq)
7549 hwc->sample_period = 1;
7550 hwc->last_period = hwc->sample_period;
7552 local64_set(&hwc->period_left, hwc->sample_period);
7555 * we currently do not support PERF_FORMAT_GROUP on inherited events
7557 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7560 if (!has_branch_stack(event))
7561 event->attr.branch_sample_type = 0;
7563 if (cgroup_fd != -1) {
7564 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7569 pmu = perf_init_event(event);
7572 else if (IS_ERR(pmu)) {
7577 err = exclusive_event_init(event);
7581 if (!event->parent) {
7582 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7583 err = get_callchain_buffers();
7592 exclusive_event_destroy(event);
7596 event->destroy(event);
7597 module_put(pmu->module);
7599 if (is_cgroup_event(event))
7600 perf_detach_cgroup(event);
7602 put_pid_ns(event->ns);
7605 return ERR_PTR(err);
7608 static int perf_copy_attr(struct perf_event_attr __user *uattr,
7609 struct perf_event_attr *attr)
7614 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
7618 * zero the full structure, so that a short copy will be nice.
7620 memset(attr, 0, sizeof(*attr));
7622 ret = get_user(size, &uattr->size);
7626 if (size > PAGE_SIZE) /* silly large */
7629 if (!size) /* abi compat */
7630 size = PERF_ATTR_SIZE_VER0;
7632 if (size < PERF_ATTR_SIZE_VER0)
7636 * If we're handed a bigger struct than we know of,
7637 * ensure all the unknown bits are 0 - i.e. new
7638 * user-space does not rely on any kernel feature
7639 * extensions we dont know about yet.
7641 if (size > sizeof(*attr)) {
7642 unsigned char __user *addr;
7643 unsigned char __user *end;
7646 addr = (void __user *)uattr + sizeof(*attr);
7647 end = (void __user *)uattr + size;
7649 for (; addr < end; addr++) {
7650 ret = get_user(val, addr);
7656 size = sizeof(*attr);
7659 ret = copy_from_user(attr, uattr, size);
7663 if (attr->__reserved_1)
7666 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
7669 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
7672 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
7673 u64 mask = attr->branch_sample_type;
7675 /* only using defined bits */
7676 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
7679 /* at least one branch bit must be set */
7680 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
7683 /* propagate priv level, when not set for branch */
7684 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
7686 /* exclude_kernel checked on syscall entry */
7687 if (!attr->exclude_kernel)
7688 mask |= PERF_SAMPLE_BRANCH_KERNEL;
7690 if (!attr->exclude_user)
7691 mask |= PERF_SAMPLE_BRANCH_USER;
7693 if (!attr->exclude_hv)
7694 mask |= PERF_SAMPLE_BRANCH_HV;
7696 * adjust user setting (for HW filter setup)
7698 attr->branch_sample_type = mask;
7700 /* privileged levels capture (kernel, hv): check permissions */
7701 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7702 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7706 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7707 ret = perf_reg_validate(attr->sample_regs_user);
7712 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7713 if (!arch_perf_have_user_stack_dump())
7717 * We have __u32 type for the size, but so far
7718 * we can only use __u16 as maximum due to the
7719 * __u16 sample size limit.
7721 if (attr->sample_stack_user >= USHRT_MAX)
7723 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7727 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
7728 ret = perf_reg_validate(attr->sample_regs_intr);
7733 put_user(sizeof(*attr), &uattr->size);
7739 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7741 struct ring_buffer *rb = NULL;
7747 /* don't allow circular references */
7748 if (event == output_event)
7752 * Don't allow cross-cpu buffers
7754 if (output_event->cpu != event->cpu)
7758 * If its not a per-cpu rb, it must be the same task.
7760 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7764 * Mixing clocks in the same buffer is trouble you don't need.
7766 if (output_event->clock != event->clock)
7770 * If both events generate aux data, they must be on the same PMU
7772 if (has_aux(event) && has_aux(output_event) &&
7773 event->pmu != output_event->pmu)
7777 mutex_lock(&event->mmap_mutex);
7778 /* Can't redirect output if we've got an active mmap() */
7779 if (atomic_read(&event->mmap_count))
7783 /* get the rb we want to redirect to */
7784 rb = ring_buffer_get(output_event);
7789 ring_buffer_attach(event, rb);
7793 mutex_unlock(&event->mmap_mutex);
7799 static void mutex_lock_double(struct mutex *a, struct mutex *b)
7805 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
7808 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
7810 bool nmi_safe = false;
7813 case CLOCK_MONOTONIC:
7814 event->clock = &ktime_get_mono_fast_ns;
7818 case CLOCK_MONOTONIC_RAW:
7819 event->clock = &ktime_get_raw_fast_ns;
7823 case CLOCK_REALTIME:
7824 event->clock = &ktime_get_real_ns;
7827 case CLOCK_BOOTTIME:
7828 event->clock = &ktime_get_boot_ns;
7832 event->clock = &ktime_get_tai_ns;
7839 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
7846 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7848 * @attr_uptr: event_id type attributes for monitoring/sampling
7851 * @group_fd: group leader event fd
7853 SYSCALL_DEFINE5(perf_event_open,
7854 struct perf_event_attr __user *, attr_uptr,
7855 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7857 struct perf_event *group_leader = NULL, *output_event = NULL;
7858 struct perf_event *event, *sibling;
7859 struct perf_event_attr attr;
7860 struct perf_event_context *ctx, *uninitialized_var(gctx);
7861 struct file *event_file = NULL;
7862 struct fd group = {NULL, 0};
7863 struct task_struct *task = NULL;
7868 int f_flags = O_RDWR;
7871 /* for future expandability... */
7872 if (flags & ~PERF_FLAG_ALL)
7875 err = perf_copy_attr(attr_uptr, &attr);
7879 if (!attr.exclude_kernel) {
7880 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7885 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7888 if (attr.sample_period & (1ULL << 63))
7893 * In cgroup mode, the pid argument is used to pass the fd
7894 * opened to the cgroup directory in cgroupfs. The cpu argument
7895 * designates the cpu on which to monitor threads from that
7898 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7901 if (flags & PERF_FLAG_FD_CLOEXEC)
7902 f_flags |= O_CLOEXEC;
7904 event_fd = get_unused_fd_flags(f_flags);
7908 if (group_fd != -1) {
7909 err = perf_fget_light(group_fd, &group);
7912 group_leader = group.file->private_data;
7913 if (flags & PERF_FLAG_FD_OUTPUT)
7914 output_event = group_leader;
7915 if (flags & PERF_FLAG_FD_NO_GROUP)
7916 group_leader = NULL;
7919 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7920 task = find_lively_task_by_vpid(pid);
7922 err = PTR_ERR(task);
7927 if (task && group_leader &&
7928 group_leader->attr.inherit != attr.inherit) {
7935 if (flags & PERF_FLAG_PID_CGROUP)
7938 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7939 NULL, NULL, cgroup_fd);
7940 if (IS_ERR(event)) {
7941 err = PTR_ERR(event);
7945 if (is_sampling_event(event)) {
7946 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7952 account_event(event);
7955 * Special case software events and allow them to be part of
7956 * any hardware group.
7960 if (attr.use_clockid) {
7961 err = perf_event_set_clock(event, attr.clockid);
7967 (is_software_event(event) != is_software_event(group_leader))) {
7968 if (is_software_event(event)) {
7970 * If event and group_leader are not both a software
7971 * event, and event is, then group leader is not.
7973 * Allow the addition of software events to !software
7974 * groups, this is safe because software events never
7977 pmu = group_leader->pmu;
7978 } else if (is_software_event(group_leader) &&
7979 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7981 * In case the group is a pure software group, and we
7982 * try to add a hardware event, move the whole group to
7983 * the hardware context.
7990 * Get the target context (task or percpu):
7992 ctx = find_get_context(pmu, task, event);
7998 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8004 put_task_struct(task);
8009 * Look up the group leader (we will attach this event to it):
8015 * Do not allow a recursive hierarchy (this new sibling
8016 * becoming part of another group-sibling):
8018 if (group_leader->group_leader != group_leader)
8021 /* All events in a group should have the same clock */
8022 if (group_leader->clock != event->clock)
8026 * Do not allow to attach to a group in a different
8027 * task or CPU context:
8031 * Make sure we're both on the same task, or both
8034 if (group_leader->ctx->task != ctx->task)
8038 * Make sure we're both events for the same CPU;
8039 * grouping events for different CPUs is broken; since
8040 * you can never concurrently schedule them anyhow.
8042 if (group_leader->cpu != event->cpu)
8045 if (group_leader->ctx != ctx)
8050 * Only a group leader can be exclusive or pinned
8052 if (attr.exclusive || attr.pinned)
8057 err = perf_event_set_output(event, output_event);
8062 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8064 if (IS_ERR(event_file)) {
8065 err = PTR_ERR(event_file);
8070 gctx = group_leader->ctx;
8073 * See perf_event_ctx_lock() for comments on the details
8074 * of swizzling perf_event::ctx.
8076 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8078 perf_remove_from_context(group_leader, false);
8080 list_for_each_entry(sibling, &group_leader->sibling_list,
8082 perf_remove_from_context(sibling, false);
8086 mutex_lock(&ctx->mutex);
8089 WARN_ON_ONCE(ctx->parent_ctx);
8093 * Wait for everybody to stop referencing the events through
8094 * the old lists, before installing it on new lists.
8099 * Install the group siblings before the group leader.
8101 * Because a group leader will try and install the entire group
8102 * (through the sibling list, which is still in-tact), we can
8103 * end up with siblings installed in the wrong context.
8105 * By installing siblings first we NO-OP because they're not
8106 * reachable through the group lists.
8108 list_for_each_entry(sibling, &group_leader->sibling_list,
8110 perf_event__state_init(sibling);
8111 perf_install_in_context(ctx, sibling, sibling->cpu);
8116 * Removing from the context ends up with disabled
8117 * event. What we want here is event in the initial
8118 * startup state, ready to be add into new context.
8120 perf_event__state_init(group_leader);
8121 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8125 if (!exclusive_event_installable(event, ctx)) {
8127 mutex_unlock(&ctx->mutex);
8132 perf_install_in_context(ctx, event, event->cpu);
8133 perf_unpin_context(ctx);
8136 mutex_unlock(&gctx->mutex);
8139 mutex_unlock(&ctx->mutex);
8143 event->owner = current;
8145 mutex_lock(¤t->perf_event_mutex);
8146 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8147 mutex_unlock(¤t->perf_event_mutex);
8150 * Precalculate sample_data sizes
8152 perf_event__header_size(event);
8153 perf_event__id_header_size(event);
8156 * Drop the reference on the group_event after placing the
8157 * new event on the sibling_list. This ensures destruction
8158 * of the group leader will find the pointer to itself in
8159 * perf_group_detach().
8162 fd_install(event_fd, event_file);
8166 perf_unpin_context(ctx);
8174 put_task_struct(task);
8178 put_unused_fd(event_fd);
8183 * perf_event_create_kernel_counter
8185 * @attr: attributes of the counter to create
8186 * @cpu: cpu in which the counter is bound
8187 * @task: task to profile (NULL for percpu)
8190 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8191 struct task_struct *task,
8192 perf_overflow_handler_t overflow_handler,
8195 struct perf_event_context *ctx;
8196 struct perf_event *event;
8200 * Get the target context (task or percpu):
8203 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8204 overflow_handler, context, -1);
8205 if (IS_ERR(event)) {
8206 err = PTR_ERR(event);
8210 /* Mark owner so we could distinguish it from user events. */
8211 event->owner = EVENT_OWNER_KERNEL;
8213 account_event(event);
8215 ctx = find_get_context(event->pmu, task, event);
8221 WARN_ON_ONCE(ctx->parent_ctx);
8222 mutex_lock(&ctx->mutex);
8223 if (!exclusive_event_installable(event, ctx)) {
8224 mutex_unlock(&ctx->mutex);
8225 perf_unpin_context(ctx);
8231 perf_install_in_context(ctx, event, cpu);
8232 perf_unpin_context(ctx);
8233 mutex_unlock(&ctx->mutex);
8240 return ERR_PTR(err);
8242 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8244 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8246 struct perf_event_context *src_ctx;
8247 struct perf_event_context *dst_ctx;
8248 struct perf_event *event, *tmp;
8251 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8252 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8255 * See perf_event_ctx_lock() for comments on the details
8256 * of swizzling perf_event::ctx.
8258 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8259 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8261 perf_remove_from_context(event, false);
8262 unaccount_event_cpu(event, src_cpu);
8264 list_add(&event->migrate_entry, &events);
8268 * Wait for the events to quiesce before re-instating them.
8273 * Re-instate events in 2 passes.
8275 * Skip over group leaders and only install siblings on this first
8276 * pass, siblings will not get enabled without a leader, however a
8277 * leader will enable its siblings, even if those are still on the old
8280 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8281 if (event->group_leader == event)
8284 list_del(&event->migrate_entry);
8285 if (event->state >= PERF_EVENT_STATE_OFF)
8286 event->state = PERF_EVENT_STATE_INACTIVE;
8287 account_event_cpu(event, dst_cpu);
8288 perf_install_in_context(dst_ctx, event, dst_cpu);
8293 * Once all the siblings are setup properly, install the group leaders
8296 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8297 list_del(&event->migrate_entry);
8298 if (event->state >= PERF_EVENT_STATE_OFF)
8299 event->state = PERF_EVENT_STATE_INACTIVE;
8300 account_event_cpu(event, dst_cpu);
8301 perf_install_in_context(dst_ctx, event, dst_cpu);
8304 mutex_unlock(&dst_ctx->mutex);
8305 mutex_unlock(&src_ctx->mutex);
8307 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8309 static void sync_child_event(struct perf_event *child_event,
8310 struct task_struct *child)
8312 struct perf_event *parent_event = child_event->parent;
8315 if (child_event->attr.inherit_stat)
8316 perf_event_read_event(child_event, child);
8318 child_val = perf_event_count(child_event);
8321 * Add back the child's count to the parent's count:
8323 atomic64_add(child_val, &parent_event->child_count);
8324 atomic64_add(child_event->total_time_enabled,
8325 &parent_event->child_total_time_enabled);
8326 atomic64_add(child_event->total_time_running,
8327 &parent_event->child_total_time_running);
8330 * Remove this event from the parent's list
8332 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8333 mutex_lock(&parent_event->child_mutex);
8334 list_del_init(&child_event->child_list);
8335 mutex_unlock(&parent_event->child_mutex);
8338 * Make sure user/parent get notified, that we just
8341 perf_event_wakeup(parent_event);
8344 * Release the parent event, if this was the last
8347 put_event(parent_event);
8351 __perf_event_exit_task(struct perf_event *child_event,
8352 struct perf_event_context *child_ctx,
8353 struct task_struct *child)
8356 * Do not destroy the 'original' grouping; because of the context
8357 * switch optimization the original events could've ended up in a
8358 * random child task.
8360 * If we were to destroy the original group, all group related
8361 * operations would cease to function properly after this random
8364 * Do destroy all inherited groups, we don't care about those
8365 * and being thorough is better.
8367 perf_remove_from_context(child_event, !!child_event->parent);
8370 * It can happen that the parent exits first, and has events
8371 * that are still around due to the child reference. These
8372 * events need to be zapped.
8374 if (child_event->parent) {
8375 sync_child_event(child_event, child);
8376 free_event(child_event);
8378 child_event->state = PERF_EVENT_STATE_EXIT;
8379 perf_event_wakeup(child_event);
8383 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8385 struct perf_event *child_event, *next;
8386 struct perf_event_context *child_ctx, *clone_ctx = NULL;
8387 unsigned long flags;
8389 if (likely(!child->perf_event_ctxp[ctxn])) {
8390 perf_event_task(child, NULL, 0);
8394 local_irq_save(flags);
8396 * We can't reschedule here because interrupts are disabled,
8397 * and either child is current or it is a task that can't be
8398 * scheduled, so we are now safe from rescheduling changing
8401 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8404 * Take the context lock here so that if find_get_context is
8405 * reading child->perf_event_ctxp, we wait until it has
8406 * incremented the context's refcount before we do put_ctx below.
8408 raw_spin_lock(&child_ctx->lock);
8409 task_ctx_sched_out(child_ctx);
8410 child->perf_event_ctxp[ctxn] = NULL;
8413 * If this context is a clone; unclone it so it can't get
8414 * swapped to another process while we're removing all
8415 * the events from it.
8417 clone_ctx = unclone_ctx(child_ctx);
8418 update_context_time(child_ctx);
8419 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8425 * Report the task dead after unscheduling the events so that we
8426 * won't get any samples after PERF_RECORD_EXIT. We can however still
8427 * get a few PERF_RECORD_READ events.
8429 perf_event_task(child, child_ctx, 0);
8432 * We can recurse on the same lock type through:
8434 * __perf_event_exit_task()
8435 * sync_child_event()
8437 * mutex_lock(&ctx->mutex)
8439 * But since its the parent context it won't be the same instance.
8441 mutex_lock(&child_ctx->mutex);
8443 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8444 __perf_event_exit_task(child_event, child_ctx, child);
8446 mutex_unlock(&child_ctx->mutex);
8452 * When a child task exits, feed back event values to parent events.
8454 void perf_event_exit_task(struct task_struct *child)
8456 struct perf_event *event, *tmp;
8459 mutex_lock(&child->perf_event_mutex);
8460 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8462 list_del_init(&event->owner_entry);
8465 * Ensure the list deletion is visible before we clear
8466 * the owner, closes a race against perf_release() where
8467 * we need to serialize on the owner->perf_event_mutex.
8470 event->owner = NULL;
8472 mutex_unlock(&child->perf_event_mutex);
8474 for_each_task_context_nr(ctxn)
8475 perf_event_exit_task_context(child, ctxn);
8478 static void perf_free_event(struct perf_event *event,
8479 struct perf_event_context *ctx)
8481 struct perf_event *parent = event->parent;
8483 if (WARN_ON_ONCE(!parent))
8486 mutex_lock(&parent->child_mutex);
8487 list_del_init(&event->child_list);
8488 mutex_unlock(&parent->child_mutex);
8492 raw_spin_lock_irq(&ctx->lock);
8493 perf_group_detach(event);
8494 list_del_event(event, ctx);
8495 raw_spin_unlock_irq(&ctx->lock);
8500 * Free an unexposed, unused context as created by inheritance by
8501 * perf_event_init_task below, used by fork() in case of fail.
8503 * Not all locks are strictly required, but take them anyway to be nice and
8504 * help out with the lockdep assertions.
8506 void perf_event_free_task(struct task_struct *task)
8508 struct perf_event_context *ctx;
8509 struct perf_event *event, *tmp;
8512 for_each_task_context_nr(ctxn) {
8513 ctx = task->perf_event_ctxp[ctxn];
8517 mutex_lock(&ctx->mutex);
8519 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8521 perf_free_event(event, ctx);
8523 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8525 perf_free_event(event, ctx);
8527 if (!list_empty(&ctx->pinned_groups) ||
8528 !list_empty(&ctx->flexible_groups))
8531 mutex_unlock(&ctx->mutex);
8537 void perf_event_delayed_put(struct task_struct *task)
8541 for_each_task_context_nr(ctxn)
8542 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
8546 * inherit a event from parent task to child task:
8548 static struct perf_event *
8549 inherit_event(struct perf_event *parent_event,
8550 struct task_struct *parent,
8551 struct perf_event_context *parent_ctx,
8552 struct task_struct *child,
8553 struct perf_event *group_leader,
8554 struct perf_event_context *child_ctx)
8556 enum perf_event_active_state parent_state = parent_event->state;
8557 struct perf_event *child_event;
8558 unsigned long flags;
8561 * Instead of creating recursive hierarchies of events,
8562 * we link inherited events back to the original parent,
8563 * which has a filp for sure, which we use as the reference
8566 if (parent_event->parent)
8567 parent_event = parent_event->parent;
8569 child_event = perf_event_alloc(&parent_event->attr,
8572 group_leader, parent_event,
8574 if (IS_ERR(child_event))
8577 if (is_orphaned_event(parent_event) ||
8578 !atomic_long_inc_not_zero(&parent_event->refcount)) {
8579 free_event(child_event);
8586 * Make the child state follow the state of the parent event,
8587 * not its attr.disabled bit. We hold the parent's mutex,
8588 * so we won't race with perf_event_{en, dis}able_family.
8590 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
8591 child_event->state = PERF_EVENT_STATE_INACTIVE;
8593 child_event->state = PERF_EVENT_STATE_OFF;
8595 if (parent_event->attr.freq) {
8596 u64 sample_period = parent_event->hw.sample_period;
8597 struct hw_perf_event *hwc = &child_event->hw;
8599 hwc->sample_period = sample_period;
8600 hwc->last_period = sample_period;
8602 local64_set(&hwc->period_left, sample_period);
8605 child_event->ctx = child_ctx;
8606 child_event->overflow_handler = parent_event->overflow_handler;
8607 child_event->overflow_handler_context
8608 = parent_event->overflow_handler_context;
8611 * Precalculate sample_data sizes
8613 perf_event__header_size(child_event);
8614 perf_event__id_header_size(child_event);
8617 * Link it up in the child's context:
8619 raw_spin_lock_irqsave(&child_ctx->lock, flags);
8620 add_event_to_ctx(child_event, child_ctx);
8621 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8624 * Link this into the parent event's child list
8626 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8627 mutex_lock(&parent_event->child_mutex);
8628 list_add_tail(&child_event->child_list, &parent_event->child_list);
8629 mutex_unlock(&parent_event->child_mutex);
8634 static int inherit_group(struct perf_event *parent_event,
8635 struct task_struct *parent,
8636 struct perf_event_context *parent_ctx,
8637 struct task_struct *child,
8638 struct perf_event_context *child_ctx)
8640 struct perf_event *leader;
8641 struct perf_event *sub;
8642 struct perf_event *child_ctr;
8644 leader = inherit_event(parent_event, parent, parent_ctx,
8645 child, NULL, child_ctx);
8647 return PTR_ERR(leader);
8648 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
8649 child_ctr = inherit_event(sub, parent, parent_ctx,
8650 child, leader, child_ctx);
8651 if (IS_ERR(child_ctr))
8652 return PTR_ERR(child_ctr);
8658 inherit_task_group(struct perf_event *event, struct task_struct *parent,
8659 struct perf_event_context *parent_ctx,
8660 struct task_struct *child, int ctxn,
8664 struct perf_event_context *child_ctx;
8666 if (!event->attr.inherit) {
8671 child_ctx = child->perf_event_ctxp[ctxn];
8674 * This is executed from the parent task context, so
8675 * inherit events that have been marked for cloning.
8676 * First allocate and initialize a context for the
8680 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
8684 child->perf_event_ctxp[ctxn] = child_ctx;
8687 ret = inherit_group(event, parent, parent_ctx,
8697 * Initialize the perf_event context in task_struct
8699 static int perf_event_init_context(struct task_struct *child, int ctxn)
8701 struct perf_event_context *child_ctx, *parent_ctx;
8702 struct perf_event_context *cloned_ctx;
8703 struct perf_event *event;
8704 struct task_struct *parent = current;
8705 int inherited_all = 1;
8706 unsigned long flags;
8709 if (likely(!parent->perf_event_ctxp[ctxn]))
8713 * If the parent's context is a clone, pin it so it won't get
8716 parent_ctx = perf_pin_task_context(parent, ctxn);
8721 * No need to check if parent_ctx != NULL here; since we saw
8722 * it non-NULL earlier, the only reason for it to become NULL
8723 * is if we exit, and since we're currently in the middle of
8724 * a fork we can't be exiting at the same time.
8728 * Lock the parent list. No need to lock the child - not PID
8729 * hashed yet and not running, so nobody can access it.
8731 mutex_lock(&parent_ctx->mutex);
8734 * We dont have to disable NMIs - we are only looking at
8735 * the list, not manipulating it:
8737 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
8738 ret = inherit_task_group(event, parent, parent_ctx,
8739 child, ctxn, &inherited_all);
8745 * We can't hold ctx->lock when iterating the ->flexible_group list due
8746 * to allocations, but we need to prevent rotation because
8747 * rotate_ctx() will change the list from interrupt context.
8749 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8750 parent_ctx->rotate_disable = 1;
8751 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8753 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
8754 ret = inherit_task_group(event, parent, parent_ctx,
8755 child, ctxn, &inherited_all);
8760 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8761 parent_ctx->rotate_disable = 0;
8763 child_ctx = child->perf_event_ctxp[ctxn];
8765 if (child_ctx && inherited_all) {
8767 * Mark the child context as a clone of the parent
8768 * context, or of whatever the parent is a clone of.
8770 * Note that if the parent is a clone, the holding of
8771 * parent_ctx->lock avoids it from being uncloned.
8773 cloned_ctx = parent_ctx->parent_ctx;
8775 child_ctx->parent_ctx = cloned_ctx;
8776 child_ctx->parent_gen = parent_ctx->parent_gen;
8778 child_ctx->parent_ctx = parent_ctx;
8779 child_ctx->parent_gen = parent_ctx->generation;
8781 get_ctx(child_ctx->parent_ctx);
8784 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8785 mutex_unlock(&parent_ctx->mutex);
8787 perf_unpin_context(parent_ctx);
8788 put_ctx(parent_ctx);
8794 * Initialize the perf_event context in task_struct
8796 int perf_event_init_task(struct task_struct *child)
8800 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
8801 mutex_init(&child->perf_event_mutex);
8802 INIT_LIST_HEAD(&child->perf_event_list);
8804 for_each_task_context_nr(ctxn) {
8805 ret = perf_event_init_context(child, ctxn);
8807 perf_event_free_task(child);
8815 static void __init perf_event_init_all_cpus(void)
8817 struct swevent_htable *swhash;
8820 for_each_possible_cpu(cpu) {
8821 swhash = &per_cpu(swevent_htable, cpu);
8822 mutex_init(&swhash->hlist_mutex);
8823 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
8827 static void perf_event_init_cpu(int cpu)
8829 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8831 mutex_lock(&swhash->hlist_mutex);
8832 swhash->online = true;
8833 if (swhash->hlist_refcount > 0) {
8834 struct swevent_hlist *hlist;
8836 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
8838 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8840 mutex_unlock(&swhash->hlist_mutex);
8843 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
8844 static void __perf_event_exit_context(void *__info)
8846 struct remove_event re = { .detach_group = true };
8847 struct perf_event_context *ctx = __info;
8850 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8851 __perf_remove_from_context(&re);
8855 static void perf_event_exit_cpu_context(int cpu)
8857 struct perf_event_context *ctx;
8861 idx = srcu_read_lock(&pmus_srcu);
8862 list_for_each_entry_rcu(pmu, &pmus, entry) {
8863 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8865 mutex_lock(&ctx->mutex);
8866 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8867 mutex_unlock(&ctx->mutex);
8869 srcu_read_unlock(&pmus_srcu, idx);
8872 static void perf_event_exit_cpu(int cpu)
8874 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8876 perf_event_exit_cpu_context(cpu);
8878 mutex_lock(&swhash->hlist_mutex);
8879 swhash->online = false;
8880 swevent_hlist_release(swhash);
8881 mutex_unlock(&swhash->hlist_mutex);
8884 static inline void perf_event_exit_cpu(int cpu) { }
8888 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8892 for_each_online_cpu(cpu)
8893 perf_event_exit_cpu(cpu);
8899 * Run the perf reboot notifier at the very last possible moment so that
8900 * the generic watchdog code runs as long as possible.
8902 static struct notifier_block perf_reboot_notifier = {
8903 .notifier_call = perf_reboot,
8904 .priority = INT_MIN,
8908 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8910 unsigned int cpu = (long)hcpu;
8912 switch (action & ~CPU_TASKS_FROZEN) {
8914 case CPU_UP_PREPARE:
8915 case CPU_DOWN_FAILED:
8916 perf_event_init_cpu(cpu);
8919 case CPU_UP_CANCELED:
8920 case CPU_DOWN_PREPARE:
8921 perf_event_exit_cpu(cpu);
8930 void __init perf_event_init(void)
8936 perf_event_init_all_cpus();
8937 init_srcu_struct(&pmus_srcu);
8938 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8939 perf_pmu_register(&perf_cpu_clock, NULL, -1);
8940 perf_pmu_register(&perf_task_clock, NULL, -1);
8942 perf_cpu_notifier(perf_cpu_notify);
8943 register_reboot_notifier(&perf_reboot_notifier);
8945 ret = init_hw_breakpoint();
8946 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8948 /* do not patch jump label more than once per second */
8949 jump_label_rate_limit(&perf_sched_events, HZ);
8952 * Build time assertion that we keep the data_head at the intended
8953 * location. IOW, validation we got the __reserved[] size right.
8955 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8959 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
8962 struct perf_pmu_events_attr *pmu_attr =
8963 container_of(attr, struct perf_pmu_events_attr, attr);
8965 if (pmu_attr->event_str)
8966 return sprintf(page, "%s\n", pmu_attr->event_str);
8971 static int __init perf_event_sysfs_init(void)
8976 mutex_lock(&pmus_lock);
8978 ret = bus_register(&pmu_bus);
8982 list_for_each_entry(pmu, &pmus, entry) {
8983 if (!pmu->name || pmu->type < 0)
8986 ret = pmu_dev_alloc(pmu);
8987 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8989 pmu_bus_running = 1;
8993 mutex_unlock(&pmus_lock);
8997 device_initcall(perf_event_sysfs_init);
8999 #ifdef CONFIG_CGROUP_PERF
9000 static struct cgroup_subsys_state *
9001 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9003 struct perf_cgroup *jc;
9005 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9007 return ERR_PTR(-ENOMEM);
9009 jc->info = alloc_percpu(struct perf_cgroup_info);
9012 return ERR_PTR(-ENOMEM);
9018 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9020 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9022 free_percpu(jc->info);
9026 static int __perf_cgroup_move(void *info)
9028 struct task_struct *task = info;
9029 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9033 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
9034 struct cgroup_taskset *tset)
9036 struct task_struct *task;
9038 cgroup_taskset_for_each(task, tset)
9039 task_function_call(task, __perf_cgroup_move, task);
9042 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
9043 struct cgroup_subsys_state *old_css,
9044 struct task_struct *task)
9047 * cgroup_exit() is called in the copy_process() failure path.
9048 * Ignore this case since the task hasn't ran yet, this avoids
9049 * trying to poke a half freed task state from generic code.
9051 if (!(task->flags & PF_EXITING))
9054 task_function_call(task, __perf_cgroup_move, task);
9057 struct cgroup_subsys perf_event_cgrp_subsys = {
9058 .css_alloc = perf_cgroup_css_alloc,
9059 .css_free = perf_cgroup_css_free,
9060 .exit = perf_cgroup_exit,
9061 .attach = perf_cgroup_attach,
9063 #endif /* CONFIG_CGROUP_PERF */