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 struct remote_function_call {
55 struct task_struct *p;
56 int (*func)(void *info);
61 static void remote_function(void *data)
63 struct remote_function_call *tfc = data;
64 struct task_struct *p = tfc->p;
68 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
72 tfc->ret = tfc->func(tfc->info);
76 * task_function_call - call a function on the cpu on which a task runs
77 * @p: the task to evaluate
78 * @func: the function to be called
79 * @info: the function call argument
81 * Calls the function @func when the task is currently running. This might
82 * be on the current CPU, which just calls the function directly
84 * returns: @func return value, or
85 * -ESRCH - when the process isn't running
86 * -EAGAIN - when the process moved away
89 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
91 struct remote_function_call data = {
95 .ret = -ESRCH, /* No such (running) process */
99 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
105 * cpu_function_call - call a function on the cpu
106 * @func: the function to be called
107 * @info: the function call argument
109 * Calls the function @func on the remote cpu.
111 * returns: @func return value or -ENXIO when the cpu is offline
113 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
115 struct remote_function_call data = {
119 .ret = -ENXIO, /* No such CPU */
122 smp_call_function_single(cpu, remote_function, &data, 1);
127 #define EVENT_OWNER_KERNEL ((void *) -1)
129 static bool is_kernel_event(struct perf_event *event)
131 return event->owner == EVENT_OWNER_KERNEL;
134 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
135 PERF_FLAG_FD_OUTPUT |\
136 PERF_FLAG_PID_CGROUP |\
137 PERF_FLAG_FD_CLOEXEC)
140 * branch priv levels that need permission checks
142 #define PERF_SAMPLE_BRANCH_PERM_PLM \
143 (PERF_SAMPLE_BRANCH_KERNEL |\
144 PERF_SAMPLE_BRANCH_HV)
147 EVENT_FLEXIBLE = 0x1,
149 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
153 * perf_sched_events : >0 events exist
154 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
156 struct static_key_deferred perf_sched_events __read_mostly;
157 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
158 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
160 static atomic_t nr_mmap_events __read_mostly;
161 static atomic_t nr_comm_events __read_mostly;
162 static atomic_t nr_task_events __read_mostly;
163 static atomic_t nr_freq_events __read_mostly;
165 static LIST_HEAD(pmus);
166 static DEFINE_MUTEX(pmus_lock);
167 static struct srcu_struct pmus_srcu;
170 * perf event paranoia level:
171 * -1 - not paranoid at all
172 * 0 - disallow raw tracepoint access for unpriv
173 * 1 - disallow cpu events for unpriv
174 * 2 - disallow kernel profiling for unpriv
176 int sysctl_perf_event_paranoid __read_mostly = 1;
178 /* Minimum for 512 kiB + 1 user control page */
179 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
182 * max perf event sample rate
184 #define DEFAULT_MAX_SAMPLE_RATE 100000
185 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
186 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
188 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
190 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
191 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
193 static int perf_sample_allowed_ns __read_mostly =
194 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
196 void update_perf_cpu_limits(void)
198 u64 tmp = perf_sample_period_ns;
200 tmp *= sysctl_perf_cpu_time_max_percent;
202 ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
205 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
207 int perf_proc_update_handler(struct ctl_table *table, int write,
208 void __user *buffer, size_t *lenp,
211 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
216 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
217 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
218 update_perf_cpu_limits();
223 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
225 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
226 void __user *buffer, size_t *lenp,
229 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
234 update_perf_cpu_limits();
240 * perf samples are done in some very critical code paths (NMIs).
241 * If they take too much CPU time, the system can lock up and not
242 * get any real work done. This will drop the sample rate when
243 * we detect that events are taking too long.
245 #define NR_ACCUMULATED_SAMPLES 128
246 static DEFINE_PER_CPU(u64, running_sample_length);
248 static void perf_duration_warn(struct irq_work *w)
250 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
251 u64 avg_local_sample_len;
252 u64 local_samples_len;
254 local_samples_len = __this_cpu_read(running_sample_length);
255 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
257 printk_ratelimited(KERN_WARNING
258 "perf interrupt took too long (%lld > %lld), lowering "
259 "kernel.perf_event_max_sample_rate to %d\n",
260 avg_local_sample_len, allowed_ns >> 1,
261 sysctl_perf_event_sample_rate);
264 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
266 void perf_sample_event_took(u64 sample_len_ns)
268 u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
269 u64 avg_local_sample_len;
270 u64 local_samples_len;
275 /* decay the counter by 1 average sample */
276 local_samples_len = __this_cpu_read(running_sample_length);
277 local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
278 local_samples_len += sample_len_ns;
279 __this_cpu_write(running_sample_length, local_samples_len);
282 * note: this will be biased artifically low until we have
283 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
284 * from having to maintain a count.
286 avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
288 if (avg_local_sample_len <= allowed_ns)
291 if (max_samples_per_tick <= 1)
294 max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
295 sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
296 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
298 update_perf_cpu_limits();
300 if (!irq_work_queue(&perf_duration_work)) {
301 early_printk("perf interrupt took too long (%lld > %lld), lowering "
302 "kernel.perf_event_max_sample_rate to %d\n",
303 avg_local_sample_len, allowed_ns >> 1,
304 sysctl_perf_event_sample_rate);
308 static atomic64_t perf_event_id;
310 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
311 enum event_type_t event_type);
313 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
314 enum event_type_t event_type,
315 struct task_struct *task);
317 static void update_context_time(struct perf_event_context *ctx);
318 static u64 perf_event_time(struct perf_event *event);
320 void __weak perf_event_print_debug(void) { }
322 extern __weak const char *perf_pmu_name(void)
327 static inline u64 perf_clock(void)
329 return local_clock();
332 static inline u64 perf_event_clock(struct perf_event *event)
334 return event->clock();
337 static inline struct perf_cpu_context *
338 __get_cpu_context(struct perf_event_context *ctx)
340 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
343 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
344 struct perf_event_context *ctx)
346 raw_spin_lock(&cpuctx->ctx.lock);
348 raw_spin_lock(&ctx->lock);
351 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
352 struct perf_event_context *ctx)
355 raw_spin_unlock(&ctx->lock);
356 raw_spin_unlock(&cpuctx->ctx.lock);
359 #ifdef CONFIG_CGROUP_PERF
362 perf_cgroup_match(struct perf_event *event)
364 struct perf_event_context *ctx = event->ctx;
365 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
367 /* @event doesn't care about cgroup */
371 /* wants specific cgroup scope but @cpuctx isn't associated with any */
376 * Cgroup scoping is recursive. An event enabled for a cgroup is
377 * also enabled for all its descendant cgroups. If @cpuctx's
378 * cgroup is a descendant of @event's (the test covers identity
379 * case), it's a match.
381 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
382 event->cgrp->css.cgroup);
385 static inline void perf_detach_cgroup(struct perf_event *event)
387 css_put(&event->cgrp->css);
391 static inline int is_cgroup_event(struct perf_event *event)
393 return event->cgrp != NULL;
396 static inline u64 perf_cgroup_event_time(struct perf_event *event)
398 struct perf_cgroup_info *t;
400 t = per_cpu_ptr(event->cgrp->info, event->cpu);
404 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
406 struct perf_cgroup_info *info;
411 info = this_cpu_ptr(cgrp->info);
413 info->time += now - info->timestamp;
414 info->timestamp = now;
417 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
419 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
421 __update_cgrp_time(cgrp_out);
424 static inline void update_cgrp_time_from_event(struct perf_event *event)
426 struct perf_cgroup *cgrp;
429 * ensure we access cgroup data only when needed and
430 * when we know the cgroup is pinned (css_get)
432 if (!is_cgroup_event(event))
435 cgrp = perf_cgroup_from_task(current);
437 * Do not update time when cgroup is not active
439 if (cgrp == event->cgrp)
440 __update_cgrp_time(event->cgrp);
444 perf_cgroup_set_timestamp(struct task_struct *task,
445 struct perf_event_context *ctx)
447 struct perf_cgroup *cgrp;
448 struct perf_cgroup_info *info;
451 * ctx->lock held by caller
452 * ensure we do not access cgroup data
453 * unless we have the cgroup pinned (css_get)
455 if (!task || !ctx->nr_cgroups)
458 cgrp = perf_cgroup_from_task(task);
459 info = this_cpu_ptr(cgrp->info);
460 info->timestamp = ctx->timestamp;
463 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
464 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
467 * reschedule events based on the cgroup constraint of task.
469 * mode SWOUT : schedule out everything
470 * mode SWIN : schedule in based on cgroup for next
472 void perf_cgroup_switch(struct task_struct *task, int mode)
474 struct perf_cpu_context *cpuctx;
479 * disable interrupts to avoid geting nr_cgroup
480 * changes via __perf_event_disable(). Also
483 local_irq_save(flags);
486 * we reschedule only in the presence of cgroup
487 * constrained events.
491 list_for_each_entry_rcu(pmu, &pmus, entry) {
492 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
493 if (cpuctx->unique_pmu != pmu)
494 continue; /* ensure we process each cpuctx once */
497 * perf_cgroup_events says at least one
498 * context on this CPU has cgroup events.
500 * ctx->nr_cgroups reports the number of cgroup
501 * events for a context.
503 if (cpuctx->ctx.nr_cgroups > 0) {
504 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
505 perf_pmu_disable(cpuctx->ctx.pmu);
507 if (mode & PERF_CGROUP_SWOUT) {
508 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
510 * must not be done before ctxswout due
511 * to event_filter_match() in event_sched_out()
516 if (mode & PERF_CGROUP_SWIN) {
517 WARN_ON_ONCE(cpuctx->cgrp);
519 * set cgrp before ctxsw in to allow
520 * event_filter_match() to not have to pass
523 cpuctx->cgrp = perf_cgroup_from_task(task);
524 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
526 perf_pmu_enable(cpuctx->ctx.pmu);
527 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
533 local_irq_restore(flags);
536 static inline void perf_cgroup_sched_out(struct task_struct *task,
537 struct task_struct *next)
539 struct perf_cgroup *cgrp1;
540 struct perf_cgroup *cgrp2 = NULL;
543 * we come here when we know perf_cgroup_events > 0
545 cgrp1 = perf_cgroup_from_task(task);
548 * next is NULL when called from perf_event_enable_on_exec()
549 * that will systematically cause a cgroup_switch()
552 cgrp2 = perf_cgroup_from_task(next);
555 * only schedule out current cgroup events if we know
556 * that we are switching to a different cgroup. Otherwise,
557 * do no touch the cgroup events.
560 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
563 static inline void perf_cgroup_sched_in(struct task_struct *prev,
564 struct task_struct *task)
566 struct perf_cgroup *cgrp1;
567 struct perf_cgroup *cgrp2 = NULL;
570 * we come here when we know perf_cgroup_events > 0
572 cgrp1 = perf_cgroup_from_task(task);
574 /* prev can never be NULL */
575 cgrp2 = perf_cgroup_from_task(prev);
578 * only need to schedule in cgroup events if we are changing
579 * cgroup during ctxsw. Cgroup events were not scheduled
580 * out of ctxsw out if that was not the case.
583 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
586 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
587 struct perf_event_attr *attr,
588 struct perf_event *group_leader)
590 struct perf_cgroup *cgrp;
591 struct cgroup_subsys_state *css;
592 struct fd f = fdget(fd);
598 css = css_tryget_online_from_dir(f.file->f_path.dentry,
599 &perf_event_cgrp_subsys);
605 cgrp = container_of(css, struct perf_cgroup, css);
609 * all events in a group must monitor
610 * the same cgroup because a task belongs
611 * to only one perf cgroup at a time
613 if (group_leader && group_leader->cgrp != cgrp) {
614 perf_detach_cgroup(event);
623 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
625 struct perf_cgroup_info *t;
626 t = per_cpu_ptr(event->cgrp->info, event->cpu);
627 event->shadow_ctx_time = now - t->timestamp;
631 perf_cgroup_defer_enabled(struct perf_event *event)
634 * when the current task's perf cgroup does not match
635 * the event's, we need to remember to call the
636 * perf_mark_enable() function the first time a task with
637 * a matching perf cgroup is scheduled in.
639 if (is_cgroup_event(event) && !perf_cgroup_match(event))
640 event->cgrp_defer_enabled = 1;
644 perf_cgroup_mark_enabled(struct perf_event *event,
645 struct perf_event_context *ctx)
647 struct perf_event *sub;
648 u64 tstamp = perf_event_time(event);
650 if (!event->cgrp_defer_enabled)
653 event->cgrp_defer_enabled = 0;
655 event->tstamp_enabled = tstamp - event->total_time_enabled;
656 list_for_each_entry(sub, &event->sibling_list, group_entry) {
657 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
658 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
659 sub->cgrp_defer_enabled = 0;
663 #else /* !CONFIG_CGROUP_PERF */
666 perf_cgroup_match(struct perf_event *event)
671 static inline void perf_detach_cgroup(struct perf_event *event)
674 static inline int is_cgroup_event(struct perf_event *event)
679 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
684 static inline void update_cgrp_time_from_event(struct perf_event *event)
688 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
692 static inline void perf_cgroup_sched_out(struct task_struct *task,
693 struct task_struct *next)
697 static inline void perf_cgroup_sched_in(struct task_struct *prev,
698 struct task_struct *task)
702 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
703 struct perf_event_attr *attr,
704 struct perf_event *group_leader)
710 perf_cgroup_set_timestamp(struct task_struct *task,
711 struct perf_event_context *ctx)
716 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
721 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
725 static inline u64 perf_cgroup_event_time(struct perf_event *event)
731 perf_cgroup_defer_enabled(struct perf_event *event)
736 perf_cgroup_mark_enabled(struct perf_event *event,
737 struct perf_event_context *ctx)
743 * set default to be dependent on timer tick just
746 #define PERF_CPU_HRTIMER (1000 / HZ)
748 * function must be called with interrupts disbled
750 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
752 struct perf_cpu_context *cpuctx;
753 enum hrtimer_restart ret = HRTIMER_NORESTART;
756 WARN_ON(!irqs_disabled());
758 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
760 rotations = perf_rotate_context(cpuctx);
763 * arm timer if needed
766 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
767 ret = HRTIMER_RESTART;
773 /* CPU is going down */
774 void perf_cpu_hrtimer_cancel(int cpu)
776 struct perf_cpu_context *cpuctx;
780 if (WARN_ON(cpu != smp_processor_id()))
783 local_irq_save(flags);
787 list_for_each_entry_rcu(pmu, &pmus, entry) {
788 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
790 if (pmu->task_ctx_nr == perf_sw_context)
793 hrtimer_cancel(&cpuctx->hrtimer);
798 local_irq_restore(flags);
801 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
803 struct hrtimer *hr = &cpuctx->hrtimer;
804 struct pmu *pmu = cpuctx->ctx.pmu;
807 /* no multiplexing needed for SW PMU */
808 if (pmu->task_ctx_nr == perf_sw_context)
812 * check default is sane, if not set then force to
813 * default interval (1/tick)
815 timer = pmu->hrtimer_interval_ms;
817 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
819 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
821 hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
822 hr->function = perf_cpu_hrtimer_handler;
825 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
827 struct hrtimer *hr = &cpuctx->hrtimer;
828 struct pmu *pmu = cpuctx->ctx.pmu;
831 if (pmu->task_ctx_nr == perf_sw_context)
834 if (hrtimer_active(hr))
837 if (!hrtimer_callback_running(hr))
838 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
839 0, HRTIMER_MODE_REL_PINNED, 0);
842 void perf_pmu_disable(struct pmu *pmu)
844 int *count = this_cpu_ptr(pmu->pmu_disable_count);
846 pmu->pmu_disable(pmu);
849 void perf_pmu_enable(struct pmu *pmu)
851 int *count = this_cpu_ptr(pmu->pmu_disable_count);
853 pmu->pmu_enable(pmu);
856 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
859 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
860 * perf_event_task_tick() are fully serialized because they're strictly cpu
861 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
862 * disabled, while perf_event_task_tick is called from IRQ context.
864 static void perf_event_ctx_activate(struct perf_event_context *ctx)
866 struct list_head *head = this_cpu_ptr(&active_ctx_list);
868 WARN_ON(!irqs_disabled());
870 WARN_ON(!list_empty(&ctx->active_ctx_list));
872 list_add(&ctx->active_ctx_list, head);
875 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
877 WARN_ON(!irqs_disabled());
879 WARN_ON(list_empty(&ctx->active_ctx_list));
881 list_del_init(&ctx->active_ctx_list);
884 static void get_ctx(struct perf_event_context *ctx)
886 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
889 static void free_ctx(struct rcu_head *head)
891 struct perf_event_context *ctx;
893 ctx = container_of(head, struct perf_event_context, rcu_head);
894 kfree(ctx->task_ctx_data);
898 static void put_ctx(struct perf_event_context *ctx)
900 if (atomic_dec_and_test(&ctx->refcount)) {
902 put_ctx(ctx->parent_ctx);
904 put_task_struct(ctx->task);
905 call_rcu(&ctx->rcu_head, free_ctx);
910 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
911 * perf_pmu_migrate_context() we need some magic.
913 * Those places that change perf_event::ctx will hold both
914 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
916 * Lock ordering is by mutex address. There are two other sites where
917 * perf_event_context::mutex nests and those are:
919 * - perf_event_exit_task_context() [ child , 0 ]
920 * __perf_event_exit_task()
922 * put_event() [ parent, 1 ]
924 * - perf_event_init_context() [ parent, 0 ]
925 * inherit_task_group()
930 * perf_try_init_event() [ child , 1 ]
932 * While it appears there is an obvious deadlock here -- the parent and child
933 * nesting levels are inverted between the two. This is in fact safe because
934 * life-time rules separate them. That is an exiting task cannot fork, and a
935 * spawning task cannot (yet) exit.
937 * But remember that that these are parent<->child context relations, and
938 * migration does not affect children, therefore these two orderings should not
941 * The change in perf_event::ctx does not affect children (as claimed above)
942 * because the sys_perf_event_open() case will install a new event and break
943 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
944 * concerned with cpuctx and that doesn't have children.
946 * The places that change perf_event::ctx will issue:
948 * perf_remove_from_context();
950 * perf_install_in_context();
952 * to affect the change. The remove_from_context() + synchronize_rcu() should
953 * quiesce the event, after which we can install it in the new location. This
954 * means that only external vectors (perf_fops, prctl) can perturb the event
955 * while in transit. Therefore all such accessors should also acquire
956 * perf_event_context::mutex to serialize against this.
958 * However; because event->ctx can change while we're waiting to acquire
959 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
963 * task_struct::perf_event_mutex
964 * perf_event_context::mutex
965 * perf_event_context::lock
966 * perf_event::child_mutex;
967 * perf_event::mmap_mutex
970 static struct perf_event_context *
971 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
973 struct perf_event_context *ctx;
977 ctx = ACCESS_ONCE(event->ctx);
978 if (!atomic_inc_not_zero(&ctx->refcount)) {
984 mutex_lock_nested(&ctx->mutex, nesting);
985 if (event->ctx != ctx) {
986 mutex_unlock(&ctx->mutex);
994 static inline struct perf_event_context *
995 perf_event_ctx_lock(struct perf_event *event)
997 return perf_event_ctx_lock_nested(event, 0);
1000 static void perf_event_ctx_unlock(struct perf_event *event,
1001 struct perf_event_context *ctx)
1003 mutex_unlock(&ctx->mutex);
1008 * This must be done under the ctx->lock, such as to serialize against
1009 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1010 * calling scheduler related locks and ctx->lock nests inside those.
1012 static __must_check struct perf_event_context *
1013 unclone_ctx(struct perf_event_context *ctx)
1015 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1017 lockdep_assert_held(&ctx->lock);
1020 ctx->parent_ctx = NULL;
1026 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1029 * only top level events have the pid namespace they were created in
1032 event = event->parent;
1034 return task_tgid_nr_ns(p, event->ns);
1037 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1040 * only top level events have the pid namespace they were created in
1043 event = event->parent;
1045 return task_pid_nr_ns(p, event->ns);
1049 * If we inherit events we want to return the parent event id
1052 static u64 primary_event_id(struct perf_event *event)
1057 id = event->parent->id;
1063 * Get the perf_event_context for a task and lock it.
1064 * This has to cope with with the fact that until it is locked,
1065 * the context could get moved to another task.
1067 static struct perf_event_context *
1068 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1070 struct perf_event_context *ctx;
1074 * One of the few rules of preemptible RCU is that one cannot do
1075 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1076 * part of the read side critical section was preemptible -- see
1077 * rcu_read_unlock_special().
1079 * Since ctx->lock nests under rq->lock we must ensure the entire read
1080 * side critical section is non-preemptible.
1084 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1087 * If this context is a clone of another, it might
1088 * get swapped for another underneath us by
1089 * perf_event_task_sched_out, though the
1090 * rcu_read_lock() protects us from any context
1091 * getting freed. Lock the context and check if it
1092 * got swapped before we could get the lock, and retry
1093 * if so. If we locked the right context, then it
1094 * can't get swapped on us any more.
1096 raw_spin_lock_irqsave(&ctx->lock, *flags);
1097 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1098 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1104 if (!atomic_inc_not_zero(&ctx->refcount)) {
1105 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1115 * Get the context for a task and increment its pin_count so it
1116 * can't get swapped to another task. This also increments its
1117 * reference count so that the context can't get freed.
1119 static struct perf_event_context *
1120 perf_pin_task_context(struct task_struct *task, int ctxn)
1122 struct perf_event_context *ctx;
1123 unsigned long flags;
1125 ctx = perf_lock_task_context(task, ctxn, &flags);
1128 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1133 static void perf_unpin_context(struct perf_event_context *ctx)
1135 unsigned long flags;
1137 raw_spin_lock_irqsave(&ctx->lock, flags);
1139 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1143 * Update the record of the current time in a context.
1145 static void update_context_time(struct perf_event_context *ctx)
1147 u64 now = perf_clock();
1149 ctx->time += now - ctx->timestamp;
1150 ctx->timestamp = now;
1153 static u64 perf_event_time(struct perf_event *event)
1155 struct perf_event_context *ctx = event->ctx;
1157 if (is_cgroup_event(event))
1158 return perf_cgroup_event_time(event);
1160 return ctx ? ctx->time : 0;
1164 * Update the total_time_enabled and total_time_running fields for a event.
1165 * The caller of this function needs to hold the ctx->lock.
1167 static void update_event_times(struct perf_event *event)
1169 struct perf_event_context *ctx = event->ctx;
1172 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1173 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1176 * in cgroup mode, time_enabled represents
1177 * the time the event was enabled AND active
1178 * tasks were in the monitored cgroup. This is
1179 * independent of the activity of the context as
1180 * there may be a mix of cgroup and non-cgroup events.
1182 * That is why we treat cgroup events differently
1185 if (is_cgroup_event(event))
1186 run_end = perf_cgroup_event_time(event);
1187 else if (ctx->is_active)
1188 run_end = ctx->time;
1190 run_end = event->tstamp_stopped;
1192 event->total_time_enabled = run_end - event->tstamp_enabled;
1194 if (event->state == PERF_EVENT_STATE_INACTIVE)
1195 run_end = event->tstamp_stopped;
1197 run_end = perf_event_time(event);
1199 event->total_time_running = run_end - event->tstamp_running;
1204 * Update total_time_enabled and total_time_running for all events in a group.
1206 static void update_group_times(struct perf_event *leader)
1208 struct perf_event *event;
1210 update_event_times(leader);
1211 list_for_each_entry(event, &leader->sibling_list, group_entry)
1212 update_event_times(event);
1215 static struct list_head *
1216 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1218 if (event->attr.pinned)
1219 return &ctx->pinned_groups;
1221 return &ctx->flexible_groups;
1225 * Add a event from the lists for its context.
1226 * Must be called with ctx->mutex and ctx->lock held.
1229 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1231 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1232 event->attach_state |= PERF_ATTACH_CONTEXT;
1235 * If we're a stand alone event or group leader, we go to the context
1236 * list, group events are kept attached to the group so that
1237 * perf_group_detach can, at all times, locate all siblings.
1239 if (event->group_leader == event) {
1240 struct list_head *list;
1242 if (is_software_event(event))
1243 event->group_flags |= PERF_GROUP_SOFTWARE;
1245 list = ctx_group_list(event, ctx);
1246 list_add_tail(&event->group_entry, list);
1249 if (is_cgroup_event(event))
1252 list_add_rcu(&event->event_entry, &ctx->event_list);
1254 if (event->attr.inherit_stat)
1261 * Initialize event state based on the perf_event_attr::disabled.
1263 static inline void perf_event__state_init(struct perf_event *event)
1265 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1266 PERF_EVENT_STATE_INACTIVE;
1270 * Called at perf_event creation and when events are attached/detached from a
1273 static void perf_event__read_size(struct perf_event *event)
1275 int entry = sizeof(u64); /* value */
1279 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1280 size += sizeof(u64);
1282 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1283 size += sizeof(u64);
1285 if (event->attr.read_format & PERF_FORMAT_ID)
1286 entry += sizeof(u64);
1288 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1289 nr += event->group_leader->nr_siblings;
1290 size += sizeof(u64);
1294 event->read_size = size;
1297 static void perf_event__header_size(struct perf_event *event)
1299 struct perf_sample_data *data;
1300 u64 sample_type = event->attr.sample_type;
1303 perf_event__read_size(event);
1305 if (sample_type & PERF_SAMPLE_IP)
1306 size += sizeof(data->ip);
1308 if (sample_type & PERF_SAMPLE_ADDR)
1309 size += sizeof(data->addr);
1311 if (sample_type & PERF_SAMPLE_PERIOD)
1312 size += sizeof(data->period);
1314 if (sample_type & PERF_SAMPLE_WEIGHT)
1315 size += sizeof(data->weight);
1317 if (sample_type & PERF_SAMPLE_READ)
1318 size += event->read_size;
1320 if (sample_type & PERF_SAMPLE_DATA_SRC)
1321 size += sizeof(data->data_src.val);
1323 if (sample_type & PERF_SAMPLE_TRANSACTION)
1324 size += sizeof(data->txn);
1326 event->header_size = size;
1329 static void perf_event__id_header_size(struct perf_event *event)
1331 struct perf_sample_data *data;
1332 u64 sample_type = event->attr.sample_type;
1335 if (sample_type & PERF_SAMPLE_TID)
1336 size += sizeof(data->tid_entry);
1338 if (sample_type & PERF_SAMPLE_TIME)
1339 size += sizeof(data->time);
1341 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1342 size += sizeof(data->id);
1344 if (sample_type & PERF_SAMPLE_ID)
1345 size += sizeof(data->id);
1347 if (sample_type & PERF_SAMPLE_STREAM_ID)
1348 size += sizeof(data->stream_id);
1350 if (sample_type & PERF_SAMPLE_CPU)
1351 size += sizeof(data->cpu_entry);
1353 event->id_header_size = size;
1356 static void perf_group_attach(struct perf_event *event)
1358 struct perf_event *group_leader = event->group_leader, *pos;
1361 * We can have double attach due to group movement in perf_event_open.
1363 if (event->attach_state & PERF_ATTACH_GROUP)
1366 event->attach_state |= PERF_ATTACH_GROUP;
1368 if (group_leader == event)
1371 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1373 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1374 !is_software_event(event))
1375 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1377 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1378 group_leader->nr_siblings++;
1380 perf_event__header_size(group_leader);
1382 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1383 perf_event__header_size(pos);
1387 * Remove a event from the lists for its context.
1388 * Must be called with ctx->mutex and ctx->lock held.
1391 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1393 struct perf_cpu_context *cpuctx;
1395 WARN_ON_ONCE(event->ctx != ctx);
1396 lockdep_assert_held(&ctx->lock);
1399 * We can have double detach due to exit/hot-unplug + close.
1401 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1404 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1406 if (is_cgroup_event(event)) {
1408 cpuctx = __get_cpu_context(ctx);
1410 * if there are no more cgroup events
1411 * then cler cgrp to avoid stale pointer
1412 * in update_cgrp_time_from_cpuctx()
1414 if (!ctx->nr_cgroups)
1415 cpuctx->cgrp = NULL;
1419 if (event->attr.inherit_stat)
1422 list_del_rcu(&event->event_entry);
1424 if (event->group_leader == event)
1425 list_del_init(&event->group_entry);
1427 update_group_times(event);
1430 * If event was in error state, then keep it
1431 * that way, otherwise bogus counts will be
1432 * returned on read(). The only way to get out
1433 * of error state is by explicit re-enabling
1436 if (event->state > PERF_EVENT_STATE_OFF)
1437 event->state = PERF_EVENT_STATE_OFF;
1442 static void perf_group_detach(struct perf_event *event)
1444 struct perf_event *sibling, *tmp;
1445 struct list_head *list = NULL;
1448 * We can have double detach due to exit/hot-unplug + close.
1450 if (!(event->attach_state & PERF_ATTACH_GROUP))
1453 event->attach_state &= ~PERF_ATTACH_GROUP;
1456 * If this is a sibling, remove it from its group.
1458 if (event->group_leader != event) {
1459 list_del_init(&event->group_entry);
1460 event->group_leader->nr_siblings--;
1464 if (!list_empty(&event->group_entry))
1465 list = &event->group_entry;
1468 * If this was a group event with sibling events then
1469 * upgrade the siblings to singleton events by adding them
1470 * to whatever list we are on.
1472 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1474 list_move_tail(&sibling->group_entry, list);
1475 sibling->group_leader = sibling;
1477 /* Inherit group flags from the previous leader */
1478 sibling->group_flags = event->group_flags;
1480 WARN_ON_ONCE(sibling->ctx != event->ctx);
1484 perf_event__header_size(event->group_leader);
1486 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1487 perf_event__header_size(tmp);
1491 * User event without the task.
1493 static bool is_orphaned_event(struct perf_event *event)
1495 return event && !is_kernel_event(event) && !event->owner;
1499 * Event has a parent but parent's task finished and it's
1500 * alive only because of children holding refference.
1502 static bool is_orphaned_child(struct perf_event *event)
1504 return is_orphaned_event(event->parent);
1507 static void orphans_remove_work(struct work_struct *work);
1509 static void schedule_orphans_remove(struct perf_event_context *ctx)
1511 if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
1514 if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
1516 ctx->orphans_remove_sched = true;
1520 static int __init perf_workqueue_init(void)
1522 perf_wq = create_singlethread_workqueue("perf");
1523 WARN(!perf_wq, "failed to create perf workqueue\n");
1524 return perf_wq ? 0 : -1;
1527 core_initcall(perf_workqueue_init);
1530 event_filter_match(struct perf_event *event)
1532 return (event->cpu == -1 || event->cpu == smp_processor_id())
1533 && perf_cgroup_match(event);
1537 event_sched_out(struct perf_event *event,
1538 struct perf_cpu_context *cpuctx,
1539 struct perf_event_context *ctx)
1541 u64 tstamp = perf_event_time(event);
1544 WARN_ON_ONCE(event->ctx != ctx);
1545 lockdep_assert_held(&ctx->lock);
1548 * An event which could not be activated because of
1549 * filter mismatch still needs to have its timings
1550 * maintained, otherwise bogus information is return
1551 * via read() for time_enabled, time_running:
1553 if (event->state == PERF_EVENT_STATE_INACTIVE
1554 && !event_filter_match(event)) {
1555 delta = tstamp - event->tstamp_stopped;
1556 event->tstamp_running += delta;
1557 event->tstamp_stopped = tstamp;
1560 if (event->state != PERF_EVENT_STATE_ACTIVE)
1563 perf_pmu_disable(event->pmu);
1565 event->state = PERF_EVENT_STATE_INACTIVE;
1566 if (event->pending_disable) {
1567 event->pending_disable = 0;
1568 event->state = PERF_EVENT_STATE_OFF;
1570 event->tstamp_stopped = tstamp;
1571 event->pmu->del(event, 0);
1574 if (!is_software_event(event))
1575 cpuctx->active_oncpu--;
1576 if (!--ctx->nr_active)
1577 perf_event_ctx_deactivate(ctx);
1578 if (event->attr.freq && event->attr.sample_freq)
1580 if (event->attr.exclusive || !cpuctx->active_oncpu)
1581 cpuctx->exclusive = 0;
1583 if (is_orphaned_child(event))
1584 schedule_orphans_remove(ctx);
1586 perf_pmu_enable(event->pmu);
1590 group_sched_out(struct perf_event *group_event,
1591 struct perf_cpu_context *cpuctx,
1592 struct perf_event_context *ctx)
1594 struct perf_event *event;
1595 int state = group_event->state;
1597 event_sched_out(group_event, cpuctx, ctx);
1600 * Schedule out siblings (if any):
1602 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1603 event_sched_out(event, cpuctx, ctx);
1605 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1606 cpuctx->exclusive = 0;
1609 struct remove_event {
1610 struct perf_event *event;
1615 * Cross CPU call to remove a performance event
1617 * We disable the event on the hardware level first. After that we
1618 * remove it from the context list.
1620 static int __perf_remove_from_context(void *info)
1622 struct remove_event *re = info;
1623 struct perf_event *event = re->event;
1624 struct perf_event_context *ctx = event->ctx;
1625 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1627 raw_spin_lock(&ctx->lock);
1628 event_sched_out(event, cpuctx, ctx);
1629 if (re->detach_group)
1630 perf_group_detach(event);
1631 list_del_event(event, ctx);
1632 if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1634 cpuctx->task_ctx = NULL;
1636 raw_spin_unlock(&ctx->lock);
1643 * Remove the event from a task's (or a CPU's) list of events.
1645 * CPU events are removed with a smp call. For task events we only
1646 * call when the task is on a CPU.
1648 * If event->ctx is a cloned context, callers must make sure that
1649 * every task struct that event->ctx->task could possibly point to
1650 * remains valid. This is OK when called from perf_release since
1651 * that only calls us on the top-level context, which can't be a clone.
1652 * When called from perf_event_exit_task, it's OK because the
1653 * context has been detached from its task.
1655 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1657 struct perf_event_context *ctx = event->ctx;
1658 struct task_struct *task = ctx->task;
1659 struct remove_event re = {
1661 .detach_group = detach_group,
1664 lockdep_assert_held(&ctx->mutex);
1668 * Per cpu events are removed via an smp call. The removal can
1669 * fail if the CPU is currently offline, but in that case we
1670 * already called __perf_remove_from_context from
1671 * perf_event_exit_cpu.
1673 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1678 if (!task_function_call(task, __perf_remove_from_context, &re))
1681 raw_spin_lock_irq(&ctx->lock);
1683 * If we failed to find a running task, but find the context active now
1684 * that we've acquired the ctx->lock, retry.
1686 if (ctx->is_active) {
1687 raw_spin_unlock_irq(&ctx->lock);
1689 * Reload the task pointer, it might have been changed by
1690 * a concurrent perf_event_context_sched_out().
1697 * Since the task isn't running, its safe to remove the event, us
1698 * holding the ctx->lock ensures the task won't get scheduled in.
1701 perf_group_detach(event);
1702 list_del_event(event, ctx);
1703 raw_spin_unlock_irq(&ctx->lock);
1707 * Cross CPU call to disable a performance event
1709 int __perf_event_disable(void *info)
1711 struct perf_event *event = info;
1712 struct perf_event_context *ctx = event->ctx;
1713 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1716 * If this is a per-task event, need to check whether this
1717 * event's task is the current task on this cpu.
1719 * Can trigger due to concurrent perf_event_context_sched_out()
1720 * flipping contexts around.
1722 if (ctx->task && cpuctx->task_ctx != ctx)
1725 raw_spin_lock(&ctx->lock);
1728 * If the event is on, turn it off.
1729 * If it is in error state, leave it in error state.
1731 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1732 update_context_time(ctx);
1733 update_cgrp_time_from_event(event);
1734 update_group_times(event);
1735 if (event == event->group_leader)
1736 group_sched_out(event, cpuctx, ctx);
1738 event_sched_out(event, cpuctx, ctx);
1739 event->state = PERF_EVENT_STATE_OFF;
1742 raw_spin_unlock(&ctx->lock);
1750 * If event->ctx is a cloned context, callers must make sure that
1751 * every task struct that event->ctx->task could possibly point to
1752 * remains valid. This condition is satisifed when called through
1753 * perf_event_for_each_child or perf_event_for_each because they
1754 * hold the top-level event's child_mutex, so any descendant that
1755 * goes to exit will block in sync_child_event.
1756 * When called from perf_pending_event it's OK because event->ctx
1757 * is the current context on this CPU and preemption is disabled,
1758 * hence we can't get into perf_event_task_sched_out for this context.
1760 static void _perf_event_disable(struct perf_event *event)
1762 struct perf_event_context *ctx = event->ctx;
1763 struct task_struct *task = ctx->task;
1767 * Disable the event on the cpu that it's on
1769 cpu_function_call(event->cpu, __perf_event_disable, event);
1774 if (!task_function_call(task, __perf_event_disable, event))
1777 raw_spin_lock_irq(&ctx->lock);
1779 * If the event is still active, we need to retry the cross-call.
1781 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1782 raw_spin_unlock_irq(&ctx->lock);
1784 * Reload the task pointer, it might have been changed by
1785 * a concurrent perf_event_context_sched_out().
1792 * Since we have the lock this context can't be scheduled
1793 * in, so we can change the state safely.
1795 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1796 update_group_times(event);
1797 event->state = PERF_EVENT_STATE_OFF;
1799 raw_spin_unlock_irq(&ctx->lock);
1803 * Strictly speaking kernel users cannot create groups and therefore this
1804 * interface does not need the perf_event_ctx_lock() magic.
1806 void perf_event_disable(struct perf_event *event)
1808 struct perf_event_context *ctx;
1810 ctx = perf_event_ctx_lock(event);
1811 _perf_event_disable(event);
1812 perf_event_ctx_unlock(event, ctx);
1814 EXPORT_SYMBOL_GPL(perf_event_disable);
1816 static void perf_set_shadow_time(struct perf_event *event,
1817 struct perf_event_context *ctx,
1821 * use the correct time source for the time snapshot
1823 * We could get by without this by leveraging the
1824 * fact that to get to this function, the caller
1825 * has most likely already called update_context_time()
1826 * and update_cgrp_time_xx() and thus both timestamp
1827 * are identical (or very close). Given that tstamp is,
1828 * already adjusted for cgroup, we could say that:
1829 * tstamp - ctx->timestamp
1831 * tstamp - cgrp->timestamp.
1833 * Then, in perf_output_read(), the calculation would
1834 * work with no changes because:
1835 * - event is guaranteed scheduled in
1836 * - no scheduled out in between
1837 * - thus the timestamp would be the same
1839 * But this is a bit hairy.
1841 * So instead, we have an explicit cgroup call to remain
1842 * within the time time source all along. We believe it
1843 * is cleaner and simpler to understand.
1845 if (is_cgroup_event(event))
1846 perf_cgroup_set_shadow_time(event, tstamp);
1848 event->shadow_ctx_time = tstamp - ctx->timestamp;
1851 #define MAX_INTERRUPTS (~0ULL)
1853 static void perf_log_throttle(struct perf_event *event, int enable);
1854 static void perf_log_itrace_start(struct perf_event *event);
1857 event_sched_in(struct perf_event *event,
1858 struct perf_cpu_context *cpuctx,
1859 struct perf_event_context *ctx)
1861 u64 tstamp = perf_event_time(event);
1864 lockdep_assert_held(&ctx->lock);
1866 if (event->state <= PERF_EVENT_STATE_OFF)
1869 event->state = PERF_EVENT_STATE_ACTIVE;
1870 event->oncpu = smp_processor_id();
1873 * Unthrottle events, since we scheduled we might have missed several
1874 * ticks already, also for a heavily scheduling task there is little
1875 * guarantee it'll get a tick in a timely manner.
1877 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1878 perf_log_throttle(event, 1);
1879 event->hw.interrupts = 0;
1883 * The new state must be visible before we turn it on in the hardware:
1887 perf_pmu_disable(event->pmu);
1889 perf_set_shadow_time(event, ctx, tstamp);
1891 perf_log_itrace_start(event);
1893 if (event->pmu->add(event, PERF_EF_START)) {
1894 event->state = PERF_EVENT_STATE_INACTIVE;
1900 event->tstamp_running += tstamp - event->tstamp_stopped;
1902 if (!is_software_event(event))
1903 cpuctx->active_oncpu++;
1904 if (!ctx->nr_active++)
1905 perf_event_ctx_activate(ctx);
1906 if (event->attr.freq && event->attr.sample_freq)
1909 if (event->attr.exclusive)
1910 cpuctx->exclusive = 1;
1912 if (is_orphaned_child(event))
1913 schedule_orphans_remove(ctx);
1916 perf_pmu_enable(event->pmu);
1922 group_sched_in(struct perf_event *group_event,
1923 struct perf_cpu_context *cpuctx,
1924 struct perf_event_context *ctx)
1926 struct perf_event *event, *partial_group = NULL;
1927 struct pmu *pmu = ctx->pmu;
1928 u64 now = ctx->time;
1929 bool simulate = false;
1931 if (group_event->state == PERF_EVENT_STATE_OFF)
1934 pmu->start_txn(pmu);
1936 if (event_sched_in(group_event, cpuctx, ctx)) {
1937 pmu->cancel_txn(pmu);
1938 perf_cpu_hrtimer_restart(cpuctx);
1943 * Schedule in siblings as one group (if any):
1945 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1946 if (event_sched_in(event, cpuctx, ctx)) {
1947 partial_group = event;
1952 if (!pmu->commit_txn(pmu))
1957 * Groups can be scheduled in as one unit only, so undo any
1958 * partial group before returning:
1959 * The events up to the failed event are scheduled out normally,
1960 * tstamp_stopped will be updated.
1962 * The failed events and the remaining siblings need to have
1963 * their timings updated as if they had gone thru event_sched_in()
1964 * and event_sched_out(). This is required to get consistent timings
1965 * across the group. This also takes care of the case where the group
1966 * could never be scheduled by ensuring tstamp_stopped is set to mark
1967 * the time the event was actually stopped, such that time delta
1968 * calculation in update_event_times() is correct.
1970 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1971 if (event == partial_group)
1975 event->tstamp_running += now - event->tstamp_stopped;
1976 event->tstamp_stopped = now;
1978 event_sched_out(event, cpuctx, ctx);
1981 event_sched_out(group_event, cpuctx, ctx);
1983 pmu->cancel_txn(pmu);
1985 perf_cpu_hrtimer_restart(cpuctx);
1991 * Work out whether we can put this event group on the CPU now.
1993 static int group_can_go_on(struct perf_event *event,
1994 struct perf_cpu_context *cpuctx,
1998 * Groups consisting entirely of software events can always go on.
2000 if (event->group_flags & PERF_GROUP_SOFTWARE)
2003 * If an exclusive group is already on, no other hardware
2006 if (cpuctx->exclusive)
2009 * If this group is exclusive and there are already
2010 * events on the CPU, it can't go on.
2012 if (event->attr.exclusive && cpuctx->active_oncpu)
2015 * Otherwise, try to add it if all previous groups were able
2021 static void add_event_to_ctx(struct perf_event *event,
2022 struct perf_event_context *ctx)
2024 u64 tstamp = perf_event_time(event);
2026 list_add_event(event, ctx);
2027 perf_group_attach(event);
2028 event->tstamp_enabled = tstamp;
2029 event->tstamp_running = tstamp;
2030 event->tstamp_stopped = tstamp;
2033 static void task_ctx_sched_out(struct perf_event_context *ctx);
2035 ctx_sched_in(struct perf_event_context *ctx,
2036 struct perf_cpu_context *cpuctx,
2037 enum event_type_t event_type,
2038 struct task_struct *task);
2040 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2041 struct perf_event_context *ctx,
2042 struct task_struct *task)
2044 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2046 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2047 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2049 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2053 * Cross CPU call to install and enable a performance event
2055 * Must be called with ctx->mutex held
2057 static int __perf_install_in_context(void *info)
2059 struct perf_event *event = info;
2060 struct perf_event_context *ctx = event->ctx;
2061 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2062 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2063 struct task_struct *task = current;
2065 perf_ctx_lock(cpuctx, task_ctx);
2066 perf_pmu_disable(cpuctx->ctx.pmu);
2069 * If there was an active task_ctx schedule it out.
2072 task_ctx_sched_out(task_ctx);
2075 * If the context we're installing events in is not the
2076 * active task_ctx, flip them.
2078 if (ctx->task && task_ctx != ctx) {
2080 raw_spin_unlock(&task_ctx->lock);
2081 raw_spin_lock(&ctx->lock);
2086 cpuctx->task_ctx = task_ctx;
2087 task = task_ctx->task;
2090 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2092 update_context_time(ctx);
2094 * update cgrp time only if current cgrp
2095 * matches event->cgrp. Must be done before
2096 * calling add_event_to_ctx()
2098 update_cgrp_time_from_event(event);
2100 add_event_to_ctx(event, ctx);
2103 * Schedule everything back in
2105 perf_event_sched_in(cpuctx, task_ctx, task);
2107 perf_pmu_enable(cpuctx->ctx.pmu);
2108 perf_ctx_unlock(cpuctx, task_ctx);
2114 * Attach a performance event to a context
2116 * First we add the event to the list with the hardware enable bit
2117 * in event->hw_config cleared.
2119 * If the event is attached to a task which is on a CPU we use a smp
2120 * call to enable it in the task context. The task might have been
2121 * scheduled away, but we check this in the smp call again.
2124 perf_install_in_context(struct perf_event_context *ctx,
2125 struct perf_event *event,
2128 struct task_struct *task = ctx->task;
2130 lockdep_assert_held(&ctx->mutex);
2133 if (event->cpu != -1)
2138 * Per cpu events are installed via an smp call and
2139 * the install is always successful.
2141 cpu_function_call(cpu, __perf_install_in_context, event);
2146 if (!task_function_call(task, __perf_install_in_context, event))
2149 raw_spin_lock_irq(&ctx->lock);
2151 * If we failed to find a running task, but find the context active now
2152 * that we've acquired the ctx->lock, retry.
2154 if (ctx->is_active) {
2155 raw_spin_unlock_irq(&ctx->lock);
2157 * Reload the task pointer, it might have been changed by
2158 * a concurrent perf_event_context_sched_out().
2165 * Since the task isn't running, its safe to add the event, us holding
2166 * the ctx->lock ensures the task won't get scheduled in.
2168 add_event_to_ctx(event, ctx);
2169 raw_spin_unlock_irq(&ctx->lock);
2173 * Put a event into inactive state and update time fields.
2174 * Enabling the leader of a group effectively enables all
2175 * the group members that aren't explicitly disabled, so we
2176 * have to update their ->tstamp_enabled also.
2177 * Note: this works for group members as well as group leaders
2178 * since the non-leader members' sibling_lists will be empty.
2180 static void __perf_event_mark_enabled(struct perf_event *event)
2182 struct perf_event *sub;
2183 u64 tstamp = perf_event_time(event);
2185 event->state = PERF_EVENT_STATE_INACTIVE;
2186 event->tstamp_enabled = tstamp - event->total_time_enabled;
2187 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2188 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2189 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2194 * Cross CPU call to enable a performance event
2196 static int __perf_event_enable(void *info)
2198 struct perf_event *event = info;
2199 struct perf_event_context *ctx = event->ctx;
2200 struct perf_event *leader = event->group_leader;
2201 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2205 * There's a time window between 'ctx->is_active' check
2206 * in perf_event_enable function and this place having:
2208 * - ctx->lock unlocked
2210 * where the task could be killed and 'ctx' deactivated
2211 * by perf_event_exit_task.
2213 if (!ctx->is_active)
2216 raw_spin_lock(&ctx->lock);
2217 update_context_time(ctx);
2219 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2223 * set current task's cgroup time reference point
2225 perf_cgroup_set_timestamp(current, ctx);
2227 __perf_event_mark_enabled(event);
2229 if (!event_filter_match(event)) {
2230 if (is_cgroup_event(event))
2231 perf_cgroup_defer_enabled(event);
2236 * If the event is in a group and isn't the group leader,
2237 * then don't put it on unless the group is on.
2239 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2242 if (!group_can_go_on(event, cpuctx, 1)) {
2245 if (event == leader)
2246 err = group_sched_in(event, cpuctx, ctx);
2248 err = event_sched_in(event, cpuctx, ctx);
2253 * If this event can't go on and it's part of a
2254 * group, then the whole group has to come off.
2256 if (leader != event) {
2257 group_sched_out(leader, cpuctx, ctx);
2258 perf_cpu_hrtimer_restart(cpuctx);
2260 if (leader->attr.pinned) {
2261 update_group_times(leader);
2262 leader->state = PERF_EVENT_STATE_ERROR;
2267 raw_spin_unlock(&ctx->lock);
2275 * If event->ctx is a cloned context, callers must make sure that
2276 * every task struct that event->ctx->task could possibly point to
2277 * remains valid. This condition is satisfied when called through
2278 * perf_event_for_each_child or perf_event_for_each as described
2279 * for perf_event_disable.
2281 static void _perf_event_enable(struct perf_event *event)
2283 struct perf_event_context *ctx = event->ctx;
2284 struct task_struct *task = ctx->task;
2288 * Enable the event on the cpu that it's on
2290 cpu_function_call(event->cpu, __perf_event_enable, event);
2294 raw_spin_lock_irq(&ctx->lock);
2295 if (event->state >= PERF_EVENT_STATE_INACTIVE)
2299 * If the event is in error state, clear that first.
2300 * That way, if we see the event in error state below, we
2301 * know that it has gone back into error state, as distinct
2302 * from the task having been scheduled away before the
2303 * cross-call arrived.
2305 if (event->state == PERF_EVENT_STATE_ERROR)
2306 event->state = PERF_EVENT_STATE_OFF;
2309 if (!ctx->is_active) {
2310 __perf_event_mark_enabled(event);
2314 raw_spin_unlock_irq(&ctx->lock);
2316 if (!task_function_call(task, __perf_event_enable, event))
2319 raw_spin_lock_irq(&ctx->lock);
2322 * If the context is active and the event is still off,
2323 * we need to retry the cross-call.
2325 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2327 * task could have been flipped by a concurrent
2328 * perf_event_context_sched_out()
2335 raw_spin_unlock_irq(&ctx->lock);
2339 * See perf_event_disable();
2341 void perf_event_enable(struct perf_event *event)
2343 struct perf_event_context *ctx;
2345 ctx = perf_event_ctx_lock(event);
2346 _perf_event_enable(event);
2347 perf_event_ctx_unlock(event, ctx);
2349 EXPORT_SYMBOL_GPL(perf_event_enable);
2351 static int _perf_event_refresh(struct perf_event *event, int refresh)
2354 * not supported on inherited events
2356 if (event->attr.inherit || !is_sampling_event(event))
2359 atomic_add(refresh, &event->event_limit);
2360 _perf_event_enable(event);
2366 * See perf_event_disable()
2368 int perf_event_refresh(struct perf_event *event, int refresh)
2370 struct perf_event_context *ctx;
2373 ctx = perf_event_ctx_lock(event);
2374 ret = _perf_event_refresh(event, refresh);
2375 perf_event_ctx_unlock(event, ctx);
2379 EXPORT_SYMBOL_GPL(perf_event_refresh);
2381 static void ctx_sched_out(struct perf_event_context *ctx,
2382 struct perf_cpu_context *cpuctx,
2383 enum event_type_t event_type)
2385 struct perf_event *event;
2386 int is_active = ctx->is_active;
2388 ctx->is_active &= ~event_type;
2389 if (likely(!ctx->nr_events))
2392 update_context_time(ctx);
2393 update_cgrp_time_from_cpuctx(cpuctx);
2394 if (!ctx->nr_active)
2397 perf_pmu_disable(ctx->pmu);
2398 if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2399 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2400 group_sched_out(event, cpuctx, ctx);
2403 if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2404 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2405 group_sched_out(event, cpuctx, ctx);
2407 perf_pmu_enable(ctx->pmu);
2411 * Test whether two contexts are equivalent, i.e. whether they have both been
2412 * cloned from the same version of the same context.
2414 * Equivalence is measured using a generation number in the context that is
2415 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2416 * and list_del_event().
2418 static int context_equiv(struct perf_event_context *ctx1,
2419 struct perf_event_context *ctx2)
2421 lockdep_assert_held(&ctx1->lock);
2422 lockdep_assert_held(&ctx2->lock);
2424 /* Pinning disables the swap optimization */
2425 if (ctx1->pin_count || ctx2->pin_count)
2428 /* If ctx1 is the parent of ctx2 */
2429 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2432 /* If ctx2 is the parent of ctx1 */
2433 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2437 * If ctx1 and ctx2 have the same parent; we flatten the parent
2438 * hierarchy, see perf_event_init_context().
2440 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2441 ctx1->parent_gen == ctx2->parent_gen)
2448 static void __perf_event_sync_stat(struct perf_event *event,
2449 struct perf_event *next_event)
2453 if (!event->attr.inherit_stat)
2457 * Update the event value, we cannot use perf_event_read()
2458 * because we're in the middle of a context switch and have IRQs
2459 * disabled, which upsets smp_call_function_single(), however
2460 * we know the event must be on the current CPU, therefore we
2461 * don't need to use it.
2463 switch (event->state) {
2464 case PERF_EVENT_STATE_ACTIVE:
2465 event->pmu->read(event);
2468 case PERF_EVENT_STATE_INACTIVE:
2469 update_event_times(event);
2477 * In order to keep per-task stats reliable we need to flip the event
2478 * values when we flip the contexts.
2480 value = local64_read(&next_event->count);
2481 value = local64_xchg(&event->count, value);
2482 local64_set(&next_event->count, value);
2484 swap(event->total_time_enabled, next_event->total_time_enabled);
2485 swap(event->total_time_running, next_event->total_time_running);
2488 * Since we swizzled the values, update the user visible data too.
2490 perf_event_update_userpage(event);
2491 perf_event_update_userpage(next_event);
2494 static void perf_event_sync_stat(struct perf_event_context *ctx,
2495 struct perf_event_context *next_ctx)
2497 struct perf_event *event, *next_event;
2502 update_context_time(ctx);
2504 event = list_first_entry(&ctx->event_list,
2505 struct perf_event, event_entry);
2507 next_event = list_first_entry(&next_ctx->event_list,
2508 struct perf_event, event_entry);
2510 while (&event->event_entry != &ctx->event_list &&
2511 &next_event->event_entry != &next_ctx->event_list) {
2513 __perf_event_sync_stat(event, next_event);
2515 event = list_next_entry(event, event_entry);
2516 next_event = list_next_entry(next_event, event_entry);
2520 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2521 struct task_struct *next)
2523 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2524 struct perf_event_context *next_ctx;
2525 struct perf_event_context *parent, *next_parent;
2526 struct perf_cpu_context *cpuctx;
2532 cpuctx = __get_cpu_context(ctx);
2533 if (!cpuctx->task_ctx)
2537 next_ctx = next->perf_event_ctxp[ctxn];
2541 parent = rcu_dereference(ctx->parent_ctx);
2542 next_parent = rcu_dereference(next_ctx->parent_ctx);
2544 /* If neither context have a parent context; they cannot be clones. */
2545 if (!parent && !next_parent)
2548 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2550 * Looks like the two contexts are clones, so we might be
2551 * able to optimize the context switch. We lock both
2552 * contexts and check that they are clones under the
2553 * lock (including re-checking that neither has been
2554 * uncloned in the meantime). It doesn't matter which
2555 * order we take the locks because no other cpu could
2556 * be trying to lock both of these tasks.
2558 raw_spin_lock(&ctx->lock);
2559 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2560 if (context_equiv(ctx, next_ctx)) {
2562 * XXX do we need a memory barrier of sorts
2563 * wrt to rcu_dereference() of perf_event_ctxp
2565 task->perf_event_ctxp[ctxn] = next_ctx;
2566 next->perf_event_ctxp[ctxn] = ctx;
2568 next_ctx->task = task;
2570 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2574 perf_event_sync_stat(ctx, next_ctx);
2576 raw_spin_unlock(&next_ctx->lock);
2577 raw_spin_unlock(&ctx->lock);
2583 raw_spin_lock(&ctx->lock);
2584 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2585 cpuctx->task_ctx = NULL;
2586 raw_spin_unlock(&ctx->lock);
2590 void perf_sched_cb_dec(struct pmu *pmu)
2592 this_cpu_dec(perf_sched_cb_usages);
2595 void perf_sched_cb_inc(struct pmu *pmu)
2597 this_cpu_inc(perf_sched_cb_usages);
2601 * This function provides the context switch callback to the lower code
2602 * layer. It is invoked ONLY when the context switch callback is enabled.
2604 static void perf_pmu_sched_task(struct task_struct *prev,
2605 struct task_struct *next,
2608 struct perf_cpu_context *cpuctx;
2610 unsigned long flags;
2615 local_irq_save(flags);
2619 list_for_each_entry_rcu(pmu, &pmus, entry) {
2620 if (pmu->sched_task) {
2621 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2623 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2625 perf_pmu_disable(pmu);
2627 pmu->sched_task(cpuctx->task_ctx, sched_in);
2629 perf_pmu_enable(pmu);
2631 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2637 local_irq_restore(flags);
2640 #define for_each_task_context_nr(ctxn) \
2641 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2644 * Called from scheduler to remove the events of the current task,
2645 * with interrupts disabled.
2647 * We stop each event and update the event value in event->count.
2649 * This does not protect us against NMI, but disable()
2650 * sets the disabled bit in the control field of event _before_
2651 * accessing the event control register. If a NMI hits, then it will
2652 * not restart the event.
2654 void __perf_event_task_sched_out(struct task_struct *task,
2655 struct task_struct *next)
2659 if (__this_cpu_read(perf_sched_cb_usages))
2660 perf_pmu_sched_task(task, next, false);
2662 for_each_task_context_nr(ctxn)
2663 perf_event_context_sched_out(task, ctxn, next);
2666 * if cgroup events exist on this CPU, then we need
2667 * to check if we have to switch out PMU state.
2668 * cgroup event are system-wide mode only
2670 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2671 perf_cgroup_sched_out(task, next);
2674 static void task_ctx_sched_out(struct perf_event_context *ctx)
2676 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2678 if (!cpuctx->task_ctx)
2681 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2684 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2685 cpuctx->task_ctx = NULL;
2689 * Called with IRQs disabled
2691 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2692 enum event_type_t event_type)
2694 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2698 ctx_pinned_sched_in(struct perf_event_context *ctx,
2699 struct perf_cpu_context *cpuctx)
2701 struct perf_event *event;
2703 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2704 if (event->state <= PERF_EVENT_STATE_OFF)
2706 if (!event_filter_match(event))
2709 /* may need to reset tstamp_enabled */
2710 if (is_cgroup_event(event))
2711 perf_cgroup_mark_enabled(event, ctx);
2713 if (group_can_go_on(event, cpuctx, 1))
2714 group_sched_in(event, cpuctx, ctx);
2717 * If this pinned group hasn't been scheduled,
2718 * put it in error state.
2720 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2721 update_group_times(event);
2722 event->state = PERF_EVENT_STATE_ERROR;
2728 ctx_flexible_sched_in(struct perf_event_context *ctx,
2729 struct perf_cpu_context *cpuctx)
2731 struct perf_event *event;
2734 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2735 /* Ignore events in OFF or ERROR state */
2736 if (event->state <= PERF_EVENT_STATE_OFF)
2739 * Listen to the 'cpu' scheduling filter constraint
2742 if (!event_filter_match(event))
2745 /* may need to reset tstamp_enabled */
2746 if (is_cgroup_event(event))
2747 perf_cgroup_mark_enabled(event, ctx);
2749 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2750 if (group_sched_in(event, cpuctx, ctx))
2757 ctx_sched_in(struct perf_event_context *ctx,
2758 struct perf_cpu_context *cpuctx,
2759 enum event_type_t event_type,
2760 struct task_struct *task)
2763 int is_active = ctx->is_active;
2765 ctx->is_active |= event_type;
2766 if (likely(!ctx->nr_events))
2770 ctx->timestamp = now;
2771 perf_cgroup_set_timestamp(task, ctx);
2773 * First go through the list and put on any pinned groups
2774 * in order to give them the best chance of going on.
2776 if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2777 ctx_pinned_sched_in(ctx, cpuctx);
2779 /* Then walk through the lower prio flexible groups */
2780 if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2781 ctx_flexible_sched_in(ctx, cpuctx);
2784 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2785 enum event_type_t event_type,
2786 struct task_struct *task)
2788 struct perf_event_context *ctx = &cpuctx->ctx;
2790 ctx_sched_in(ctx, cpuctx, event_type, task);
2793 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2794 struct task_struct *task)
2796 struct perf_cpu_context *cpuctx;
2798 cpuctx = __get_cpu_context(ctx);
2799 if (cpuctx->task_ctx == ctx)
2802 perf_ctx_lock(cpuctx, ctx);
2803 perf_pmu_disable(ctx->pmu);
2805 * We want to keep the following priority order:
2806 * cpu pinned (that don't need to move), task pinned,
2807 * cpu flexible, task flexible.
2809 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2812 cpuctx->task_ctx = ctx;
2814 perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2816 perf_pmu_enable(ctx->pmu);
2817 perf_ctx_unlock(cpuctx, ctx);
2821 * Called from scheduler to add the events of the current task
2822 * with interrupts disabled.
2824 * We restore the event value and then enable it.
2826 * This does not protect us against NMI, but enable()
2827 * sets the enabled bit in the control field of event _before_
2828 * accessing the event control register. If a NMI hits, then it will
2829 * keep the event running.
2831 void __perf_event_task_sched_in(struct task_struct *prev,
2832 struct task_struct *task)
2834 struct perf_event_context *ctx;
2837 for_each_task_context_nr(ctxn) {
2838 ctx = task->perf_event_ctxp[ctxn];
2842 perf_event_context_sched_in(ctx, task);
2845 * if cgroup events exist on this CPU, then we need
2846 * to check if we have to switch in PMU state.
2847 * cgroup event are system-wide mode only
2849 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2850 perf_cgroup_sched_in(prev, task);
2852 if (__this_cpu_read(perf_sched_cb_usages))
2853 perf_pmu_sched_task(prev, task, true);
2856 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2858 u64 frequency = event->attr.sample_freq;
2859 u64 sec = NSEC_PER_SEC;
2860 u64 divisor, dividend;
2862 int count_fls, nsec_fls, frequency_fls, sec_fls;
2864 count_fls = fls64(count);
2865 nsec_fls = fls64(nsec);
2866 frequency_fls = fls64(frequency);
2870 * We got @count in @nsec, with a target of sample_freq HZ
2871 * the target period becomes:
2874 * period = -------------------
2875 * @nsec * sample_freq
2880 * Reduce accuracy by one bit such that @a and @b converge
2881 * to a similar magnitude.
2883 #define REDUCE_FLS(a, b) \
2885 if (a##_fls > b##_fls) { \
2895 * Reduce accuracy until either term fits in a u64, then proceed with
2896 * the other, so that finally we can do a u64/u64 division.
2898 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2899 REDUCE_FLS(nsec, frequency);
2900 REDUCE_FLS(sec, count);
2903 if (count_fls + sec_fls > 64) {
2904 divisor = nsec * frequency;
2906 while (count_fls + sec_fls > 64) {
2907 REDUCE_FLS(count, sec);
2911 dividend = count * sec;
2913 dividend = count * sec;
2915 while (nsec_fls + frequency_fls > 64) {
2916 REDUCE_FLS(nsec, frequency);
2920 divisor = nsec * frequency;
2926 return div64_u64(dividend, divisor);
2929 static DEFINE_PER_CPU(int, perf_throttled_count);
2930 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2932 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2934 struct hw_perf_event *hwc = &event->hw;
2935 s64 period, sample_period;
2938 period = perf_calculate_period(event, nsec, count);
2940 delta = (s64)(period - hwc->sample_period);
2941 delta = (delta + 7) / 8; /* low pass filter */
2943 sample_period = hwc->sample_period + delta;
2948 hwc->sample_period = sample_period;
2950 if (local64_read(&hwc->period_left) > 8*sample_period) {
2952 event->pmu->stop(event, PERF_EF_UPDATE);
2954 local64_set(&hwc->period_left, 0);
2957 event->pmu->start(event, PERF_EF_RELOAD);
2962 * combine freq adjustment with unthrottling to avoid two passes over the
2963 * events. At the same time, make sure, having freq events does not change
2964 * the rate of unthrottling as that would introduce bias.
2966 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2969 struct perf_event *event;
2970 struct hw_perf_event *hwc;
2971 u64 now, period = TICK_NSEC;
2975 * only need to iterate over all events iff:
2976 * - context have events in frequency mode (needs freq adjust)
2977 * - there are events to unthrottle on this cpu
2979 if (!(ctx->nr_freq || needs_unthr))
2982 raw_spin_lock(&ctx->lock);
2983 perf_pmu_disable(ctx->pmu);
2985 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2986 if (event->state != PERF_EVENT_STATE_ACTIVE)
2989 if (!event_filter_match(event))
2992 perf_pmu_disable(event->pmu);
2996 if (hwc->interrupts == MAX_INTERRUPTS) {
2997 hwc->interrupts = 0;
2998 perf_log_throttle(event, 1);
2999 event->pmu->start(event, 0);
3002 if (!event->attr.freq || !event->attr.sample_freq)
3006 * stop the event and update event->count
3008 event->pmu->stop(event, PERF_EF_UPDATE);
3010 now = local64_read(&event->count);
3011 delta = now - hwc->freq_count_stamp;
3012 hwc->freq_count_stamp = now;
3016 * reload only if value has changed
3017 * we have stopped the event so tell that
3018 * to perf_adjust_period() to avoid stopping it
3022 perf_adjust_period(event, period, delta, false);
3024 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3026 perf_pmu_enable(event->pmu);
3029 perf_pmu_enable(ctx->pmu);
3030 raw_spin_unlock(&ctx->lock);
3034 * Round-robin a context's events:
3036 static void rotate_ctx(struct perf_event_context *ctx)
3039 * Rotate the first entry last of non-pinned groups. Rotation might be
3040 * disabled by the inheritance code.
3042 if (!ctx->rotate_disable)
3043 list_rotate_left(&ctx->flexible_groups);
3046 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3048 struct perf_event_context *ctx = NULL;
3051 if (cpuctx->ctx.nr_events) {
3052 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3056 ctx = cpuctx->task_ctx;
3057 if (ctx && ctx->nr_events) {
3058 if (ctx->nr_events != ctx->nr_active)
3065 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3066 perf_pmu_disable(cpuctx->ctx.pmu);
3068 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3070 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3072 rotate_ctx(&cpuctx->ctx);
3076 perf_event_sched_in(cpuctx, ctx, current);
3078 perf_pmu_enable(cpuctx->ctx.pmu);
3079 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3085 #ifdef CONFIG_NO_HZ_FULL
3086 bool perf_event_can_stop_tick(void)
3088 if (atomic_read(&nr_freq_events) ||
3089 __this_cpu_read(perf_throttled_count))
3096 void perf_event_task_tick(void)
3098 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3099 struct perf_event_context *ctx, *tmp;
3102 WARN_ON(!irqs_disabled());
3104 __this_cpu_inc(perf_throttled_seq);
3105 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3107 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3108 perf_adjust_freq_unthr_context(ctx, throttled);
3111 static int event_enable_on_exec(struct perf_event *event,
3112 struct perf_event_context *ctx)
3114 if (!event->attr.enable_on_exec)
3117 event->attr.enable_on_exec = 0;
3118 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3121 __perf_event_mark_enabled(event);
3127 * Enable all of a task's events that have been marked enable-on-exec.
3128 * This expects task == current.
3130 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
3132 struct perf_event_context *clone_ctx = NULL;
3133 struct perf_event *event;
3134 unsigned long flags;
3138 local_irq_save(flags);
3139 if (!ctx || !ctx->nr_events)
3143 * We must ctxsw out cgroup events to avoid conflict
3144 * when invoking perf_task_event_sched_in() later on
3145 * in this function. Otherwise we end up trying to
3146 * ctxswin cgroup events which are already scheduled
3149 perf_cgroup_sched_out(current, NULL);
3151 raw_spin_lock(&ctx->lock);
3152 task_ctx_sched_out(ctx);
3154 list_for_each_entry(event, &ctx->event_list, event_entry) {
3155 ret = event_enable_on_exec(event, ctx);
3161 * Unclone this context if we enabled any event.
3164 clone_ctx = unclone_ctx(ctx);
3166 raw_spin_unlock(&ctx->lock);
3169 * Also calls ctxswin for cgroup events, if any:
3171 perf_event_context_sched_in(ctx, ctx->task);
3173 local_irq_restore(flags);
3179 void perf_event_exec(void)
3181 struct perf_event_context *ctx;
3185 for_each_task_context_nr(ctxn) {
3186 ctx = current->perf_event_ctxp[ctxn];
3190 perf_event_enable_on_exec(ctx);
3196 * Cross CPU call to read the hardware event
3198 static void __perf_event_read(void *info)
3200 struct perf_event *event = info;
3201 struct perf_event_context *ctx = event->ctx;
3202 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3205 * If this is a task context, we need to check whether it is
3206 * the current task context of this cpu. If not it has been
3207 * scheduled out before the smp call arrived. In that case
3208 * event->count would have been updated to a recent sample
3209 * when the event was scheduled out.
3211 if (ctx->task && cpuctx->task_ctx != ctx)
3214 raw_spin_lock(&ctx->lock);
3215 if (ctx->is_active) {
3216 update_context_time(ctx);
3217 update_cgrp_time_from_event(event);
3219 update_event_times(event);
3220 if (event->state == PERF_EVENT_STATE_ACTIVE)
3221 event->pmu->read(event);
3222 raw_spin_unlock(&ctx->lock);
3225 static inline u64 perf_event_count(struct perf_event *event)
3227 if (event->pmu->count)
3228 return event->pmu->count(event);
3230 return __perf_event_count(event);
3233 static u64 perf_event_read(struct perf_event *event)
3236 * If event is enabled and currently active on a CPU, update the
3237 * value in the event structure:
3239 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3240 smp_call_function_single(event->oncpu,
3241 __perf_event_read, event, 1);
3242 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3243 struct perf_event_context *ctx = event->ctx;
3244 unsigned long flags;
3246 raw_spin_lock_irqsave(&ctx->lock, flags);
3248 * may read while context is not active
3249 * (e.g., thread is blocked), in that case
3250 * we cannot update context time
3252 if (ctx->is_active) {
3253 update_context_time(ctx);
3254 update_cgrp_time_from_event(event);
3256 update_event_times(event);
3257 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3260 return perf_event_count(event);
3264 * Initialize the perf_event context in a task_struct:
3266 static void __perf_event_init_context(struct perf_event_context *ctx)
3268 raw_spin_lock_init(&ctx->lock);
3269 mutex_init(&ctx->mutex);
3270 INIT_LIST_HEAD(&ctx->active_ctx_list);
3271 INIT_LIST_HEAD(&ctx->pinned_groups);
3272 INIT_LIST_HEAD(&ctx->flexible_groups);
3273 INIT_LIST_HEAD(&ctx->event_list);
3274 atomic_set(&ctx->refcount, 1);
3275 INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3278 static struct perf_event_context *
3279 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3281 struct perf_event_context *ctx;
3283 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3287 __perf_event_init_context(ctx);
3290 get_task_struct(task);
3297 static struct task_struct *
3298 find_lively_task_by_vpid(pid_t vpid)
3300 struct task_struct *task;
3307 task = find_task_by_vpid(vpid);
3309 get_task_struct(task);
3313 return ERR_PTR(-ESRCH);
3315 /* Reuse ptrace permission checks for now. */
3317 if (!ptrace_may_access(task, PTRACE_MODE_READ))
3322 put_task_struct(task);
3323 return ERR_PTR(err);
3328 * Returns a matching context with refcount and pincount.
3330 static struct perf_event_context *
3331 find_get_context(struct pmu *pmu, struct task_struct *task,
3332 struct perf_event *event)
3334 struct perf_event_context *ctx, *clone_ctx = NULL;
3335 struct perf_cpu_context *cpuctx;
3336 void *task_ctx_data = NULL;
3337 unsigned long flags;
3339 int cpu = event->cpu;
3342 /* Must be root to operate on a CPU event: */
3343 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3344 return ERR_PTR(-EACCES);
3347 * We could be clever and allow to attach a event to an
3348 * offline CPU and activate it when the CPU comes up, but
3351 if (!cpu_online(cpu))
3352 return ERR_PTR(-ENODEV);
3354 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3363 ctxn = pmu->task_ctx_nr;
3367 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3368 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3369 if (!task_ctx_data) {
3376 ctx = perf_lock_task_context(task, ctxn, &flags);
3378 clone_ctx = unclone_ctx(ctx);
3381 if (task_ctx_data && !ctx->task_ctx_data) {
3382 ctx->task_ctx_data = task_ctx_data;
3383 task_ctx_data = NULL;
3385 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3390 ctx = alloc_perf_context(pmu, task);
3395 if (task_ctx_data) {
3396 ctx->task_ctx_data = task_ctx_data;
3397 task_ctx_data = NULL;
3401 mutex_lock(&task->perf_event_mutex);
3403 * If it has already passed perf_event_exit_task().
3404 * we must see PF_EXITING, it takes this mutex too.
3406 if (task->flags & PF_EXITING)
3408 else if (task->perf_event_ctxp[ctxn])
3413 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3415 mutex_unlock(&task->perf_event_mutex);
3417 if (unlikely(err)) {
3426 kfree(task_ctx_data);
3430 kfree(task_ctx_data);
3431 return ERR_PTR(err);
3434 static void perf_event_free_filter(struct perf_event *event);
3435 static void perf_event_free_bpf_prog(struct perf_event *event);
3437 static void free_event_rcu(struct rcu_head *head)
3439 struct perf_event *event;
3441 event = container_of(head, struct perf_event, rcu_head);
3443 put_pid_ns(event->ns);
3444 perf_event_free_filter(event);
3448 static void ring_buffer_attach(struct perf_event *event,
3449 struct ring_buffer *rb);
3451 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3456 if (is_cgroup_event(event))
3457 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3460 static void unaccount_event(struct perf_event *event)
3465 if (event->attach_state & PERF_ATTACH_TASK)
3466 static_key_slow_dec_deferred(&perf_sched_events);
3467 if (event->attr.mmap || event->attr.mmap_data)
3468 atomic_dec(&nr_mmap_events);
3469 if (event->attr.comm)
3470 atomic_dec(&nr_comm_events);
3471 if (event->attr.task)
3472 atomic_dec(&nr_task_events);
3473 if (event->attr.freq)
3474 atomic_dec(&nr_freq_events);
3475 if (is_cgroup_event(event))
3476 static_key_slow_dec_deferred(&perf_sched_events);
3477 if (has_branch_stack(event))
3478 static_key_slow_dec_deferred(&perf_sched_events);
3480 unaccount_event_cpu(event, event->cpu);
3484 * The following implement mutual exclusion of events on "exclusive" pmus
3485 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3486 * at a time, so we disallow creating events that might conflict, namely:
3488 * 1) cpu-wide events in the presence of per-task events,
3489 * 2) per-task events in the presence of cpu-wide events,
3490 * 3) two matching events on the same context.
3492 * The former two cases are handled in the allocation path (perf_event_alloc(),
3493 * __free_event()), the latter -- before the first perf_install_in_context().
3495 static int exclusive_event_init(struct perf_event *event)
3497 struct pmu *pmu = event->pmu;
3499 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3503 * Prevent co-existence of per-task and cpu-wide events on the
3504 * same exclusive pmu.
3506 * Negative pmu::exclusive_cnt means there are cpu-wide
3507 * events on this "exclusive" pmu, positive means there are
3510 * Since this is called in perf_event_alloc() path, event::ctx
3511 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3512 * to mean "per-task event", because unlike other attach states it
3513 * never gets cleared.
3515 if (event->attach_state & PERF_ATTACH_TASK) {
3516 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3519 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3526 static void exclusive_event_destroy(struct perf_event *event)
3528 struct pmu *pmu = event->pmu;
3530 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3533 /* see comment in exclusive_event_init() */
3534 if (event->attach_state & PERF_ATTACH_TASK)
3535 atomic_dec(&pmu->exclusive_cnt);
3537 atomic_inc(&pmu->exclusive_cnt);
3540 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3542 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3543 (e1->cpu == e2->cpu ||
3550 /* Called under the same ctx::mutex as perf_install_in_context() */
3551 static bool exclusive_event_installable(struct perf_event *event,
3552 struct perf_event_context *ctx)
3554 struct perf_event *iter_event;
3555 struct pmu *pmu = event->pmu;
3557 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3560 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3561 if (exclusive_event_match(iter_event, event))
3568 static void __free_event(struct perf_event *event)
3570 if (!event->parent) {
3571 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3572 put_callchain_buffers();
3575 perf_event_free_bpf_prog(event);
3578 event->destroy(event);
3581 put_ctx(event->ctx);
3584 exclusive_event_destroy(event);
3585 module_put(event->pmu->module);
3588 call_rcu(&event->rcu_head, free_event_rcu);
3591 static void _free_event(struct perf_event *event)
3593 irq_work_sync(&event->pending);
3595 unaccount_event(event);
3599 * Can happen when we close an event with re-directed output.
3601 * Since we have a 0 refcount, perf_mmap_close() will skip
3602 * over us; possibly making our ring_buffer_put() the last.
3604 mutex_lock(&event->mmap_mutex);
3605 ring_buffer_attach(event, NULL);
3606 mutex_unlock(&event->mmap_mutex);
3609 if (is_cgroup_event(event))
3610 perf_detach_cgroup(event);
3612 __free_event(event);
3616 * Used to free events which have a known refcount of 1, such as in error paths
3617 * where the event isn't exposed yet and inherited events.
3619 static void free_event(struct perf_event *event)
3621 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3622 "unexpected event refcount: %ld; ptr=%p\n",
3623 atomic_long_read(&event->refcount), event)) {
3624 /* leak to avoid use-after-free */
3632 * Remove user event from the owner task.
3634 static void perf_remove_from_owner(struct perf_event *event)
3636 struct task_struct *owner;
3639 owner = ACCESS_ONCE(event->owner);
3641 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3642 * !owner it means the list deletion is complete and we can indeed
3643 * free this event, otherwise we need to serialize on
3644 * owner->perf_event_mutex.
3646 smp_read_barrier_depends();
3649 * Since delayed_put_task_struct() also drops the last
3650 * task reference we can safely take a new reference
3651 * while holding the rcu_read_lock().
3653 get_task_struct(owner);
3659 * If we're here through perf_event_exit_task() we're already
3660 * holding ctx->mutex which would be an inversion wrt. the
3661 * normal lock order.
3663 * However we can safely take this lock because its the child
3666 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3669 * We have to re-check the event->owner field, if it is cleared
3670 * we raced with perf_event_exit_task(), acquiring the mutex
3671 * ensured they're done, and we can proceed with freeing the
3675 list_del_init(&event->owner_entry);
3676 mutex_unlock(&owner->perf_event_mutex);
3677 put_task_struct(owner);
3681 static void put_event(struct perf_event *event)
3683 struct perf_event_context *ctx;
3685 if (!atomic_long_dec_and_test(&event->refcount))
3688 if (!is_kernel_event(event))
3689 perf_remove_from_owner(event);
3692 * There are two ways this annotation is useful:
3694 * 1) there is a lock recursion from perf_event_exit_task
3695 * see the comment there.
3697 * 2) there is a lock-inversion with mmap_sem through
3698 * perf_event_read_group(), which takes faults while
3699 * holding ctx->mutex, however this is called after
3700 * the last filedesc died, so there is no possibility
3701 * to trigger the AB-BA case.
3703 ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3704 WARN_ON_ONCE(ctx->parent_ctx);
3705 perf_remove_from_context(event, true);
3706 perf_event_ctx_unlock(event, ctx);
3711 int perf_event_release_kernel(struct perf_event *event)
3716 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3719 * Called when the last reference to the file is gone.
3721 static int perf_release(struct inode *inode, struct file *file)
3723 put_event(file->private_data);
3728 * Remove all orphanes events from the context.
3730 static void orphans_remove_work(struct work_struct *work)
3732 struct perf_event_context *ctx;
3733 struct perf_event *event, *tmp;
3735 ctx = container_of(work, struct perf_event_context,
3736 orphans_remove.work);
3738 mutex_lock(&ctx->mutex);
3739 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3740 struct perf_event *parent_event = event->parent;
3742 if (!is_orphaned_child(event))
3745 perf_remove_from_context(event, true);
3747 mutex_lock(&parent_event->child_mutex);
3748 list_del_init(&event->child_list);
3749 mutex_unlock(&parent_event->child_mutex);
3752 put_event(parent_event);
3755 raw_spin_lock_irq(&ctx->lock);
3756 ctx->orphans_remove_sched = false;
3757 raw_spin_unlock_irq(&ctx->lock);
3758 mutex_unlock(&ctx->mutex);
3763 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3765 struct perf_event *child;
3771 mutex_lock(&event->child_mutex);
3772 total += perf_event_read(event);
3773 *enabled += event->total_time_enabled +
3774 atomic64_read(&event->child_total_time_enabled);
3775 *running += event->total_time_running +
3776 atomic64_read(&event->child_total_time_running);
3778 list_for_each_entry(child, &event->child_list, child_list) {
3779 total += perf_event_read(child);
3780 *enabled += child->total_time_enabled;
3781 *running += child->total_time_running;
3783 mutex_unlock(&event->child_mutex);
3787 EXPORT_SYMBOL_GPL(perf_event_read_value);
3789 static int perf_event_read_group(struct perf_event *event,
3790 u64 read_format, char __user *buf)
3792 struct perf_event *leader = event->group_leader, *sub;
3793 struct perf_event_context *ctx = leader->ctx;
3794 int n = 0, size = 0, ret;
3795 u64 count, enabled, running;
3798 lockdep_assert_held(&ctx->mutex);
3800 count = perf_event_read_value(leader, &enabled, &running);
3802 values[n++] = 1 + leader->nr_siblings;
3803 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3804 values[n++] = enabled;
3805 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3806 values[n++] = running;
3807 values[n++] = count;
3808 if (read_format & PERF_FORMAT_ID)
3809 values[n++] = primary_event_id(leader);
3811 size = n * sizeof(u64);
3813 if (copy_to_user(buf, values, size))
3818 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3821 values[n++] = perf_event_read_value(sub, &enabled, &running);
3822 if (read_format & PERF_FORMAT_ID)
3823 values[n++] = primary_event_id(sub);
3825 size = n * sizeof(u64);
3827 if (copy_to_user(buf + ret, values, size)) {
3837 static int perf_event_read_one(struct perf_event *event,
3838 u64 read_format, char __user *buf)
3840 u64 enabled, running;
3844 values[n++] = perf_event_read_value(event, &enabled, &running);
3845 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3846 values[n++] = enabled;
3847 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3848 values[n++] = running;
3849 if (read_format & PERF_FORMAT_ID)
3850 values[n++] = primary_event_id(event);
3852 if (copy_to_user(buf, values, n * sizeof(u64)))
3855 return n * sizeof(u64);
3858 static bool is_event_hup(struct perf_event *event)
3862 if (event->state != PERF_EVENT_STATE_EXIT)
3865 mutex_lock(&event->child_mutex);
3866 no_children = list_empty(&event->child_list);
3867 mutex_unlock(&event->child_mutex);
3872 * Read the performance event - simple non blocking version for now
3875 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3877 u64 read_format = event->attr.read_format;
3881 * Return end-of-file for a read on a event that is in
3882 * error state (i.e. because it was pinned but it couldn't be
3883 * scheduled on to the CPU at some point).
3885 if (event->state == PERF_EVENT_STATE_ERROR)
3888 if (count < event->read_size)
3891 WARN_ON_ONCE(event->ctx->parent_ctx);
3892 if (read_format & PERF_FORMAT_GROUP)
3893 ret = perf_event_read_group(event, read_format, buf);
3895 ret = perf_event_read_one(event, read_format, buf);
3901 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3903 struct perf_event *event = file->private_data;
3904 struct perf_event_context *ctx;
3907 ctx = perf_event_ctx_lock(event);
3908 ret = perf_read_hw(event, buf, count);
3909 perf_event_ctx_unlock(event, ctx);
3914 static unsigned int perf_poll(struct file *file, poll_table *wait)
3916 struct perf_event *event = file->private_data;
3917 struct ring_buffer *rb;
3918 unsigned int events = POLLHUP;
3920 poll_wait(file, &event->waitq, wait);
3922 if (is_event_hup(event))
3926 * Pin the event->rb by taking event->mmap_mutex; otherwise
3927 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3929 mutex_lock(&event->mmap_mutex);
3932 events = atomic_xchg(&rb->poll, 0);
3933 mutex_unlock(&event->mmap_mutex);
3937 static void _perf_event_reset(struct perf_event *event)
3939 (void)perf_event_read(event);
3940 local64_set(&event->count, 0);
3941 perf_event_update_userpage(event);
3945 * Holding the top-level event's child_mutex means that any
3946 * descendant process that has inherited this event will block
3947 * in sync_child_event if it goes to exit, thus satisfying the
3948 * task existence requirements of perf_event_enable/disable.
3950 static void perf_event_for_each_child(struct perf_event *event,
3951 void (*func)(struct perf_event *))
3953 struct perf_event *child;
3955 WARN_ON_ONCE(event->ctx->parent_ctx);
3957 mutex_lock(&event->child_mutex);
3959 list_for_each_entry(child, &event->child_list, child_list)
3961 mutex_unlock(&event->child_mutex);
3964 static void perf_event_for_each(struct perf_event *event,
3965 void (*func)(struct perf_event *))
3967 struct perf_event_context *ctx = event->ctx;
3968 struct perf_event *sibling;
3970 lockdep_assert_held(&ctx->mutex);
3972 event = event->group_leader;
3974 perf_event_for_each_child(event, func);
3975 list_for_each_entry(sibling, &event->sibling_list, group_entry)
3976 perf_event_for_each_child(sibling, func);
3979 struct period_event {
3980 struct perf_event *event;
3984 static int __perf_event_period(void *info)
3986 struct period_event *pe = info;
3987 struct perf_event *event = pe->event;
3988 struct perf_event_context *ctx = event->ctx;
3989 u64 value = pe->value;
3992 raw_spin_lock(&ctx->lock);
3993 if (event->attr.freq) {
3994 event->attr.sample_freq = value;
3996 event->attr.sample_period = value;
3997 event->hw.sample_period = value;
4000 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4002 perf_pmu_disable(ctx->pmu);
4003 event->pmu->stop(event, PERF_EF_UPDATE);
4006 local64_set(&event->hw.period_left, 0);
4009 event->pmu->start(event, PERF_EF_RELOAD);
4010 perf_pmu_enable(ctx->pmu);
4012 raw_spin_unlock(&ctx->lock);
4017 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4019 struct period_event pe = { .event = event, };
4020 struct perf_event_context *ctx = event->ctx;
4021 struct task_struct *task;
4024 if (!is_sampling_event(event))
4027 if (copy_from_user(&value, arg, sizeof(value)))
4033 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4040 cpu_function_call(event->cpu, __perf_event_period, &pe);
4045 if (!task_function_call(task, __perf_event_period, &pe))
4048 raw_spin_lock_irq(&ctx->lock);
4049 if (ctx->is_active) {
4050 raw_spin_unlock_irq(&ctx->lock);
4055 __perf_event_period(&pe);
4056 raw_spin_unlock_irq(&ctx->lock);
4061 static const struct file_operations perf_fops;
4063 static inline int perf_fget_light(int fd, struct fd *p)
4065 struct fd f = fdget(fd);
4069 if (f.file->f_op != &perf_fops) {
4077 static int perf_event_set_output(struct perf_event *event,
4078 struct perf_event *output_event);
4079 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4080 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4082 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4084 void (*func)(struct perf_event *);
4088 case PERF_EVENT_IOC_ENABLE:
4089 func = _perf_event_enable;
4091 case PERF_EVENT_IOC_DISABLE:
4092 func = _perf_event_disable;
4094 case PERF_EVENT_IOC_RESET:
4095 func = _perf_event_reset;
4098 case PERF_EVENT_IOC_REFRESH:
4099 return _perf_event_refresh(event, arg);
4101 case PERF_EVENT_IOC_PERIOD:
4102 return perf_event_period(event, (u64 __user *)arg);
4104 case PERF_EVENT_IOC_ID:
4106 u64 id = primary_event_id(event);
4108 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4113 case PERF_EVENT_IOC_SET_OUTPUT:
4117 struct perf_event *output_event;
4119 ret = perf_fget_light(arg, &output);
4122 output_event = output.file->private_data;
4123 ret = perf_event_set_output(event, output_event);
4126 ret = perf_event_set_output(event, NULL);
4131 case PERF_EVENT_IOC_SET_FILTER:
4132 return perf_event_set_filter(event, (void __user *)arg);
4134 case PERF_EVENT_IOC_SET_BPF:
4135 return perf_event_set_bpf_prog(event, arg);
4141 if (flags & PERF_IOC_FLAG_GROUP)
4142 perf_event_for_each(event, func);
4144 perf_event_for_each_child(event, func);
4149 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4151 struct perf_event *event = file->private_data;
4152 struct perf_event_context *ctx;
4155 ctx = perf_event_ctx_lock(event);
4156 ret = _perf_ioctl(event, cmd, arg);
4157 perf_event_ctx_unlock(event, ctx);
4162 #ifdef CONFIG_COMPAT
4163 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4166 switch (_IOC_NR(cmd)) {
4167 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4168 case _IOC_NR(PERF_EVENT_IOC_ID):
4169 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4170 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4171 cmd &= ~IOCSIZE_MASK;
4172 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4176 return perf_ioctl(file, cmd, arg);
4179 # define perf_compat_ioctl NULL
4182 int perf_event_task_enable(void)
4184 struct perf_event_context *ctx;
4185 struct perf_event *event;
4187 mutex_lock(¤t->perf_event_mutex);
4188 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4189 ctx = perf_event_ctx_lock(event);
4190 perf_event_for_each_child(event, _perf_event_enable);
4191 perf_event_ctx_unlock(event, ctx);
4193 mutex_unlock(¤t->perf_event_mutex);
4198 int perf_event_task_disable(void)
4200 struct perf_event_context *ctx;
4201 struct perf_event *event;
4203 mutex_lock(¤t->perf_event_mutex);
4204 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4205 ctx = perf_event_ctx_lock(event);
4206 perf_event_for_each_child(event, _perf_event_disable);
4207 perf_event_ctx_unlock(event, ctx);
4209 mutex_unlock(¤t->perf_event_mutex);
4214 static int perf_event_index(struct perf_event *event)
4216 if (event->hw.state & PERF_HES_STOPPED)
4219 if (event->state != PERF_EVENT_STATE_ACTIVE)
4222 return event->pmu->event_idx(event);
4225 static void calc_timer_values(struct perf_event *event,
4232 *now = perf_clock();
4233 ctx_time = event->shadow_ctx_time + *now;
4234 *enabled = ctx_time - event->tstamp_enabled;
4235 *running = ctx_time - event->tstamp_running;
4238 static void perf_event_init_userpage(struct perf_event *event)
4240 struct perf_event_mmap_page *userpg;
4241 struct ring_buffer *rb;
4244 rb = rcu_dereference(event->rb);
4248 userpg = rb->user_page;
4250 /* Allow new userspace to detect that bit 0 is deprecated */
4251 userpg->cap_bit0_is_deprecated = 1;
4252 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4253 userpg->data_offset = PAGE_SIZE;
4254 userpg->data_size = perf_data_size(rb);
4260 void __weak arch_perf_update_userpage(
4261 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4266 * Callers need to ensure there can be no nesting of this function, otherwise
4267 * the seqlock logic goes bad. We can not serialize this because the arch
4268 * code calls this from NMI context.
4270 void perf_event_update_userpage(struct perf_event *event)
4272 struct perf_event_mmap_page *userpg;
4273 struct ring_buffer *rb;
4274 u64 enabled, running, now;
4277 rb = rcu_dereference(event->rb);
4282 * compute total_time_enabled, total_time_running
4283 * based on snapshot values taken when the event
4284 * was last scheduled in.
4286 * we cannot simply called update_context_time()
4287 * because of locking issue as we can be called in
4290 calc_timer_values(event, &now, &enabled, &running);
4292 userpg = rb->user_page;
4294 * Disable preemption so as to not let the corresponding user-space
4295 * spin too long if we get preempted.
4300 userpg->index = perf_event_index(event);
4301 userpg->offset = perf_event_count(event);
4303 userpg->offset -= local64_read(&event->hw.prev_count);
4305 userpg->time_enabled = enabled +
4306 atomic64_read(&event->child_total_time_enabled);
4308 userpg->time_running = running +
4309 atomic64_read(&event->child_total_time_running);
4311 arch_perf_update_userpage(event, userpg, now);
4320 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4322 struct perf_event *event = vma->vm_file->private_data;
4323 struct ring_buffer *rb;
4324 int ret = VM_FAULT_SIGBUS;
4326 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4327 if (vmf->pgoff == 0)
4333 rb = rcu_dereference(event->rb);
4337 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4340 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4344 get_page(vmf->page);
4345 vmf->page->mapping = vma->vm_file->f_mapping;
4346 vmf->page->index = vmf->pgoff;
4355 static void ring_buffer_attach(struct perf_event *event,
4356 struct ring_buffer *rb)
4358 struct ring_buffer *old_rb = NULL;
4359 unsigned long flags;
4363 * Should be impossible, we set this when removing
4364 * event->rb_entry and wait/clear when adding event->rb_entry.
4366 WARN_ON_ONCE(event->rcu_pending);
4369 spin_lock_irqsave(&old_rb->event_lock, flags);
4370 list_del_rcu(&event->rb_entry);
4371 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4373 event->rcu_batches = get_state_synchronize_rcu();
4374 event->rcu_pending = 1;
4378 if (event->rcu_pending) {
4379 cond_synchronize_rcu(event->rcu_batches);
4380 event->rcu_pending = 0;
4383 spin_lock_irqsave(&rb->event_lock, flags);
4384 list_add_rcu(&event->rb_entry, &rb->event_list);
4385 spin_unlock_irqrestore(&rb->event_lock, flags);
4388 rcu_assign_pointer(event->rb, rb);
4391 ring_buffer_put(old_rb);
4393 * Since we detached before setting the new rb, so that we
4394 * could attach the new rb, we could have missed a wakeup.
4397 wake_up_all(&event->waitq);
4401 static void ring_buffer_wakeup(struct perf_event *event)
4403 struct ring_buffer *rb;
4406 rb = rcu_dereference(event->rb);
4408 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4409 wake_up_all(&event->waitq);
4414 static void rb_free_rcu(struct rcu_head *rcu_head)
4416 struct ring_buffer *rb;
4418 rb = container_of(rcu_head, struct ring_buffer, rcu_head);
4422 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4424 struct ring_buffer *rb;
4427 rb = rcu_dereference(event->rb);
4429 if (!atomic_inc_not_zero(&rb->refcount))
4437 void ring_buffer_put(struct ring_buffer *rb)
4439 if (!atomic_dec_and_test(&rb->refcount))
4442 WARN_ON_ONCE(!list_empty(&rb->event_list));
4444 call_rcu(&rb->rcu_head, rb_free_rcu);
4447 static void perf_mmap_open(struct vm_area_struct *vma)
4449 struct perf_event *event = vma->vm_file->private_data;
4451 atomic_inc(&event->mmap_count);
4452 atomic_inc(&event->rb->mmap_count);
4455 atomic_inc(&event->rb->aux_mmap_count);
4457 if (event->pmu->event_mapped)
4458 event->pmu->event_mapped(event);
4462 * A buffer can be mmap()ed multiple times; either directly through the same
4463 * event, or through other events by use of perf_event_set_output().
4465 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4466 * the buffer here, where we still have a VM context. This means we need
4467 * to detach all events redirecting to us.
4469 static void perf_mmap_close(struct vm_area_struct *vma)
4471 struct perf_event *event = vma->vm_file->private_data;
4473 struct ring_buffer *rb = ring_buffer_get(event);
4474 struct user_struct *mmap_user = rb->mmap_user;
4475 int mmap_locked = rb->mmap_locked;
4476 unsigned long size = perf_data_size(rb);
4478 if (event->pmu->event_unmapped)
4479 event->pmu->event_unmapped(event);
4482 * rb->aux_mmap_count will always drop before rb->mmap_count and
4483 * event->mmap_count, so it is ok to use event->mmap_mutex to
4484 * serialize with perf_mmap here.
4486 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4487 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4488 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4489 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4492 mutex_unlock(&event->mmap_mutex);
4495 atomic_dec(&rb->mmap_count);
4497 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4500 ring_buffer_attach(event, NULL);
4501 mutex_unlock(&event->mmap_mutex);
4503 /* If there's still other mmap()s of this buffer, we're done. */
4504 if (atomic_read(&rb->mmap_count))
4508 * No other mmap()s, detach from all other events that might redirect
4509 * into the now unreachable buffer. Somewhat complicated by the
4510 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4514 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4515 if (!atomic_long_inc_not_zero(&event->refcount)) {
4517 * This event is en-route to free_event() which will
4518 * detach it and remove it from the list.
4524 mutex_lock(&event->mmap_mutex);
4526 * Check we didn't race with perf_event_set_output() which can
4527 * swizzle the rb from under us while we were waiting to
4528 * acquire mmap_mutex.
4530 * If we find a different rb; ignore this event, a next
4531 * iteration will no longer find it on the list. We have to
4532 * still restart the iteration to make sure we're not now
4533 * iterating the wrong list.
4535 if (event->rb == rb)
4536 ring_buffer_attach(event, NULL);
4538 mutex_unlock(&event->mmap_mutex);
4542 * Restart the iteration; either we're on the wrong list or
4543 * destroyed its integrity by doing a deletion.
4550 * It could be there's still a few 0-ref events on the list; they'll
4551 * get cleaned up by free_event() -- they'll also still have their
4552 * ref on the rb and will free it whenever they are done with it.
4554 * Aside from that, this buffer is 'fully' detached and unmapped,
4555 * undo the VM accounting.
4558 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4559 vma->vm_mm->pinned_vm -= mmap_locked;
4560 free_uid(mmap_user);
4563 ring_buffer_put(rb); /* could be last */
4566 static const struct vm_operations_struct perf_mmap_vmops = {
4567 .open = perf_mmap_open,
4568 .close = perf_mmap_close, /* non mergable */
4569 .fault = perf_mmap_fault,
4570 .page_mkwrite = perf_mmap_fault,
4573 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4575 struct perf_event *event = file->private_data;
4576 unsigned long user_locked, user_lock_limit;
4577 struct user_struct *user = current_user();
4578 unsigned long locked, lock_limit;
4579 struct ring_buffer *rb = NULL;
4580 unsigned long vma_size;
4581 unsigned long nr_pages;
4582 long user_extra = 0, extra = 0;
4583 int ret = 0, flags = 0;
4586 * Don't allow mmap() of inherited per-task counters. This would
4587 * create a performance issue due to all children writing to the
4590 if (event->cpu == -1 && event->attr.inherit)
4593 if (!(vma->vm_flags & VM_SHARED))
4596 vma_size = vma->vm_end - vma->vm_start;
4598 if (vma->vm_pgoff == 0) {
4599 nr_pages = (vma_size / PAGE_SIZE) - 1;
4602 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4603 * mapped, all subsequent mappings should have the same size
4604 * and offset. Must be above the normal perf buffer.
4606 u64 aux_offset, aux_size;
4611 nr_pages = vma_size / PAGE_SIZE;
4613 mutex_lock(&event->mmap_mutex);
4620 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4621 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4623 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4626 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4629 /* already mapped with a different offset */
4630 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4633 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4636 /* already mapped with a different size */
4637 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4640 if (!is_power_of_2(nr_pages))
4643 if (!atomic_inc_not_zero(&rb->mmap_count))
4646 if (rb_has_aux(rb)) {
4647 atomic_inc(&rb->aux_mmap_count);
4652 atomic_set(&rb->aux_mmap_count, 1);
4653 user_extra = nr_pages;
4659 * If we have rb pages ensure they're a power-of-two number, so we
4660 * can do bitmasks instead of modulo.
4662 if (nr_pages != 0 && !is_power_of_2(nr_pages))
4665 if (vma_size != PAGE_SIZE * (1 + nr_pages))
4668 WARN_ON_ONCE(event->ctx->parent_ctx);
4670 mutex_lock(&event->mmap_mutex);
4672 if (event->rb->nr_pages != nr_pages) {
4677 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4679 * Raced against perf_mmap_close() through
4680 * perf_event_set_output(). Try again, hope for better
4683 mutex_unlock(&event->mmap_mutex);
4690 user_extra = nr_pages + 1;
4693 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4696 * Increase the limit linearly with more CPUs:
4698 user_lock_limit *= num_online_cpus();
4700 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4702 if (user_locked > user_lock_limit)
4703 extra = user_locked - user_lock_limit;
4705 lock_limit = rlimit(RLIMIT_MEMLOCK);
4706 lock_limit >>= PAGE_SHIFT;
4707 locked = vma->vm_mm->pinned_vm + extra;
4709 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4710 !capable(CAP_IPC_LOCK)) {
4715 WARN_ON(!rb && event->rb);
4717 if (vma->vm_flags & VM_WRITE)
4718 flags |= RING_BUFFER_WRITABLE;
4721 rb = rb_alloc(nr_pages,
4722 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4730 atomic_set(&rb->mmap_count, 1);
4731 rb->mmap_user = get_current_user();
4732 rb->mmap_locked = extra;
4734 ring_buffer_attach(event, rb);
4736 perf_event_init_userpage(event);
4737 perf_event_update_userpage(event);
4739 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4740 event->attr.aux_watermark, flags);
4742 rb->aux_mmap_locked = extra;
4747 atomic_long_add(user_extra, &user->locked_vm);
4748 vma->vm_mm->pinned_vm += extra;
4750 atomic_inc(&event->mmap_count);
4752 atomic_dec(&rb->mmap_count);
4755 mutex_unlock(&event->mmap_mutex);
4758 * Since pinned accounting is per vm we cannot allow fork() to copy our
4761 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4762 vma->vm_ops = &perf_mmap_vmops;
4764 if (event->pmu->event_mapped)
4765 event->pmu->event_mapped(event);
4770 static int perf_fasync(int fd, struct file *filp, int on)
4772 struct inode *inode = file_inode(filp);
4773 struct perf_event *event = filp->private_data;
4776 mutex_lock(&inode->i_mutex);
4777 retval = fasync_helper(fd, filp, on, &event->fasync);
4778 mutex_unlock(&inode->i_mutex);
4786 static const struct file_operations perf_fops = {
4787 .llseek = no_llseek,
4788 .release = perf_release,
4791 .unlocked_ioctl = perf_ioctl,
4792 .compat_ioctl = perf_compat_ioctl,
4794 .fasync = perf_fasync,
4800 * If there's data, ensure we set the poll() state and publish everything
4801 * to user-space before waking everybody up.
4804 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4806 /* only the parent has fasync state */
4808 event = event->parent;
4809 return &event->fasync;
4812 void perf_event_wakeup(struct perf_event *event)
4814 ring_buffer_wakeup(event);
4816 if (event->pending_kill) {
4817 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
4818 event->pending_kill = 0;
4822 static void perf_pending_event(struct irq_work *entry)
4824 struct perf_event *event = container_of(entry,
4825 struct perf_event, pending);
4828 rctx = perf_swevent_get_recursion_context();
4830 * If we 'fail' here, that's OK, it means recursion is already disabled
4831 * and we won't recurse 'further'.
4834 if (event->pending_disable) {
4835 event->pending_disable = 0;
4836 __perf_event_disable(event);
4839 if (event->pending_wakeup) {
4840 event->pending_wakeup = 0;
4841 perf_event_wakeup(event);
4845 perf_swevent_put_recursion_context(rctx);
4849 * We assume there is only KVM supporting the callbacks.
4850 * Later on, we might change it to a list if there is
4851 * another virtualization implementation supporting the callbacks.
4853 struct perf_guest_info_callbacks *perf_guest_cbs;
4855 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4857 perf_guest_cbs = cbs;
4860 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4862 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4864 perf_guest_cbs = NULL;
4867 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4870 perf_output_sample_regs(struct perf_output_handle *handle,
4871 struct pt_regs *regs, u64 mask)
4875 for_each_set_bit(bit, (const unsigned long *) &mask,
4876 sizeof(mask) * BITS_PER_BYTE) {
4879 val = perf_reg_value(regs, bit);
4880 perf_output_put(handle, val);
4884 static void perf_sample_regs_user(struct perf_regs *regs_user,
4885 struct pt_regs *regs,
4886 struct pt_regs *regs_user_copy)
4888 if (user_mode(regs)) {
4889 regs_user->abi = perf_reg_abi(current);
4890 regs_user->regs = regs;
4891 } else if (current->mm) {
4892 perf_get_regs_user(regs_user, regs, regs_user_copy);
4894 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
4895 regs_user->regs = NULL;
4899 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
4900 struct pt_regs *regs)
4902 regs_intr->regs = regs;
4903 regs_intr->abi = perf_reg_abi(current);
4908 * Get remaining task size from user stack pointer.
4910 * It'd be better to take stack vma map and limit this more
4911 * precisly, but there's no way to get it safely under interrupt,
4912 * so using TASK_SIZE as limit.
4914 static u64 perf_ustack_task_size(struct pt_regs *regs)
4916 unsigned long addr = perf_user_stack_pointer(regs);
4918 if (!addr || addr >= TASK_SIZE)
4921 return TASK_SIZE - addr;
4925 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4926 struct pt_regs *regs)
4930 /* No regs, no stack pointer, no dump. */
4935 * Check if we fit in with the requested stack size into the:
4937 * If we don't, we limit the size to the TASK_SIZE.
4939 * - remaining sample size
4940 * If we don't, we customize the stack size to
4941 * fit in to the remaining sample size.
4944 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4945 stack_size = min(stack_size, (u16) task_size);
4947 /* Current header size plus static size and dynamic size. */
4948 header_size += 2 * sizeof(u64);
4950 /* Do we fit in with the current stack dump size? */
4951 if ((u16) (header_size + stack_size) < header_size) {
4953 * If we overflow the maximum size for the sample,
4954 * we customize the stack dump size to fit in.
4956 stack_size = USHRT_MAX - header_size - sizeof(u64);
4957 stack_size = round_up(stack_size, sizeof(u64));
4964 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4965 struct pt_regs *regs)
4967 /* Case of a kernel thread, nothing to dump */
4970 perf_output_put(handle, size);
4979 * - the size requested by user or the best one we can fit
4980 * in to the sample max size
4982 * - user stack dump data
4984 * - the actual dumped size
4988 perf_output_put(handle, dump_size);
4991 sp = perf_user_stack_pointer(regs);
4992 rem = __output_copy_user(handle, (void *) sp, dump_size);
4993 dyn_size = dump_size - rem;
4995 perf_output_skip(handle, rem);
4998 perf_output_put(handle, dyn_size);
5002 static void __perf_event_header__init_id(struct perf_event_header *header,
5003 struct perf_sample_data *data,
5004 struct perf_event *event)
5006 u64 sample_type = event->attr.sample_type;
5008 data->type = sample_type;
5009 header->size += event->id_header_size;
5011 if (sample_type & PERF_SAMPLE_TID) {
5012 /* namespace issues */
5013 data->tid_entry.pid = perf_event_pid(event, current);
5014 data->tid_entry.tid = perf_event_tid(event, current);
5017 if (sample_type & PERF_SAMPLE_TIME)
5018 data->time = perf_event_clock(event);
5020 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5021 data->id = primary_event_id(event);
5023 if (sample_type & PERF_SAMPLE_STREAM_ID)
5024 data->stream_id = event->id;
5026 if (sample_type & PERF_SAMPLE_CPU) {
5027 data->cpu_entry.cpu = raw_smp_processor_id();
5028 data->cpu_entry.reserved = 0;
5032 void perf_event_header__init_id(struct perf_event_header *header,
5033 struct perf_sample_data *data,
5034 struct perf_event *event)
5036 if (event->attr.sample_id_all)
5037 __perf_event_header__init_id(header, data, event);
5040 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5041 struct perf_sample_data *data)
5043 u64 sample_type = data->type;
5045 if (sample_type & PERF_SAMPLE_TID)
5046 perf_output_put(handle, data->tid_entry);
5048 if (sample_type & PERF_SAMPLE_TIME)
5049 perf_output_put(handle, data->time);
5051 if (sample_type & PERF_SAMPLE_ID)
5052 perf_output_put(handle, data->id);
5054 if (sample_type & PERF_SAMPLE_STREAM_ID)
5055 perf_output_put(handle, data->stream_id);
5057 if (sample_type & PERF_SAMPLE_CPU)
5058 perf_output_put(handle, data->cpu_entry);
5060 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5061 perf_output_put(handle, data->id);
5064 void perf_event__output_id_sample(struct perf_event *event,
5065 struct perf_output_handle *handle,
5066 struct perf_sample_data *sample)
5068 if (event->attr.sample_id_all)
5069 __perf_event__output_id_sample(handle, sample);
5072 static void perf_output_read_one(struct perf_output_handle *handle,
5073 struct perf_event *event,
5074 u64 enabled, u64 running)
5076 u64 read_format = event->attr.read_format;
5080 values[n++] = perf_event_count(event);
5081 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5082 values[n++] = enabled +
5083 atomic64_read(&event->child_total_time_enabled);
5085 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5086 values[n++] = running +
5087 atomic64_read(&event->child_total_time_running);
5089 if (read_format & PERF_FORMAT_ID)
5090 values[n++] = primary_event_id(event);
5092 __output_copy(handle, values, n * sizeof(u64));
5096 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5098 static void perf_output_read_group(struct perf_output_handle *handle,
5099 struct perf_event *event,
5100 u64 enabled, u64 running)
5102 struct perf_event *leader = event->group_leader, *sub;
5103 u64 read_format = event->attr.read_format;
5107 values[n++] = 1 + leader->nr_siblings;
5109 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5110 values[n++] = enabled;
5112 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5113 values[n++] = running;
5115 if (leader != event)
5116 leader->pmu->read(leader);
5118 values[n++] = perf_event_count(leader);
5119 if (read_format & PERF_FORMAT_ID)
5120 values[n++] = primary_event_id(leader);
5122 __output_copy(handle, values, n * sizeof(u64));
5124 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5127 if ((sub != event) &&
5128 (sub->state == PERF_EVENT_STATE_ACTIVE))
5129 sub->pmu->read(sub);
5131 values[n++] = perf_event_count(sub);
5132 if (read_format & PERF_FORMAT_ID)
5133 values[n++] = primary_event_id(sub);
5135 __output_copy(handle, values, n * sizeof(u64));
5139 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5140 PERF_FORMAT_TOTAL_TIME_RUNNING)
5142 static void perf_output_read(struct perf_output_handle *handle,
5143 struct perf_event *event)
5145 u64 enabled = 0, running = 0, now;
5146 u64 read_format = event->attr.read_format;
5149 * compute total_time_enabled, total_time_running
5150 * based on snapshot values taken when the event
5151 * was last scheduled in.
5153 * we cannot simply called update_context_time()
5154 * because of locking issue as we are called in
5157 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5158 calc_timer_values(event, &now, &enabled, &running);
5160 if (event->attr.read_format & PERF_FORMAT_GROUP)
5161 perf_output_read_group(handle, event, enabled, running);
5163 perf_output_read_one(handle, event, enabled, running);
5166 void perf_output_sample(struct perf_output_handle *handle,
5167 struct perf_event_header *header,
5168 struct perf_sample_data *data,
5169 struct perf_event *event)
5171 u64 sample_type = data->type;
5173 perf_output_put(handle, *header);
5175 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5176 perf_output_put(handle, data->id);
5178 if (sample_type & PERF_SAMPLE_IP)
5179 perf_output_put(handle, data->ip);
5181 if (sample_type & PERF_SAMPLE_TID)
5182 perf_output_put(handle, data->tid_entry);
5184 if (sample_type & PERF_SAMPLE_TIME)
5185 perf_output_put(handle, data->time);
5187 if (sample_type & PERF_SAMPLE_ADDR)
5188 perf_output_put(handle, data->addr);
5190 if (sample_type & PERF_SAMPLE_ID)
5191 perf_output_put(handle, data->id);
5193 if (sample_type & PERF_SAMPLE_STREAM_ID)
5194 perf_output_put(handle, data->stream_id);
5196 if (sample_type & PERF_SAMPLE_CPU)
5197 perf_output_put(handle, data->cpu_entry);
5199 if (sample_type & PERF_SAMPLE_PERIOD)
5200 perf_output_put(handle, data->period);
5202 if (sample_type & PERF_SAMPLE_READ)
5203 perf_output_read(handle, event);
5205 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5206 if (data->callchain) {
5209 if (data->callchain)
5210 size += data->callchain->nr;
5212 size *= sizeof(u64);
5214 __output_copy(handle, data->callchain, size);
5217 perf_output_put(handle, nr);
5221 if (sample_type & PERF_SAMPLE_RAW) {
5223 perf_output_put(handle, data->raw->size);
5224 __output_copy(handle, data->raw->data,
5231 .size = sizeof(u32),
5234 perf_output_put(handle, raw);
5238 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5239 if (data->br_stack) {
5242 size = data->br_stack->nr
5243 * sizeof(struct perf_branch_entry);
5245 perf_output_put(handle, data->br_stack->nr);
5246 perf_output_copy(handle, data->br_stack->entries, size);
5249 * we always store at least the value of nr
5252 perf_output_put(handle, nr);
5256 if (sample_type & PERF_SAMPLE_REGS_USER) {
5257 u64 abi = data->regs_user.abi;
5260 * If there are no regs to dump, notice it through
5261 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5263 perf_output_put(handle, abi);
5266 u64 mask = event->attr.sample_regs_user;
5267 perf_output_sample_regs(handle,
5268 data->regs_user.regs,
5273 if (sample_type & PERF_SAMPLE_STACK_USER) {
5274 perf_output_sample_ustack(handle,
5275 data->stack_user_size,
5276 data->regs_user.regs);
5279 if (sample_type & PERF_SAMPLE_WEIGHT)
5280 perf_output_put(handle, data->weight);
5282 if (sample_type & PERF_SAMPLE_DATA_SRC)
5283 perf_output_put(handle, data->data_src.val);
5285 if (sample_type & PERF_SAMPLE_TRANSACTION)
5286 perf_output_put(handle, data->txn);
5288 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5289 u64 abi = data->regs_intr.abi;
5291 * If there are no regs to dump, notice it through
5292 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5294 perf_output_put(handle, abi);
5297 u64 mask = event->attr.sample_regs_intr;
5299 perf_output_sample_regs(handle,
5300 data->regs_intr.regs,
5305 if (!event->attr.watermark) {
5306 int wakeup_events = event->attr.wakeup_events;
5308 if (wakeup_events) {
5309 struct ring_buffer *rb = handle->rb;
5310 int events = local_inc_return(&rb->events);
5312 if (events >= wakeup_events) {
5313 local_sub(wakeup_events, &rb->events);
5314 local_inc(&rb->wakeup);
5320 void perf_prepare_sample(struct perf_event_header *header,
5321 struct perf_sample_data *data,
5322 struct perf_event *event,
5323 struct pt_regs *regs)
5325 u64 sample_type = event->attr.sample_type;
5327 header->type = PERF_RECORD_SAMPLE;
5328 header->size = sizeof(*header) + event->header_size;
5331 header->misc |= perf_misc_flags(regs);
5333 __perf_event_header__init_id(header, data, event);
5335 if (sample_type & PERF_SAMPLE_IP)
5336 data->ip = perf_instruction_pointer(regs);
5338 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5341 data->callchain = perf_callchain(event, regs);
5343 if (data->callchain)
5344 size += data->callchain->nr;
5346 header->size += size * sizeof(u64);
5349 if (sample_type & PERF_SAMPLE_RAW) {
5350 int size = sizeof(u32);
5353 size += data->raw->size;
5355 size += sizeof(u32);
5357 WARN_ON_ONCE(size & (sizeof(u64)-1));
5358 header->size += size;
5361 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5362 int size = sizeof(u64); /* nr */
5363 if (data->br_stack) {
5364 size += data->br_stack->nr
5365 * sizeof(struct perf_branch_entry);
5367 header->size += size;
5370 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5371 perf_sample_regs_user(&data->regs_user, regs,
5372 &data->regs_user_copy);
5374 if (sample_type & PERF_SAMPLE_REGS_USER) {
5375 /* regs dump ABI info */
5376 int size = sizeof(u64);
5378 if (data->regs_user.regs) {
5379 u64 mask = event->attr.sample_regs_user;
5380 size += hweight64(mask) * sizeof(u64);
5383 header->size += size;
5386 if (sample_type & PERF_SAMPLE_STACK_USER) {
5388 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5389 * processed as the last one or have additional check added
5390 * in case new sample type is added, because we could eat
5391 * up the rest of the sample size.
5393 u16 stack_size = event->attr.sample_stack_user;
5394 u16 size = sizeof(u64);
5396 stack_size = perf_sample_ustack_size(stack_size, header->size,
5397 data->regs_user.regs);
5400 * If there is something to dump, add space for the dump
5401 * itself and for the field that tells the dynamic size,
5402 * which is how many have been actually dumped.
5405 size += sizeof(u64) + stack_size;
5407 data->stack_user_size = stack_size;
5408 header->size += size;
5411 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5412 /* regs dump ABI info */
5413 int size = sizeof(u64);
5415 perf_sample_regs_intr(&data->regs_intr, regs);
5417 if (data->regs_intr.regs) {
5418 u64 mask = event->attr.sample_regs_intr;
5420 size += hweight64(mask) * sizeof(u64);
5423 header->size += size;
5427 static void perf_event_output(struct perf_event *event,
5428 struct perf_sample_data *data,
5429 struct pt_regs *regs)
5431 struct perf_output_handle handle;
5432 struct perf_event_header header;
5434 /* protect the callchain buffers */
5437 perf_prepare_sample(&header, data, event, regs);
5439 if (perf_output_begin(&handle, event, header.size))
5442 perf_output_sample(&handle, &header, data, event);
5444 perf_output_end(&handle);
5454 struct perf_read_event {
5455 struct perf_event_header header;
5462 perf_event_read_event(struct perf_event *event,
5463 struct task_struct *task)
5465 struct perf_output_handle handle;
5466 struct perf_sample_data sample;
5467 struct perf_read_event read_event = {
5469 .type = PERF_RECORD_READ,
5471 .size = sizeof(read_event) + event->read_size,
5473 .pid = perf_event_pid(event, task),
5474 .tid = perf_event_tid(event, task),
5478 perf_event_header__init_id(&read_event.header, &sample, event);
5479 ret = perf_output_begin(&handle, event, read_event.header.size);
5483 perf_output_put(&handle, read_event);
5484 perf_output_read(&handle, event);
5485 perf_event__output_id_sample(event, &handle, &sample);
5487 perf_output_end(&handle);
5490 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5493 perf_event_aux_ctx(struct perf_event_context *ctx,
5494 perf_event_aux_output_cb output,
5497 struct perf_event *event;
5499 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5500 if (event->state < PERF_EVENT_STATE_INACTIVE)
5502 if (!event_filter_match(event))
5504 output(event, data);
5509 perf_event_aux(perf_event_aux_output_cb output, void *data,
5510 struct perf_event_context *task_ctx)
5512 struct perf_cpu_context *cpuctx;
5513 struct perf_event_context *ctx;
5518 list_for_each_entry_rcu(pmu, &pmus, entry) {
5519 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5520 if (cpuctx->unique_pmu != pmu)
5522 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5525 ctxn = pmu->task_ctx_nr;
5528 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5530 perf_event_aux_ctx(ctx, output, data);
5532 put_cpu_ptr(pmu->pmu_cpu_context);
5537 perf_event_aux_ctx(task_ctx, output, data);
5544 * task tracking -- fork/exit
5546 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5549 struct perf_task_event {
5550 struct task_struct *task;
5551 struct perf_event_context *task_ctx;
5554 struct perf_event_header header;
5564 static int perf_event_task_match(struct perf_event *event)
5566 return event->attr.comm || event->attr.mmap ||
5567 event->attr.mmap2 || event->attr.mmap_data ||
5571 static void perf_event_task_output(struct perf_event *event,
5574 struct perf_task_event *task_event = data;
5575 struct perf_output_handle handle;
5576 struct perf_sample_data sample;
5577 struct task_struct *task = task_event->task;
5578 int ret, size = task_event->event_id.header.size;
5580 if (!perf_event_task_match(event))
5583 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5585 ret = perf_output_begin(&handle, event,
5586 task_event->event_id.header.size);
5590 task_event->event_id.pid = perf_event_pid(event, task);
5591 task_event->event_id.ppid = perf_event_pid(event, current);
5593 task_event->event_id.tid = perf_event_tid(event, task);
5594 task_event->event_id.ptid = perf_event_tid(event, current);
5596 task_event->event_id.time = perf_event_clock(event);
5598 perf_output_put(&handle, task_event->event_id);
5600 perf_event__output_id_sample(event, &handle, &sample);
5602 perf_output_end(&handle);
5604 task_event->event_id.header.size = size;
5607 static void perf_event_task(struct task_struct *task,
5608 struct perf_event_context *task_ctx,
5611 struct perf_task_event task_event;
5613 if (!atomic_read(&nr_comm_events) &&
5614 !atomic_read(&nr_mmap_events) &&
5615 !atomic_read(&nr_task_events))
5618 task_event = (struct perf_task_event){
5620 .task_ctx = task_ctx,
5623 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5625 .size = sizeof(task_event.event_id),
5635 perf_event_aux(perf_event_task_output,
5640 void perf_event_fork(struct task_struct *task)
5642 perf_event_task(task, NULL, 1);
5649 struct perf_comm_event {
5650 struct task_struct *task;
5655 struct perf_event_header header;
5662 static int perf_event_comm_match(struct perf_event *event)
5664 return event->attr.comm;
5667 static void perf_event_comm_output(struct perf_event *event,
5670 struct perf_comm_event *comm_event = data;
5671 struct perf_output_handle handle;
5672 struct perf_sample_data sample;
5673 int size = comm_event->event_id.header.size;
5676 if (!perf_event_comm_match(event))
5679 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5680 ret = perf_output_begin(&handle, event,
5681 comm_event->event_id.header.size);
5686 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5687 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5689 perf_output_put(&handle, comm_event->event_id);
5690 __output_copy(&handle, comm_event->comm,
5691 comm_event->comm_size);
5693 perf_event__output_id_sample(event, &handle, &sample);
5695 perf_output_end(&handle);
5697 comm_event->event_id.header.size = size;
5700 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5702 char comm[TASK_COMM_LEN];
5705 memset(comm, 0, sizeof(comm));
5706 strlcpy(comm, comm_event->task->comm, sizeof(comm));
5707 size = ALIGN(strlen(comm)+1, sizeof(u64));
5709 comm_event->comm = comm;
5710 comm_event->comm_size = size;
5712 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5714 perf_event_aux(perf_event_comm_output,
5719 void perf_event_comm(struct task_struct *task, bool exec)
5721 struct perf_comm_event comm_event;
5723 if (!atomic_read(&nr_comm_events))
5726 comm_event = (struct perf_comm_event){
5732 .type = PERF_RECORD_COMM,
5733 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5741 perf_event_comm_event(&comm_event);
5748 struct perf_mmap_event {
5749 struct vm_area_struct *vma;
5751 const char *file_name;
5759 struct perf_event_header header;
5769 static int perf_event_mmap_match(struct perf_event *event,
5772 struct perf_mmap_event *mmap_event = data;
5773 struct vm_area_struct *vma = mmap_event->vma;
5774 int executable = vma->vm_flags & VM_EXEC;
5776 return (!executable && event->attr.mmap_data) ||
5777 (executable && (event->attr.mmap || event->attr.mmap2));
5780 static void perf_event_mmap_output(struct perf_event *event,
5783 struct perf_mmap_event *mmap_event = data;
5784 struct perf_output_handle handle;
5785 struct perf_sample_data sample;
5786 int size = mmap_event->event_id.header.size;
5789 if (!perf_event_mmap_match(event, data))
5792 if (event->attr.mmap2) {
5793 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5794 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5795 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5796 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5797 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5798 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5799 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5802 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5803 ret = perf_output_begin(&handle, event,
5804 mmap_event->event_id.header.size);
5808 mmap_event->event_id.pid = perf_event_pid(event, current);
5809 mmap_event->event_id.tid = perf_event_tid(event, current);
5811 perf_output_put(&handle, mmap_event->event_id);
5813 if (event->attr.mmap2) {
5814 perf_output_put(&handle, mmap_event->maj);
5815 perf_output_put(&handle, mmap_event->min);
5816 perf_output_put(&handle, mmap_event->ino);
5817 perf_output_put(&handle, mmap_event->ino_generation);
5818 perf_output_put(&handle, mmap_event->prot);
5819 perf_output_put(&handle, mmap_event->flags);
5822 __output_copy(&handle, mmap_event->file_name,
5823 mmap_event->file_size);
5825 perf_event__output_id_sample(event, &handle, &sample);
5827 perf_output_end(&handle);
5829 mmap_event->event_id.header.size = size;
5832 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5834 struct vm_area_struct *vma = mmap_event->vma;
5835 struct file *file = vma->vm_file;
5836 int maj = 0, min = 0;
5837 u64 ino = 0, gen = 0;
5838 u32 prot = 0, flags = 0;
5845 struct inode *inode;
5848 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5854 * d_path() works from the end of the rb backwards, so we
5855 * need to add enough zero bytes after the string to handle
5856 * the 64bit alignment we do later.
5858 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5863 inode = file_inode(vma->vm_file);
5864 dev = inode->i_sb->s_dev;
5866 gen = inode->i_generation;
5870 if (vma->vm_flags & VM_READ)
5872 if (vma->vm_flags & VM_WRITE)
5874 if (vma->vm_flags & VM_EXEC)
5877 if (vma->vm_flags & VM_MAYSHARE)
5880 flags = MAP_PRIVATE;
5882 if (vma->vm_flags & VM_DENYWRITE)
5883 flags |= MAP_DENYWRITE;
5884 if (vma->vm_flags & VM_MAYEXEC)
5885 flags |= MAP_EXECUTABLE;
5886 if (vma->vm_flags & VM_LOCKED)
5887 flags |= MAP_LOCKED;
5888 if (vma->vm_flags & VM_HUGETLB)
5889 flags |= MAP_HUGETLB;
5893 if (vma->vm_ops && vma->vm_ops->name) {
5894 name = (char *) vma->vm_ops->name(vma);
5899 name = (char *)arch_vma_name(vma);
5903 if (vma->vm_start <= vma->vm_mm->start_brk &&
5904 vma->vm_end >= vma->vm_mm->brk) {
5908 if (vma->vm_start <= vma->vm_mm->start_stack &&
5909 vma->vm_end >= vma->vm_mm->start_stack) {
5919 strlcpy(tmp, name, sizeof(tmp));
5923 * Since our buffer works in 8 byte units we need to align our string
5924 * size to a multiple of 8. However, we must guarantee the tail end is
5925 * zero'd out to avoid leaking random bits to userspace.
5927 size = strlen(name)+1;
5928 while (!IS_ALIGNED(size, sizeof(u64)))
5929 name[size++] = '\0';
5931 mmap_event->file_name = name;
5932 mmap_event->file_size = size;
5933 mmap_event->maj = maj;
5934 mmap_event->min = min;
5935 mmap_event->ino = ino;
5936 mmap_event->ino_generation = gen;
5937 mmap_event->prot = prot;
5938 mmap_event->flags = flags;
5940 if (!(vma->vm_flags & VM_EXEC))
5941 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5943 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5945 perf_event_aux(perf_event_mmap_output,
5952 void perf_event_mmap(struct vm_area_struct *vma)
5954 struct perf_mmap_event mmap_event;
5956 if (!atomic_read(&nr_mmap_events))
5959 mmap_event = (struct perf_mmap_event){
5965 .type = PERF_RECORD_MMAP,
5966 .misc = PERF_RECORD_MISC_USER,
5971 .start = vma->vm_start,
5972 .len = vma->vm_end - vma->vm_start,
5973 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
5975 /* .maj (attr_mmap2 only) */
5976 /* .min (attr_mmap2 only) */
5977 /* .ino (attr_mmap2 only) */
5978 /* .ino_generation (attr_mmap2 only) */
5979 /* .prot (attr_mmap2 only) */
5980 /* .flags (attr_mmap2 only) */
5983 perf_event_mmap_event(&mmap_event);
5986 void perf_event_aux_event(struct perf_event *event, unsigned long head,
5987 unsigned long size, u64 flags)
5989 struct perf_output_handle handle;
5990 struct perf_sample_data sample;
5991 struct perf_aux_event {
5992 struct perf_event_header header;
5998 .type = PERF_RECORD_AUX,
6000 .size = sizeof(rec),
6008 perf_event_header__init_id(&rec.header, &sample, event);
6009 ret = perf_output_begin(&handle, event, rec.header.size);
6014 perf_output_put(&handle, rec);
6015 perf_event__output_id_sample(event, &handle, &sample);
6017 perf_output_end(&handle);
6021 * IRQ throttle logging
6024 static void perf_log_throttle(struct perf_event *event, int enable)
6026 struct perf_output_handle handle;
6027 struct perf_sample_data sample;
6031 struct perf_event_header header;
6035 } throttle_event = {
6037 .type = PERF_RECORD_THROTTLE,
6039 .size = sizeof(throttle_event),
6041 .time = perf_event_clock(event),
6042 .id = primary_event_id(event),
6043 .stream_id = event->id,
6047 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6049 perf_event_header__init_id(&throttle_event.header, &sample, event);
6051 ret = perf_output_begin(&handle, event,
6052 throttle_event.header.size);
6056 perf_output_put(&handle, throttle_event);
6057 perf_event__output_id_sample(event, &handle, &sample);
6058 perf_output_end(&handle);
6061 static void perf_log_itrace_start(struct perf_event *event)
6063 struct perf_output_handle handle;
6064 struct perf_sample_data sample;
6065 struct perf_aux_event {
6066 struct perf_event_header header;
6073 event = event->parent;
6075 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6076 event->hw.itrace_started)
6079 event->hw.itrace_started = 1;
6081 rec.header.type = PERF_RECORD_ITRACE_START;
6082 rec.header.misc = 0;
6083 rec.header.size = sizeof(rec);
6084 rec.pid = perf_event_pid(event, current);
6085 rec.tid = perf_event_tid(event, current);
6087 perf_event_header__init_id(&rec.header, &sample, event);
6088 ret = perf_output_begin(&handle, event, rec.header.size);
6093 perf_output_put(&handle, rec);
6094 perf_event__output_id_sample(event, &handle, &sample);
6096 perf_output_end(&handle);
6100 * Generic event overflow handling, sampling.
6103 static int __perf_event_overflow(struct perf_event *event,
6104 int throttle, struct perf_sample_data *data,
6105 struct pt_regs *regs)
6107 int events = atomic_read(&event->event_limit);
6108 struct hw_perf_event *hwc = &event->hw;
6113 * Non-sampling counters might still use the PMI to fold short
6114 * hardware counters, ignore those.
6116 if (unlikely(!is_sampling_event(event)))
6119 seq = __this_cpu_read(perf_throttled_seq);
6120 if (seq != hwc->interrupts_seq) {
6121 hwc->interrupts_seq = seq;
6122 hwc->interrupts = 1;
6125 if (unlikely(throttle
6126 && hwc->interrupts >= max_samples_per_tick)) {
6127 __this_cpu_inc(perf_throttled_count);
6128 hwc->interrupts = MAX_INTERRUPTS;
6129 perf_log_throttle(event, 0);
6130 tick_nohz_full_kick();
6135 if (event->attr.freq) {
6136 u64 now = perf_clock();
6137 s64 delta = now - hwc->freq_time_stamp;
6139 hwc->freq_time_stamp = now;
6141 if (delta > 0 && delta < 2*TICK_NSEC)
6142 perf_adjust_period(event, delta, hwc->last_period, true);
6146 * XXX event_limit might not quite work as expected on inherited
6150 event->pending_kill = POLL_IN;
6151 if (events && atomic_dec_and_test(&event->event_limit)) {
6153 event->pending_kill = POLL_HUP;
6154 event->pending_disable = 1;
6155 irq_work_queue(&event->pending);
6158 if (event->overflow_handler)
6159 event->overflow_handler(event, data, regs);
6161 perf_event_output(event, data, regs);
6163 if (*perf_event_fasync(event) && event->pending_kill) {
6164 event->pending_wakeup = 1;
6165 irq_work_queue(&event->pending);
6171 int perf_event_overflow(struct perf_event *event,
6172 struct perf_sample_data *data,
6173 struct pt_regs *regs)
6175 return __perf_event_overflow(event, 1, data, regs);
6179 * Generic software event infrastructure
6182 struct swevent_htable {
6183 struct swevent_hlist *swevent_hlist;
6184 struct mutex hlist_mutex;
6187 /* Recursion avoidance in each contexts */
6188 int recursion[PERF_NR_CONTEXTS];
6190 /* Keeps track of cpu being initialized/exited */
6194 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6197 * We directly increment event->count and keep a second value in
6198 * event->hw.period_left to count intervals. This period event
6199 * is kept in the range [-sample_period, 0] so that we can use the
6203 u64 perf_swevent_set_period(struct perf_event *event)
6205 struct hw_perf_event *hwc = &event->hw;
6206 u64 period = hwc->last_period;
6210 hwc->last_period = hwc->sample_period;
6213 old = val = local64_read(&hwc->period_left);
6217 nr = div64_u64(period + val, period);
6218 offset = nr * period;
6220 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6226 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6227 struct perf_sample_data *data,
6228 struct pt_regs *regs)
6230 struct hw_perf_event *hwc = &event->hw;
6234 overflow = perf_swevent_set_period(event);
6236 if (hwc->interrupts == MAX_INTERRUPTS)
6239 for (; overflow; overflow--) {
6240 if (__perf_event_overflow(event, throttle,
6243 * We inhibit the overflow from happening when
6244 * hwc->interrupts == MAX_INTERRUPTS.
6252 static void perf_swevent_event(struct perf_event *event, u64 nr,
6253 struct perf_sample_data *data,
6254 struct pt_regs *regs)
6256 struct hw_perf_event *hwc = &event->hw;
6258 local64_add(nr, &event->count);
6263 if (!is_sampling_event(event))
6266 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6268 return perf_swevent_overflow(event, 1, data, regs);
6270 data->period = event->hw.last_period;
6272 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6273 return perf_swevent_overflow(event, 1, data, regs);
6275 if (local64_add_negative(nr, &hwc->period_left))
6278 perf_swevent_overflow(event, 0, data, regs);
6281 static int perf_exclude_event(struct perf_event *event,
6282 struct pt_regs *regs)
6284 if (event->hw.state & PERF_HES_STOPPED)
6288 if (event->attr.exclude_user && user_mode(regs))
6291 if (event->attr.exclude_kernel && !user_mode(regs))
6298 static int perf_swevent_match(struct perf_event *event,
6299 enum perf_type_id type,
6301 struct perf_sample_data *data,
6302 struct pt_regs *regs)
6304 if (event->attr.type != type)
6307 if (event->attr.config != event_id)
6310 if (perf_exclude_event(event, regs))
6316 static inline u64 swevent_hash(u64 type, u32 event_id)
6318 u64 val = event_id | (type << 32);
6320 return hash_64(val, SWEVENT_HLIST_BITS);
6323 static inline struct hlist_head *
6324 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6326 u64 hash = swevent_hash(type, event_id);
6328 return &hlist->heads[hash];
6331 /* For the read side: events when they trigger */
6332 static inline struct hlist_head *
6333 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6335 struct swevent_hlist *hlist;
6337 hlist = rcu_dereference(swhash->swevent_hlist);
6341 return __find_swevent_head(hlist, type, event_id);
6344 /* For the event head insertion and removal in the hlist */
6345 static inline struct hlist_head *
6346 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6348 struct swevent_hlist *hlist;
6349 u32 event_id = event->attr.config;
6350 u64 type = event->attr.type;
6353 * Event scheduling is always serialized against hlist allocation
6354 * and release. Which makes the protected version suitable here.
6355 * The context lock guarantees that.
6357 hlist = rcu_dereference_protected(swhash->swevent_hlist,
6358 lockdep_is_held(&event->ctx->lock));
6362 return __find_swevent_head(hlist, type, event_id);
6365 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6367 struct perf_sample_data *data,
6368 struct pt_regs *regs)
6370 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6371 struct perf_event *event;
6372 struct hlist_head *head;
6375 head = find_swevent_head_rcu(swhash, type, event_id);
6379 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6380 if (perf_swevent_match(event, type, event_id, data, regs))
6381 perf_swevent_event(event, nr, data, regs);
6387 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6389 int perf_swevent_get_recursion_context(void)
6391 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6393 return get_recursion_context(swhash->recursion);
6395 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6397 inline void perf_swevent_put_recursion_context(int rctx)
6399 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6401 put_recursion_context(swhash->recursion, rctx);
6404 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6406 struct perf_sample_data data;
6408 if (WARN_ON_ONCE(!regs))
6411 perf_sample_data_init(&data, addr, 0);
6412 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6415 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6419 preempt_disable_notrace();
6420 rctx = perf_swevent_get_recursion_context();
6421 if (unlikely(rctx < 0))
6424 ___perf_sw_event(event_id, nr, regs, addr);
6426 perf_swevent_put_recursion_context(rctx);
6428 preempt_enable_notrace();
6431 static void perf_swevent_read(struct perf_event *event)
6435 static int perf_swevent_add(struct perf_event *event, int flags)
6437 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6438 struct hw_perf_event *hwc = &event->hw;
6439 struct hlist_head *head;
6441 if (is_sampling_event(event)) {
6442 hwc->last_period = hwc->sample_period;
6443 perf_swevent_set_period(event);
6446 hwc->state = !(flags & PERF_EF_START);
6448 head = find_swevent_head(swhash, event);
6451 * We can race with cpu hotplug code. Do not
6452 * WARN if the cpu just got unplugged.
6454 WARN_ON_ONCE(swhash->online);
6458 hlist_add_head_rcu(&event->hlist_entry, head);
6459 perf_event_update_userpage(event);
6464 static void perf_swevent_del(struct perf_event *event, int flags)
6466 hlist_del_rcu(&event->hlist_entry);
6469 static void perf_swevent_start(struct perf_event *event, int flags)
6471 event->hw.state = 0;
6474 static void perf_swevent_stop(struct perf_event *event, int flags)
6476 event->hw.state = PERF_HES_STOPPED;
6479 /* Deref the hlist from the update side */
6480 static inline struct swevent_hlist *
6481 swevent_hlist_deref(struct swevent_htable *swhash)
6483 return rcu_dereference_protected(swhash->swevent_hlist,
6484 lockdep_is_held(&swhash->hlist_mutex));
6487 static void swevent_hlist_release(struct swevent_htable *swhash)
6489 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6494 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6495 kfree_rcu(hlist, rcu_head);
6498 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6500 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6502 mutex_lock(&swhash->hlist_mutex);
6504 if (!--swhash->hlist_refcount)
6505 swevent_hlist_release(swhash);
6507 mutex_unlock(&swhash->hlist_mutex);
6510 static void swevent_hlist_put(struct perf_event *event)
6514 for_each_possible_cpu(cpu)
6515 swevent_hlist_put_cpu(event, cpu);
6518 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6520 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6523 mutex_lock(&swhash->hlist_mutex);
6525 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6526 struct swevent_hlist *hlist;
6528 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6533 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6535 swhash->hlist_refcount++;
6537 mutex_unlock(&swhash->hlist_mutex);
6542 static int swevent_hlist_get(struct perf_event *event)
6545 int cpu, failed_cpu;
6548 for_each_possible_cpu(cpu) {
6549 err = swevent_hlist_get_cpu(event, cpu);
6559 for_each_possible_cpu(cpu) {
6560 if (cpu == failed_cpu)
6562 swevent_hlist_put_cpu(event, cpu);
6569 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6571 static void sw_perf_event_destroy(struct perf_event *event)
6573 u64 event_id = event->attr.config;
6575 WARN_ON(event->parent);
6577 static_key_slow_dec(&perf_swevent_enabled[event_id]);
6578 swevent_hlist_put(event);
6581 static int perf_swevent_init(struct perf_event *event)
6583 u64 event_id = event->attr.config;
6585 if (event->attr.type != PERF_TYPE_SOFTWARE)
6589 * no branch sampling for software events
6591 if (has_branch_stack(event))
6595 case PERF_COUNT_SW_CPU_CLOCK:
6596 case PERF_COUNT_SW_TASK_CLOCK:
6603 if (event_id >= PERF_COUNT_SW_MAX)
6606 if (!event->parent) {
6609 err = swevent_hlist_get(event);
6613 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6614 event->destroy = sw_perf_event_destroy;
6620 static struct pmu perf_swevent = {
6621 .task_ctx_nr = perf_sw_context,
6623 .capabilities = PERF_PMU_CAP_NO_NMI,
6625 .event_init = perf_swevent_init,
6626 .add = perf_swevent_add,
6627 .del = perf_swevent_del,
6628 .start = perf_swevent_start,
6629 .stop = perf_swevent_stop,
6630 .read = perf_swevent_read,
6633 #ifdef CONFIG_EVENT_TRACING
6635 static int perf_tp_filter_match(struct perf_event *event,
6636 struct perf_sample_data *data)
6638 void *record = data->raw->data;
6640 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6645 static int perf_tp_event_match(struct perf_event *event,
6646 struct perf_sample_data *data,
6647 struct pt_regs *regs)
6649 if (event->hw.state & PERF_HES_STOPPED)
6652 * All tracepoints are from kernel-space.
6654 if (event->attr.exclude_kernel)
6657 if (!perf_tp_filter_match(event, data))
6663 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6664 struct pt_regs *regs, struct hlist_head *head, int rctx,
6665 struct task_struct *task)
6667 struct perf_sample_data data;
6668 struct perf_event *event;
6670 struct perf_raw_record raw = {
6675 perf_sample_data_init(&data, addr, 0);
6678 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6679 if (perf_tp_event_match(event, &data, regs))
6680 perf_swevent_event(event, count, &data, regs);
6684 * If we got specified a target task, also iterate its context and
6685 * deliver this event there too.
6687 if (task && task != current) {
6688 struct perf_event_context *ctx;
6689 struct trace_entry *entry = record;
6692 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6696 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6697 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6699 if (event->attr.config != entry->type)
6701 if (perf_tp_event_match(event, &data, regs))
6702 perf_swevent_event(event, count, &data, regs);
6708 perf_swevent_put_recursion_context(rctx);
6710 EXPORT_SYMBOL_GPL(perf_tp_event);
6712 static void tp_perf_event_destroy(struct perf_event *event)
6714 perf_trace_destroy(event);
6717 static int perf_tp_event_init(struct perf_event *event)
6721 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6725 * no branch sampling for tracepoint events
6727 if (has_branch_stack(event))
6730 err = perf_trace_init(event);
6734 event->destroy = tp_perf_event_destroy;
6739 static struct pmu perf_tracepoint = {
6740 .task_ctx_nr = perf_sw_context,
6742 .event_init = perf_tp_event_init,
6743 .add = perf_trace_add,
6744 .del = perf_trace_del,
6745 .start = perf_swevent_start,
6746 .stop = perf_swevent_stop,
6747 .read = perf_swevent_read,
6750 static inline void perf_tp_register(void)
6752 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6755 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6760 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6763 filter_str = strndup_user(arg, PAGE_SIZE);
6764 if (IS_ERR(filter_str))
6765 return PTR_ERR(filter_str);
6767 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6773 static void perf_event_free_filter(struct perf_event *event)
6775 ftrace_profile_free_filter(event);
6778 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
6780 struct bpf_prog *prog;
6782 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6785 if (event->tp_event->prog)
6788 if (!(event->tp_event->flags & TRACE_EVENT_FL_KPROBE))
6789 /* bpf programs can only be attached to kprobes */
6792 prog = bpf_prog_get(prog_fd);
6794 return PTR_ERR(prog);
6796 if (prog->type != BPF_PROG_TYPE_KPROBE) {
6797 /* valid fd, but invalid bpf program type */
6802 event->tp_event->prog = prog;
6807 static void perf_event_free_bpf_prog(struct perf_event *event)
6809 struct bpf_prog *prog;
6811 if (!event->tp_event)
6814 prog = event->tp_event->prog;
6816 event->tp_event->prog = NULL;
6823 static inline void perf_tp_register(void)
6827 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6832 static void perf_event_free_filter(struct perf_event *event)
6836 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
6841 static void perf_event_free_bpf_prog(struct perf_event *event)
6844 #endif /* CONFIG_EVENT_TRACING */
6846 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6847 void perf_bp_event(struct perf_event *bp, void *data)
6849 struct perf_sample_data sample;
6850 struct pt_regs *regs = data;
6852 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6854 if (!bp->hw.state && !perf_exclude_event(bp, regs))
6855 perf_swevent_event(bp, 1, &sample, regs);
6860 * hrtimer based swevent callback
6863 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6865 enum hrtimer_restart ret = HRTIMER_RESTART;
6866 struct perf_sample_data data;
6867 struct pt_regs *regs;
6868 struct perf_event *event;
6871 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6873 if (event->state != PERF_EVENT_STATE_ACTIVE)
6874 return HRTIMER_NORESTART;
6876 event->pmu->read(event);
6878 perf_sample_data_init(&data, 0, event->hw.last_period);
6879 regs = get_irq_regs();
6881 if (regs && !perf_exclude_event(event, regs)) {
6882 if (!(event->attr.exclude_idle && is_idle_task(current)))
6883 if (__perf_event_overflow(event, 1, &data, regs))
6884 ret = HRTIMER_NORESTART;
6887 period = max_t(u64, 10000, event->hw.sample_period);
6888 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6893 static void perf_swevent_start_hrtimer(struct perf_event *event)
6895 struct hw_perf_event *hwc = &event->hw;
6898 if (!is_sampling_event(event))
6901 period = local64_read(&hwc->period_left);
6906 local64_set(&hwc->period_left, 0);
6908 period = max_t(u64, 10000, hwc->sample_period);
6910 __hrtimer_start_range_ns(&hwc->hrtimer,
6911 ns_to_ktime(period), 0,
6912 HRTIMER_MODE_REL_PINNED, 0);
6915 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6917 struct hw_perf_event *hwc = &event->hw;
6919 if (is_sampling_event(event)) {
6920 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6921 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6923 hrtimer_cancel(&hwc->hrtimer);
6927 static void perf_swevent_init_hrtimer(struct perf_event *event)
6929 struct hw_perf_event *hwc = &event->hw;
6931 if (!is_sampling_event(event))
6934 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6935 hwc->hrtimer.function = perf_swevent_hrtimer;
6936 hwc->hrtimer.irqsafe = 1;
6939 * Since hrtimers have a fixed rate, we can do a static freq->period
6940 * mapping and avoid the whole period adjust feedback stuff.
6942 if (event->attr.freq) {
6943 long freq = event->attr.sample_freq;
6945 event->attr.sample_period = NSEC_PER_SEC / freq;
6946 hwc->sample_period = event->attr.sample_period;
6947 local64_set(&hwc->period_left, hwc->sample_period);
6948 hwc->last_period = hwc->sample_period;
6949 event->attr.freq = 0;
6954 * Software event: cpu wall time clock
6957 static void cpu_clock_event_update(struct perf_event *event)
6962 now = local_clock();
6963 prev = local64_xchg(&event->hw.prev_count, now);
6964 local64_add(now - prev, &event->count);
6967 static void cpu_clock_event_start(struct perf_event *event, int flags)
6969 local64_set(&event->hw.prev_count, local_clock());
6970 perf_swevent_start_hrtimer(event);
6973 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6975 perf_swevent_cancel_hrtimer(event);
6976 cpu_clock_event_update(event);
6979 static int cpu_clock_event_add(struct perf_event *event, int flags)
6981 if (flags & PERF_EF_START)
6982 cpu_clock_event_start(event, flags);
6983 perf_event_update_userpage(event);
6988 static void cpu_clock_event_del(struct perf_event *event, int flags)
6990 cpu_clock_event_stop(event, flags);
6993 static void cpu_clock_event_read(struct perf_event *event)
6995 cpu_clock_event_update(event);
6998 static int cpu_clock_event_init(struct perf_event *event)
7000 if (event->attr.type != PERF_TYPE_SOFTWARE)
7003 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7007 * no branch sampling for software events
7009 if (has_branch_stack(event))
7012 perf_swevent_init_hrtimer(event);
7017 static struct pmu perf_cpu_clock = {
7018 .task_ctx_nr = perf_sw_context,
7020 .capabilities = PERF_PMU_CAP_NO_NMI,
7022 .event_init = cpu_clock_event_init,
7023 .add = cpu_clock_event_add,
7024 .del = cpu_clock_event_del,
7025 .start = cpu_clock_event_start,
7026 .stop = cpu_clock_event_stop,
7027 .read = cpu_clock_event_read,
7031 * Software event: task time clock
7034 static void task_clock_event_update(struct perf_event *event, u64 now)
7039 prev = local64_xchg(&event->hw.prev_count, now);
7041 local64_add(delta, &event->count);
7044 static void task_clock_event_start(struct perf_event *event, int flags)
7046 local64_set(&event->hw.prev_count, event->ctx->time);
7047 perf_swevent_start_hrtimer(event);
7050 static void task_clock_event_stop(struct perf_event *event, int flags)
7052 perf_swevent_cancel_hrtimer(event);
7053 task_clock_event_update(event, event->ctx->time);
7056 static int task_clock_event_add(struct perf_event *event, int flags)
7058 if (flags & PERF_EF_START)
7059 task_clock_event_start(event, flags);
7060 perf_event_update_userpage(event);
7065 static void task_clock_event_del(struct perf_event *event, int flags)
7067 task_clock_event_stop(event, PERF_EF_UPDATE);
7070 static void task_clock_event_read(struct perf_event *event)
7072 u64 now = perf_clock();
7073 u64 delta = now - event->ctx->timestamp;
7074 u64 time = event->ctx->time + delta;
7076 task_clock_event_update(event, time);
7079 static int task_clock_event_init(struct perf_event *event)
7081 if (event->attr.type != PERF_TYPE_SOFTWARE)
7084 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7088 * no branch sampling for software events
7090 if (has_branch_stack(event))
7093 perf_swevent_init_hrtimer(event);
7098 static struct pmu perf_task_clock = {
7099 .task_ctx_nr = perf_sw_context,
7101 .capabilities = PERF_PMU_CAP_NO_NMI,
7103 .event_init = task_clock_event_init,
7104 .add = task_clock_event_add,
7105 .del = task_clock_event_del,
7106 .start = task_clock_event_start,
7107 .stop = task_clock_event_stop,
7108 .read = task_clock_event_read,
7111 static void perf_pmu_nop_void(struct pmu *pmu)
7115 static int perf_pmu_nop_int(struct pmu *pmu)
7120 static void perf_pmu_start_txn(struct pmu *pmu)
7122 perf_pmu_disable(pmu);
7125 static int perf_pmu_commit_txn(struct pmu *pmu)
7127 perf_pmu_enable(pmu);
7131 static void perf_pmu_cancel_txn(struct pmu *pmu)
7133 perf_pmu_enable(pmu);
7136 static int perf_event_idx_default(struct perf_event *event)
7142 * Ensures all contexts with the same task_ctx_nr have the same
7143 * pmu_cpu_context too.
7145 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7152 list_for_each_entry(pmu, &pmus, entry) {
7153 if (pmu->task_ctx_nr == ctxn)
7154 return pmu->pmu_cpu_context;
7160 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7164 for_each_possible_cpu(cpu) {
7165 struct perf_cpu_context *cpuctx;
7167 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7169 if (cpuctx->unique_pmu == old_pmu)
7170 cpuctx->unique_pmu = pmu;
7174 static void free_pmu_context(struct pmu *pmu)
7178 mutex_lock(&pmus_lock);
7180 * Like a real lame refcount.
7182 list_for_each_entry(i, &pmus, entry) {
7183 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7184 update_pmu_context(i, pmu);
7189 free_percpu(pmu->pmu_cpu_context);
7191 mutex_unlock(&pmus_lock);
7193 static struct idr pmu_idr;
7196 type_show(struct device *dev, struct device_attribute *attr, char *page)
7198 struct pmu *pmu = dev_get_drvdata(dev);
7200 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7202 static DEVICE_ATTR_RO(type);
7205 perf_event_mux_interval_ms_show(struct device *dev,
7206 struct device_attribute *attr,
7209 struct pmu *pmu = dev_get_drvdata(dev);
7211 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7215 perf_event_mux_interval_ms_store(struct device *dev,
7216 struct device_attribute *attr,
7217 const char *buf, size_t count)
7219 struct pmu *pmu = dev_get_drvdata(dev);
7220 int timer, cpu, ret;
7222 ret = kstrtoint(buf, 0, &timer);
7229 /* same value, noting to do */
7230 if (timer == pmu->hrtimer_interval_ms)
7233 pmu->hrtimer_interval_ms = timer;
7235 /* update all cpuctx for this PMU */
7236 for_each_possible_cpu(cpu) {
7237 struct perf_cpu_context *cpuctx;
7238 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7239 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7241 if (hrtimer_active(&cpuctx->hrtimer))
7242 hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
7247 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7249 static struct attribute *pmu_dev_attrs[] = {
7250 &dev_attr_type.attr,
7251 &dev_attr_perf_event_mux_interval_ms.attr,
7254 ATTRIBUTE_GROUPS(pmu_dev);
7256 static int pmu_bus_running;
7257 static struct bus_type pmu_bus = {
7258 .name = "event_source",
7259 .dev_groups = pmu_dev_groups,
7262 static void pmu_dev_release(struct device *dev)
7267 static int pmu_dev_alloc(struct pmu *pmu)
7271 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7275 pmu->dev->groups = pmu->attr_groups;
7276 device_initialize(pmu->dev);
7277 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7281 dev_set_drvdata(pmu->dev, pmu);
7282 pmu->dev->bus = &pmu_bus;
7283 pmu->dev->release = pmu_dev_release;
7284 ret = device_add(pmu->dev);
7292 put_device(pmu->dev);
7296 static struct lock_class_key cpuctx_mutex;
7297 static struct lock_class_key cpuctx_lock;
7299 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7303 mutex_lock(&pmus_lock);
7305 pmu->pmu_disable_count = alloc_percpu(int);
7306 if (!pmu->pmu_disable_count)
7315 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7323 if (pmu_bus_running) {
7324 ret = pmu_dev_alloc(pmu);
7330 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7331 if (pmu->pmu_cpu_context)
7332 goto got_cpu_context;
7335 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7336 if (!pmu->pmu_cpu_context)
7339 for_each_possible_cpu(cpu) {
7340 struct perf_cpu_context *cpuctx;
7342 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7343 __perf_event_init_context(&cpuctx->ctx);
7344 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7345 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7346 cpuctx->ctx.pmu = pmu;
7348 __perf_cpu_hrtimer_init(cpuctx, cpu);
7350 cpuctx->unique_pmu = pmu;
7354 if (!pmu->start_txn) {
7355 if (pmu->pmu_enable) {
7357 * If we have pmu_enable/pmu_disable calls, install
7358 * transaction stubs that use that to try and batch
7359 * hardware accesses.
7361 pmu->start_txn = perf_pmu_start_txn;
7362 pmu->commit_txn = perf_pmu_commit_txn;
7363 pmu->cancel_txn = perf_pmu_cancel_txn;
7365 pmu->start_txn = perf_pmu_nop_void;
7366 pmu->commit_txn = perf_pmu_nop_int;
7367 pmu->cancel_txn = perf_pmu_nop_void;
7371 if (!pmu->pmu_enable) {
7372 pmu->pmu_enable = perf_pmu_nop_void;
7373 pmu->pmu_disable = perf_pmu_nop_void;
7376 if (!pmu->event_idx)
7377 pmu->event_idx = perf_event_idx_default;
7379 list_add_rcu(&pmu->entry, &pmus);
7380 atomic_set(&pmu->exclusive_cnt, 0);
7383 mutex_unlock(&pmus_lock);
7388 device_del(pmu->dev);
7389 put_device(pmu->dev);
7392 if (pmu->type >= PERF_TYPE_MAX)
7393 idr_remove(&pmu_idr, pmu->type);
7396 free_percpu(pmu->pmu_disable_count);
7399 EXPORT_SYMBOL_GPL(perf_pmu_register);
7401 void perf_pmu_unregister(struct pmu *pmu)
7403 mutex_lock(&pmus_lock);
7404 list_del_rcu(&pmu->entry);
7405 mutex_unlock(&pmus_lock);
7408 * We dereference the pmu list under both SRCU and regular RCU, so
7409 * synchronize against both of those.
7411 synchronize_srcu(&pmus_srcu);
7414 free_percpu(pmu->pmu_disable_count);
7415 if (pmu->type >= PERF_TYPE_MAX)
7416 idr_remove(&pmu_idr, pmu->type);
7417 device_del(pmu->dev);
7418 put_device(pmu->dev);
7419 free_pmu_context(pmu);
7421 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7423 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7425 struct perf_event_context *ctx = NULL;
7428 if (!try_module_get(pmu->module))
7431 if (event->group_leader != event) {
7433 * This ctx->mutex can nest when we're called through
7434 * inheritance. See the perf_event_ctx_lock_nested() comment.
7436 ctx = perf_event_ctx_lock_nested(event->group_leader,
7437 SINGLE_DEPTH_NESTING);
7442 ret = pmu->event_init(event);
7445 perf_event_ctx_unlock(event->group_leader, ctx);
7448 module_put(pmu->module);
7453 struct pmu *perf_init_event(struct perf_event *event)
7455 struct pmu *pmu = NULL;
7459 idx = srcu_read_lock(&pmus_srcu);
7462 pmu = idr_find(&pmu_idr, event->attr.type);
7465 ret = perf_try_init_event(pmu, event);
7471 list_for_each_entry_rcu(pmu, &pmus, entry) {
7472 ret = perf_try_init_event(pmu, event);
7476 if (ret != -ENOENT) {
7481 pmu = ERR_PTR(-ENOENT);
7483 srcu_read_unlock(&pmus_srcu, idx);
7488 static void account_event_cpu(struct perf_event *event, int cpu)
7493 if (is_cgroup_event(event))
7494 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7497 static void account_event(struct perf_event *event)
7502 if (event->attach_state & PERF_ATTACH_TASK)
7503 static_key_slow_inc(&perf_sched_events.key);
7504 if (event->attr.mmap || event->attr.mmap_data)
7505 atomic_inc(&nr_mmap_events);
7506 if (event->attr.comm)
7507 atomic_inc(&nr_comm_events);
7508 if (event->attr.task)
7509 atomic_inc(&nr_task_events);
7510 if (event->attr.freq) {
7511 if (atomic_inc_return(&nr_freq_events) == 1)
7512 tick_nohz_full_kick_all();
7514 if (has_branch_stack(event))
7515 static_key_slow_inc(&perf_sched_events.key);
7516 if (is_cgroup_event(event))
7517 static_key_slow_inc(&perf_sched_events.key);
7519 account_event_cpu(event, event->cpu);
7523 * Allocate and initialize a event structure
7525 static struct perf_event *
7526 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7527 struct task_struct *task,
7528 struct perf_event *group_leader,
7529 struct perf_event *parent_event,
7530 perf_overflow_handler_t overflow_handler,
7531 void *context, int cgroup_fd)
7534 struct perf_event *event;
7535 struct hw_perf_event *hwc;
7538 if ((unsigned)cpu >= nr_cpu_ids) {
7539 if (!task || cpu != -1)
7540 return ERR_PTR(-EINVAL);
7543 event = kzalloc(sizeof(*event), GFP_KERNEL);
7545 return ERR_PTR(-ENOMEM);
7548 * Single events are their own group leaders, with an
7549 * empty sibling list:
7552 group_leader = event;
7554 mutex_init(&event->child_mutex);
7555 INIT_LIST_HEAD(&event->child_list);
7557 INIT_LIST_HEAD(&event->group_entry);
7558 INIT_LIST_HEAD(&event->event_entry);
7559 INIT_LIST_HEAD(&event->sibling_list);
7560 INIT_LIST_HEAD(&event->rb_entry);
7561 INIT_LIST_HEAD(&event->active_entry);
7562 INIT_HLIST_NODE(&event->hlist_entry);
7565 init_waitqueue_head(&event->waitq);
7566 init_irq_work(&event->pending, perf_pending_event);
7568 mutex_init(&event->mmap_mutex);
7570 atomic_long_set(&event->refcount, 1);
7572 event->attr = *attr;
7573 event->group_leader = group_leader;
7577 event->parent = parent_event;
7579 event->ns = get_pid_ns(task_active_pid_ns(current));
7580 event->id = atomic64_inc_return(&perf_event_id);
7582 event->state = PERF_EVENT_STATE_INACTIVE;
7585 event->attach_state = PERF_ATTACH_TASK;
7587 * XXX pmu::event_init needs to know what task to account to
7588 * and we cannot use the ctx information because we need the
7589 * pmu before we get a ctx.
7591 event->hw.target = task;
7594 event->clock = &local_clock;
7596 event->clock = parent_event->clock;
7598 if (!overflow_handler && parent_event) {
7599 overflow_handler = parent_event->overflow_handler;
7600 context = parent_event->overflow_handler_context;
7603 event->overflow_handler = overflow_handler;
7604 event->overflow_handler_context = context;
7606 perf_event__state_init(event);
7611 hwc->sample_period = attr->sample_period;
7612 if (attr->freq && attr->sample_freq)
7613 hwc->sample_period = 1;
7614 hwc->last_period = hwc->sample_period;
7616 local64_set(&hwc->period_left, hwc->sample_period);
7619 * we currently do not support PERF_FORMAT_GROUP on inherited events
7621 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7624 if (!has_branch_stack(event))
7625 event->attr.branch_sample_type = 0;
7627 if (cgroup_fd != -1) {
7628 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7633 pmu = perf_init_event(event);
7636 else if (IS_ERR(pmu)) {
7641 err = exclusive_event_init(event);
7645 if (!event->parent) {
7646 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7647 err = get_callchain_buffers();
7656 exclusive_event_destroy(event);
7660 event->destroy(event);
7661 module_put(pmu->module);
7663 if (is_cgroup_event(event))
7664 perf_detach_cgroup(event);
7666 put_pid_ns(event->ns);
7669 return ERR_PTR(err);
7672 static int perf_copy_attr(struct perf_event_attr __user *uattr,
7673 struct perf_event_attr *attr)
7678 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
7682 * zero the full structure, so that a short copy will be nice.
7684 memset(attr, 0, sizeof(*attr));
7686 ret = get_user(size, &uattr->size);
7690 if (size > PAGE_SIZE) /* silly large */
7693 if (!size) /* abi compat */
7694 size = PERF_ATTR_SIZE_VER0;
7696 if (size < PERF_ATTR_SIZE_VER0)
7700 * If we're handed a bigger struct than we know of,
7701 * ensure all the unknown bits are 0 - i.e. new
7702 * user-space does not rely on any kernel feature
7703 * extensions we dont know about yet.
7705 if (size > sizeof(*attr)) {
7706 unsigned char __user *addr;
7707 unsigned char __user *end;
7710 addr = (void __user *)uattr + sizeof(*attr);
7711 end = (void __user *)uattr + size;
7713 for (; addr < end; addr++) {
7714 ret = get_user(val, addr);
7720 size = sizeof(*attr);
7723 ret = copy_from_user(attr, uattr, size);
7727 if (attr->__reserved_1)
7730 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
7733 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
7736 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
7737 u64 mask = attr->branch_sample_type;
7739 /* only using defined bits */
7740 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
7743 /* at least one branch bit must be set */
7744 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
7747 /* propagate priv level, when not set for branch */
7748 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
7750 /* exclude_kernel checked on syscall entry */
7751 if (!attr->exclude_kernel)
7752 mask |= PERF_SAMPLE_BRANCH_KERNEL;
7754 if (!attr->exclude_user)
7755 mask |= PERF_SAMPLE_BRANCH_USER;
7757 if (!attr->exclude_hv)
7758 mask |= PERF_SAMPLE_BRANCH_HV;
7760 * adjust user setting (for HW filter setup)
7762 attr->branch_sample_type = mask;
7764 /* privileged levels capture (kernel, hv): check permissions */
7765 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7766 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7770 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7771 ret = perf_reg_validate(attr->sample_regs_user);
7776 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7777 if (!arch_perf_have_user_stack_dump())
7781 * We have __u32 type for the size, but so far
7782 * we can only use __u16 as maximum due to the
7783 * __u16 sample size limit.
7785 if (attr->sample_stack_user >= USHRT_MAX)
7787 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7791 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
7792 ret = perf_reg_validate(attr->sample_regs_intr);
7797 put_user(sizeof(*attr), &uattr->size);
7803 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7805 struct ring_buffer *rb = NULL;
7811 /* don't allow circular references */
7812 if (event == output_event)
7816 * Don't allow cross-cpu buffers
7818 if (output_event->cpu != event->cpu)
7822 * If its not a per-cpu rb, it must be the same task.
7824 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7828 * Mixing clocks in the same buffer is trouble you don't need.
7830 if (output_event->clock != event->clock)
7834 * If both events generate aux data, they must be on the same PMU
7836 if (has_aux(event) && has_aux(output_event) &&
7837 event->pmu != output_event->pmu)
7841 mutex_lock(&event->mmap_mutex);
7842 /* Can't redirect output if we've got an active mmap() */
7843 if (atomic_read(&event->mmap_count))
7847 /* get the rb we want to redirect to */
7848 rb = ring_buffer_get(output_event);
7853 ring_buffer_attach(event, rb);
7857 mutex_unlock(&event->mmap_mutex);
7863 static void mutex_lock_double(struct mutex *a, struct mutex *b)
7869 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
7872 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
7874 bool nmi_safe = false;
7877 case CLOCK_MONOTONIC:
7878 event->clock = &ktime_get_mono_fast_ns;
7882 case CLOCK_MONOTONIC_RAW:
7883 event->clock = &ktime_get_raw_fast_ns;
7887 case CLOCK_REALTIME:
7888 event->clock = &ktime_get_real_ns;
7891 case CLOCK_BOOTTIME:
7892 event->clock = &ktime_get_boot_ns;
7896 event->clock = &ktime_get_tai_ns;
7903 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
7910 * sys_perf_event_open - open a performance event, associate it to a task/cpu
7912 * @attr_uptr: event_id type attributes for monitoring/sampling
7915 * @group_fd: group leader event fd
7917 SYSCALL_DEFINE5(perf_event_open,
7918 struct perf_event_attr __user *, attr_uptr,
7919 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7921 struct perf_event *group_leader = NULL, *output_event = NULL;
7922 struct perf_event *event, *sibling;
7923 struct perf_event_attr attr;
7924 struct perf_event_context *ctx, *uninitialized_var(gctx);
7925 struct file *event_file = NULL;
7926 struct fd group = {NULL, 0};
7927 struct task_struct *task = NULL;
7932 int f_flags = O_RDWR;
7935 /* for future expandability... */
7936 if (flags & ~PERF_FLAG_ALL)
7939 err = perf_copy_attr(attr_uptr, &attr);
7943 if (!attr.exclude_kernel) {
7944 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7949 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7952 if (attr.sample_period & (1ULL << 63))
7957 * In cgroup mode, the pid argument is used to pass the fd
7958 * opened to the cgroup directory in cgroupfs. The cpu argument
7959 * designates the cpu on which to monitor threads from that
7962 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7965 if (flags & PERF_FLAG_FD_CLOEXEC)
7966 f_flags |= O_CLOEXEC;
7968 event_fd = get_unused_fd_flags(f_flags);
7972 if (group_fd != -1) {
7973 err = perf_fget_light(group_fd, &group);
7976 group_leader = group.file->private_data;
7977 if (flags & PERF_FLAG_FD_OUTPUT)
7978 output_event = group_leader;
7979 if (flags & PERF_FLAG_FD_NO_GROUP)
7980 group_leader = NULL;
7983 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7984 task = find_lively_task_by_vpid(pid);
7986 err = PTR_ERR(task);
7991 if (task && group_leader &&
7992 group_leader->attr.inherit != attr.inherit) {
7999 if (flags & PERF_FLAG_PID_CGROUP)
8002 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8003 NULL, NULL, cgroup_fd);
8004 if (IS_ERR(event)) {
8005 err = PTR_ERR(event);
8009 if (is_sampling_event(event)) {
8010 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8016 account_event(event);
8019 * Special case software events and allow them to be part of
8020 * any hardware group.
8024 if (attr.use_clockid) {
8025 err = perf_event_set_clock(event, attr.clockid);
8031 (is_software_event(event) != is_software_event(group_leader))) {
8032 if (is_software_event(event)) {
8034 * If event and group_leader are not both a software
8035 * event, and event is, then group leader is not.
8037 * Allow the addition of software events to !software
8038 * groups, this is safe because software events never
8041 pmu = group_leader->pmu;
8042 } else if (is_software_event(group_leader) &&
8043 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8045 * In case the group is a pure software group, and we
8046 * try to add a hardware event, move the whole group to
8047 * the hardware context.
8054 * Get the target context (task or percpu):
8056 ctx = find_get_context(pmu, task, event);
8062 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8068 put_task_struct(task);
8073 * Look up the group leader (we will attach this event to it):
8079 * Do not allow a recursive hierarchy (this new sibling
8080 * becoming part of another group-sibling):
8082 if (group_leader->group_leader != group_leader)
8085 /* All events in a group should have the same clock */
8086 if (group_leader->clock != event->clock)
8090 * Do not allow to attach to a group in a different
8091 * task or CPU context:
8095 * Make sure we're both on the same task, or both
8098 if (group_leader->ctx->task != ctx->task)
8102 * Make sure we're both events for the same CPU;
8103 * grouping events for different CPUs is broken; since
8104 * you can never concurrently schedule them anyhow.
8106 if (group_leader->cpu != event->cpu)
8109 if (group_leader->ctx != ctx)
8114 * Only a group leader can be exclusive or pinned
8116 if (attr.exclusive || attr.pinned)
8121 err = perf_event_set_output(event, output_event);
8126 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8128 if (IS_ERR(event_file)) {
8129 err = PTR_ERR(event_file);
8134 gctx = group_leader->ctx;
8137 * See perf_event_ctx_lock() for comments on the details
8138 * of swizzling perf_event::ctx.
8140 mutex_lock_double(&gctx->mutex, &ctx->mutex);
8142 perf_remove_from_context(group_leader, false);
8144 list_for_each_entry(sibling, &group_leader->sibling_list,
8146 perf_remove_from_context(sibling, false);
8150 mutex_lock(&ctx->mutex);
8153 WARN_ON_ONCE(ctx->parent_ctx);
8157 * Wait for everybody to stop referencing the events through
8158 * the old lists, before installing it on new lists.
8163 * Install the group siblings before the group leader.
8165 * Because a group leader will try and install the entire group
8166 * (through the sibling list, which is still in-tact), we can
8167 * end up with siblings installed in the wrong context.
8169 * By installing siblings first we NO-OP because they're not
8170 * reachable through the group lists.
8172 list_for_each_entry(sibling, &group_leader->sibling_list,
8174 perf_event__state_init(sibling);
8175 perf_install_in_context(ctx, sibling, sibling->cpu);
8180 * Removing from the context ends up with disabled
8181 * event. What we want here is event in the initial
8182 * startup state, ready to be add into new context.
8184 perf_event__state_init(group_leader);
8185 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8189 if (!exclusive_event_installable(event, ctx)) {
8191 mutex_unlock(&ctx->mutex);
8196 perf_install_in_context(ctx, event, event->cpu);
8197 perf_unpin_context(ctx);
8200 mutex_unlock(&gctx->mutex);
8203 mutex_unlock(&ctx->mutex);
8207 event->owner = current;
8209 mutex_lock(¤t->perf_event_mutex);
8210 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
8211 mutex_unlock(¤t->perf_event_mutex);
8214 * Precalculate sample_data sizes
8216 perf_event__header_size(event);
8217 perf_event__id_header_size(event);
8220 * Drop the reference on the group_event after placing the
8221 * new event on the sibling_list. This ensures destruction
8222 * of the group leader will find the pointer to itself in
8223 * perf_group_detach().
8226 fd_install(event_fd, event_file);
8230 perf_unpin_context(ctx);
8238 put_task_struct(task);
8242 put_unused_fd(event_fd);
8247 * perf_event_create_kernel_counter
8249 * @attr: attributes of the counter to create
8250 * @cpu: cpu in which the counter is bound
8251 * @task: task to profile (NULL for percpu)
8254 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8255 struct task_struct *task,
8256 perf_overflow_handler_t overflow_handler,
8259 struct perf_event_context *ctx;
8260 struct perf_event *event;
8264 * Get the target context (task or percpu):
8267 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8268 overflow_handler, context, -1);
8269 if (IS_ERR(event)) {
8270 err = PTR_ERR(event);
8274 /* Mark owner so we could distinguish it from user events. */
8275 event->owner = EVENT_OWNER_KERNEL;
8277 account_event(event);
8279 ctx = find_get_context(event->pmu, task, event);
8285 WARN_ON_ONCE(ctx->parent_ctx);
8286 mutex_lock(&ctx->mutex);
8287 if (!exclusive_event_installable(event, ctx)) {
8288 mutex_unlock(&ctx->mutex);
8289 perf_unpin_context(ctx);
8295 perf_install_in_context(ctx, event, cpu);
8296 perf_unpin_context(ctx);
8297 mutex_unlock(&ctx->mutex);
8304 return ERR_PTR(err);
8306 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8308 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8310 struct perf_event_context *src_ctx;
8311 struct perf_event_context *dst_ctx;
8312 struct perf_event *event, *tmp;
8315 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8316 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8319 * See perf_event_ctx_lock() for comments on the details
8320 * of swizzling perf_event::ctx.
8322 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8323 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8325 perf_remove_from_context(event, false);
8326 unaccount_event_cpu(event, src_cpu);
8328 list_add(&event->migrate_entry, &events);
8332 * Wait for the events to quiesce before re-instating them.
8337 * Re-instate events in 2 passes.
8339 * Skip over group leaders and only install siblings on this first
8340 * pass, siblings will not get enabled without a leader, however a
8341 * leader will enable its siblings, even if those are still on the old
8344 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8345 if (event->group_leader == event)
8348 list_del(&event->migrate_entry);
8349 if (event->state >= PERF_EVENT_STATE_OFF)
8350 event->state = PERF_EVENT_STATE_INACTIVE;
8351 account_event_cpu(event, dst_cpu);
8352 perf_install_in_context(dst_ctx, event, dst_cpu);
8357 * Once all the siblings are setup properly, install the group leaders
8360 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8361 list_del(&event->migrate_entry);
8362 if (event->state >= PERF_EVENT_STATE_OFF)
8363 event->state = PERF_EVENT_STATE_INACTIVE;
8364 account_event_cpu(event, dst_cpu);
8365 perf_install_in_context(dst_ctx, event, dst_cpu);
8368 mutex_unlock(&dst_ctx->mutex);
8369 mutex_unlock(&src_ctx->mutex);
8371 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8373 static void sync_child_event(struct perf_event *child_event,
8374 struct task_struct *child)
8376 struct perf_event *parent_event = child_event->parent;
8379 if (child_event->attr.inherit_stat)
8380 perf_event_read_event(child_event, child);
8382 child_val = perf_event_count(child_event);
8385 * Add back the child's count to the parent's count:
8387 atomic64_add(child_val, &parent_event->child_count);
8388 atomic64_add(child_event->total_time_enabled,
8389 &parent_event->child_total_time_enabled);
8390 atomic64_add(child_event->total_time_running,
8391 &parent_event->child_total_time_running);
8394 * Remove this event from the parent's list
8396 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8397 mutex_lock(&parent_event->child_mutex);
8398 list_del_init(&child_event->child_list);
8399 mutex_unlock(&parent_event->child_mutex);
8402 * Make sure user/parent get notified, that we just
8405 perf_event_wakeup(parent_event);
8408 * Release the parent event, if this was the last
8411 put_event(parent_event);
8415 __perf_event_exit_task(struct perf_event *child_event,
8416 struct perf_event_context *child_ctx,
8417 struct task_struct *child)
8420 * Do not destroy the 'original' grouping; because of the context
8421 * switch optimization the original events could've ended up in a
8422 * random child task.
8424 * If we were to destroy the original group, all group related
8425 * operations would cease to function properly after this random
8428 * Do destroy all inherited groups, we don't care about those
8429 * and being thorough is better.
8431 perf_remove_from_context(child_event, !!child_event->parent);
8434 * It can happen that the parent exits first, and has events
8435 * that are still around due to the child reference. These
8436 * events need to be zapped.
8438 if (child_event->parent) {
8439 sync_child_event(child_event, child);
8440 free_event(child_event);
8442 child_event->state = PERF_EVENT_STATE_EXIT;
8443 perf_event_wakeup(child_event);
8447 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8449 struct perf_event *child_event, *next;
8450 struct perf_event_context *child_ctx, *clone_ctx = NULL;
8451 unsigned long flags;
8453 if (likely(!child->perf_event_ctxp[ctxn])) {
8454 perf_event_task(child, NULL, 0);
8458 local_irq_save(flags);
8460 * We can't reschedule here because interrupts are disabled,
8461 * and either child is current or it is a task that can't be
8462 * scheduled, so we are now safe from rescheduling changing
8465 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8468 * Take the context lock here so that if find_get_context is
8469 * reading child->perf_event_ctxp, we wait until it has
8470 * incremented the context's refcount before we do put_ctx below.
8472 raw_spin_lock(&child_ctx->lock);
8473 task_ctx_sched_out(child_ctx);
8474 child->perf_event_ctxp[ctxn] = NULL;
8477 * If this context is a clone; unclone it so it can't get
8478 * swapped to another process while we're removing all
8479 * the events from it.
8481 clone_ctx = unclone_ctx(child_ctx);
8482 update_context_time(child_ctx);
8483 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8489 * Report the task dead after unscheduling the events so that we
8490 * won't get any samples after PERF_RECORD_EXIT. We can however still
8491 * get a few PERF_RECORD_READ events.
8493 perf_event_task(child, child_ctx, 0);
8496 * We can recurse on the same lock type through:
8498 * __perf_event_exit_task()
8499 * sync_child_event()
8501 * mutex_lock(&ctx->mutex)
8503 * But since its the parent context it won't be the same instance.
8505 mutex_lock(&child_ctx->mutex);
8507 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8508 __perf_event_exit_task(child_event, child_ctx, child);
8510 mutex_unlock(&child_ctx->mutex);
8516 * When a child task exits, feed back event values to parent events.
8518 void perf_event_exit_task(struct task_struct *child)
8520 struct perf_event *event, *tmp;
8523 mutex_lock(&child->perf_event_mutex);
8524 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8526 list_del_init(&event->owner_entry);
8529 * Ensure the list deletion is visible before we clear
8530 * the owner, closes a race against perf_release() where
8531 * we need to serialize on the owner->perf_event_mutex.
8534 event->owner = NULL;
8536 mutex_unlock(&child->perf_event_mutex);
8538 for_each_task_context_nr(ctxn)
8539 perf_event_exit_task_context(child, ctxn);
8542 static void perf_free_event(struct perf_event *event,
8543 struct perf_event_context *ctx)
8545 struct perf_event *parent = event->parent;
8547 if (WARN_ON_ONCE(!parent))
8550 mutex_lock(&parent->child_mutex);
8551 list_del_init(&event->child_list);
8552 mutex_unlock(&parent->child_mutex);
8556 raw_spin_lock_irq(&ctx->lock);
8557 perf_group_detach(event);
8558 list_del_event(event, ctx);
8559 raw_spin_unlock_irq(&ctx->lock);
8564 * Free an unexposed, unused context as created by inheritance by
8565 * perf_event_init_task below, used by fork() in case of fail.
8567 * Not all locks are strictly required, but take them anyway to be nice and
8568 * help out with the lockdep assertions.
8570 void perf_event_free_task(struct task_struct *task)
8572 struct perf_event_context *ctx;
8573 struct perf_event *event, *tmp;
8576 for_each_task_context_nr(ctxn) {
8577 ctx = task->perf_event_ctxp[ctxn];
8581 mutex_lock(&ctx->mutex);
8583 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8585 perf_free_event(event, ctx);
8587 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8589 perf_free_event(event, ctx);
8591 if (!list_empty(&ctx->pinned_groups) ||
8592 !list_empty(&ctx->flexible_groups))
8595 mutex_unlock(&ctx->mutex);
8601 void perf_event_delayed_put(struct task_struct *task)
8605 for_each_task_context_nr(ctxn)
8606 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
8610 * inherit a event from parent task to child task:
8612 static struct perf_event *
8613 inherit_event(struct perf_event *parent_event,
8614 struct task_struct *parent,
8615 struct perf_event_context *parent_ctx,
8616 struct task_struct *child,
8617 struct perf_event *group_leader,
8618 struct perf_event_context *child_ctx)
8620 enum perf_event_active_state parent_state = parent_event->state;
8621 struct perf_event *child_event;
8622 unsigned long flags;
8625 * Instead of creating recursive hierarchies of events,
8626 * we link inherited events back to the original parent,
8627 * which has a filp for sure, which we use as the reference
8630 if (parent_event->parent)
8631 parent_event = parent_event->parent;
8633 child_event = perf_event_alloc(&parent_event->attr,
8636 group_leader, parent_event,
8638 if (IS_ERR(child_event))
8641 if (is_orphaned_event(parent_event) ||
8642 !atomic_long_inc_not_zero(&parent_event->refcount)) {
8643 free_event(child_event);
8650 * Make the child state follow the state of the parent event,
8651 * not its attr.disabled bit. We hold the parent's mutex,
8652 * so we won't race with perf_event_{en, dis}able_family.
8654 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
8655 child_event->state = PERF_EVENT_STATE_INACTIVE;
8657 child_event->state = PERF_EVENT_STATE_OFF;
8659 if (parent_event->attr.freq) {
8660 u64 sample_period = parent_event->hw.sample_period;
8661 struct hw_perf_event *hwc = &child_event->hw;
8663 hwc->sample_period = sample_period;
8664 hwc->last_period = sample_period;
8666 local64_set(&hwc->period_left, sample_period);
8669 child_event->ctx = child_ctx;
8670 child_event->overflow_handler = parent_event->overflow_handler;
8671 child_event->overflow_handler_context
8672 = parent_event->overflow_handler_context;
8675 * Precalculate sample_data sizes
8677 perf_event__header_size(child_event);
8678 perf_event__id_header_size(child_event);
8681 * Link it up in the child's context:
8683 raw_spin_lock_irqsave(&child_ctx->lock, flags);
8684 add_event_to_ctx(child_event, child_ctx);
8685 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8688 * Link this into the parent event's child list
8690 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8691 mutex_lock(&parent_event->child_mutex);
8692 list_add_tail(&child_event->child_list, &parent_event->child_list);
8693 mutex_unlock(&parent_event->child_mutex);
8698 static int inherit_group(struct perf_event *parent_event,
8699 struct task_struct *parent,
8700 struct perf_event_context *parent_ctx,
8701 struct task_struct *child,
8702 struct perf_event_context *child_ctx)
8704 struct perf_event *leader;
8705 struct perf_event *sub;
8706 struct perf_event *child_ctr;
8708 leader = inherit_event(parent_event, parent, parent_ctx,
8709 child, NULL, child_ctx);
8711 return PTR_ERR(leader);
8712 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
8713 child_ctr = inherit_event(sub, parent, parent_ctx,
8714 child, leader, child_ctx);
8715 if (IS_ERR(child_ctr))
8716 return PTR_ERR(child_ctr);
8722 inherit_task_group(struct perf_event *event, struct task_struct *parent,
8723 struct perf_event_context *parent_ctx,
8724 struct task_struct *child, int ctxn,
8728 struct perf_event_context *child_ctx;
8730 if (!event->attr.inherit) {
8735 child_ctx = child->perf_event_ctxp[ctxn];
8738 * This is executed from the parent task context, so
8739 * inherit events that have been marked for cloning.
8740 * First allocate and initialize a context for the
8744 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
8748 child->perf_event_ctxp[ctxn] = child_ctx;
8751 ret = inherit_group(event, parent, parent_ctx,
8761 * Initialize the perf_event context in task_struct
8763 static int perf_event_init_context(struct task_struct *child, int ctxn)
8765 struct perf_event_context *child_ctx, *parent_ctx;
8766 struct perf_event_context *cloned_ctx;
8767 struct perf_event *event;
8768 struct task_struct *parent = current;
8769 int inherited_all = 1;
8770 unsigned long flags;
8773 if (likely(!parent->perf_event_ctxp[ctxn]))
8777 * If the parent's context is a clone, pin it so it won't get
8780 parent_ctx = perf_pin_task_context(parent, ctxn);
8785 * No need to check if parent_ctx != NULL here; since we saw
8786 * it non-NULL earlier, the only reason for it to become NULL
8787 * is if we exit, and since we're currently in the middle of
8788 * a fork we can't be exiting at the same time.
8792 * Lock the parent list. No need to lock the child - not PID
8793 * hashed yet and not running, so nobody can access it.
8795 mutex_lock(&parent_ctx->mutex);
8798 * We dont have to disable NMIs - we are only looking at
8799 * the list, not manipulating it:
8801 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
8802 ret = inherit_task_group(event, parent, parent_ctx,
8803 child, ctxn, &inherited_all);
8809 * We can't hold ctx->lock when iterating the ->flexible_group list due
8810 * to allocations, but we need to prevent rotation because
8811 * rotate_ctx() will change the list from interrupt context.
8813 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8814 parent_ctx->rotate_disable = 1;
8815 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8817 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
8818 ret = inherit_task_group(event, parent, parent_ctx,
8819 child, ctxn, &inherited_all);
8824 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8825 parent_ctx->rotate_disable = 0;
8827 child_ctx = child->perf_event_ctxp[ctxn];
8829 if (child_ctx && inherited_all) {
8831 * Mark the child context as a clone of the parent
8832 * context, or of whatever the parent is a clone of.
8834 * Note that if the parent is a clone, the holding of
8835 * parent_ctx->lock avoids it from being uncloned.
8837 cloned_ctx = parent_ctx->parent_ctx;
8839 child_ctx->parent_ctx = cloned_ctx;
8840 child_ctx->parent_gen = parent_ctx->parent_gen;
8842 child_ctx->parent_ctx = parent_ctx;
8843 child_ctx->parent_gen = parent_ctx->generation;
8845 get_ctx(child_ctx->parent_ctx);
8848 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8849 mutex_unlock(&parent_ctx->mutex);
8851 perf_unpin_context(parent_ctx);
8852 put_ctx(parent_ctx);
8858 * Initialize the perf_event context in task_struct
8860 int perf_event_init_task(struct task_struct *child)
8864 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
8865 mutex_init(&child->perf_event_mutex);
8866 INIT_LIST_HEAD(&child->perf_event_list);
8868 for_each_task_context_nr(ctxn) {
8869 ret = perf_event_init_context(child, ctxn);
8871 perf_event_free_task(child);
8879 static void __init perf_event_init_all_cpus(void)
8881 struct swevent_htable *swhash;
8884 for_each_possible_cpu(cpu) {
8885 swhash = &per_cpu(swevent_htable, cpu);
8886 mutex_init(&swhash->hlist_mutex);
8887 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
8891 static void perf_event_init_cpu(int cpu)
8893 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8895 mutex_lock(&swhash->hlist_mutex);
8896 swhash->online = true;
8897 if (swhash->hlist_refcount > 0) {
8898 struct swevent_hlist *hlist;
8900 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
8902 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8904 mutex_unlock(&swhash->hlist_mutex);
8907 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
8908 static void __perf_event_exit_context(void *__info)
8910 struct remove_event re = { .detach_group = true };
8911 struct perf_event_context *ctx = __info;
8914 list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8915 __perf_remove_from_context(&re);
8919 static void perf_event_exit_cpu_context(int cpu)
8921 struct perf_event_context *ctx;
8925 idx = srcu_read_lock(&pmus_srcu);
8926 list_for_each_entry_rcu(pmu, &pmus, entry) {
8927 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8929 mutex_lock(&ctx->mutex);
8930 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8931 mutex_unlock(&ctx->mutex);
8933 srcu_read_unlock(&pmus_srcu, idx);
8936 static void perf_event_exit_cpu(int cpu)
8938 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8940 perf_event_exit_cpu_context(cpu);
8942 mutex_lock(&swhash->hlist_mutex);
8943 swhash->online = false;
8944 swevent_hlist_release(swhash);
8945 mutex_unlock(&swhash->hlist_mutex);
8948 static inline void perf_event_exit_cpu(int cpu) { }
8952 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8956 for_each_online_cpu(cpu)
8957 perf_event_exit_cpu(cpu);
8963 * Run the perf reboot notifier at the very last possible moment so that
8964 * the generic watchdog code runs as long as possible.
8966 static struct notifier_block perf_reboot_notifier = {
8967 .notifier_call = perf_reboot,
8968 .priority = INT_MIN,
8972 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8974 unsigned int cpu = (long)hcpu;
8976 switch (action & ~CPU_TASKS_FROZEN) {
8978 case CPU_UP_PREPARE:
8979 case CPU_DOWN_FAILED:
8980 perf_event_init_cpu(cpu);
8983 case CPU_UP_CANCELED:
8984 case CPU_DOWN_PREPARE:
8985 perf_event_exit_cpu(cpu);
8994 void __init perf_event_init(void)
9000 perf_event_init_all_cpus();
9001 init_srcu_struct(&pmus_srcu);
9002 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9003 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9004 perf_pmu_register(&perf_task_clock, NULL, -1);
9006 perf_cpu_notifier(perf_cpu_notify);
9007 register_reboot_notifier(&perf_reboot_notifier);
9009 ret = init_hw_breakpoint();
9010 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9012 /* do not patch jump label more than once per second */
9013 jump_label_rate_limit(&perf_sched_events, HZ);
9016 * Build time assertion that we keep the data_head at the intended
9017 * location. IOW, validation we got the __reserved[] size right.
9019 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9023 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9026 struct perf_pmu_events_attr *pmu_attr =
9027 container_of(attr, struct perf_pmu_events_attr, attr);
9029 if (pmu_attr->event_str)
9030 return sprintf(page, "%s\n", pmu_attr->event_str);
9035 static int __init perf_event_sysfs_init(void)
9040 mutex_lock(&pmus_lock);
9042 ret = bus_register(&pmu_bus);
9046 list_for_each_entry(pmu, &pmus, entry) {
9047 if (!pmu->name || pmu->type < 0)
9050 ret = pmu_dev_alloc(pmu);
9051 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9053 pmu_bus_running = 1;
9057 mutex_unlock(&pmus_lock);
9061 device_initcall(perf_event_sysfs_init);
9063 #ifdef CONFIG_CGROUP_PERF
9064 static struct cgroup_subsys_state *
9065 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9067 struct perf_cgroup *jc;
9069 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9071 return ERR_PTR(-ENOMEM);
9073 jc->info = alloc_percpu(struct perf_cgroup_info);
9076 return ERR_PTR(-ENOMEM);
9082 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9084 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9086 free_percpu(jc->info);
9090 static int __perf_cgroup_move(void *info)
9092 struct task_struct *task = info;
9093 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9097 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
9098 struct cgroup_taskset *tset)
9100 struct task_struct *task;
9102 cgroup_taskset_for_each(task, tset)
9103 task_function_call(task, __perf_cgroup_move, task);
9106 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
9107 struct cgroup_subsys_state *old_css,
9108 struct task_struct *task)
9111 * cgroup_exit() is called in the copy_process() failure path.
9112 * Ignore this case since the task hasn't ran yet, this avoids
9113 * trying to poke a half freed task state from generic code.
9115 if (!(task->flags & PF_EXITING))
9118 task_function_call(task, __perf_cgroup_move, task);
9121 struct cgroup_subsys perf_event_cgrp_subsys = {
9122 .css_alloc = perf_cgroup_css_alloc,
9123 .css_free = perf_cgroup_css_free,
9124 .exit = perf_cgroup_exit,
9125 .attach = perf_cgroup_attach,
9127 #endif /* CONFIG_CGROUP_PERF */