2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
52 #include <asm/irq_regs.h>
54 typedef int (*remote_function_f)(void *);
56 struct remote_function_call {
57 struct task_struct *p;
58 remote_function_f func;
63 static void remote_function(void *data)
65 struct remote_function_call *tfc = data;
66 struct task_struct *p = tfc->p;
70 if (task_cpu(p) != smp_processor_id())
74 * Now that we're on right CPU with IRQs disabled, we can test
75 * if we hit the right task without races.
78 tfc->ret = -ESRCH; /* No such (running) process */
83 tfc->ret = tfc->func(tfc->info);
87 * task_function_call - call a function on the cpu on which a task runs
88 * @p: the task to evaluate
89 * @func: the function to be called
90 * @info: the function call argument
92 * Calls the function @func when the task is currently running. This might
93 * be on the current CPU, which just calls the function directly
95 * returns: @func return value, or
96 * -ESRCH - when the process isn't running
97 * -EAGAIN - when the process moved away
100 task_function_call(struct task_struct *p, remote_function_f func, void *info)
102 struct remote_function_call data = {
111 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
114 } while (ret == -EAGAIN);
120 * cpu_function_call - call a function on the cpu
121 * @func: the function to be called
122 * @info: the function call argument
124 * Calls the function @func on the remote cpu.
126 * returns: @func return value or -ENXIO when the cpu is offline
128 static int cpu_function_call(int cpu, remote_function_f func, void *info)
130 struct remote_function_call data = {
134 .ret = -ENXIO, /* No such CPU */
137 smp_call_function_single(cpu, remote_function, &data, 1);
142 static inline struct perf_cpu_context *
143 __get_cpu_context(struct perf_event_context *ctx)
145 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
148 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
149 struct perf_event_context *ctx)
151 raw_spin_lock(&cpuctx->ctx.lock);
153 raw_spin_lock(&ctx->lock);
156 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
157 struct perf_event_context *ctx)
160 raw_spin_unlock(&ctx->lock);
161 raw_spin_unlock(&cpuctx->ctx.lock);
164 #define TASK_TOMBSTONE ((void *)-1L)
166 static bool is_kernel_event(struct perf_event *event)
168 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
172 * On task ctx scheduling...
174 * When !ctx->nr_events a task context will not be scheduled. This means
175 * we can disable the scheduler hooks (for performance) without leaving
176 * pending task ctx state.
178 * This however results in two special cases:
180 * - removing the last event from a task ctx; this is relatively straight
181 * forward and is done in __perf_remove_from_context.
183 * - adding the first event to a task ctx; this is tricky because we cannot
184 * rely on ctx->is_active and therefore cannot use event_function_call().
185 * See perf_install_in_context().
187 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
190 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
191 struct perf_event_context *, void *);
193 struct event_function_struct {
194 struct perf_event *event;
199 static int event_function(void *info)
201 struct event_function_struct *efs = info;
202 struct perf_event *event = efs->event;
203 struct perf_event_context *ctx = event->ctx;
204 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
205 struct perf_event_context *task_ctx = cpuctx->task_ctx;
208 WARN_ON_ONCE(!irqs_disabled());
210 perf_ctx_lock(cpuctx, task_ctx);
212 * Since we do the IPI call without holding ctx->lock things can have
213 * changed, double check we hit the task we set out to hit.
216 if (ctx->task != current) {
222 * We only use event_function_call() on established contexts,
223 * and event_function() is only ever called when active (or
224 * rather, we'll have bailed in task_function_call() or the
225 * above ctx->task != current test), therefore we must have
226 * ctx->is_active here.
228 WARN_ON_ONCE(!ctx->is_active);
230 * And since we have ctx->is_active, cpuctx->task_ctx must
233 WARN_ON_ONCE(task_ctx != ctx);
235 WARN_ON_ONCE(&cpuctx->ctx != ctx);
238 efs->func(event, cpuctx, ctx, efs->data);
240 perf_ctx_unlock(cpuctx, task_ctx);
245 static void event_function_local(struct perf_event *event, event_f func, void *data)
247 struct event_function_struct efs = {
253 int ret = event_function(&efs);
257 static void event_function_call(struct perf_event *event, event_f func, void *data)
259 struct perf_event_context *ctx = event->ctx;
260 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
261 struct event_function_struct efs = {
267 if (!event->parent) {
269 * If this is a !child event, we must hold ctx::mutex to
270 * stabilize the the event->ctx relation. See
271 * perf_event_ctx_lock().
273 lockdep_assert_held(&ctx->mutex);
277 cpu_function_call(event->cpu, event_function, &efs);
281 if (task == TASK_TOMBSTONE)
285 if (!task_function_call(task, event_function, &efs))
288 raw_spin_lock_irq(&ctx->lock);
290 * Reload the task pointer, it might have been changed by
291 * a concurrent perf_event_context_sched_out().
294 if (task == TASK_TOMBSTONE) {
295 raw_spin_unlock_irq(&ctx->lock);
298 if (ctx->is_active) {
299 raw_spin_unlock_irq(&ctx->lock);
302 func(event, NULL, ctx, data);
303 raw_spin_unlock_irq(&ctx->lock);
306 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
307 PERF_FLAG_FD_OUTPUT |\
308 PERF_FLAG_PID_CGROUP |\
309 PERF_FLAG_FD_CLOEXEC)
312 * branch priv levels that need permission checks
314 #define PERF_SAMPLE_BRANCH_PERM_PLM \
315 (PERF_SAMPLE_BRANCH_KERNEL |\
316 PERF_SAMPLE_BRANCH_HV)
319 EVENT_FLEXIBLE = 0x1,
322 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
326 * perf_sched_events : >0 events exist
327 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
330 static void perf_sched_delayed(struct work_struct *work);
331 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
332 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
333 static DEFINE_MUTEX(perf_sched_mutex);
334 static atomic_t perf_sched_count;
336 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
337 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
338 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
340 static atomic_t nr_mmap_events __read_mostly;
341 static atomic_t nr_comm_events __read_mostly;
342 static atomic_t nr_task_events __read_mostly;
343 static atomic_t nr_freq_events __read_mostly;
344 static atomic_t nr_switch_events __read_mostly;
346 static LIST_HEAD(pmus);
347 static DEFINE_MUTEX(pmus_lock);
348 static struct srcu_struct pmus_srcu;
351 * perf event paranoia level:
352 * -1 - not paranoid at all
353 * 0 - disallow raw tracepoint access for unpriv
354 * 1 - disallow cpu events for unpriv
355 * 2 - disallow kernel profiling for unpriv
357 int sysctl_perf_event_paranoid __read_mostly = 2;
359 /* Minimum for 512 kiB + 1 user control page */
360 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
363 * max perf event sample rate
365 #define DEFAULT_MAX_SAMPLE_RATE 100000
366 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
367 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
369 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
371 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
372 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
374 static int perf_sample_allowed_ns __read_mostly =
375 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
377 static void update_perf_cpu_limits(void)
379 u64 tmp = perf_sample_period_ns;
381 tmp *= sysctl_perf_cpu_time_max_percent;
382 tmp = div_u64(tmp, 100);
386 WRITE_ONCE(perf_sample_allowed_ns, tmp);
389 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
391 int perf_proc_update_handler(struct ctl_table *table, int write,
392 void __user *buffer, size_t *lenp,
395 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
401 * If throttling is disabled don't allow the write:
403 if (sysctl_perf_cpu_time_max_percent == 100 ||
404 sysctl_perf_cpu_time_max_percent == 0)
407 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
408 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
409 update_perf_cpu_limits();
414 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
416 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
417 void __user *buffer, size_t *lenp,
420 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
425 if (sysctl_perf_cpu_time_max_percent == 100 ||
426 sysctl_perf_cpu_time_max_percent == 0) {
428 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
429 WRITE_ONCE(perf_sample_allowed_ns, 0);
431 update_perf_cpu_limits();
438 * perf samples are done in some very critical code paths (NMIs).
439 * If they take too much CPU time, the system can lock up and not
440 * get any real work done. This will drop the sample rate when
441 * we detect that events are taking too long.
443 #define NR_ACCUMULATED_SAMPLES 128
444 static DEFINE_PER_CPU(u64, running_sample_length);
446 static u64 __report_avg;
447 static u64 __report_allowed;
449 static void perf_duration_warn(struct irq_work *w)
451 printk_ratelimited(KERN_WARNING
452 "perf: interrupt took too long (%lld > %lld), lowering "
453 "kernel.perf_event_max_sample_rate to %d\n",
454 __report_avg, __report_allowed,
455 sysctl_perf_event_sample_rate);
458 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
460 void perf_sample_event_took(u64 sample_len_ns)
462 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
470 /* Decay the counter by 1 average sample. */
471 running_len = __this_cpu_read(running_sample_length);
472 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
473 running_len += sample_len_ns;
474 __this_cpu_write(running_sample_length, running_len);
477 * Note: this will be biased artifically low until we have
478 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
479 * from having to maintain a count.
481 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
482 if (avg_len <= max_len)
485 __report_avg = avg_len;
486 __report_allowed = max_len;
489 * Compute a throttle threshold 25% below the current duration.
491 avg_len += avg_len / 4;
492 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
498 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
499 WRITE_ONCE(max_samples_per_tick, max);
501 sysctl_perf_event_sample_rate = max * HZ;
502 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
504 if (!irq_work_queue(&perf_duration_work)) {
505 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
506 "kernel.perf_event_max_sample_rate to %d\n",
507 __report_avg, __report_allowed,
508 sysctl_perf_event_sample_rate);
512 static atomic64_t perf_event_id;
514 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
515 enum event_type_t event_type);
517 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
518 enum event_type_t event_type,
519 struct task_struct *task);
521 static void update_context_time(struct perf_event_context *ctx);
522 static u64 perf_event_time(struct perf_event *event);
524 void __weak perf_event_print_debug(void) { }
526 extern __weak const char *perf_pmu_name(void)
531 static inline u64 perf_clock(void)
533 return local_clock();
536 static inline u64 perf_event_clock(struct perf_event *event)
538 return event->clock();
541 #ifdef CONFIG_CGROUP_PERF
544 perf_cgroup_match(struct perf_event *event)
546 struct perf_event_context *ctx = event->ctx;
547 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
549 /* @event doesn't care about cgroup */
553 /* wants specific cgroup scope but @cpuctx isn't associated with any */
558 * Cgroup scoping is recursive. An event enabled for a cgroup is
559 * also enabled for all its descendant cgroups. If @cpuctx's
560 * cgroup is a descendant of @event's (the test covers identity
561 * case), it's a match.
563 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
564 event->cgrp->css.cgroup);
567 static inline void perf_detach_cgroup(struct perf_event *event)
569 css_put(&event->cgrp->css);
573 static inline int is_cgroup_event(struct perf_event *event)
575 return event->cgrp != NULL;
578 static inline u64 perf_cgroup_event_time(struct perf_event *event)
580 struct perf_cgroup_info *t;
582 t = per_cpu_ptr(event->cgrp->info, event->cpu);
586 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
588 struct perf_cgroup_info *info;
593 info = this_cpu_ptr(cgrp->info);
595 info->time += now - info->timestamp;
596 info->timestamp = now;
599 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
601 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
603 __update_cgrp_time(cgrp_out);
606 static inline void update_cgrp_time_from_event(struct perf_event *event)
608 struct perf_cgroup *cgrp;
611 * ensure we access cgroup data only when needed and
612 * when we know the cgroup is pinned (css_get)
614 if (!is_cgroup_event(event))
617 cgrp = perf_cgroup_from_task(current, event->ctx);
619 * Do not update time when cgroup is not active
621 if (cgrp == event->cgrp)
622 __update_cgrp_time(event->cgrp);
626 perf_cgroup_set_timestamp(struct task_struct *task,
627 struct perf_event_context *ctx)
629 struct perf_cgroup *cgrp;
630 struct perf_cgroup_info *info;
633 * ctx->lock held by caller
634 * ensure we do not access cgroup data
635 * unless we have the cgroup pinned (css_get)
637 if (!task || !ctx->nr_cgroups)
640 cgrp = perf_cgroup_from_task(task, ctx);
641 info = this_cpu_ptr(cgrp->info);
642 info->timestamp = ctx->timestamp;
645 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
646 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
649 * reschedule events based on the cgroup constraint of task.
651 * mode SWOUT : schedule out everything
652 * mode SWIN : schedule in based on cgroup for next
654 static void perf_cgroup_switch(struct task_struct *task, int mode)
656 struct perf_cpu_context *cpuctx;
661 * disable interrupts to avoid geting nr_cgroup
662 * changes via __perf_event_disable(). Also
665 local_irq_save(flags);
668 * we reschedule only in the presence of cgroup
669 * constrained events.
672 list_for_each_entry_rcu(pmu, &pmus, entry) {
673 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
674 if (cpuctx->unique_pmu != pmu)
675 continue; /* ensure we process each cpuctx once */
678 * perf_cgroup_events says at least one
679 * context on this CPU has cgroup events.
681 * ctx->nr_cgroups reports the number of cgroup
682 * events for a context.
684 if (cpuctx->ctx.nr_cgroups > 0) {
685 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
686 perf_pmu_disable(cpuctx->ctx.pmu);
688 if (mode & PERF_CGROUP_SWOUT) {
689 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
691 * must not be done before ctxswout due
692 * to event_filter_match() in event_sched_out()
697 if (mode & PERF_CGROUP_SWIN) {
698 WARN_ON_ONCE(cpuctx->cgrp);
700 * set cgrp before ctxsw in to allow
701 * event_filter_match() to not have to pass
703 * we pass the cpuctx->ctx to perf_cgroup_from_task()
704 * because cgorup events are only per-cpu
706 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
707 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
709 perf_pmu_enable(cpuctx->ctx.pmu);
710 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
714 local_irq_restore(flags);
717 static inline void perf_cgroup_sched_out(struct task_struct *task,
718 struct task_struct *next)
720 struct perf_cgroup *cgrp1;
721 struct perf_cgroup *cgrp2 = NULL;
725 * we come here when we know perf_cgroup_events > 0
726 * we do not need to pass the ctx here because we know
727 * we are holding the rcu lock
729 cgrp1 = perf_cgroup_from_task(task, NULL);
730 cgrp2 = perf_cgroup_from_task(next, NULL);
733 * only schedule out current cgroup events if we know
734 * that we are switching to a different cgroup. Otherwise,
735 * do no touch the cgroup events.
738 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
743 static inline void perf_cgroup_sched_in(struct task_struct *prev,
744 struct task_struct *task)
746 struct perf_cgroup *cgrp1;
747 struct perf_cgroup *cgrp2 = NULL;
751 * we come here when we know perf_cgroup_events > 0
752 * we do not need to pass the ctx here because we know
753 * we are holding the rcu lock
755 cgrp1 = perf_cgroup_from_task(task, NULL);
756 cgrp2 = perf_cgroup_from_task(prev, NULL);
759 * only need to schedule in cgroup events if we are changing
760 * cgroup during ctxsw. Cgroup events were not scheduled
761 * out of ctxsw out if that was not the case.
764 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
769 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
770 struct perf_event_attr *attr,
771 struct perf_event *group_leader)
773 struct perf_cgroup *cgrp;
774 struct cgroup_subsys_state *css;
775 struct fd f = fdget(fd);
781 css = css_tryget_online_from_dir(f.file->f_path.dentry,
782 &perf_event_cgrp_subsys);
788 cgrp = container_of(css, struct perf_cgroup, css);
792 * all events in a group must monitor
793 * the same cgroup because a task belongs
794 * to only one perf cgroup at a time
796 if (group_leader && group_leader->cgrp != cgrp) {
797 perf_detach_cgroup(event);
806 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
808 struct perf_cgroup_info *t;
809 t = per_cpu_ptr(event->cgrp->info, event->cpu);
810 event->shadow_ctx_time = now - t->timestamp;
814 perf_cgroup_defer_enabled(struct perf_event *event)
817 * when the current task's perf cgroup does not match
818 * the event's, we need to remember to call the
819 * perf_mark_enable() function the first time a task with
820 * a matching perf cgroup is scheduled in.
822 if (is_cgroup_event(event) && !perf_cgroup_match(event))
823 event->cgrp_defer_enabled = 1;
827 perf_cgroup_mark_enabled(struct perf_event *event,
828 struct perf_event_context *ctx)
830 struct perf_event *sub;
831 u64 tstamp = perf_event_time(event);
833 if (!event->cgrp_defer_enabled)
836 event->cgrp_defer_enabled = 0;
838 event->tstamp_enabled = tstamp - event->total_time_enabled;
839 list_for_each_entry(sub, &event->sibling_list, group_entry) {
840 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
841 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
842 sub->cgrp_defer_enabled = 0;
846 #else /* !CONFIG_CGROUP_PERF */
849 perf_cgroup_match(struct perf_event *event)
854 static inline void perf_detach_cgroup(struct perf_event *event)
857 static inline int is_cgroup_event(struct perf_event *event)
862 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
867 static inline void update_cgrp_time_from_event(struct perf_event *event)
871 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
875 static inline void perf_cgroup_sched_out(struct task_struct *task,
876 struct task_struct *next)
880 static inline void perf_cgroup_sched_in(struct task_struct *prev,
881 struct task_struct *task)
885 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
886 struct perf_event_attr *attr,
887 struct perf_event *group_leader)
893 perf_cgroup_set_timestamp(struct task_struct *task,
894 struct perf_event_context *ctx)
899 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
904 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
908 static inline u64 perf_cgroup_event_time(struct perf_event *event)
914 perf_cgroup_defer_enabled(struct perf_event *event)
919 perf_cgroup_mark_enabled(struct perf_event *event,
920 struct perf_event_context *ctx)
926 * set default to be dependent on timer tick just
929 #define PERF_CPU_HRTIMER (1000 / HZ)
931 * function must be called with interrupts disbled
933 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
935 struct perf_cpu_context *cpuctx;
938 WARN_ON(!irqs_disabled());
940 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
941 rotations = perf_rotate_context(cpuctx);
943 raw_spin_lock(&cpuctx->hrtimer_lock);
945 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
947 cpuctx->hrtimer_active = 0;
948 raw_spin_unlock(&cpuctx->hrtimer_lock);
950 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
953 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
955 struct hrtimer *timer = &cpuctx->hrtimer;
956 struct pmu *pmu = cpuctx->ctx.pmu;
959 /* no multiplexing needed for SW PMU */
960 if (pmu->task_ctx_nr == perf_sw_context)
964 * check default is sane, if not set then force to
965 * default interval (1/tick)
967 interval = pmu->hrtimer_interval_ms;
969 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
971 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
973 raw_spin_lock_init(&cpuctx->hrtimer_lock);
974 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
975 timer->function = perf_mux_hrtimer_handler;
978 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
980 struct hrtimer *timer = &cpuctx->hrtimer;
981 struct pmu *pmu = cpuctx->ctx.pmu;
985 if (pmu->task_ctx_nr == perf_sw_context)
988 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
989 if (!cpuctx->hrtimer_active) {
990 cpuctx->hrtimer_active = 1;
991 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
992 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
994 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
999 void perf_pmu_disable(struct pmu *pmu)
1001 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1003 pmu->pmu_disable(pmu);
1006 void perf_pmu_enable(struct pmu *pmu)
1008 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1010 pmu->pmu_enable(pmu);
1013 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1016 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1017 * perf_event_task_tick() are fully serialized because they're strictly cpu
1018 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1019 * disabled, while perf_event_task_tick is called from IRQ context.
1021 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1023 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1025 WARN_ON(!irqs_disabled());
1027 WARN_ON(!list_empty(&ctx->active_ctx_list));
1029 list_add(&ctx->active_ctx_list, head);
1032 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1034 WARN_ON(!irqs_disabled());
1036 WARN_ON(list_empty(&ctx->active_ctx_list));
1038 list_del_init(&ctx->active_ctx_list);
1041 static void get_ctx(struct perf_event_context *ctx)
1043 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1046 static void free_ctx(struct rcu_head *head)
1048 struct perf_event_context *ctx;
1050 ctx = container_of(head, struct perf_event_context, rcu_head);
1051 kfree(ctx->task_ctx_data);
1055 static void put_ctx(struct perf_event_context *ctx)
1057 if (atomic_dec_and_test(&ctx->refcount)) {
1058 if (ctx->parent_ctx)
1059 put_ctx(ctx->parent_ctx);
1060 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1061 put_task_struct(ctx->task);
1062 call_rcu(&ctx->rcu_head, free_ctx);
1067 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1068 * perf_pmu_migrate_context() we need some magic.
1070 * Those places that change perf_event::ctx will hold both
1071 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1073 * Lock ordering is by mutex address. There are two other sites where
1074 * perf_event_context::mutex nests and those are:
1076 * - perf_event_exit_task_context() [ child , 0 ]
1077 * perf_event_exit_event()
1078 * put_event() [ parent, 1 ]
1080 * - perf_event_init_context() [ parent, 0 ]
1081 * inherit_task_group()
1084 * perf_event_alloc()
1086 * perf_try_init_event() [ child , 1 ]
1088 * While it appears there is an obvious deadlock here -- the parent and child
1089 * nesting levels are inverted between the two. This is in fact safe because
1090 * life-time rules separate them. That is an exiting task cannot fork, and a
1091 * spawning task cannot (yet) exit.
1093 * But remember that that these are parent<->child context relations, and
1094 * migration does not affect children, therefore these two orderings should not
1097 * The change in perf_event::ctx does not affect children (as claimed above)
1098 * because the sys_perf_event_open() case will install a new event and break
1099 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1100 * concerned with cpuctx and that doesn't have children.
1102 * The places that change perf_event::ctx will issue:
1104 * perf_remove_from_context();
1105 * synchronize_rcu();
1106 * perf_install_in_context();
1108 * to affect the change. The remove_from_context() + synchronize_rcu() should
1109 * quiesce the event, after which we can install it in the new location. This
1110 * means that only external vectors (perf_fops, prctl) can perturb the event
1111 * while in transit. Therefore all such accessors should also acquire
1112 * perf_event_context::mutex to serialize against this.
1114 * However; because event->ctx can change while we're waiting to acquire
1115 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1120 * task_struct::perf_event_mutex
1121 * perf_event_context::mutex
1122 * perf_event::child_mutex;
1123 * perf_event_context::lock
1124 * perf_event::mmap_mutex
1127 static struct perf_event_context *
1128 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1130 struct perf_event_context *ctx;
1134 ctx = ACCESS_ONCE(event->ctx);
1135 if (!atomic_inc_not_zero(&ctx->refcount)) {
1141 mutex_lock_nested(&ctx->mutex, nesting);
1142 if (event->ctx != ctx) {
1143 mutex_unlock(&ctx->mutex);
1151 static inline struct perf_event_context *
1152 perf_event_ctx_lock(struct perf_event *event)
1154 return perf_event_ctx_lock_nested(event, 0);
1157 static void perf_event_ctx_unlock(struct perf_event *event,
1158 struct perf_event_context *ctx)
1160 mutex_unlock(&ctx->mutex);
1165 * This must be done under the ctx->lock, such as to serialize against
1166 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1167 * calling scheduler related locks and ctx->lock nests inside those.
1169 static __must_check struct perf_event_context *
1170 unclone_ctx(struct perf_event_context *ctx)
1172 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1174 lockdep_assert_held(&ctx->lock);
1177 ctx->parent_ctx = NULL;
1183 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1186 * only top level events have the pid namespace they were created in
1189 event = event->parent;
1191 return task_tgid_nr_ns(p, event->ns);
1194 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1197 * only top level events have the pid namespace they were created in
1200 event = event->parent;
1202 return task_pid_nr_ns(p, event->ns);
1206 * If we inherit events we want to return the parent event id
1209 static u64 primary_event_id(struct perf_event *event)
1214 id = event->parent->id;
1220 * Get the perf_event_context for a task and lock it.
1222 * This has to cope with with the fact that until it is locked,
1223 * the context could get moved to another task.
1225 static struct perf_event_context *
1226 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1228 struct perf_event_context *ctx;
1232 * One of the few rules of preemptible RCU is that one cannot do
1233 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1234 * part of the read side critical section was irqs-enabled -- see
1235 * rcu_read_unlock_special().
1237 * Since ctx->lock nests under rq->lock we must ensure the entire read
1238 * side critical section has interrupts disabled.
1240 local_irq_save(*flags);
1242 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1245 * If this context is a clone of another, it might
1246 * get swapped for another underneath us by
1247 * perf_event_task_sched_out, though the
1248 * rcu_read_lock() protects us from any context
1249 * getting freed. Lock the context and check if it
1250 * got swapped before we could get the lock, and retry
1251 * if so. If we locked the right context, then it
1252 * can't get swapped on us any more.
1254 raw_spin_lock(&ctx->lock);
1255 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1256 raw_spin_unlock(&ctx->lock);
1258 local_irq_restore(*flags);
1262 if (ctx->task == TASK_TOMBSTONE ||
1263 !atomic_inc_not_zero(&ctx->refcount)) {
1264 raw_spin_unlock(&ctx->lock);
1267 WARN_ON_ONCE(ctx->task != task);
1272 local_irq_restore(*flags);
1277 * Get the context for a task and increment its pin_count so it
1278 * can't get swapped to another task. This also increments its
1279 * reference count so that the context can't get freed.
1281 static struct perf_event_context *
1282 perf_pin_task_context(struct task_struct *task, int ctxn)
1284 struct perf_event_context *ctx;
1285 unsigned long flags;
1287 ctx = perf_lock_task_context(task, ctxn, &flags);
1290 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1295 static void perf_unpin_context(struct perf_event_context *ctx)
1297 unsigned long flags;
1299 raw_spin_lock_irqsave(&ctx->lock, flags);
1301 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1305 * Update the record of the current time in a context.
1307 static void update_context_time(struct perf_event_context *ctx)
1309 u64 now = perf_clock();
1311 ctx->time += now - ctx->timestamp;
1312 ctx->timestamp = now;
1315 static u64 perf_event_time(struct perf_event *event)
1317 struct perf_event_context *ctx = event->ctx;
1319 if (is_cgroup_event(event))
1320 return perf_cgroup_event_time(event);
1322 return ctx ? ctx->time : 0;
1326 * Update the total_time_enabled and total_time_running fields for a event.
1328 static void update_event_times(struct perf_event *event)
1330 struct perf_event_context *ctx = event->ctx;
1333 lockdep_assert_held(&ctx->lock);
1335 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1336 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1340 * in cgroup mode, time_enabled represents
1341 * the time the event was enabled AND active
1342 * tasks were in the monitored cgroup. This is
1343 * independent of the activity of the context as
1344 * there may be a mix of cgroup and non-cgroup events.
1346 * That is why we treat cgroup events differently
1349 if (is_cgroup_event(event))
1350 run_end = perf_cgroup_event_time(event);
1351 else if (ctx->is_active)
1352 run_end = ctx->time;
1354 run_end = event->tstamp_stopped;
1356 event->total_time_enabled = run_end - event->tstamp_enabled;
1358 if (event->state == PERF_EVENT_STATE_INACTIVE)
1359 run_end = event->tstamp_stopped;
1361 run_end = perf_event_time(event);
1363 event->total_time_running = run_end - event->tstamp_running;
1368 * Update total_time_enabled and total_time_running for all events in a group.
1370 static void update_group_times(struct perf_event *leader)
1372 struct perf_event *event;
1374 update_event_times(leader);
1375 list_for_each_entry(event, &leader->sibling_list, group_entry)
1376 update_event_times(event);
1379 static struct list_head *
1380 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1382 if (event->attr.pinned)
1383 return &ctx->pinned_groups;
1385 return &ctx->flexible_groups;
1389 * Add a event from the lists for its context.
1390 * Must be called with ctx->mutex and ctx->lock held.
1393 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1395 lockdep_assert_held(&ctx->lock);
1397 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1398 event->attach_state |= PERF_ATTACH_CONTEXT;
1401 * If we're a stand alone event or group leader, we go to the context
1402 * list, group events are kept attached to the group so that
1403 * perf_group_detach can, at all times, locate all siblings.
1405 if (event->group_leader == event) {
1406 struct list_head *list;
1408 if (is_software_event(event))
1409 event->group_flags |= PERF_GROUP_SOFTWARE;
1411 list = ctx_group_list(event, ctx);
1412 list_add_tail(&event->group_entry, list);
1415 if (is_cgroup_event(event))
1418 list_add_rcu(&event->event_entry, &ctx->event_list);
1420 if (event->attr.inherit_stat)
1427 * Initialize event state based on the perf_event_attr::disabled.
1429 static inline void perf_event__state_init(struct perf_event *event)
1431 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1432 PERF_EVENT_STATE_INACTIVE;
1435 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1437 int entry = sizeof(u64); /* value */
1441 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1442 size += sizeof(u64);
1444 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1445 size += sizeof(u64);
1447 if (event->attr.read_format & PERF_FORMAT_ID)
1448 entry += sizeof(u64);
1450 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1452 size += sizeof(u64);
1456 event->read_size = size;
1459 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1461 struct perf_sample_data *data;
1464 if (sample_type & PERF_SAMPLE_IP)
1465 size += sizeof(data->ip);
1467 if (sample_type & PERF_SAMPLE_ADDR)
1468 size += sizeof(data->addr);
1470 if (sample_type & PERF_SAMPLE_PERIOD)
1471 size += sizeof(data->period);
1473 if (sample_type & PERF_SAMPLE_WEIGHT)
1474 size += sizeof(data->weight);
1476 if (sample_type & PERF_SAMPLE_READ)
1477 size += event->read_size;
1479 if (sample_type & PERF_SAMPLE_DATA_SRC)
1480 size += sizeof(data->data_src.val);
1482 if (sample_type & PERF_SAMPLE_TRANSACTION)
1483 size += sizeof(data->txn);
1485 event->header_size = size;
1489 * Called at perf_event creation and when events are attached/detached from a
1492 static void perf_event__header_size(struct perf_event *event)
1494 __perf_event_read_size(event,
1495 event->group_leader->nr_siblings);
1496 __perf_event_header_size(event, event->attr.sample_type);
1499 static void perf_event__id_header_size(struct perf_event *event)
1501 struct perf_sample_data *data;
1502 u64 sample_type = event->attr.sample_type;
1505 if (sample_type & PERF_SAMPLE_TID)
1506 size += sizeof(data->tid_entry);
1508 if (sample_type & PERF_SAMPLE_TIME)
1509 size += sizeof(data->time);
1511 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1512 size += sizeof(data->id);
1514 if (sample_type & PERF_SAMPLE_ID)
1515 size += sizeof(data->id);
1517 if (sample_type & PERF_SAMPLE_STREAM_ID)
1518 size += sizeof(data->stream_id);
1520 if (sample_type & PERF_SAMPLE_CPU)
1521 size += sizeof(data->cpu_entry);
1523 event->id_header_size = size;
1526 static bool perf_event_validate_size(struct perf_event *event)
1529 * The values computed here will be over-written when we actually
1532 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1533 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1534 perf_event__id_header_size(event);
1537 * Sum the lot; should not exceed the 64k limit we have on records.
1538 * Conservative limit to allow for callchains and other variable fields.
1540 if (event->read_size + event->header_size +
1541 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1547 static void perf_group_attach(struct perf_event *event)
1549 struct perf_event *group_leader = event->group_leader, *pos;
1552 * We can have double attach due to group movement in perf_event_open.
1554 if (event->attach_state & PERF_ATTACH_GROUP)
1557 event->attach_state |= PERF_ATTACH_GROUP;
1559 if (group_leader == event)
1562 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1564 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1565 !is_software_event(event))
1566 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1568 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1569 group_leader->nr_siblings++;
1571 perf_event__header_size(group_leader);
1573 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1574 perf_event__header_size(pos);
1578 * Remove a event from the lists for its context.
1579 * Must be called with ctx->mutex and ctx->lock held.
1582 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1584 struct perf_cpu_context *cpuctx;
1586 WARN_ON_ONCE(event->ctx != ctx);
1587 lockdep_assert_held(&ctx->lock);
1590 * We can have double detach due to exit/hot-unplug + close.
1592 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1595 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1597 if (is_cgroup_event(event)) {
1600 * Because cgroup events are always per-cpu events, this will
1601 * always be called from the right CPU.
1603 cpuctx = __get_cpu_context(ctx);
1605 * If there are no more cgroup events then clear cgrp to avoid
1606 * stale pointer in update_cgrp_time_from_cpuctx().
1608 if (!ctx->nr_cgroups)
1609 cpuctx->cgrp = NULL;
1613 if (event->attr.inherit_stat)
1616 list_del_rcu(&event->event_entry);
1618 if (event->group_leader == event)
1619 list_del_init(&event->group_entry);
1621 update_group_times(event);
1624 * If event was in error state, then keep it
1625 * that way, otherwise bogus counts will be
1626 * returned on read(). The only way to get out
1627 * of error state is by explicit re-enabling
1630 if (event->state > PERF_EVENT_STATE_OFF)
1631 event->state = PERF_EVENT_STATE_OFF;
1636 static void perf_group_detach(struct perf_event *event)
1638 struct perf_event *sibling, *tmp;
1639 struct list_head *list = NULL;
1642 * We can have double detach due to exit/hot-unplug + close.
1644 if (!(event->attach_state & PERF_ATTACH_GROUP))
1647 event->attach_state &= ~PERF_ATTACH_GROUP;
1650 * If this is a sibling, remove it from its group.
1652 if (event->group_leader != event) {
1653 list_del_init(&event->group_entry);
1654 event->group_leader->nr_siblings--;
1658 if (!list_empty(&event->group_entry))
1659 list = &event->group_entry;
1662 * If this was a group event with sibling events then
1663 * upgrade the siblings to singleton events by adding them
1664 * to whatever list we are on.
1666 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1668 list_move_tail(&sibling->group_entry, list);
1669 sibling->group_leader = sibling;
1671 /* Inherit group flags from the previous leader */
1672 sibling->group_flags = event->group_flags;
1674 WARN_ON_ONCE(sibling->ctx != event->ctx);
1678 perf_event__header_size(event->group_leader);
1680 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1681 perf_event__header_size(tmp);
1684 static bool is_orphaned_event(struct perf_event *event)
1686 return event->state == PERF_EVENT_STATE_DEAD;
1689 static inline int pmu_filter_match(struct perf_event *event)
1691 struct pmu *pmu = event->pmu;
1692 return pmu->filter_match ? pmu->filter_match(event) : 1;
1696 event_filter_match(struct perf_event *event)
1698 return (event->cpu == -1 || event->cpu == smp_processor_id())
1699 && perf_cgroup_match(event) && pmu_filter_match(event);
1703 event_sched_out(struct perf_event *event,
1704 struct perf_cpu_context *cpuctx,
1705 struct perf_event_context *ctx)
1707 u64 tstamp = perf_event_time(event);
1710 WARN_ON_ONCE(event->ctx != ctx);
1711 lockdep_assert_held(&ctx->lock);
1714 * An event which could not be activated because of
1715 * filter mismatch still needs to have its timings
1716 * maintained, otherwise bogus information is return
1717 * via read() for time_enabled, time_running:
1719 if (event->state == PERF_EVENT_STATE_INACTIVE
1720 && !event_filter_match(event)) {
1721 delta = tstamp - event->tstamp_stopped;
1722 event->tstamp_running += delta;
1723 event->tstamp_stopped = tstamp;
1726 if (event->state != PERF_EVENT_STATE_ACTIVE)
1729 perf_pmu_disable(event->pmu);
1731 event->tstamp_stopped = tstamp;
1732 event->pmu->del(event, 0);
1734 event->state = PERF_EVENT_STATE_INACTIVE;
1735 if (event->pending_disable) {
1736 event->pending_disable = 0;
1737 event->state = PERF_EVENT_STATE_OFF;
1740 if (!is_software_event(event))
1741 cpuctx->active_oncpu--;
1742 if (!--ctx->nr_active)
1743 perf_event_ctx_deactivate(ctx);
1744 if (event->attr.freq && event->attr.sample_freq)
1746 if (event->attr.exclusive || !cpuctx->active_oncpu)
1747 cpuctx->exclusive = 0;
1749 perf_pmu_enable(event->pmu);
1753 group_sched_out(struct perf_event *group_event,
1754 struct perf_cpu_context *cpuctx,
1755 struct perf_event_context *ctx)
1757 struct perf_event *event;
1758 int state = group_event->state;
1760 event_sched_out(group_event, cpuctx, ctx);
1763 * Schedule out siblings (if any):
1765 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1766 event_sched_out(event, cpuctx, ctx);
1768 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1769 cpuctx->exclusive = 0;
1772 #define DETACH_GROUP 0x01UL
1775 * Cross CPU call to remove a performance event
1777 * We disable the event on the hardware level first. After that we
1778 * remove it from the context list.
1781 __perf_remove_from_context(struct perf_event *event,
1782 struct perf_cpu_context *cpuctx,
1783 struct perf_event_context *ctx,
1786 unsigned long flags = (unsigned long)info;
1788 event_sched_out(event, cpuctx, ctx);
1789 if (flags & DETACH_GROUP)
1790 perf_group_detach(event);
1791 list_del_event(event, ctx);
1793 if (!ctx->nr_events && ctx->is_active) {
1796 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1797 cpuctx->task_ctx = NULL;
1803 * Remove the event from a task's (or a CPU's) list of events.
1805 * If event->ctx is a cloned context, callers must make sure that
1806 * every task struct that event->ctx->task could possibly point to
1807 * remains valid. This is OK when called from perf_release since
1808 * that only calls us on the top-level context, which can't be a clone.
1809 * When called from perf_event_exit_task, it's OK because the
1810 * context has been detached from its task.
1812 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1814 lockdep_assert_held(&event->ctx->mutex);
1816 event_function_call(event, __perf_remove_from_context, (void *)flags);
1820 * Cross CPU call to disable a performance event
1822 static void __perf_event_disable(struct perf_event *event,
1823 struct perf_cpu_context *cpuctx,
1824 struct perf_event_context *ctx,
1827 if (event->state < PERF_EVENT_STATE_INACTIVE)
1830 update_context_time(ctx);
1831 update_cgrp_time_from_event(event);
1832 update_group_times(event);
1833 if (event == event->group_leader)
1834 group_sched_out(event, cpuctx, ctx);
1836 event_sched_out(event, cpuctx, ctx);
1837 event->state = PERF_EVENT_STATE_OFF;
1843 * If event->ctx is a cloned context, callers must make sure that
1844 * every task struct that event->ctx->task could possibly point to
1845 * remains valid. This condition is satisifed when called through
1846 * perf_event_for_each_child or perf_event_for_each because they
1847 * hold the top-level event's child_mutex, so any descendant that
1848 * goes to exit will block in perf_event_exit_event().
1850 * When called from perf_pending_event it's OK because event->ctx
1851 * is the current context on this CPU and preemption is disabled,
1852 * hence we can't get into perf_event_task_sched_out for this context.
1854 static void _perf_event_disable(struct perf_event *event)
1856 struct perf_event_context *ctx = event->ctx;
1858 raw_spin_lock_irq(&ctx->lock);
1859 if (event->state <= PERF_EVENT_STATE_OFF) {
1860 raw_spin_unlock_irq(&ctx->lock);
1863 raw_spin_unlock_irq(&ctx->lock);
1865 event_function_call(event, __perf_event_disable, NULL);
1868 void perf_event_disable_local(struct perf_event *event)
1870 event_function_local(event, __perf_event_disable, NULL);
1874 * Strictly speaking kernel users cannot create groups and therefore this
1875 * interface does not need the perf_event_ctx_lock() magic.
1877 void perf_event_disable(struct perf_event *event)
1879 struct perf_event_context *ctx;
1881 ctx = perf_event_ctx_lock(event);
1882 _perf_event_disable(event);
1883 perf_event_ctx_unlock(event, ctx);
1885 EXPORT_SYMBOL_GPL(perf_event_disable);
1887 static void perf_set_shadow_time(struct perf_event *event,
1888 struct perf_event_context *ctx,
1892 * use the correct time source for the time snapshot
1894 * We could get by without this by leveraging the
1895 * fact that to get to this function, the caller
1896 * has most likely already called update_context_time()
1897 * and update_cgrp_time_xx() and thus both timestamp
1898 * are identical (or very close). Given that tstamp is,
1899 * already adjusted for cgroup, we could say that:
1900 * tstamp - ctx->timestamp
1902 * tstamp - cgrp->timestamp.
1904 * Then, in perf_output_read(), the calculation would
1905 * work with no changes because:
1906 * - event is guaranteed scheduled in
1907 * - no scheduled out in between
1908 * - thus the timestamp would be the same
1910 * But this is a bit hairy.
1912 * So instead, we have an explicit cgroup call to remain
1913 * within the time time source all along. We believe it
1914 * is cleaner and simpler to understand.
1916 if (is_cgroup_event(event))
1917 perf_cgroup_set_shadow_time(event, tstamp);
1919 event->shadow_ctx_time = tstamp - ctx->timestamp;
1922 #define MAX_INTERRUPTS (~0ULL)
1924 static void perf_log_throttle(struct perf_event *event, int enable);
1925 static void perf_log_itrace_start(struct perf_event *event);
1928 event_sched_in(struct perf_event *event,
1929 struct perf_cpu_context *cpuctx,
1930 struct perf_event_context *ctx)
1932 u64 tstamp = perf_event_time(event);
1935 lockdep_assert_held(&ctx->lock);
1937 if (event->state <= PERF_EVENT_STATE_OFF)
1940 WRITE_ONCE(event->oncpu, smp_processor_id());
1942 * Order event::oncpu write to happen before the ACTIVE state
1946 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
1949 * Unthrottle events, since we scheduled we might have missed several
1950 * ticks already, also for a heavily scheduling task there is little
1951 * guarantee it'll get a tick in a timely manner.
1953 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1954 perf_log_throttle(event, 1);
1955 event->hw.interrupts = 0;
1959 * The new state must be visible before we turn it on in the hardware:
1963 perf_pmu_disable(event->pmu);
1965 perf_set_shadow_time(event, ctx, tstamp);
1967 perf_log_itrace_start(event);
1969 if (event->pmu->add(event, PERF_EF_START)) {
1970 event->state = PERF_EVENT_STATE_INACTIVE;
1976 event->tstamp_running += tstamp - event->tstamp_stopped;
1978 if (!is_software_event(event))
1979 cpuctx->active_oncpu++;
1980 if (!ctx->nr_active++)
1981 perf_event_ctx_activate(ctx);
1982 if (event->attr.freq && event->attr.sample_freq)
1985 if (event->attr.exclusive)
1986 cpuctx->exclusive = 1;
1989 perf_pmu_enable(event->pmu);
1995 group_sched_in(struct perf_event *group_event,
1996 struct perf_cpu_context *cpuctx,
1997 struct perf_event_context *ctx)
1999 struct perf_event *event, *partial_group = NULL;
2000 struct pmu *pmu = ctx->pmu;
2001 u64 now = ctx->time;
2002 bool simulate = false;
2004 if (group_event->state == PERF_EVENT_STATE_OFF)
2007 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2009 if (event_sched_in(group_event, cpuctx, ctx)) {
2010 pmu->cancel_txn(pmu);
2011 perf_mux_hrtimer_restart(cpuctx);
2016 * Schedule in siblings as one group (if any):
2018 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2019 if (event_sched_in(event, cpuctx, ctx)) {
2020 partial_group = event;
2025 if (!pmu->commit_txn(pmu))
2030 * Groups can be scheduled in as one unit only, so undo any
2031 * partial group before returning:
2032 * The events up to the failed event are scheduled out normally,
2033 * tstamp_stopped will be updated.
2035 * The failed events and the remaining siblings need to have
2036 * their timings updated as if they had gone thru event_sched_in()
2037 * and event_sched_out(). This is required to get consistent timings
2038 * across the group. This also takes care of the case where the group
2039 * could never be scheduled by ensuring tstamp_stopped is set to mark
2040 * the time the event was actually stopped, such that time delta
2041 * calculation in update_event_times() is correct.
2043 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2044 if (event == partial_group)
2048 event->tstamp_running += now - event->tstamp_stopped;
2049 event->tstamp_stopped = now;
2051 event_sched_out(event, cpuctx, ctx);
2054 event_sched_out(group_event, cpuctx, ctx);
2056 pmu->cancel_txn(pmu);
2058 perf_mux_hrtimer_restart(cpuctx);
2064 * Work out whether we can put this event group on the CPU now.
2066 static int group_can_go_on(struct perf_event *event,
2067 struct perf_cpu_context *cpuctx,
2071 * Groups consisting entirely of software events can always go on.
2073 if (event->group_flags & PERF_GROUP_SOFTWARE)
2076 * If an exclusive group is already on, no other hardware
2079 if (cpuctx->exclusive)
2082 * If this group is exclusive and there are already
2083 * events on the CPU, it can't go on.
2085 if (event->attr.exclusive && cpuctx->active_oncpu)
2088 * Otherwise, try to add it if all previous groups were able
2094 static void add_event_to_ctx(struct perf_event *event,
2095 struct perf_event_context *ctx)
2097 u64 tstamp = perf_event_time(event);
2099 list_add_event(event, ctx);
2100 perf_group_attach(event);
2101 event->tstamp_enabled = tstamp;
2102 event->tstamp_running = tstamp;
2103 event->tstamp_stopped = tstamp;
2106 static void ctx_sched_out(struct perf_event_context *ctx,
2107 struct perf_cpu_context *cpuctx,
2108 enum event_type_t event_type);
2110 ctx_sched_in(struct perf_event_context *ctx,
2111 struct perf_cpu_context *cpuctx,
2112 enum event_type_t event_type,
2113 struct task_struct *task);
2115 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2116 struct perf_event_context *ctx)
2118 if (!cpuctx->task_ctx)
2121 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2124 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2127 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2128 struct perf_event_context *ctx,
2129 struct task_struct *task)
2131 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2133 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2134 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2136 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2139 static void ctx_resched(struct perf_cpu_context *cpuctx,
2140 struct perf_event_context *task_ctx)
2142 perf_pmu_disable(cpuctx->ctx.pmu);
2144 task_ctx_sched_out(cpuctx, task_ctx);
2145 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2146 perf_event_sched_in(cpuctx, task_ctx, current);
2147 perf_pmu_enable(cpuctx->ctx.pmu);
2151 * Cross CPU call to install and enable a performance event
2153 * Very similar to remote_function() + event_function() but cannot assume that
2154 * things like ctx->is_active and cpuctx->task_ctx are set.
2156 static int __perf_install_in_context(void *info)
2158 struct perf_event *event = info;
2159 struct perf_event_context *ctx = event->ctx;
2160 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2161 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2162 bool activate = true;
2165 raw_spin_lock(&cpuctx->ctx.lock);
2167 raw_spin_lock(&ctx->lock);
2170 /* If we're on the wrong CPU, try again */
2171 if (task_cpu(ctx->task) != smp_processor_id()) {
2177 * If we're on the right CPU, see if the task we target is
2178 * current, if not we don't have to activate the ctx, a future
2179 * context switch will do that for us.
2181 if (ctx->task != current)
2184 WARN_ON_ONCE(cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2186 } else if (task_ctx) {
2187 raw_spin_lock(&task_ctx->lock);
2191 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2192 add_event_to_ctx(event, ctx);
2193 ctx_resched(cpuctx, task_ctx);
2195 add_event_to_ctx(event, ctx);
2199 perf_ctx_unlock(cpuctx, task_ctx);
2205 * Attach a performance event to a context.
2207 * Very similar to event_function_call, see comment there.
2210 perf_install_in_context(struct perf_event_context *ctx,
2211 struct perf_event *event,
2214 struct task_struct *task = READ_ONCE(ctx->task);
2216 lockdep_assert_held(&ctx->mutex);
2219 if (event->cpu != -1)
2223 cpu_function_call(cpu, __perf_install_in_context, event);
2228 * Should not happen, we validate the ctx is still alive before calling.
2230 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2234 * Installing events is tricky because we cannot rely on ctx->is_active
2235 * to be set in case this is the nr_events 0 -> 1 transition.
2239 * Cannot use task_function_call() because we need to run on the task's
2240 * CPU regardless of whether its current or not.
2242 if (!cpu_function_call(task_cpu(task), __perf_install_in_context, event))
2245 raw_spin_lock_irq(&ctx->lock);
2247 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2249 * Cannot happen because we already checked above (which also
2250 * cannot happen), and we hold ctx->mutex, which serializes us
2251 * against perf_event_exit_task_context().
2253 raw_spin_unlock_irq(&ctx->lock);
2256 raw_spin_unlock_irq(&ctx->lock);
2258 * Since !ctx->is_active doesn't mean anything, we must IPI
2265 * Put a event into inactive state and update time fields.
2266 * Enabling the leader of a group effectively enables all
2267 * the group members that aren't explicitly disabled, so we
2268 * have to update their ->tstamp_enabled also.
2269 * Note: this works for group members as well as group leaders
2270 * since the non-leader members' sibling_lists will be empty.
2272 static void __perf_event_mark_enabled(struct perf_event *event)
2274 struct perf_event *sub;
2275 u64 tstamp = perf_event_time(event);
2277 event->state = PERF_EVENT_STATE_INACTIVE;
2278 event->tstamp_enabled = tstamp - event->total_time_enabled;
2279 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2280 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2281 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2286 * Cross CPU call to enable a performance event
2288 static void __perf_event_enable(struct perf_event *event,
2289 struct perf_cpu_context *cpuctx,
2290 struct perf_event_context *ctx,
2293 struct perf_event *leader = event->group_leader;
2294 struct perf_event_context *task_ctx;
2296 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2297 event->state <= PERF_EVENT_STATE_ERROR)
2301 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2303 __perf_event_mark_enabled(event);
2305 if (!ctx->is_active)
2308 if (!event_filter_match(event)) {
2309 if (is_cgroup_event(event))
2310 perf_cgroup_defer_enabled(event);
2311 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2316 * If the event is in a group and isn't the group leader,
2317 * then don't put it on unless the group is on.
2319 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2320 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2324 task_ctx = cpuctx->task_ctx;
2326 WARN_ON_ONCE(task_ctx != ctx);
2328 ctx_resched(cpuctx, task_ctx);
2334 * If event->ctx is a cloned context, callers must make sure that
2335 * every task struct that event->ctx->task could possibly point to
2336 * remains valid. This condition is satisfied when called through
2337 * perf_event_for_each_child or perf_event_for_each as described
2338 * for perf_event_disable.
2340 static void _perf_event_enable(struct perf_event *event)
2342 struct perf_event_context *ctx = event->ctx;
2344 raw_spin_lock_irq(&ctx->lock);
2345 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2346 event->state < PERF_EVENT_STATE_ERROR) {
2347 raw_spin_unlock_irq(&ctx->lock);
2352 * If the event is in error state, clear that first.
2354 * That way, if we see the event in error state below, we know that it
2355 * has gone back into error state, as distinct from the task having
2356 * been scheduled away before the cross-call arrived.
2358 if (event->state == PERF_EVENT_STATE_ERROR)
2359 event->state = PERF_EVENT_STATE_OFF;
2360 raw_spin_unlock_irq(&ctx->lock);
2362 event_function_call(event, __perf_event_enable, NULL);
2366 * See perf_event_disable();
2368 void perf_event_enable(struct perf_event *event)
2370 struct perf_event_context *ctx;
2372 ctx = perf_event_ctx_lock(event);
2373 _perf_event_enable(event);
2374 perf_event_ctx_unlock(event, ctx);
2376 EXPORT_SYMBOL_GPL(perf_event_enable);
2378 struct stop_event_data {
2379 struct perf_event *event;
2380 unsigned int restart;
2383 static int __perf_event_stop(void *info)
2385 struct stop_event_data *sd = info;
2386 struct perf_event *event = sd->event;
2388 /* if it's already INACTIVE, do nothing */
2389 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2392 /* matches smp_wmb() in event_sched_in() */
2396 * There is a window with interrupts enabled before we get here,
2397 * so we need to check again lest we try to stop another CPU's event.
2399 if (READ_ONCE(event->oncpu) != smp_processor_id())
2402 event->pmu->stop(event, PERF_EF_UPDATE);
2405 * May race with the actual stop (through perf_pmu_output_stop()),
2406 * but it is only used for events with AUX ring buffer, and such
2407 * events will refuse to restart because of rb::aux_mmap_count==0,
2408 * see comments in perf_aux_output_begin().
2410 * Since this is happening on a event-local CPU, no trace is lost
2414 event->pmu->start(event, PERF_EF_START);
2419 static int perf_event_restart(struct perf_event *event)
2421 struct stop_event_data sd = {
2428 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2431 /* matches smp_wmb() in event_sched_in() */
2435 * We only want to restart ACTIVE events, so if the event goes
2436 * inactive here (event->oncpu==-1), there's nothing more to do;
2437 * fall through with ret==-ENXIO.
2439 ret = cpu_function_call(READ_ONCE(event->oncpu),
2440 __perf_event_stop, &sd);
2441 } while (ret == -EAGAIN);
2447 * In order to contain the amount of racy and tricky in the address filter
2448 * configuration management, it is a two part process:
2450 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2451 * we update the addresses of corresponding vmas in
2452 * event::addr_filters_offs array and bump the event::addr_filters_gen;
2453 * (p2) when an event is scheduled in (pmu::add), it calls
2454 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2455 * if the generation has changed since the previous call.
2457 * If (p1) happens while the event is active, we restart it to force (p2).
2459 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2460 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2462 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2463 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2465 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2468 void perf_event_addr_filters_sync(struct perf_event *event)
2470 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2472 if (!has_addr_filter(event))
2475 raw_spin_lock(&ifh->lock);
2476 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2477 event->pmu->addr_filters_sync(event);
2478 event->hw.addr_filters_gen = event->addr_filters_gen;
2480 raw_spin_unlock(&ifh->lock);
2482 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2484 static int _perf_event_refresh(struct perf_event *event, int refresh)
2487 * not supported on inherited events
2489 if (event->attr.inherit || !is_sampling_event(event))
2492 atomic_add(refresh, &event->event_limit);
2493 _perf_event_enable(event);
2499 * See perf_event_disable()
2501 int perf_event_refresh(struct perf_event *event, int refresh)
2503 struct perf_event_context *ctx;
2506 ctx = perf_event_ctx_lock(event);
2507 ret = _perf_event_refresh(event, refresh);
2508 perf_event_ctx_unlock(event, ctx);
2512 EXPORT_SYMBOL_GPL(perf_event_refresh);
2514 static void ctx_sched_out(struct perf_event_context *ctx,
2515 struct perf_cpu_context *cpuctx,
2516 enum event_type_t event_type)
2518 int is_active = ctx->is_active;
2519 struct perf_event *event;
2521 lockdep_assert_held(&ctx->lock);
2523 if (likely(!ctx->nr_events)) {
2525 * See __perf_remove_from_context().
2527 WARN_ON_ONCE(ctx->is_active);
2529 WARN_ON_ONCE(cpuctx->task_ctx);
2533 ctx->is_active &= ~event_type;
2534 if (!(ctx->is_active & EVENT_ALL))
2538 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2539 if (!ctx->is_active)
2540 cpuctx->task_ctx = NULL;
2544 * Always update time if it was set; not only when it changes.
2545 * Otherwise we can 'forget' to update time for any but the last
2546 * context we sched out. For example:
2548 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2549 * ctx_sched_out(.event_type = EVENT_PINNED)
2551 * would only update time for the pinned events.
2553 if (is_active & EVENT_TIME) {
2554 /* update (and stop) ctx time */
2555 update_context_time(ctx);
2556 update_cgrp_time_from_cpuctx(cpuctx);
2559 is_active ^= ctx->is_active; /* changed bits */
2561 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2564 perf_pmu_disable(ctx->pmu);
2565 if (is_active & EVENT_PINNED) {
2566 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2567 group_sched_out(event, cpuctx, ctx);
2570 if (is_active & EVENT_FLEXIBLE) {
2571 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2572 group_sched_out(event, cpuctx, ctx);
2574 perf_pmu_enable(ctx->pmu);
2578 * Test whether two contexts are equivalent, i.e. whether they have both been
2579 * cloned from the same version of the same context.
2581 * Equivalence is measured using a generation number in the context that is
2582 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2583 * and list_del_event().
2585 static int context_equiv(struct perf_event_context *ctx1,
2586 struct perf_event_context *ctx2)
2588 lockdep_assert_held(&ctx1->lock);
2589 lockdep_assert_held(&ctx2->lock);
2591 /* Pinning disables the swap optimization */
2592 if (ctx1->pin_count || ctx2->pin_count)
2595 /* If ctx1 is the parent of ctx2 */
2596 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2599 /* If ctx2 is the parent of ctx1 */
2600 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2604 * If ctx1 and ctx2 have the same parent; we flatten the parent
2605 * hierarchy, see perf_event_init_context().
2607 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2608 ctx1->parent_gen == ctx2->parent_gen)
2615 static void __perf_event_sync_stat(struct perf_event *event,
2616 struct perf_event *next_event)
2620 if (!event->attr.inherit_stat)
2624 * Update the event value, we cannot use perf_event_read()
2625 * because we're in the middle of a context switch and have IRQs
2626 * disabled, which upsets smp_call_function_single(), however
2627 * we know the event must be on the current CPU, therefore we
2628 * don't need to use it.
2630 switch (event->state) {
2631 case PERF_EVENT_STATE_ACTIVE:
2632 event->pmu->read(event);
2635 case PERF_EVENT_STATE_INACTIVE:
2636 update_event_times(event);
2644 * In order to keep per-task stats reliable we need to flip the event
2645 * values when we flip the contexts.
2647 value = local64_read(&next_event->count);
2648 value = local64_xchg(&event->count, value);
2649 local64_set(&next_event->count, value);
2651 swap(event->total_time_enabled, next_event->total_time_enabled);
2652 swap(event->total_time_running, next_event->total_time_running);
2655 * Since we swizzled the values, update the user visible data too.
2657 perf_event_update_userpage(event);
2658 perf_event_update_userpage(next_event);
2661 static void perf_event_sync_stat(struct perf_event_context *ctx,
2662 struct perf_event_context *next_ctx)
2664 struct perf_event *event, *next_event;
2669 update_context_time(ctx);
2671 event = list_first_entry(&ctx->event_list,
2672 struct perf_event, event_entry);
2674 next_event = list_first_entry(&next_ctx->event_list,
2675 struct perf_event, event_entry);
2677 while (&event->event_entry != &ctx->event_list &&
2678 &next_event->event_entry != &next_ctx->event_list) {
2680 __perf_event_sync_stat(event, next_event);
2682 event = list_next_entry(event, event_entry);
2683 next_event = list_next_entry(next_event, event_entry);
2687 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2688 struct task_struct *next)
2690 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2691 struct perf_event_context *next_ctx;
2692 struct perf_event_context *parent, *next_parent;
2693 struct perf_cpu_context *cpuctx;
2699 cpuctx = __get_cpu_context(ctx);
2700 if (!cpuctx->task_ctx)
2704 next_ctx = next->perf_event_ctxp[ctxn];
2708 parent = rcu_dereference(ctx->parent_ctx);
2709 next_parent = rcu_dereference(next_ctx->parent_ctx);
2711 /* If neither context have a parent context; they cannot be clones. */
2712 if (!parent && !next_parent)
2715 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2717 * Looks like the two contexts are clones, so we might be
2718 * able to optimize the context switch. We lock both
2719 * contexts and check that they are clones under the
2720 * lock (including re-checking that neither has been
2721 * uncloned in the meantime). It doesn't matter which
2722 * order we take the locks because no other cpu could
2723 * be trying to lock both of these tasks.
2725 raw_spin_lock(&ctx->lock);
2726 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2727 if (context_equiv(ctx, next_ctx)) {
2728 WRITE_ONCE(ctx->task, next);
2729 WRITE_ONCE(next_ctx->task, task);
2731 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2734 * RCU_INIT_POINTER here is safe because we've not
2735 * modified the ctx and the above modification of
2736 * ctx->task and ctx->task_ctx_data are immaterial
2737 * since those values are always verified under
2738 * ctx->lock which we're now holding.
2740 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2741 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2745 perf_event_sync_stat(ctx, next_ctx);
2747 raw_spin_unlock(&next_ctx->lock);
2748 raw_spin_unlock(&ctx->lock);
2754 raw_spin_lock(&ctx->lock);
2755 task_ctx_sched_out(cpuctx, ctx);
2756 raw_spin_unlock(&ctx->lock);
2760 void perf_sched_cb_dec(struct pmu *pmu)
2762 this_cpu_dec(perf_sched_cb_usages);
2765 void perf_sched_cb_inc(struct pmu *pmu)
2767 this_cpu_inc(perf_sched_cb_usages);
2771 * This function provides the context switch callback to the lower code
2772 * layer. It is invoked ONLY when the context switch callback is enabled.
2774 static void perf_pmu_sched_task(struct task_struct *prev,
2775 struct task_struct *next,
2778 struct perf_cpu_context *cpuctx;
2780 unsigned long flags;
2785 local_irq_save(flags);
2789 list_for_each_entry_rcu(pmu, &pmus, entry) {
2790 if (pmu->sched_task) {
2791 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2793 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2795 perf_pmu_disable(pmu);
2797 pmu->sched_task(cpuctx->task_ctx, sched_in);
2799 perf_pmu_enable(pmu);
2801 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2807 local_irq_restore(flags);
2810 static void perf_event_switch(struct task_struct *task,
2811 struct task_struct *next_prev, bool sched_in);
2813 #define for_each_task_context_nr(ctxn) \
2814 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2817 * Called from scheduler to remove the events of the current task,
2818 * with interrupts disabled.
2820 * We stop each event and update the event value in event->count.
2822 * This does not protect us against NMI, but disable()
2823 * sets the disabled bit in the control field of event _before_
2824 * accessing the event control register. If a NMI hits, then it will
2825 * not restart the event.
2827 void __perf_event_task_sched_out(struct task_struct *task,
2828 struct task_struct *next)
2832 if (__this_cpu_read(perf_sched_cb_usages))
2833 perf_pmu_sched_task(task, next, false);
2835 if (atomic_read(&nr_switch_events))
2836 perf_event_switch(task, next, false);
2838 for_each_task_context_nr(ctxn)
2839 perf_event_context_sched_out(task, ctxn, next);
2842 * if cgroup events exist on this CPU, then we need
2843 * to check if we have to switch out PMU state.
2844 * cgroup event are system-wide mode only
2846 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2847 perf_cgroup_sched_out(task, next);
2851 * Called with IRQs disabled
2853 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2854 enum event_type_t event_type)
2856 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2860 ctx_pinned_sched_in(struct perf_event_context *ctx,
2861 struct perf_cpu_context *cpuctx)
2863 struct perf_event *event;
2865 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2866 if (event->state <= PERF_EVENT_STATE_OFF)
2868 if (!event_filter_match(event))
2871 /* may need to reset tstamp_enabled */
2872 if (is_cgroup_event(event))
2873 perf_cgroup_mark_enabled(event, ctx);
2875 if (group_can_go_on(event, cpuctx, 1))
2876 group_sched_in(event, cpuctx, ctx);
2879 * If this pinned group hasn't been scheduled,
2880 * put it in error state.
2882 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2883 update_group_times(event);
2884 event->state = PERF_EVENT_STATE_ERROR;
2890 ctx_flexible_sched_in(struct perf_event_context *ctx,
2891 struct perf_cpu_context *cpuctx)
2893 struct perf_event *event;
2896 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2897 /* Ignore events in OFF or ERROR state */
2898 if (event->state <= PERF_EVENT_STATE_OFF)
2901 * Listen to the 'cpu' scheduling filter constraint
2904 if (!event_filter_match(event))
2907 /* may need to reset tstamp_enabled */
2908 if (is_cgroup_event(event))
2909 perf_cgroup_mark_enabled(event, ctx);
2911 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2912 if (group_sched_in(event, cpuctx, ctx))
2919 ctx_sched_in(struct perf_event_context *ctx,
2920 struct perf_cpu_context *cpuctx,
2921 enum event_type_t event_type,
2922 struct task_struct *task)
2924 int is_active = ctx->is_active;
2927 lockdep_assert_held(&ctx->lock);
2929 if (likely(!ctx->nr_events))
2932 ctx->is_active |= (event_type | EVENT_TIME);
2935 cpuctx->task_ctx = ctx;
2937 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2940 is_active ^= ctx->is_active; /* changed bits */
2942 if (is_active & EVENT_TIME) {
2943 /* start ctx time */
2945 ctx->timestamp = now;
2946 perf_cgroup_set_timestamp(task, ctx);
2950 * First go through the list and put on any pinned groups
2951 * in order to give them the best chance of going on.
2953 if (is_active & EVENT_PINNED)
2954 ctx_pinned_sched_in(ctx, cpuctx);
2956 /* Then walk through the lower prio flexible groups */
2957 if (is_active & EVENT_FLEXIBLE)
2958 ctx_flexible_sched_in(ctx, cpuctx);
2961 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2962 enum event_type_t event_type,
2963 struct task_struct *task)
2965 struct perf_event_context *ctx = &cpuctx->ctx;
2967 ctx_sched_in(ctx, cpuctx, event_type, task);
2970 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2971 struct task_struct *task)
2973 struct perf_cpu_context *cpuctx;
2975 cpuctx = __get_cpu_context(ctx);
2976 if (cpuctx->task_ctx == ctx)
2979 perf_ctx_lock(cpuctx, ctx);
2980 perf_pmu_disable(ctx->pmu);
2982 * We want to keep the following priority order:
2983 * cpu pinned (that don't need to move), task pinned,
2984 * cpu flexible, task flexible.
2986 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2987 perf_event_sched_in(cpuctx, ctx, task);
2988 perf_pmu_enable(ctx->pmu);
2989 perf_ctx_unlock(cpuctx, ctx);
2993 * Called from scheduler to add the events of the current task
2994 * with interrupts disabled.
2996 * We restore the event value and then enable it.
2998 * This does not protect us against NMI, but enable()
2999 * sets the enabled bit in the control field of event _before_
3000 * accessing the event control register. If a NMI hits, then it will
3001 * keep the event running.
3003 void __perf_event_task_sched_in(struct task_struct *prev,
3004 struct task_struct *task)
3006 struct perf_event_context *ctx;
3010 * If cgroup events exist on this CPU, then we need to check if we have
3011 * to switch in PMU state; cgroup event are system-wide mode only.
3013 * Since cgroup events are CPU events, we must schedule these in before
3014 * we schedule in the task events.
3016 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3017 perf_cgroup_sched_in(prev, task);
3019 for_each_task_context_nr(ctxn) {
3020 ctx = task->perf_event_ctxp[ctxn];
3024 perf_event_context_sched_in(ctx, task);
3027 if (atomic_read(&nr_switch_events))
3028 perf_event_switch(task, prev, true);
3030 if (__this_cpu_read(perf_sched_cb_usages))
3031 perf_pmu_sched_task(prev, task, true);
3034 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3036 u64 frequency = event->attr.sample_freq;
3037 u64 sec = NSEC_PER_SEC;
3038 u64 divisor, dividend;
3040 int count_fls, nsec_fls, frequency_fls, sec_fls;
3042 count_fls = fls64(count);
3043 nsec_fls = fls64(nsec);
3044 frequency_fls = fls64(frequency);
3048 * We got @count in @nsec, with a target of sample_freq HZ
3049 * the target period becomes:
3052 * period = -------------------
3053 * @nsec * sample_freq
3058 * Reduce accuracy by one bit such that @a and @b converge
3059 * to a similar magnitude.
3061 #define REDUCE_FLS(a, b) \
3063 if (a##_fls > b##_fls) { \
3073 * Reduce accuracy until either term fits in a u64, then proceed with
3074 * the other, so that finally we can do a u64/u64 division.
3076 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3077 REDUCE_FLS(nsec, frequency);
3078 REDUCE_FLS(sec, count);
3081 if (count_fls + sec_fls > 64) {
3082 divisor = nsec * frequency;
3084 while (count_fls + sec_fls > 64) {
3085 REDUCE_FLS(count, sec);
3089 dividend = count * sec;
3091 dividend = count * sec;
3093 while (nsec_fls + frequency_fls > 64) {
3094 REDUCE_FLS(nsec, frequency);
3098 divisor = nsec * frequency;
3104 return div64_u64(dividend, divisor);
3107 static DEFINE_PER_CPU(int, perf_throttled_count);
3108 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3110 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3112 struct hw_perf_event *hwc = &event->hw;
3113 s64 period, sample_period;
3116 period = perf_calculate_period(event, nsec, count);
3118 delta = (s64)(period - hwc->sample_period);
3119 delta = (delta + 7) / 8; /* low pass filter */
3121 sample_period = hwc->sample_period + delta;
3126 hwc->sample_period = sample_period;
3128 if (local64_read(&hwc->period_left) > 8*sample_period) {
3130 event->pmu->stop(event, PERF_EF_UPDATE);
3132 local64_set(&hwc->period_left, 0);
3135 event->pmu->start(event, PERF_EF_RELOAD);
3140 * combine freq adjustment with unthrottling to avoid two passes over the
3141 * events. At the same time, make sure, having freq events does not change
3142 * the rate of unthrottling as that would introduce bias.
3144 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3147 struct perf_event *event;
3148 struct hw_perf_event *hwc;
3149 u64 now, period = TICK_NSEC;
3153 * only need to iterate over all events iff:
3154 * - context have events in frequency mode (needs freq adjust)
3155 * - there are events to unthrottle on this cpu
3157 if (!(ctx->nr_freq || needs_unthr))
3160 raw_spin_lock(&ctx->lock);
3161 perf_pmu_disable(ctx->pmu);
3163 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3164 if (event->state != PERF_EVENT_STATE_ACTIVE)
3167 if (!event_filter_match(event))
3170 perf_pmu_disable(event->pmu);
3174 if (hwc->interrupts == MAX_INTERRUPTS) {
3175 hwc->interrupts = 0;
3176 perf_log_throttle(event, 1);
3177 event->pmu->start(event, 0);
3180 if (!event->attr.freq || !event->attr.sample_freq)
3184 * stop the event and update event->count
3186 event->pmu->stop(event, PERF_EF_UPDATE);
3188 now = local64_read(&event->count);
3189 delta = now - hwc->freq_count_stamp;
3190 hwc->freq_count_stamp = now;
3194 * reload only if value has changed
3195 * we have stopped the event so tell that
3196 * to perf_adjust_period() to avoid stopping it
3200 perf_adjust_period(event, period, delta, false);
3202 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3204 perf_pmu_enable(event->pmu);
3207 perf_pmu_enable(ctx->pmu);
3208 raw_spin_unlock(&ctx->lock);
3212 * Round-robin a context's events:
3214 static void rotate_ctx(struct perf_event_context *ctx)
3217 * Rotate the first entry last of non-pinned groups. Rotation might be
3218 * disabled by the inheritance code.
3220 if (!ctx->rotate_disable)
3221 list_rotate_left(&ctx->flexible_groups);
3224 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3226 struct perf_event_context *ctx = NULL;
3229 if (cpuctx->ctx.nr_events) {
3230 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3234 ctx = cpuctx->task_ctx;
3235 if (ctx && ctx->nr_events) {
3236 if (ctx->nr_events != ctx->nr_active)
3243 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3244 perf_pmu_disable(cpuctx->ctx.pmu);
3246 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3248 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3250 rotate_ctx(&cpuctx->ctx);
3254 perf_event_sched_in(cpuctx, ctx, current);
3256 perf_pmu_enable(cpuctx->ctx.pmu);
3257 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3263 void perf_event_task_tick(void)
3265 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3266 struct perf_event_context *ctx, *tmp;
3269 WARN_ON(!irqs_disabled());
3271 __this_cpu_inc(perf_throttled_seq);
3272 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3273 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3275 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3276 perf_adjust_freq_unthr_context(ctx, throttled);
3279 static int event_enable_on_exec(struct perf_event *event,
3280 struct perf_event_context *ctx)
3282 if (!event->attr.enable_on_exec)
3285 event->attr.enable_on_exec = 0;
3286 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3289 __perf_event_mark_enabled(event);
3295 * Enable all of a task's events that have been marked enable-on-exec.
3296 * This expects task == current.
3298 static void perf_event_enable_on_exec(int ctxn)
3300 struct perf_event_context *ctx, *clone_ctx = NULL;
3301 struct perf_cpu_context *cpuctx;
3302 struct perf_event *event;
3303 unsigned long flags;
3306 local_irq_save(flags);
3307 ctx = current->perf_event_ctxp[ctxn];
3308 if (!ctx || !ctx->nr_events)
3311 cpuctx = __get_cpu_context(ctx);
3312 perf_ctx_lock(cpuctx, ctx);
3313 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3314 list_for_each_entry(event, &ctx->event_list, event_entry)
3315 enabled |= event_enable_on_exec(event, ctx);
3318 * Unclone and reschedule this context if we enabled any event.
3321 clone_ctx = unclone_ctx(ctx);
3322 ctx_resched(cpuctx, ctx);
3324 perf_ctx_unlock(cpuctx, ctx);
3327 local_irq_restore(flags);
3333 struct perf_read_data {
3334 struct perf_event *event;
3340 * Cross CPU call to read the hardware event
3342 static void __perf_event_read(void *info)
3344 struct perf_read_data *data = info;
3345 struct perf_event *sub, *event = data->event;
3346 struct perf_event_context *ctx = event->ctx;
3347 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3348 struct pmu *pmu = event->pmu;
3351 * If this is a task context, we need to check whether it is
3352 * the current task context of this cpu. If not it has been
3353 * scheduled out before the smp call arrived. In that case
3354 * event->count would have been updated to a recent sample
3355 * when the event was scheduled out.
3357 if (ctx->task && cpuctx->task_ctx != ctx)
3360 raw_spin_lock(&ctx->lock);
3361 if (ctx->is_active) {
3362 update_context_time(ctx);
3363 update_cgrp_time_from_event(event);
3366 update_event_times(event);
3367 if (event->state != PERF_EVENT_STATE_ACTIVE)
3376 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3380 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3381 update_event_times(sub);
3382 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3384 * Use sibling's PMU rather than @event's since
3385 * sibling could be on different (eg: software) PMU.
3387 sub->pmu->read(sub);
3391 data->ret = pmu->commit_txn(pmu);
3394 raw_spin_unlock(&ctx->lock);
3397 static inline u64 perf_event_count(struct perf_event *event)
3399 if (event->pmu->count)
3400 return event->pmu->count(event);
3402 return __perf_event_count(event);
3406 * NMI-safe method to read a local event, that is an event that
3408 * - either for the current task, or for this CPU
3409 * - does not have inherit set, for inherited task events
3410 * will not be local and we cannot read them atomically
3411 * - must not have a pmu::count method
3413 u64 perf_event_read_local(struct perf_event *event)
3415 unsigned long flags;
3419 * Disabling interrupts avoids all counter scheduling (context
3420 * switches, timer based rotation and IPIs).
3422 local_irq_save(flags);
3424 /* If this is a per-task event, it must be for current */
3425 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3426 event->hw.target != current);
3428 /* If this is a per-CPU event, it must be for this CPU */
3429 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3430 event->cpu != smp_processor_id());
3433 * It must not be an event with inherit set, we cannot read
3434 * all child counters from atomic context.
3436 WARN_ON_ONCE(event->attr.inherit);
3439 * It must not have a pmu::count method, those are not
3442 WARN_ON_ONCE(event->pmu->count);
3445 * If the event is currently on this CPU, its either a per-task event,
3446 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3449 if (event->oncpu == smp_processor_id())
3450 event->pmu->read(event);
3452 val = local64_read(&event->count);
3453 local_irq_restore(flags);
3458 static int perf_event_read(struct perf_event *event, bool group)
3463 * If event is enabled and currently active on a CPU, update the
3464 * value in the event structure:
3466 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3467 struct perf_read_data data = {
3472 smp_call_function_single(event->oncpu,
3473 __perf_event_read, &data, 1);
3475 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3476 struct perf_event_context *ctx = event->ctx;
3477 unsigned long flags;
3479 raw_spin_lock_irqsave(&ctx->lock, flags);
3481 * may read while context is not active
3482 * (e.g., thread is blocked), in that case
3483 * we cannot update context time
3485 if (ctx->is_active) {
3486 update_context_time(ctx);
3487 update_cgrp_time_from_event(event);
3490 update_group_times(event);
3492 update_event_times(event);
3493 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3500 * Initialize the perf_event context in a task_struct:
3502 static void __perf_event_init_context(struct perf_event_context *ctx)
3504 raw_spin_lock_init(&ctx->lock);
3505 mutex_init(&ctx->mutex);
3506 INIT_LIST_HEAD(&ctx->active_ctx_list);
3507 INIT_LIST_HEAD(&ctx->pinned_groups);
3508 INIT_LIST_HEAD(&ctx->flexible_groups);
3509 INIT_LIST_HEAD(&ctx->event_list);
3510 atomic_set(&ctx->refcount, 1);
3513 static struct perf_event_context *
3514 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3516 struct perf_event_context *ctx;
3518 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3522 __perf_event_init_context(ctx);
3525 get_task_struct(task);
3532 static struct task_struct *
3533 find_lively_task_by_vpid(pid_t vpid)
3535 struct task_struct *task;
3541 task = find_task_by_vpid(vpid);
3543 get_task_struct(task);
3547 return ERR_PTR(-ESRCH);
3553 * Returns a matching context with refcount and pincount.
3555 static struct perf_event_context *
3556 find_get_context(struct pmu *pmu, struct task_struct *task,
3557 struct perf_event *event)
3559 struct perf_event_context *ctx, *clone_ctx = NULL;
3560 struct perf_cpu_context *cpuctx;
3561 void *task_ctx_data = NULL;
3562 unsigned long flags;
3564 int cpu = event->cpu;
3567 /* Must be root to operate on a CPU event: */
3568 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3569 return ERR_PTR(-EACCES);
3572 * We could be clever and allow to attach a event to an
3573 * offline CPU and activate it when the CPU comes up, but
3576 if (!cpu_online(cpu))
3577 return ERR_PTR(-ENODEV);
3579 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3588 ctxn = pmu->task_ctx_nr;
3592 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3593 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3594 if (!task_ctx_data) {
3601 ctx = perf_lock_task_context(task, ctxn, &flags);
3603 clone_ctx = unclone_ctx(ctx);
3606 if (task_ctx_data && !ctx->task_ctx_data) {
3607 ctx->task_ctx_data = task_ctx_data;
3608 task_ctx_data = NULL;
3610 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3615 ctx = alloc_perf_context(pmu, task);
3620 if (task_ctx_data) {
3621 ctx->task_ctx_data = task_ctx_data;
3622 task_ctx_data = NULL;
3626 mutex_lock(&task->perf_event_mutex);
3628 * If it has already passed perf_event_exit_task().
3629 * we must see PF_EXITING, it takes this mutex too.
3631 if (task->flags & PF_EXITING)
3633 else if (task->perf_event_ctxp[ctxn])
3638 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3640 mutex_unlock(&task->perf_event_mutex);
3642 if (unlikely(err)) {
3651 kfree(task_ctx_data);
3655 kfree(task_ctx_data);
3656 return ERR_PTR(err);
3659 static void perf_event_free_filter(struct perf_event *event);
3660 static void perf_event_free_bpf_prog(struct perf_event *event);
3662 static void free_event_rcu(struct rcu_head *head)
3664 struct perf_event *event;
3666 event = container_of(head, struct perf_event, rcu_head);
3668 put_pid_ns(event->ns);
3669 perf_event_free_filter(event);
3673 static void ring_buffer_attach(struct perf_event *event,
3674 struct ring_buffer *rb);
3676 static void detach_sb_event(struct perf_event *event)
3678 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
3680 raw_spin_lock(&pel->lock);
3681 list_del_rcu(&event->sb_list);
3682 raw_spin_unlock(&pel->lock);
3685 static bool is_sb_event(struct perf_event *event)
3687 struct perf_event_attr *attr = &event->attr;
3692 if (event->attach_state & PERF_ATTACH_TASK)
3695 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
3696 attr->comm || attr->comm_exec ||
3698 attr->context_switch)
3703 static void unaccount_pmu_sb_event(struct perf_event *event)
3705 if (is_sb_event(event))
3706 detach_sb_event(event);
3709 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3714 if (is_cgroup_event(event))
3715 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3718 #ifdef CONFIG_NO_HZ_FULL
3719 static DEFINE_SPINLOCK(nr_freq_lock);
3722 static void unaccount_freq_event_nohz(void)
3724 #ifdef CONFIG_NO_HZ_FULL
3725 spin_lock(&nr_freq_lock);
3726 if (atomic_dec_and_test(&nr_freq_events))
3727 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
3728 spin_unlock(&nr_freq_lock);
3732 static void unaccount_freq_event(void)
3734 if (tick_nohz_full_enabled())
3735 unaccount_freq_event_nohz();
3737 atomic_dec(&nr_freq_events);
3740 static void unaccount_event(struct perf_event *event)
3747 if (event->attach_state & PERF_ATTACH_TASK)
3749 if (event->attr.mmap || event->attr.mmap_data)
3750 atomic_dec(&nr_mmap_events);
3751 if (event->attr.comm)
3752 atomic_dec(&nr_comm_events);
3753 if (event->attr.task)
3754 atomic_dec(&nr_task_events);
3755 if (event->attr.freq)
3756 unaccount_freq_event();
3757 if (event->attr.context_switch) {
3759 atomic_dec(&nr_switch_events);
3761 if (is_cgroup_event(event))
3763 if (has_branch_stack(event))
3767 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3768 schedule_delayed_work(&perf_sched_work, HZ);
3771 unaccount_event_cpu(event, event->cpu);
3773 unaccount_pmu_sb_event(event);
3776 static void perf_sched_delayed(struct work_struct *work)
3778 mutex_lock(&perf_sched_mutex);
3779 if (atomic_dec_and_test(&perf_sched_count))
3780 static_branch_disable(&perf_sched_events);
3781 mutex_unlock(&perf_sched_mutex);
3785 * The following implement mutual exclusion of events on "exclusive" pmus
3786 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3787 * at a time, so we disallow creating events that might conflict, namely:
3789 * 1) cpu-wide events in the presence of per-task events,
3790 * 2) per-task events in the presence of cpu-wide events,
3791 * 3) two matching events on the same context.
3793 * The former two cases are handled in the allocation path (perf_event_alloc(),
3794 * _free_event()), the latter -- before the first perf_install_in_context().
3796 static int exclusive_event_init(struct perf_event *event)
3798 struct pmu *pmu = event->pmu;
3800 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3804 * Prevent co-existence of per-task and cpu-wide events on the
3805 * same exclusive pmu.
3807 * Negative pmu::exclusive_cnt means there are cpu-wide
3808 * events on this "exclusive" pmu, positive means there are
3811 * Since this is called in perf_event_alloc() path, event::ctx
3812 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3813 * to mean "per-task event", because unlike other attach states it
3814 * never gets cleared.
3816 if (event->attach_state & PERF_ATTACH_TASK) {
3817 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3820 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3827 static void exclusive_event_destroy(struct perf_event *event)
3829 struct pmu *pmu = event->pmu;
3831 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3834 /* see comment in exclusive_event_init() */
3835 if (event->attach_state & PERF_ATTACH_TASK)
3836 atomic_dec(&pmu->exclusive_cnt);
3838 atomic_inc(&pmu->exclusive_cnt);
3841 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3843 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3844 (e1->cpu == e2->cpu ||
3851 /* Called under the same ctx::mutex as perf_install_in_context() */
3852 static bool exclusive_event_installable(struct perf_event *event,
3853 struct perf_event_context *ctx)
3855 struct perf_event *iter_event;
3856 struct pmu *pmu = event->pmu;
3858 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3861 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3862 if (exclusive_event_match(iter_event, event))
3869 static void perf_addr_filters_splice(struct perf_event *event,
3870 struct list_head *head);
3872 static void _free_event(struct perf_event *event)
3874 irq_work_sync(&event->pending);
3876 unaccount_event(event);
3880 * Can happen when we close an event with re-directed output.
3882 * Since we have a 0 refcount, perf_mmap_close() will skip
3883 * over us; possibly making our ring_buffer_put() the last.
3885 mutex_lock(&event->mmap_mutex);
3886 ring_buffer_attach(event, NULL);
3887 mutex_unlock(&event->mmap_mutex);
3890 if (is_cgroup_event(event))
3891 perf_detach_cgroup(event);
3893 if (!event->parent) {
3894 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3895 put_callchain_buffers();
3898 perf_event_free_bpf_prog(event);
3899 perf_addr_filters_splice(event, NULL);
3900 kfree(event->addr_filters_offs);
3903 event->destroy(event);
3906 put_ctx(event->ctx);
3909 exclusive_event_destroy(event);
3910 module_put(event->pmu->module);
3913 call_rcu(&event->rcu_head, free_event_rcu);
3917 * Used to free events which have a known refcount of 1, such as in error paths
3918 * where the event isn't exposed yet and inherited events.
3920 static void free_event(struct perf_event *event)
3922 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3923 "unexpected event refcount: %ld; ptr=%p\n",
3924 atomic_long_read(&event->refcount), event)) {
3925 /* leak to avoid use-after-free */
3933 * Remove user event from the owner task.
3935 static void perf_remove_from_owner(struct perf_event *event)
3937 struct task_struct *owner;
3941 * Matches the smp_store_release() in perf_event_exit_task(). If we
3942 * observe !owner it means the list deletion is complete and we can
3943 * indeed free this event, otherwise we need to serialize on
3944 * owner->perf_event_mutex.
3946 owner = lockless_dereference(event->owner);
3949 * Since delayed_put_task_struct() also drops the last
3950 * task reference we can safely take a new reference
3951 * while holding the rcu_read_lock().
3953 get_task_struct(owner);
3959 * If we're here through perf_event_exit_task() we're already
3960 * holding ctx->mutex which would be an inversion wrt. the
3961 * normal lock order.
3963 * However we can safely take this lock because its the child
3966 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3969 * We have to re-check the event->owner field, if it is cleared
3970 * we raced with perf_event_exit_task(), acquiring the mutex
3971 * ensured they're done, and we can proceed with freeing the
3975 list_del_init(&event->owner_entry);
3976 smp_store_release(&event->owner, NULL);
3978 mutex_unlock(&owner->perf_event_mutex);
3979 put_task_struct(owner);
3983 static void put_event(struct perf_event *event)
3985 if (!atomic_long_dec_and_test(&event->refcount))
3992 * Kill an event dead; while event:refcount will preserve the event
3993 * object, it will not preserve its functionality. Once the last 'user'
3994 * gives up the object, we'll destroy the thing.
3996 int perf_event_release_kernel(struct perf_event *event)
3998 struct perf_event_context *ctx = event->ctx;
3999 struct perf_event *child, *tmp;
4002 * If we got here through err_file: fput(event_file); we will not have
4003 * attached to a context yet.
4006 WARN_ON_ONCE(event->attach_state &
4007 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4011 if (!is_kernel_event(event))
4012 perf_remove_from_owner(event);
4014 ctx = perf_event_ctx_lock(event);
4015 WARN_ON_ONCE(ctx->parent_ctx);
4016 perf_remove_from_context(event, DETACH_GROUP);
4018 raw_spin_lock_irq(&ctx->lock);
4020 * Mark this even as STATE_DEAD, there is no external reference to it
4023 * Anybody acquiring event->child_mutex after the below loop _must_
4024 * also see this, most importantly inherit_event() which will avoid
4025 * placing more children on the list.
4027 * Thus this guarantees that we will in fact observe and kill _ALL_
4030 event->state = PERF_EVENT_STATE_DEAD;
4031 raw_spin_unlock_irq(&ctx->lock);
4033 perf_event_ctx_unlock(event, ctx);
4036 mutex_lock(&event->child_mutex);
4037 list_for_each_entry(child, &event->child_list, child_list) {
4040 * Cannot change, child events are not migrated, see the
4041 * comment with perf_event_ctx_lock_nested().
4043 ctx = lockless_dereference(child->ctx);
4045 * Since child_mutex nests inside ctx::mutex, we must jump
4046 * through hoops. We start by grabbing a reference on the ctx.
4048 * Since the event cannot get freed while we hold the
4049 * child_mutex, the context must also exist and have a !0
4055 * Now that we have a ctx ref, we can drop child_mutex, and
4056 * acquire ctx::mutex without fear of it going away. Then we
4057 * can re-acquire child_mutex.
4059 mutex_unlock(&event->child_mutex);
4060 mutex_lock(&ctx->mutex);
4061 mutex_lock(&event->child_mutex);
4064 * Now that we hold ctx::mutex and child_mutex, revalidate our
4065 * state, if child is still the first entry, it didn't get freed
4066 * and we can continue doing so.
4068 tmp = list_first_entry_or_null(&event->child_list,
4069 struct perf_event, child_list);
4071 perf_remove_from_context(child, DETACH_GROUP);
4072 list_del(&child->child_list);
4075 * This matches the refcount bump in inherit_event();
4076 * this can't be the last reference.
4081 mutex_unlock(&event->child_mutex);
4082 mutex_unlock(&ctx->mutex);
4086 mutex_unlock(&event->child_mutex);
4089 put_event(event); /* Must be the 'last' reference */
4092 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4095 * Called when the last reference to the file is gone.
4097 static int perf_release(struct inode *inode, struct file *file)
4099 perf_event_release_kernel(file->private_data);
4103 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4105 struct perf_event *child;
4111 mutex_lock(&event->child_mutex);
4113 (void)perf_event_read(event, false);
4114 total += perf_event_count(event);
4116 *enabled += event->total_time_enabled +
4117 atomic64_read(&event->child_total_time_enabled);
4118 *running += event->total_time_running +
4119 atomic64_read(&event->child_total_time_running);
4121 list_for_each_entry(child, &event->child_list, child_list) {
4122 (void)perf_event_read(child, false);
4123 total += perf_event_count(child);
4124 *enabled += child->total_time_enabled;
4125 *running += child->total_time_running;
4127 mutex_unlock(&event->child_mutex);
4131 EXPORT_SYMBOL_GPL(perf_event_read_value);
4133 static int __perf_read_group_add(struct perf_event *leader,
4134 u64 read_format, u64 *values)
4136 struct perf_event *sub;
4137 int n = 1; /* skip @nr */
4140 ret = perf_event_read(leader, true);
4145 * Since we co-schedule groups, {enabled,running} times of siblings
4146 * will be identical to those of the leader, so we only publish one
4149 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4150 values[n++] += leader->total_time_enabled +
4151 atomic64_read(&leader->child_total_time_enabled);
4154 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4155 values[n++] += leader->total_time_running +
4156 atomic64_read(&leader->child_total_time_running);
4160 * Write {count,id} tuples for every sibling.
4162 values[n++] += perf_event_count(leader);
4163 if (read_format & PERF_FORMAT_ID)
4164 values[n++] = primary_event_id(leader);
4166 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4167 values[n++] += perf_event_count(sub);
4168 if (read_format & PERF_FORMAT_ID)
4169 values[n++] = primary_event_id(sub);
4175 static int perf_read_group(struct perf_event *event,
4176 u64 read_format, char __user *buf)
4178 struct perf_event *leader = event->group_leader, *child;
4179 struct perf_event_context *ctx = leader->ctx;
4183 lockdep_assert_held(&ctx->mutex);
4185 values = kzalloc(event->read_size, GFP_KERNEL);
4189 values[0] = 1 + leader->nr_siblings;
4192 * By locking the child_mutex of the leader we effectively
4193 * lock the child list of all siblings.. XXX explain how.
4195 mutex_lock(&leader->child_mutex);
4197 ret = __perf_read_group_add(leader, read_format, values);
4201 list_for_each_entry(child, &leader->child_list, child_list) {
4202 ret = __perf_read_group_add(child, read_format, values);
4207 mutex_unlock(&leader->child_mutex);
4209 ret = event->read_size;
4210 if (copy_to_user(buf, values, event->read_size))
4215 mutex_unlock(&leader->child_mutex);
4221 static int perf_read_one(struct perf_event *event,
4222 u64 read_format, char __user *buf)
4224 u64 enabled, running;
4228 values[n++] = perf_event_read_value(event, &enabled, &running);
4229 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4230 values[n++] = enabled;
4231 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4232 values[n++] = running;
4233 if (read_format & PERF_FORMAT_ID)
4234 values[n++] = primary_event_id(event);
4236 if (copy_to_user(buf, values, n * sizeof(u64)))
4239 return n * sizeof(u64);
4242 static bool is_event_hup(struct perf_event *event)
4246 if (event->state > PERF_EVENT_STATE_EXIT)
4249 mutex_lock(&event->child_mutex);
4250 no_children = list_empty(&event->child_list);
4251 mutex_unlock(&event->child_mutex);
4256 * Read the performance event - simple non blocking version for now
4259 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4261 u64 read_format = event->attr.read_format;
4265 * Return end-of-file for a read on a event that is in
4266 * error state (i.e. because it was pinned but it couldn't be
4267 * scheduled on to the CPU at some point).
4269 if (event->state == PERF_EVENT_STATE_ERROR)
4272 if (count < event->read_size)
4275 WARN_ON_ONCE(event->ctx->parent_ctx);
4276 if (read_format & PERF_FORMAT_GROUP)
4277 ret = perf_read_group(event, read_format, buf);
4279 ret = perf_read_one(event, read_format, buf);
4285 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4287 struct perf_event *event = file->private_data;
4288 struct perf_event_context *ctx;
4291 ctx = perf_event_ctx_lock(event);
4292 ret = __perf_read(event, buf, count);
4293 perf_event_ctx_unlock(event, ctx);
4298 static unsigned int perf_poll(struct file *file, poll_table *wait)
4300 struct perf_event *event = file->private_data;
4301 struct ring_buffer *rb;
4302 unsigned int events = POLLHUP;
4304 poll_wait(file, &event->waitq, wait);
4306 if (is_event_hup(event))
4310 * Pin the event->rb by taking event->mmap_mutex; otherwise
4311 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4313 mutex_lock(&event->mmap_mutex);
4316 events = atomic_xchg(&rb->poll, 0);
4317 mutex_unlock(&event->mmap_mutex);
4321 static void _perf_event_reset(struct perf_event *event)
4323 (void)perf_event_read(event, false);
4324 local64_set(&event->count, 0);
4325 perf_event_update_userpage(event);
4329 * Holding the top-level event's child_mutex means that any
4330 * descendant process that has inherited this event will block
4331 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4332 * task existence requirements of perf_event_enable/disable.
4334 static void perf_event_for_each_child(struct perf_event *event,
4335 void (*func)(struct perf_event *))
4337 struct perf_event *child;
4339 WARN_ON_ONCE(event->ctx->parent_ctx);
4341 mutex_lock(&event->child_mutex);
4343 list_for_each_entry(child, &event->child_list, child_list)
4345 mutex_unlock(&event->child_mutex);
4348 static void perf_event_for_each(struct perf_event *event,
4349 void (*func)(struct perf_event *))
4351 struct perf_event_context *ctx = event->ctx;
4352 struct perf_event *sibling;
4354 lockdep_assert_held(&ctx->mutex);
4356 event = event->group_leader;
4358 perf_event_for_each_child(event, func);
4359 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4360 perf_event_for_each_child(sibling, func);
4363 static void __perf_event_period(struct perf_event *event,
4364 struct perf_cpu_context *cpuctx,
4365 struct perf_event_context *ctx,
4368 u64 value = *((u64 *)info);
4371 if (event->attr.freq) {
4372 event->attr.sample_freq = value;
4374 event->attr.sample_period = value;
4375 event->hw.sample_period = value;
4378 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4380 perf_pmu_disable(ctx->pmu);
4382 * We could be throttled; unthrottle now to avoid the tick
4383 * trying to unthrottle while we already re-started the event.
4385 if (event->hw.interrupts == MAX_INTERRUPTS) {
4386 event->hw.interrupts = 0;
4387 perf_log_throttle(event, 1);
4389 event->pmu->stop(event, PERF_EF_UPDATE);
4392 local64_set(&event->hw.period_left, 0);
4395 event->pmu->start(event, PERF_EF_RELOAD);
4396 perf_pmu_enable(ctx->pmu);
4400 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4404 if (!is_sampling_event(event))
4407 if (copy_from_user(&value, arg, sizeof(value)))
4413 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4416 event_function_call(event, __perf_event_period, &value);
4421 static const struct file_operations perf_fops;
4423 static inline int perf_fget_light(int fd, struct fd *p)
4425 struct fd f = fdget(fd);
4429 if (f.file->f_op != &perf_fops) {
4437 static int perf_event_set_output(struct perf_event *event,
4438 struct perf_event *output_event);
4439 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4440 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4442 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4444 void (*func)(struct perf_event *);
4448 case PERF_EVENT_IOC_ENABLE:
4449 func = _perf_event_enable;
4451 case PERF_EVENT_IOC_DISABLE:
4452 func = _perf_event_disable;
4454 case PERF_EVENT_IOC_RESET:
4455 func = _perf_event_reset;
4458 case PERF_EVENT_IOC_REFRESH:
4459 return _perf_event_refresh(event, arg);
4461 case PERF_EVENT_IOC_PERIOD:
4462 return perf_event_period(event, (u64 __user *)arg);
4464 case PERF_EVENT_IOC_ID:
4466 u64 id = primary_event_id(event);
4468 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4473 case PERF_EVENT_IOC_SET_OUTPUT:
4477 struct perf_event *output_event;
4479 ret = perf_fget_light(arg, &output);
4482 output_event = output.file->private_data;
4483 ret = perf_event_set_output(event, output_event);
4486 ret = perf_event_set_output(event, NULL);
4491 case PERF_EVENT_IOC_SET_FILTER:
4492 return perf_event_set_filter(event, (void __user *)arg);
4494 case PERF_EVENT_IOC_SET_BPF:
4495 return perf_event_set_bpf_prog(event, arg);
4497 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
4498 struct ring_buffer *rb;
4501 rb = rcu_dereference(event->rb);
4502 if (!rb || !rb->nr_pages) {
4506 rb_toggle_paused(rb, !!arg);
4514 if (flags & PERF_IOC_FLAG_GROUP)
4515 perf_event_for_each(event, func);
4517 perf_event_for_each_child(event, func);
4522 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4524 struct perf_event *event = file->private_data;
4525 struct perf_event_context *ctx;
4528 ctx = perf_event_ctx_lock(event);
4529 ret = _perf_ioctl(event, cmd, arg);
4530 perf_event_ctx_unlock(event, ctx);
4535 #ifdef CONFIG_COMPAT
4536 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4539 switch (_IOC_NR(cmd)) {
4540 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4541 case _IOC_NR(PERF_EVENT_IOC_ID):
4542 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4543 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4544 cmd &= ~IOCSIZE_MASK;
4545 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4549 return perf_ioctl(file, cmd, arg);
4552 # define perf_compat_ioctl NULL
4555 int perf_event_task_enable(void)
4557 struct perf_event_context *ctx;
4558 struct perf_event *event;
4560 mutex_lock(¤t->perf_event_mutex);
4561 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4562 ctx = perf_event_ctx_lock(event);
4563 perf_event_for_each_child(event, _perf_event_enable);
4564 perf_event_ctx_unlock(event, ctx);
4566 mutex_unlock(¤t->perf_event_mutex);
4571 int perf_event_task_disable(void)
4573 struct perf_event_context *ctx;
4574 struct perf_event *event;
4576 mutex_lock(¤t->perf_event_mutex);
4577 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4578 ctx = perf_event_ctx_lock(event);
4579 perf_event_for_each_child(event, _perf_event_disable);
4580 perf_event_ctx_unlock(event, ctx);
4582 mutex_unlock(¤t->perf_event_mutex);
4587 static int perf_event_index(struct perf_event *event)
4589 if (event->hw.state & PERF_HES_STOPPED)
4592 if (event->state != PERF_EVENT_STATE_ACTIVE)
4595 return event->pmu->event_idx(event);
4598 static void calc_timer_values(struct perf_event *event,
4605 *now = perf_clock();
4606 ctx_time = event->shadow_ctx_time + *now;
4607 *enabled = ctx_time - event->tstamp_enabled;
4608 *running = ctx_time - event->tstamp_running;
4611 static void perf_event_init_userpage(struct perf_event *event)
4613 struct perf_event_mmap_page *userpg;
4614 struct ring_buffer *rb;
4617 rb = rcu_dereference(event->rb);
4621 userpg = rb->user_page;
4623 /* Allow new userspace to detect that bit 0 is deprecated */
4624 userpg->cap_bit0_is_deprecated = 1;
4625 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4626 userpg->data_offset = PAGE_SIZE;
4627 userpg->data_size = perf_data_size(rb);
4633 void __weak arch_perf_update_userpage(
4634 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4639 * Callers need to ensure there can be no nesting of this function, otherwise
4640 * the seqlock logic goes bad. We can not serialize this because the arch
4641 * code calls this from NMI context.
4643 void perf_event_update_userpage(struct perf_event *event)
4645 struct perf_event_mmap_page *userpg;
4646 struct ring_buffer *rb;
4647 u64 enabled, running, now;
4650 rb = rcu_dereference(event->rb);
4655 * compute total_time_enabled, total_time_running
4656 * based on snapshot values taken when the event
4657 * was last scheduled in.
4659 * we cannot simply called update_context_time()
4660 * because of locking issue as we can be called in
4663 calc_timer_values(event, &now, &enabled, &running);
4665 userpg = rb->user_page;
4667 * Disable preemption so as to not let the corresponding user-space
4668 * spin too long if we get preempted.
4673 userpg->index = perf_event_index(event);
4674 userpg->offset = perf_event_count(event);
4676 userpg->offset -= local64_read(&event->hw.prev_count);
4678 userpg->time_enabled = enabled +
4679 atomic64_read(&event->child_total_time_enabled);
4681 userpg->time_running = running +
4682 atomic64_read(&event->child_total_time_running);
4684 arch_perf_update_userpage(event, userpg, now);
4693 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4695 struct perf_event *event = vma->vm_file->private_data;
4696 struct ring_buffer *rb;
4697 int ret = VM_FAULT_SIGBUS;
4699 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4700 if (vmf->pgoff == 0)
4706 rb = rcu_dereference(event->rb);
4710 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4713 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4717 get_page(vmf->page);
4718 vmf->page->mapping = vma->vm_file->f_mapping;
4719 vmf->page->index = vmf->pgoff;
4728 static void ring_buffer_attach(struct perf_event *event,
4729 struct ring_buffer *rb)
4731 struct ring_buffer *old_rb = NULL;
4732 unsigned long flags;
4736 * Should be impossible, we set this when removing
4737 * event->rb_entry and wait/clear when adding event->rb_entry.
4739 WARN_ON_ONCE(event->rcu_pending);
4742 spin_lock_irqsave(&old_rb->event_lock, flags);
4743 list_del_rcu(&event->rb_entry);
4744 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4746 event->rcu_batches = get_state_synchronize_rcu();
4747 event->rcu_pending = 1;
4751 if (event->rcu_pending) {
4752 cond_synchronize_rcu(event->rcu_batches);
4753 event->rcu_pending = 0;
4756 spin_lock_irqsave(&rb->event_lock, flags);
4757 list_add_rcu(&event->rb_entry, &rb->event_list);
4758 spin_unlock_irqrestore(&rb->event_lock, flags);
4761 rcu_assign_pointer(event->rb, rb);
4764 ring_buffer_put(old_rb);
4766 * Since we detached before setting the new rb, so that we
4767 * could attach the new rb, we could have missed a wakeup.
4770 wake_up_all(&event->waitq);
4774 static void ring_buffer_wakeup(struct perf_event *event)
4776 struct ring_buffer *rb;
4779 rb = rcu_dereference(event->rb);
4781 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4782 wake_up_all(&event->waitq);
4787 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4789 struct ring_buffer *rb;
4792 rb = rcu_dereference(event->rb);
4794 if (!atomic_inc_not_zero(&rb->refcount))
4802 void ring_buffer_put(struct ring_buffer *rb)
4804 if (!atomic_dec_and_test(&rb->refcount))
4807 WARN_ON_ONCE(!list_empty(&rb->event_list));
4809 call_rcu(&rb->rcu_head, rb_free_rcu);
4812 static void perf_mmap_open(struct vm_area_struct *vma)
4814 struct perf_event *event = vma->vm_file->private_data;
4816 atomic_inc(&event->mmap_count);
4817 atomic_inc(&event->rb->mmap_count);
4820 atomic_inc(&event->rb->aux_mmap_count);
4822 if (event->pmu->event_mapped)
4823 event->pmu->event_mapped(event);
4826 static void perf_pmu_output_stop(struct perf_event *event);
4829 * A buffer can be mmap()ed multiple times; either directly through the same
4830 * event, or through other events by use of perf_event_set_output().
4832 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4833 * the buffer here, where we still have a VM context. This means we need
4834 * to detach all events redirecting to us.
4836 static void perf_mmap_close(struct vm_area_struct *vma)
4838 struct perf_event *event = vma->vm_file->private_data;
4840 struct ring_buffer *rb = ring_buffer_get(event);
4841 struct user_struct *mmap_user = rb->mmap_user;
4842 int mmap_locked = rb->mmap_locked;
4843 unsigned long size = perf_data_size(rb);
4845 if (event->pmu->event_unmapped)
4846 event->pmu->event_unmapped(event);
4849 * rb->aux_mmap_count will always drop before rb->mmap_count and
4850 * event->mmap_count, so it is ok to use event->mmap_mutex to
4851 * serialize with perf_mmap here.
4853 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4854 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4856 * Stop all AUX events that are writing to this buffer,
4857 * so that we can free its AUX pages and corresponding PMU
4858 * data. Note that after rb::aux_mmap_count dropped to zero,
4859 * they won't start any more (see perf_aux_output_begin()).
4861 perf_pmu_output_stop(event);
4863 /* now it's safe to free the pages */
4864 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4865 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4867 /* this has to be the last one */
4869 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
4871 mutex_unlock(&event->mmap_mutex);
4874 atomic_dec(&rb->mmap_count);
4876 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4879 ring_buffer_attach(event, NULL);
4880 mutex_unlock(&event->mmap_mutex);
4882 /* If there's still other mmap()s of this buffer, we're done. */
4883 if (atomic_read(&rb->mmap_count))
4887 * No other mmap()s, detach from all other events that might redirect
4888 * into the now unreachable buffer. Somewhat complicated by the
4889 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4893 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4894 if (!atomic_long_inc_not_zero(&event->refcount)) {
4896 * This event is en-route to free_event() which will
4897 * detach it and remove it from the list.
4903 mutex_lock(&event->mmap_mutex);
4905 * Check we didn't race with perf_event_set_output() which can
4906 * swizzle the rb from under us while we were waiting to
4907 * acquire mmap_mutex.
4909 * If we find a different rb; ignore this event, a next
4910 * iteration will no longer find it on the list. We have to
4911 * still restart the iteration to make sure we're not now
4912 * iterating the wrong list.
4914 if (event->rb == rb)
4915 ring_buffer_attach(event, NULL);
4917 mutex_unlock(&event->mmap_mutex);
4921 * Restart the iteration; either we're on the wrong list or
4922 * destroyed its integrity by doing a deletion.
4929 * It could be there's still a few 0-ref events on the list; they'll
4930 * get cleaned up by free_event() -- they'll also still have their
4931 * ref on the rb and will free it whenever they are done with it.
4933 * Aside from that, this buffer is 'fully' detached and unmapped,
4934 * undo the VM accounting.
4937 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4938 vma->vm_mm->pinned_vm -= mmap_locked;
4939 free_uid(mmap_user);
4942 ring_buffer_put(rb); /* could be last */
4945 static const struct vm_operations_struct perf_mmap_vmops = {
4946 .open = perf_mmap_open,
4947 .close = perf_mmap_close, /* non mergable */
4948 .fault = perf_mmap_fault,
4949 .page_mkwrite = perf_mmap_fault,
4952 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4954 struct perf_event *event = file->private_data;
4955 unsigned long user_locked, user_lock_limit;
4956 struct user_struct *user = current_user();
4957 unsigned long locked, lock_limit;
4958 struct ring_buffer *rb = NULL;
4959 unsigned long vma_size;
4960 unsigned long nr_pages;
4961 long user_extra = 0, extra = 0;
4962 int ret = 0, flags = 0;
4965 * Don't allow mmap() of inherited per-task counters. This would
4966 * create a performance issue due to all children writing to the
4969 if (event->cpu == -1 && event->attr.inherit)
4972 if (!(vma->vm_flags & VM_SHARED))
4975 vma_size = vma->vm_end - vma->vm_start;
4977 if (vma->vm_pgoff == 0) {
4978 nr_pages = (vma_size / PAGE_SIZE) - 1;
4981 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4982 * mapped, all subsequent mappings should have the same size
4983 * and offset. Must be above the normal perf buffer.
4985 u64 aux_offset, aux_size;
4990 nr_pages = vma_size / PAGE_SIZE;
4992 mutex_lock(&event->mmap_mutex);
4999 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
5000 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
5002 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5005 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5008 /* already mapped with a different offset */
5009 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5012 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5015 /* already mapped with a different size */
5016 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5019 if (!is_power_of_2(nr_pages))
5022 if (!atomic_inc_not_zero(&rb->mmap_count))
5025 if (rb_has_aux(rb)) {
5026 atomic_inc(&rb->aux_mmap_count);
5031 atomic_set(&rb->aux_mmap_count, 1);
5032 user_extra = nr_pages;
5038 * If we have rb pages ensure they're a power-of-two number, so we
5039 * can do bitmasks instead of modulo.
5041 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5044 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5047 WARN_ON_ONCE(event->ctx->parent_ctx);
5049 mutex_lock(&event->mmap_mutex);
5051 if (event->rb->nr_pages != nr_pages) {
5056 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5058 * Raced against perf_mmap_close() through
5059 * perf_event_set_output(). Try again, hope for better
5062 mutex_unlock(&event->mmap_mutex);
5069 user_extra = nr_pages + 1;
5072 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5075 * Increase the limit linearly with more CPUs:
5077 user_lock_limit *= num_online_cpus();
5079 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5081 if (user_locked > user_lock_limit)
5082 extra = user_locked - user_lock_limit;
5084 lock_limit = rlimit(RLIMIT_MEMLOCK);
5085 lock_limit >>= PAGE_SHIFT;
5086 locked = vma->vm_mm->pinned_vm + extra;
5088 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5089 !capable(CAP_IPC_LOCK)) {
5094 WARN_ON(!rb && event->rb);
5096 if (vma->vm_flags & VM_WRITE)
5097 flags |= RING_BUFFER_WRITABLE;
5100 rb = rb_alloc(nr_pages,
5101 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5109 atomic_set(&rb->mmap_count, 1);
5110 rb->mmap_user = get_current_user();
5111 rb->mmap_locked = extra;
5113 ring_buffer_attach(event, rb);
5115 perf_event_init_userpage(event);
5116 perf_event_update_userpage(event);
5118 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5119 event->attr.aux_watermark, flags);
5121 rb->aux_mmap_locked = extra;
5126 atomic_long_add(user_extra, &user->locked_vm);
5127 vma->vm_mm->pinned_vm += extra;
5129 atomic_inc(&event->mmap_count);
5131 atomic_dec(&rb->mmap_count);
5134 mutex_unlock(&event->mmap_mutex);
5137 * Since pinned accounting is per vm we cannot allow fork() to copy our
5140 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5141 vma->vm_ops = &perf_mmap_vmops;
5143 if (event->pmu->event_mapped)
5144 event->pmu->event_mapped(event);
5149 static int perf_fasync(int fd, struct file *filp, int on)
5151 struct inode *inode = file_inode(filp);
5152 struct perf_event *event = filp->private_data;
5156 retval = fasync_helper(fd, filp, on, &event->fasync);
5157 inode_unlock(inode);
5165 static const struct file_operations perf_fops = {
5166 .llseek = no_llseek,
5167 .release = perf_release,
5170 .unlocked_ioctl = perf_ioctl,
5171 .compat_ioctl = perf_compat_ioctl,
5173 .fasync = perf_fasync,
5179 * If there's data, ensure we set the poll() state and publish everything
5180 * to user-space before waking everybody up.
5183 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5185 /* only the parent has fasync state */
5187 event = event->parent;
5188 return &event->fasync;
5191 void perf_event_wakeup(struct perf_event *event)
5193 ring_buffer_wakeup(event);
5195 if (event->pending_kill) {
5196 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5197 event->pending_kill = 0;
5201 static void perf_pending_event(struct irq_work *entry)
5203 struct perf_event *event = container_of(entry,
5204 struct perf_event, pending);
5207 rctx = perf_swevent_get_recursion_context();
5209 * If we 'fail' here, that's OK, it means recursion is already disabled
5210 * and we won't recurse 'further'.
5213 if (event->pending_disable) {
5214 event->pending_disable = 0;
5215 perf_event_disable_local(event);
5218 if (event->pending_wakeup) {
5219 event->pending_wakeup = 0;
5220 perf_event_wakeup(event);
5224 perf_swevent_put_recursion_context(rctx);
5228 * We assume there is only KVM supporting the callbacks.
5229 * Later on, we might change it to a list if there is
5230 * another virtualization implementation supporting the callbacks.
5232 struct perf_guest_info_callbacks *perf_guest_cbs;
5234 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5236 perf_guest_cbs = cbs;
5239 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5241 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5243 perf_guest_cbs = NULL;
5246 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5249 perf_output_sample_regs(struct perf_output_handle *handle,
5250 struct pt_regs *regs, u64 mask)
5254 for_each_set_bit(bit, (const unsigned long *) &mask,
5255 sizeof(mask) * BITS_PER_BYTE) {
5258 val = perf_reg_value(regs, bit);
5259 perf_output_put(handle, val);
5263 static void perf_sample_regs_user(struct perf_regs *regs_user,
5264 struct pt_regs *regs,
5265 struct pt_regs *regs_user_copy)
5267 if (user_mode(regs)) {
5268 regs_user->abi = perf_reg_abi(current);
5269 regs_user->regs = regs;
5270 } else if (current->mm) {
5271 perf_get_regs_user(regs_user, regs, regs_user_copy);
5273 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5274 regs_user->regs = NULL;
5278 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5279 struct pt_regs *regs)
5281 regs_intr->regs = regs;
5282 regs_intr->abi = perf_reg_abi(current);
5287 * Get remaining task size from user stack pointer.
5289 * It'd be better to take stack vma map and limit this more
5290 * precisly, but there's no way to get it safely under interrupt,
5291 * so using TASK_SIZE as limit.
5293 static u64 perf_ustack_task_size(struct pt_regs *regs)
5295 unsigned long addr = perf_user_stack_pointer(regs);
5297 if (!addr || addr >= TASK_SIZE)
5300 return TASK_SIZE - addr;
5304 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5305 struct pt_regs *regs)
5309 /* No regs, no stack pointer, no dump. */
5314 * Check if we fit in with the requested stack size into the:
5316 * If we don't, we limit the size to the TASK_SIZE.
5318 * - remaining sample size
5319 * If we don't, we customize the stack size to
5320 * fit in to the remaining sample size.
5323 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5324 stack_size = min(stack_size, (u16) task_size);
5326 /* Current header size plus static size and dynamic size. */
5327 header_size += 2 * sizeof(u64);
5329 /* Do we fit in with the current stack dump size? */
5330 if ((u16) (header_size + stack_size) < header_size) {
5332 * If we overflow the maximum size for the sample,
5333 * we customize the stack dump size to fit in.
5335 stack_size = USHRT_MAX - header_size - sizeof(u64);
5336 stack_size = round_up(stack_size, sizeof(u64));
5343 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5344 struct pt_regs *regs)
5346 /* Case of a kernel thread, nothing to dump */
5349 perf_output_put(handle, size);
5358 * - the size requested by user or the best one we can fit
5359 * in to the sample max size
5361 * - user stack dump data
5363 * - the actual dumped size
5367 perf_output_put(handle, dump_size);
5370 sp = perf_user_stack_pointer(regs);
5371 rem = __output_copy_user(handle, (void *) sp, dump_size);
5372 dyn_size = dump_size - rem;
5374 perf_output_skip(handle, rem);
5377 perf_output_put(handle, dyn_size);
5381 static void __perf_event_header__init_id(struct perf_event_header *header,
5382 struct perf_sample_data *data,
5383 struct perf_event *event)
5385 u64 sample_type = event->attr.sample_type;
5387 data->type = sample_type;
5388 header->size += event->id_header_size;
5390 if (sample_type & PERF_SAMPLE_TID) {
5391 /* namespace issues */
5392 data->tid_entry.pid = perf_event_pid(event, current);
5393 data->tid_entry.tid = perf_event_tid(event, current);
5396 if (sample_type & PERF_SAMPLE_TIME)
5397 data->time = perf_event_clock(event);
5399 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5400 data->id = primary_event_id(event);
5402 if (sample_type & PERF_SAMPLE_STREAM_ID)
5403 data->stream_id = event->id;
5405 if (sample_type & PERF_SAMPLE_CPU) {
5406 data->cpu_entry.cpu = raw_smp_processor_id();
5407 data->cpu_entry.reserved = 0;
5411 void perf_event_header__init_id(struct perf_event_header *header,
5412 struct perf_sample_data *data,
5413 struct perf_event *event)
5415 if (event->attr.sample_id_all)
5416 __perf_event_header__init_id(header, data, event);
5419 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5420 struct perf_sample_data *data)
5422 u64 sample_type = data->type;
5424 if (sample_type & PERF_SAMPLE_TID)
5425 perf_output_put(handle, data->tid_entry);
5427 if (sample_type & PERF_SAMPLE_TIME)
5428 perf_output_put(handle, data->time);
5430 if (sample_type & PERF_SAMPLE_ID)
5431 perf_output_put(handle, data->id);
5433 if (sample_type & PERF_SAMPLE_STREAM_ID)
5434 perf_output_put(handle, data->stream_id);
5436 if (sample_type & PERF_SAMPLE_CPU)
5437 perf_output_put(handle, data->cpu_entry);
5439 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5440 perf_output_put(handle, data->id);
5443 void perf_event__output_id_sample(struct perf_event *event,
5444 struct perf_output_handle *handle,
5445 struct perf_sample_data *sample)
5447 if (event->attr.sample_id_all)
5448 __perf_event__output_id_sample(handle, sample);
5451 static void perf_output_read_one(struct perf_output_handle *handle,
5452 struct perf_event *event,
5453 u64 enabled, u64 running)
5455 u64 read_format = event->attr.read_format;
5459 values[n++] = perf_event_count(event);
5460 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5461 values[n++] = enabled +
5462 atomic64_read(&event->child_total_time_enabled);
5464 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5465 values[n++] = running +
5466 atomic64_read(&event->child_total_time_running);
5468 if (read_format & PERF_FORMAT_ID)
5469 values[n++] = primary_event_id(event);
5471 __output_copy(handle, values, n * sizeof(u64));
5475 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5477 static void perf_output_read_group(struct perf_output_handle *handle,
5478 struct perf_event *event,
5479 u64 enabled, u64 running)
5481 struct perf_event *leader = event->group_leader, *sub;
5482 u64 read_format = event->attr.read_format;
5486 values[n++] = 1 + leader->nr_siblings;
5488 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5489 values[n++] = enabled;
5491 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5492 values[n++] = running;
5494 if (leader != event)
5495 leader->pmu->read(leader);
5497 values[n++] = perf_event_count(leader);
5498 if (read_format & PERF_FORMAT_ID)
5499 values[n++] = primary_event_id(leader);
5501 __output_copy(handle, values, n * sizeof(u64));
5503 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5506 if ((sub != event) &&
5507 (sub->state == PERF_EVENT_STATE_ACTIVE))
5508 sub->pmu->read(sub);
5510 values[n++] = perf_event_count(sub);
5511 if (read_format & PERF_FORMAT_ID)
5512 values[n++] = primary_event_id(sub);
5514 __output_copy(handle, values, n * sizeof(u64));
5518 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5519 PERF_FORMAT_TOTAL_TIME_RUNNING)
5521 static void perf_output_read(struct perf_output_handle *handle,
5522 struct perf_event *event)
5524 u64 enabled = 0, running = 0, now;
5525 u64 read_format = event->attr.read_format;
5528 * compute total_time_enabled, total_time_running
5529 * based on snapshot values taken when the event
5530 * was last scheduled in.
5532 * we cannot simply called update_context_time()
5533 * because of locking issue as we are called in
5536 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5537 calc_timer_values(event, &now, &enabled, &running);
5539 if (event->attr.read_format & PERF_FORMAT_GROUP)
5540 perf_output_read_group(handle, event, enabled, running);
5542 perf_output_read_one(handle, event, enabled, running);
5545 void perf_output_sample(struct perf_output_handle *handle,
5546 struct perf_event_header *header,
5547 struct perf_sample_data *data,
5548 struct perf_event *event)
5550 u64 sample_type = data->type;
5552 perf_output_put(handle, *header);
5554 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5555 perf_output_put(handle, data->id);
5557 if (sample_type & PERF_SAMPLE_IP)
5558 perf_output_put(handle, data->ip);
5560 if (sample_type & PERF_SAMPLE_TID)
5561 perf_output_put(handle, data->tid_entry);
5563 if (sample_type & PERF_SAMPLE_TIME)
5564 perf_output_put(handle, data->time);
5566 if (sample_type & PERF_SAMPLE_ADDR)
5567 perf_output_put(handle, data->addr);
5569 if (sample_type & PERF_SAMPLE_ID)
5570 perf_output_put(handle, data->id);
5572 if (sample_type & PERF_SAMPLE_STREAM_ID)
5573 perf_output_put(handle, data->stream_id);
5575 if (sample_type & PERF_SAMPLE_CPU)
5576 perf_output_put(handle, data->cpu_entry);
5578 if (sample_type & PERF_SAMPLE_PERIOD)
5579 perf_output_put(handle, data->period);
5581 if (sample_type & PERF_SAMPLE_READ)
5582 perf_output_read(handle, event);
5584 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5585 if (data->callchain) {
5588 if (data->callchain)
5589 size += data->callchain->nr;
5591 size *= sizeof(u64);
5593 __output_copy(handle, data->callchain, size);
5596 perf_output_put(handle, nr);
5600 if (sample_type & PERF_SAMPLE_RAW) {
5602 u32 raw_size = data->raw->size;
5603 u32 real_size = round_up(raw_size + sizeof(u32),
5604 sizeof(u64)) - sizeof(u32);
5607 perf_output_put(handle, real_size);
5608 __output_copy(handle, data->raw->data, raw_size);
5609 if (real_size - raw_size)
5610 __output_copy(handle, &zero, real_size - raw_size);
5616 .size = sizeof(u32),
5619 perf_output_put(handle, raw);
5623 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5624 if (data->br_stack) {
5627 size = data->br_stack->nr
5628 * sizeof(struct perf_branch_entry);
5630 perf_output_put(handle, data->br_stack->nr);
5631 perf_output_copy(handle, data->br_stack->entries, size);
5634 * we always store at least the value of nr
5637 perf_output_put(handle, nr);
5641 if (sample_type & PERF_SAMPLE_REGS_USER) {
5642 u64 abi = data->regs_user.abi;
5645 * If there are no regs to dump, notice it through
5646 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5648 perf_output_put(handle, abi);
5651 u64 mask = event->attr.sample_regs_user;
5652 perf_output_sample_regs(handle,
5653 data->regs_user.regs,
5658 if (sample_type & PERF_SAMPLE_STACK_USER) {
5659 perf_output_sample_ustack(handle,
5660 data->stack_user_size,
5661 data->regs_user.regs);
5664 if (sample_type & PERF_SAMPLE_WEIGHT)
5665 perf_output_put(handle, data->weight);
5667 if (sample_type & PERF_SAMPLE_DATA_SRC)
5668 perf_output_put(handle, data->data_src.val);
5670 if (sample_type & PERF_SAMPLE_TRANSACTION)
5671 perf_output_put(handle, data->txn);
5673 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5674 u64 abi = data->regs_intr.abi;
5676 * If there are no regs to dump, notice it through
5677 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5679 perf_output_put(handle, abi);
5682 u64 mask = event->attr.sample_regs_intr;
5684 perf_output_sample_regs(handle,
5685 data->regs_intr.regs,
5690 if (!event->attr.watermark) {
5691 int wakeup_events = event->attr.wakeup_events;
5693 if (wakeup_events) {
5694 struct ring_buffer *rb = handle->rb;
5695 int events = local_inc_return(&rb->events);
5697 if (events >= wakeup_events) {
5698 local_sub(wakeup_events, &rb->events);
5699 local_inc(&rb->wakeup);
5705 void perf_prepare_sample(struct perf_event_header *header,
5706 struct perf_sample_data *data,
5707 struct perf_event *event,
5708 struct pt_regs *regs)
5710 u64 sample_type = event->attr.sample_type;
5712 header->type = PERF_RECORD_SAMPLE;
5713 header->size = sizeof(*header) + event->header_size;
5716 header->misc |= perf_misc_flags(regs);
5718 __perf_event_header__init_id(header, data, event);
5720 if (sample_type & PERF_SAMPLE_IP)
5721 data->ip = perf_instruction_pointer(regs);
5723 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5726 data->callchain = perf_callchain(event, regs);
5728 if (data->callchain)
5729 size += data->callchain->nr;
5731 header->size += size * sizeof(u64);
5734 if (sample_type & PERF_SAMPLE_RAW) {
5735 int size = sizeof(u32);
5738 size += data->raw->size;
5740 size += sizeof(u32);
5742 header->size += round_up(size, sizeof(u64));
5745 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5746 int size = sizeof(u64); /* nr */
5747 if (data->br_stack) {
5748 size += data->br_stack->nr
5749 * sizeof(struct perf_branch_entry);
5751 header->size += size;
5754 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5755 perf_sample_regs_user(&data->regs_user, regs,
5756 &data->regs_user_copy);
5758 if (sample_type & PERF_SAMPLE_REGS_USER) {
5759 /* regs dump ABI info */
5760 int size = sizeof(u64);
5762 if (data->regs_user.regs) {
5763 u64 mask = event->attr.sample_regs_user;
5764 size += hweight64(mask) * sizeof(u64);
5767 header->size += size;
5770 if (sample_type & PERF_SAMPLE_STACK_USER) {
5772 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5773 * processed as the last one or have additional check added
5774 * in case new sample type is added, because we could eat
5775 * up the rest of the sample size.
5777 u16 stack_size = event->attr.sample_stack_user;
5778 u16 size = sizeof(u64);
5780 stack_size = perf_sample_ustack_size(stack_size, header->size,
5781 data->regs_user.regs);
5784 * If there is something to dump, add space for the dump
5785 * itself and for the field that tells the dynamic size,
5786 * which is how many have been actually dumped.
5789 size += sizeof(u64) + stack_size;
5791 data->stack_user_size = stack_size;
5792 header->size += size;
5795 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5796 /* regs dump ABI info */
5797 int size = sizeof(u64);
5799 perf_sample_regs_intr(&data->regs_intr, regs);
5801 if (data->regs_intr.regs) {
5802 u64 mask = event->attr.sample_regs_intr;
5804 size += hweight64(mask) * sizeof(u64);
5807 header->size += size;
5811 static void __always_inline
5812 __perf_event_output(struct perf_event *event,
5813 struct perf_sample_data *data,
5814 struct pt_regs *regs,
5815 int (*output_begin)(struct perf_output_handle *,
5816 struct perf_event *,
5819 struct perf_output_handle handle;
5820 struct perf_event_header header;
5822 /* protect the callchain buffers */
5825 perf_prepare_sample(&header, data, event, regs);
5827 if (output_begin(&handle, event, header.size))
5830 perf_output_sample(&handle, &header, data, event);
5832 perf_output_end(&handle);
5839 perf_event_output_forward(struct perf_event *event,
5840 struct perf_sample_data *data,
5841 struct pt_regs *regs)
5843 __perf_event_output(event, data, regs, perf_output_begin_forward);
5847 perf_event_output_backward(struct perf_event *event,
5848 struct perf_sample_data *data,
5849 struct pt_regs *regs)
5851 __perf_event_output(event, data, regs, perf_output_begin_backward);
5855 perf_event_output(struct perf_event *event,
5856 struct perf_sample_data *data,
5857 struct pt_regs *regs)
5859 __perf_event_output(event, data, regs, perf_output_begin);
5866 struct perf_read_event {
5867 struct perf_event_header header;
5874 perf_event_read_event(struct perf_event *event,
5875 struct task_struct *task)
5877 struct perf_output_handle handle;
5878 struct perf_sample_data sample;
5879 struct perf_read_event read_event = {
5881 .type = PERF_RECORD_READ,
5883 .size = sizeof(read_event) + event->read_size,
5885 .pid = perf_event_pid(event, task),
5886 .tid = perf_event_tid(event, task),
5890 perf_event_header__init_id(&read_event.header, &sample, event);
5891 ret = perf_output_begin(&handle, event, read_event.header.size);
5895 perf_output_put(&handle, read_event);
5896 perf_output_read(&handle, event);
5897 perf_event__output_id_sample(event, &handle, &sample);
5899 perf_output_end(&handle);
5902 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
5905 perf_iterate_ctx(struct perf_event_context *ctx,
5906 perf_iterate_f output,
5907 void *data, bool all)
5909 struct perf_event *event;
5911 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5913 if (event->state < PERF_EVENT_STATE_INACTIVE)
5915 if (!event_filter_match(event))
5919 output(event, data);
5923 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
5925 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
5926 struct perf_event *event;
5928 list_for_each_entry_rcu(event, &pel->list, sb_list) {
5929 if (event->state < PERF_EVENT_STATE_INACTIVE)
5931 if (!event_filter_match(event))
5933 output(event, data);
5938 * Iterate all events that need to receive side-band events.
5940 * For new callers; ensure that account_pmu_sb_event() includes
5941 * your event, otherwise it might not get delivered.
5944 perf_iterate_sb(perf_iterate_f output, void *data,
5945 struct perf_event_context *task_ctx)
5947 struct perf_event_context *ctx;
5954 * If we have task_ctx != NULL we only notify the task context itself.
5955 * The task_ctx is set only for EXIT events before releasing task
5959 perf_iterate_ctx(task_ctx, output, data, false);
5963 perf_iterate_sb_cpu(output, data);
5965 for_each_task_context_nr(ctxn) {
5966 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5968 perf_iterate_ctx(ctx, output, data, false);
5976 * Clear all file-based filters at exec, they'll have to be
5977 * re-instated when/if these objects are mmapped again.
5979 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
5981 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
5982 struct perf_addr_filter *filter;
5983 unsigned int restart = 0, count = 0;
5984 unsigned long flags;
5986 if (!has_addr_filter(event))
5989 raw_spin_lock_irqsave(&ifh->lock, flags);
5990 list_for_each_entry(filter, &ifh->list, entry) {
5991 if (filter->inode) {
5992 event->addr_filters_offs[count] = 0;
6000 event->addr_filters_gen++;
6001 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6004 perf_event_restart(event);
6007 void perf_event_exec(void)
6009 struct perf_event_context *ctx;
6013 for_each_task_context_nr(ctxn) {
6014 ctx = current->perf_event_ctxp[ctxn];
6018 perf_event_enable_on_exec(ctxn);
6020 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6026 struct remote_output {
6027 struct ring_buffer *rb;
6031 static void __perf_event_output_stop(struct perf_event *event, void *data)
6033 struct perf_event *parent = event->parent;
6034 struct remote_output *ro = data;
6035 struct ring_buffer *rb = ro->rb;
6036 struct stop_event_data sd = {
6040 if (!has_aux(event))
6047 * In case of inheritance, it will be the parent that links to the
6048 * ring-buffer, but it will be the child that's actually using it:
6050 if (rcu_dereference(parent->rb) == rb)
6051 ro->err = __perf_event_stop(&sd);
6054 static int __perf_pmu_output_stop(void *info)
6056 struct perf_event *event = info;
6057 struct pmu *pmu = event->pmu;
6058 struct perf_cpu_context *cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
6059 struct remote_output ro = {
6064 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6065 if (cpuctx->task_ctx)
6066 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6073 static void perf_pmu_output_stop(struct perf_event *event)
6075 struct perf_event *iter;
6080 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6082 * For per-CPU events, we need to make sure that neither they
6083 * nor their children are running; for cpu==-1 events it's
6084 * sufficient to stop the event itself if it's active, since
6085 * it can't have children.
6089 cpu = READ_ONCE(iter->oncpu);
6094 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6095 if (err == -EAGAIN) {
6104 * task tracking -- fork/exit
6106 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6109 struct perf_task_event {
6110 struct task_struct *task;
6111 struct perf_event_context *task_ctx;
6114 struct perf_event_header header;
6124 static int perf_event_task_match(struct perf_event *event)
6126 return event->attr.comm || event->attr.mmap ||
6127 event->attr.mmap2 || event->attr.mmap_data ||
6131 static void perf_event_task_output(struct perf_event *event,
6134 struct perf_task_event *task_event = data;
6135 struct perf_output_handle handle;
6136 struct perf_sample_data sample;
6137 struct task_struct *task = task_event->task;
6138 int ret, size = task_event->event_id.header.size;
6140 if (!perf_event_task_match(event))
6143 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6145 ret = perf_output_begin(&handle, event,
6146 task_event->event_id.header.size);
6150 task_event->event_id.pid = perf_event_pid(event, task);
6151 task_event->event_id.ppid = perf_event_pid(event, current);
6153 task_event->event_id.tid = perf_event_tid(event, task);
6154 task_event->event_id.ptid = perf_event_tid(event, current);
6156 task_event->event_id.time = perf_event_clock(event);
6158 perf_output_put(&handle, task_event->event_id);
6160 perf_event__output_id_sample(event, &handle, &sample);
6162 perf_output_end(&handle);
6164 task_event->event_id.header.size = size;
6167 static void perf_event_task(struct task_struct *task,
6168 struct perf_event_context *task_ctx,
6171 struct perf_task_event task_event;
6173 if (!atomic_read(&nr_comm_events) &&
6174 !atomic_read(&nr_mmap_events) &&
6175 !atomic_read(&nr_task_events))
6178 task_event = (struct perf_task_event){
6180 .task_ctx = task_ctx,
6183 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6185 .size = sizeof(task_event.event_id),
6195 perf_iterate_sb(perf_event_task_output,
6200 void perf_event_fork(struct task_struct *task)
6202 perf_event_task(task, NULL, 1);
6209 struct perf_comm_event {
6210 struct task_struct *task;
6215 struct perf_event_header header;
6222 static int perf_event_comm_match(struct perf_event *event)
6224 return event->attr.comm;
6227 static void perf_event_comm_output(struct perf_event *event,
6230 struct perf_comm_event *comm_event = data;
6231 struct perf_output_handle handle;
6232 struct perf_sample_data sample;
6233 int size = comm_event->event_id.header.size;
6236 if (!perf_event_comm_match(event))
6239 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6240 ret = perf_output_begin(&handle, event,
6241 comm_event->event_id.header.size);
6246 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6247 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6249 perf_output_put(&handle, comm_event->event_id);
6250 __output_copy(&handle, comm_event->comm,
6251 comm_event->comm_size);
6253 perf_event__output_id_sample(event, &handle, &sample);
6255 perf_output_end(&handle);
6257 comm_event->event_id.header.size = size;
6260 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6262 char comm[TASK_COMM_LEN];
6265 memset(comm, 0, sizeof(comm));
6266 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6267 size = ALIGN(strlen(comm)+1, sizeof(u64));
6269 comm_event->comm = comm;
6270 comm_event->comm_size = size;
6272 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6274 perf_iterate_sb(perf_event_comm_output,
6279 void perf_event_comm(struct task_struct *task, bool exec)
6281 struct perf_comm_event comm_event;
6283 if (!atomic_read(&nr_comm_events))
6286 comm_event = (struct perf_comm_event){
6292 .type = PERF_RECORD_COMM,
6293 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6301 perf_event_comm_event(&comm_event);
6308 struct perf_mmap_event {
6309 struct vm_area_struct *vma;
6311 const char *file_name;
6319 struct perf_event_header header;
6329 static int perf_event_mmap_match(struct perf_event *event,
6332 struct perf_mmap_event *mmap_event = data;
6333 struct vm_area_struct *vma = mmap_event->vma;
6334 int executable = vma->vm_flags & VM_EXEC;
6336 return (!executable && event->attr.mmap_data) ||
6337 (executable && (event->attr.mmap || event->attr.mmap2));
6340 static void perf_event_mmap_output(struct perf_event *event,
6343 struct perf_mmap_event *mmap_event = data;
6344 struct perf_output_handle handle;
6345 struct perf_sample_data sample;
6346 int size = mmap_event->event_id.header.size;
6349 if (!perf_event_mmap_match(event, data))
6352 if (event->attr.mmap2) {
6353 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6354 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6355 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6356 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6357 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6358 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6359 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6362 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6363 ret = perf_output_begin(&handle, event,
6364 mmap_event->event_id.header.size);
6368 mmap_event->event_id.pid = perf_event_pid(event, current);
6369 mmap_event->event_id.tid = perf_event_tid(event, current);
6371 perf_output_put(&handle, mmap_event->event_id);
6373 if (event->attr.mmap2) {
6374 perf_output_put(&handle, mmap_event->maj);
6375 perf_output_put(&handle, mmap_event->min);
6376 perf_output_put(&handle, mmap_event->ino);
6377 perf_output_put(&handle, mmap_event->ino_generation);
6378 perf_output_put(&handle, mmap_event->prot);
6379 perf_output_put(&handle, mmap_event->flags);
6382 __output_copy(&handle, mmap_event->file_name,
6383 mmap_event->file_size);
6385 perf_event__output_id_sample(event, &handle, &sample);
6387 perf_output_end(&handle);
6389 mmap_event->event_id.header.size = size;
6392 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6394 struct vm_area_struct *vma = mmap_event->vma;
6395 struct file *file = vma->vm_file;
6396 int maj = 0, min = 0;
6397 u64 ino = 0, gen = 0;
6398 u32 prot = 0, flags = 0;
6405 struct inode *inode;
6408 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6414 * d_path() works from the end of the rb backwards, so we
6415 * need to add enough zero bytes after the string to handle
6416 * the 64bit alignment we do later.
6418 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6423 inode = file_inode(vma->vm_file);
6424 dev = inode->i_sb->s_dev;
6426 gen = inode->i_generation;
6430 if (vma->vm_flags & VM_READ)
6432 if (vma->vm_flags & VM_WRITE)
6434 if (vma->vm_flags & VM_EXEC)
6437 if (vma->vm_flags & VM_MAYSHARE)
6440 flags = MAP_PRIVATE;
6442 if (vma->vm_flags & VM_DENYWRITE)
6443 flags |= MAP_DENYWRITE;
6444 if (vma->vm_flags & VM_MAYEXEC)
6445 flags |= MAP_EXECUTABLE;
6446 if (vma->vm_flags & VM_LOCKED)
6447 flags |= MAP_LOCKED;
6448 if (vma->vm_flags & VM_HUGETLB)
6449 flags |= MAP_HUGETLB;
6453 if (vma->vm_ops && vma->vm_ops->name) {
6454 name = (char *) vma->vm_ops->name(vma);
6459 name = (char *)arch_vma_name(vma);
6463 if (vma->vm_start <= vma->vm_mm->start_brk &&
6464 vma->vm_end >= vma->vm_mm->brk) {
6468 if (vma->vm_start <= vma->vm_mm->start_stack &&
6469 vma->vm_end >= vma->vm_mm->start_stack) {
6479 strlcpy(tmp, name, sizeof(tmp));
6483 * Since our buffer works in 8 byte units we need to align our string
6484 * size to a multiple of 8. However, we must guarantee the tail end is
6485 * zero'd out to avoid leaking random bits to userspace.
6487 size = strlen(name)+1;
6488 while (!IS_ALIGNED(size, sizeof(u64)))
6489 name[size++] = '\0';
6491 mmap_event->file_name = name;
6492 mmap_event->file_size = size;
6493 mmap_event->maj = maj;
6494 mmap_event->min = min;
6495 mmap_event->ino = ino;
6496 mmap_event->ino_generation = gen;
6497 mmap_event->prot = prot;
6498 mmap_event->flags = flags;
6500 if (!(vma->vm_flags & VM_EXEC))
6501 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6503 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6505 perf_iterate_sb(perf_event_mmap_output,
6513 * Whether this @filter depends on a dynamic object which is not loaded
6514 * yet or its load addresses are not known.
6516 static bool perf_addr_filter_needs_mmap(struct perf_addr_filter *filter)
6518 return filter->filter && filter->inode;
6522 * Check whether inode and address range match filter criteria.
6524 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
6525 struct file *file, unsigned long offset,
6528 if (filter->inode != file->f_inode)
6531 if (filter->offset > offset + size)
6534 if (filter->offset + filter->size < offset)
6540 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
6542 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6543 struct vm_area_struct *vma = data;
6544 unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
6545 struct file *file = vma->vm_file;
6546 struct perf_addr_filter *filter;
6547 unsigned int restart = 0, count = 0;
6549 if (!has_addr_filter(event))
6555 raw_spin_lock_irqsave(&ifh->lock, flags);
6556 list_for_each_entry(filter, &ifh->list, entry) {
6557 if (perf_addr_filter_match(filter, file, off,
6558 vma->vm_end - vma->vm_start)) {
6559 event->addr_filters_offs[count] = vma->vm_start;
6567 event->addr_filters_gen++;
6568 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6571 perf_event_restart(event);
6575 * Adjust all task's events' filters to the new vma
6577 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
6579 struct perf_event_context *ctx;
6583 for_each_task_context_nr(ctxn) {
6584 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6588 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
6593 void perf_event_mmap(struct vm_area_struct *vma)
6595 struct perf_mmap_event mmap_event;
6597 if (!atomic_read(&nr_mmap_events))
6600 mmap_event = (struct perf_mmap_event){
6606 .type = PERF_RECORD_MMAP,
6607 .misc = PERF_RECORD_MISC_USER,
6612 .start = vma->vm_start,
6613 .len = vma->vm_end - vma->vm_start,
6614 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6616 /* .maj (attr_mmap2 only) */
6617 /* .min (attr_mmap2 only) */
6618 /* .ino (attr_mmap2 only) */
6619 /* .ino_generation (attr_mmap2 only) */
6620 /* .prot (attr_mmap2 only) */
6621 /* .flags (attr_mmap2 only) */
6624 perf_addr_filters_adjust(vma);
6625 perf_event_mmap_event(&mmap_event);
6628 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6629 unsigned long size, u64 flags)
6631 struct perf_output_handle handle;
6632 struct perf_sample_data sample;
6633 struct perf_aux_event {
6634 struct perf_event_header header;
6640 .type = PERF_RECORD_AUX,
6642 .size = sizeof(rec),
6650 perf_event_header__init_id(&rec.header, &sample, event);
6651 ret = perf_output_begin(&handle, event, rec.header.size);
6656 perf_output_put(&handle, rec);
6657 perf_event__output_id_sample(event, &handle, &sample);
6659 perf_output_end(&handle);
6663 * Lost/dropped samples logging
6665 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6667 struct perf_output_handle handle;
6668 struct perf_sample_data sample;
6672 struct perf_event_header header;
6674 } lost_samples_event = {
6676 .type = PERF_RECORD_LOST_SAMPLES,
6678 .size = sizeof(lost_samples_event),
6683 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6685 ret = perf_output_begin(&handle, event,
6686 lost_samples_event.header.size);
6690 perf_output_put(&handle, lost_samples_event);
6691 perf_event__output_id_sample(event, &handle, &sample);
6692 perf_output_end(&handle);
6696 * context_switch tracking
6699 struct perf_switch_event {
6700 struct task_struct *task;
6701 struct task_struct *next_prev;
6704 struct perf_event_header header;
6710 static int perf_event_switch_match(struct perf_event *event)
6712 return event->attr.context_switch;
6715 static void perf_event_switch_output(struct perf_event *event, void *data)
6717 struct perf_switch_event *se = data;
6718 struct perf_output_handle handle;
6719 struct perf_sample_data sample;
6722 if (!perf_event_switch_match(event))
6725 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6726 if (event->ctx->task) {
6727 se->event_id.header.type = PERF_RECORD_SWITCH;
6728 se->event_id.header.size = sizeof(se->event_id.header);
6730 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6731 se->event_id.header.size = sizeof(se->event_id);
6732 se->event_id.next_prev_pid =
6733 perf_event_pid(event, se->next_prev);
6734 se->event_id.next_prev_tid =
6735 perf_event_tid(event, se->next_prev);
6738 perf_event_header__init_id(&se->event_id.header, &sample, event);
6740 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6744 if (event->ctx->task)
6745 perf_output_put(&handle, se->event_id.header);
6747 perf_output_put(&handle, se->event_id);
6749 perf_event__output_id_sample(event, &handle, &sample);
6751 perf_output_end(&handle);
6754 static void perf_event_switch(struct task_struct *task,
6755 struct task_struct *next_prev, bool sched_in)
6757 struct perf_switch_event switch_event;
6759 /* N.B. caller checks nr_switch_events != 0 */
6761 switch_event = (struct perf_switch_event){
6763 .next_prev = next_prev,
6767 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6770 /* .next_prev_pid */
6771 /* .next_prev_tid */
6775 perf_iterate_sb(perf_event_switch_output,
6781 * IRQ throttle logging
6784 static void perf_log_throttle(struct perf_event *event, int enable)
6786 struct perf_output_handle handle;
6787 struct perf_sample_data sample;
6791 struct perf_event_header header;
6795 } throttle_event = {
6797 .type = PERF_RECORD_THROTTLE,
6799 .size = sizeof(throttle_event),
6801 .time = perf_event_clock(event),
6802 .id = primary_event_id(event),
6803 .stream_id = event->id,
6807 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6809 perf_event_header__init_id(&throttle_event.header, &sample, event);
6811 ret = perf_output_begin(&handle, event,
6812 throttle_event.header.size);
6816 perf_output_put(&handle, throttle_event);
6817 perf_event__output_id_sample(event, &handle, &sample);
6818 perf_output_end(&handle);
6821 static void perf_log_itrace_start(struct perf_event *event)
6823 struct perf_output_handle handle;
6824 struct perf_sample_data sample;
6825 struct perf_aux_event {
6826 struct perf_event_header header;
6833 event = event->parent;
6835 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6836 event->hw.itrace_started)
6839 rec.header.type = PERF_RECORD_ITRACE_START;
6840 rec.header.misc = 0;
6841 rec.header.size = sizeof(rec);
6842 rec.pid = perf_event_pid(event, current);
6843 rec.tid = perf_event_tid(event, current);
6845 perf_event_header__init_id(&rec.header, &sample, event);
6846 ret = perf_output_begin(&handle, event, rec.header.size);
6851 perf_output_put(&handle, rec);
6852 perf_event__output_id_sample(event, &handle, &sample);
6854 perf_output_end(&handle);
6858 * Generic event overflow handling, sampling.
6861 static int __perf_event_overflow(struct perf_event *event,
6862 int throttle, struct perf_sample_data *data,
6863 struct pt_regs *regs)
6865 int events = atomic_read(&event->event_limit);
6866 struct hw_perf_event *hwc = &event->hw;
6871 * Non-sampling counters might still use the PMI to fold short
6872 * hardware counters, ignore those.
6874 if (unlikely(!is_sampling_event(event)))
6877 seq = __this_cpu_read(perf_throttled_seq);
6878 if (seq != hwc->interrupts_seq) {
6879 hwc->interrupts_seq = seq;
6880 hwc->interrupts = 1;
6883 if (unlikely(throttle
6884 && hwc->interrupts >= max_samples_per_tick)) {
6885 __this_cpu_inc(perf_throttled_count);
6886 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
6887 hwc->interrupts = MAX_INTERRUPTS;
6888 perf_log_throttle(event, 0);
6893 if (event->attr.freq) {
6894 u64 now = perf_clock();
6895 s64 delta = now - hwc->freq_time_stamp;
6897 hwc->freq_time_stamp = now;
6899 if (delta > 0 && delta < 2*TICK_NSEC)
6900 perf_adjust_period(event, delta, hwc->last_period, true);
6904 * XXX event_limit might not quite work as expected on inherited
6908 event->pending_kill = POLL_IN;
6909 if (events && atomic_dec_and_test(&event->event_limit)) {
6911 event->pending_kill = POLL_HUP;
6912 event->pending_disable = 1;
6913 irq_work_queue(&event->pending);
6916 event->overflow_handler(event, data, regs);
6918 if (*perf_event_fasync(event) && event->pending_kill) {
6919 event->pending_wakeup = 1;
6920 irq_work_queue(&event->pending);
6926 int perf_event_overflow(struct perf_event *event,
6927 struct perf_sample_data *data,
6928 struct pt_regs *regs)
6930 return __perf_event_overflow(event, 1, data, regs);
6934 * Generic software event infrastructure
6937 struct swevent_htable {
6938 struct swevent_hlist *swevent_hlist;
6939 struct mutex hlist_mutex;
6942 /* Recursion avoidance in each contexts */
6943 int recursion[PERF_NR_CONTEXTS];
6946 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6949 * We directly increment event->count and keep a second value in
6950 * event->hw.period_left to count intervals. This period event
6951 * is kept in the range [-sample_period, 0] so that we can use the
6955 u64 perf_swevent_set_period(struct perf_event *event)
6957 struct hw_perf_event *hwc = &event->hw;
6958 u64 period = hwc->last_period;
6962 hwc->last_period = hwc->sample_period;
6965 old = val = local64_read(&hwc->period_left);
6969 nr = div64_u64(period + val, period);
6970 offset = nr * period;
6972 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6978 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6979 struct perf_sample_data *data,
6980 struct pt_regs *regs)
6982 struct hw_perf_event *hwc = &event->hw;
6986 overflow = perf_swevent_set_period(event);
6988 if (hwc->interrupts == MAX_INTERRUPTS)
6991 for (; overflow; overflow--) {
6992 if (__perf_event_overflow(event, throttle,
6995 * We inhibit the overflow from happening when
6996 * hwc->interrupts == MAX_INTERRUPTS.
7004 static void perf_swevent_event(struct perf_event *event, u64 nr,
7005 struct perf_sample_data *data,
7006 struct pt_regs *regs)
7008 struct hw_perf_event *hwc = &event->hw;
7010 local64_add(nr, &event->count);
7015 if (!is_sampling_event(event))
7018 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
7020 return perf_swevent_overflow(event, 1, data, regs);
7022 data->period = event->hw.last_period;
7024 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
7025 return perf_swevent_overflow(event, 1, data, regs);
7027 if (local64_add_negative(nr, &hwc->period_left))
7030 perf_swevent_overflow(event, 0, data, regs);
7033 static int perf_exclude_event(struct perf_event *event,
7034 struct pt_regs *regs)
7036 if (event->hw.state & PERF_HES_STOPPED)
7040 if (event->attr.exclude_user && user_mode(regs))
7043 if (event->attr.exclude_kernel && !user_mode(regs))
7050 static int perf_swevent_match(struct perf_event *event,
7051 enum perf_type_id type,
7053 struct perf_sample_data *data,
7054 struct pt_regs *regs)
7056 if (event->attr.type != type)
7059 if (event->attr.config != event_id)
7062 if (perf_exclude_event(event, regs))
7068 static inline u64 swevent_hash(u64 type, u32 event_id)
7070 u64 val = event_id | (type << 32);
7072 return hash_64(val, SWEVENT_HLIST_BITS);
7075 static inline struct hlist_head *
7076 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
7078 u64 hash = swevent_hash(type, event_id);
7080 return &hlist->heads[hash];
7083 /* For the read side: events when they trigger */
7084 static inline struct hlist_head *
7085 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
7087 struct swevent_hlist *hlist;
7089 hlist = rcu_dereference(swhash->swevent_hlist);
7093 return __find_swevent_head(hlist, type, event_id);
7096 /* For the event head insertion and removal in the hlist */
7097 static inline struct hlist_head *
7098 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
7100 struct swevent_hlist *hlist;
7101 u32 event_id = event->attr.config;
7102 u64 type = event->attr.type;
7105 * Event scheduling is always serialized against hlist allocation
7106 * and release. Which makes the protected version suitable here.
7107 * The context lock guarantees that.
7109 hlist = rcu_dereference_protected(swhash->swevent_hlist,
7110 lockdep_is_held(&event->ctx->lock));
7114 return __find_swevent_head(hlist, type, event_id);
7117 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
7119 struct perf_sample_data *data,
7120 struct pt_regs *regs)
7122 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7123 struct perf_event *event;
7124 struct hlist_head *head;
7127 head = find_swevent_head_rcu(swhash, type, event_id);
7131 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7132 if (perf_swevent_match(event, type, event_id, data, regs))
7133 perf_swevent_event(event, nr, data, regs);
7139 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
7141 int perf_swevent_get_recursion_context(void)
7143 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7145 return get_recursion_context(swhash->recursion);
7147 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
7149 void perf_swevent_put_recursion_context(int rctx)
7151 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7153 put_recursion_context(swhash->recursion, rctx);
7156 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7158 struct perf_sample_data data;
7160 if (WARN_ON_ONCE(!regs))
7163 perf_sample_data_init(&data, addr, 0);
7164 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
7167 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7171 preempt_disable_notrace();
7172 rctx = perf_swevent_get_recursion_context();
7173 if (unlikely(rctx < 0))
7176 ___perf_sw_event(event_id, nr, regs, addr);
7178 perf_swevent_put_recursion_context(rctx);
7180 preempt_enable_notrace();
7183 static void perf_swevent_read(struct perf_event *event)
7187 static int perf_swevent_add(struct perf_event *event, int flags)
7189 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7190 struct hw_perf_event *hwc = &event->hw;
7191 struct hlist_head *head;
7193 if (is_sampling_event(event)) {
7194 hwc->last_period = hwc->sample_period;
7195 perf_swevent_set_period(event);
7198 hwc->state = !(flags & PERF_EF_START);
7200 head = find_swevent_head(swhash, event);
7201 if (WARN_ON_ONCE(!head))
7204 hlist_add_head_rcu(&event->hlist_entry, head);
7205 perf_event_update_userpage(event);
7210 static void perf_swevent_del(struct perf_event *event, int flags)
7212 hlist_del_rcu(&event->hlist_entry);
7215 static void perf_swevent_start(struct perf_event *event, int flags)
7217 event->hw.state = 0;
7220 static void perf_swevent_stop(struct perf_event *event, int flags)
7222 event->hw.state = PERF_HES_STOPPED;
7225 /* Deref the hlist from the update side */
7226 static inline struct swevent_hlist *
7227 swevent_hlist_deref(struct swevent_htable *swhash)
7229 return rcu_dereference_protected(swhash->swevent_hlist,
7230 lockdep_is_held(&swhash->hlist_mutex));
7233 static void swevent_hlist_release(struct swevent_htable *swhash)
7235 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7240 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7241 kfree_rcu(hlist, rcu_head);
7244 static void swevent_hlist_put_cpu(int cpu)
7246 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7248 mutex_lock(&swhash->hlist_mutex);
7250 if (!--swhash->hlist_refcount)
7251 swevent_hlist_release(swhash);
7253 mutex_unlock(&swhash->hlist_mutex);
7256 static void swevent_hlist_put(void)
7260 for_each_possible_cpu(cpu)
7261 swevent_hlist_put_cpu(cpu);
7264 static int swevent_hlist_get_cpu(int cpu)
7266 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7269 mutex_lock(&swhash->hlist_mutex);
7270 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7271 struct swevent_hlist *hlist;
7273 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7278 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7280 swhash->hlist_refcount++;
7282 mutex_unlock(&swhash->hlist_mutex);
7287 static int swevent_hlist_get(void)
7289 int err, cpu, failed_cpu;
7292 for_each_possible_cpu(cpu) {
7293 err = swevent_hlist_get_cpu(cpu);
7303 for_each_possible_cpu(cpu) {
7304 if (cpu == failed_cpu)
7306 swevent_hlist_put_cpu(cpu);
7313 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7315 static void sw_perf_event_destroy(struct perf_event *event)
7317 u64 event_id = event->attr.config;
7319 WARN_ON(event->parent);
7321 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7322 swevent_hlist_put();
7325 static int perf_swevent_init(struct perf_event *event)
7327 u64 event_id = event->attr.config;
7329 if (event->attr.type != PERF_TYPE_SOFTWARE)
7333 * no branch sampling for software events
7335 if (has_branch_stack(event))
7339 case PERF_COUNT_SW_CPU_CLOCK:
7340 case PERF_COUNT_SW_TASK_CLOCK:
7347 if (event_id >= PERF_COUNT_SW_MAX)
7350 if (!event->parent) {
7353 err = swevent_hlist_get();
7357 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7358 event->destroy = sw_perf_event_destroy;
7364 static struct pmu perf_swevent = {
7365 .task_ctx_nr = perf_sw_context,
7367 .capabilities = PERF_PMU_CAP_NO_NMI,
7369 .event_init = perf_swevent_init,
7370 .add = perf_swevent_add,
7371 .del = perf_swevent_del,
7372 .start = perf_swevent_start,
7373 .stop = perf_swevent_stop,
7374 .read = perf_swevent_read,
7377 #ifdef CONFIG_EVENT_TRACING
7379 static int perf_tp_filter_match(struct perf_event *event,
7380 struct perf_sample_data *data)
7382 void *record = data->raw->data;
7384 /* only top level events have filters set */
7386 event = event->parent;
7388 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7393 static int perf_tp_event_match(struct perf_event *event,
7394 struct perf_sample_data *data,
7395 struct pt_regs *regs)
7397 if (event->hw.state & PERF_HES_STOPPED)
7400 * All tracepoints are from kernel-space.
7402 if (event->attr.exclude_kernel)
7405 if (!perf_tp_filter_match(event, data))
7411 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
7412 struct trace_event_call *call, u64 count,
7413 struct pt_regs *regs, struct hlist_head *head,
7414 struct task_struct *task)
7416 struct bpf_prog *prog = call->prog;
7419 *(struct pt_regs **)raw_data = regs;
7420 if (!trace_call_bpf(prog, raw_data) || hlist_empty(head)) {
7421 perf_swevent_put_recursion_context(rctx);
7425 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
7428 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
7430 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
7431 struct pt_regs *regs, struct hlist_head *head, int rctx,
7432 struct task_struct *task)
7434 struct perf_sample_data data;
7435 struct perf_event *event;
7437 struct perf_raw_record raw = {
7442 perf_sample_data_init(&data, 0, 0);
7445 perf_trace_buf_update(record, event_type);
7447 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7448 if (perf_tp_event_match(event, &data, regs))
7449 perf_swevent_event(event, count, &data, regs);
7453 * If we got specified a target task, also iterate its context and
7454 * deliver this event there too.
7456 if (task && task != current) {
7457 struct perf_event_context *ctx;
7458 struct trace_entry *entry = record;
7461 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7465 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7466 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7468 if (event->attr.config != entry->type)
7470 if (perf_tp_event_match(event, &data, regs))
7471 perf_swevent_event(event, count, &data, regs);
7477 perf_swevent_put_recursion_context(rctx);
7479 EXPORT_SYMBOL_GPL(perf_tp_event);
7481 static void tp_perf_event_destroy(struct perf_event *event)
7483 perf_trace_destroy(event);
7486 static int perf_tp_event_init(struct perf_event *event)
7490 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7494 * no branch sampling for tracepoint events
7496 if (has_branch_stack(event))
7499 err = perf_trace_init(event);
7503 event->destroy = tp_perf_event_destroy;
7508 static struct pmu perf_tracepoint = {
7509 .task_ctx_nr = perf_sw_context,
7511 .event_init = perf_tp_event_init,
7512 .add = perf_trace_add,
7513 .del = perf_trace_del,
7514 .start = perf_swevent_start,
7515 .stop = perf_swevent_stop,
7516 .read = perf_swevent_read,
7519 static inline void perf_tp_register(void)
7521 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7524 static void perf_event_free_filter(struct perf_event *event)
7526 ftrace_profile_free_filter(event);
7529 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7531 bool is_kprobe, is_tracepoint;
7532 struct bpf_prog *prog;
7534 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7537 if (event->tp_event->prog)
7540 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
7541 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
7542 if (!is_kprobe && !is_tracepoint)
7543 /* bpf programs can only be attached to u/kprobe or tracepoint */
7546 prog = bpf_prog_get(prog_fd);
7548 return PTR_ERR(prog);
7550 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
7551 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
7552 /* valid fd, but invalid bpf program type */
7557 if (is_tracepoint) {
7558 int off = trace_event_get_offsets(event->tp_event);
7560 if (prog->aux->max_ctx_offset > off) {
7565 event->tp_event->prog = prog;
7570 static void perf_event_free_bpf_prog(struct perf_event *event)
7572 struct bpf_prog *prog;
7574 if (!event->tp_event)
7577 prog = event->tp_event->prog;
7579 event->tp_event->prog = NULL;
7586 static inline void perf_tp_register(void)
7590 static void perf_event_free_filter(struct perf_event *event)
7594 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7599 static void perf_event_free_bpf_prog(struct perf_event *event)
7602 #endif /* CONFIG_EVENT_TRACING */
7604 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7605 void perf_bp_event(struct perf_event *bp, void *data)
7607 struct perf_sample_data sample;
7608 struct pt_regs *regs = data;
7610 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7612 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7613 perf_swevent_event(bp, 1, &sample, regs);
7618 * Allocate a new address filter
7620 static struct perf_addr_filter *
7621 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
7623 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
7624 struct perf_addr_filter *filter;
7626 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
7630 INIT_LIST_HEAD(&filter->entry);
7631 list_add_tail(&filter->entry, filters);
7636 static void free_filters_list(struct list_head *filters)
7638 struct perf_addr_filter *filter, *iter;
7640 list_for_each_entry_safe(filter, iter, filters, entry) {
7642 iput(filter->inode);
7643 list_del(&filter->entry);
7649 * Free existing address filters and optionally install new ones
7651 static void perf_addr_filters_splice(struct perf_event *event,
7652 struct list_head *head)
7654 unsigned long flags;
7657 if (!has_addr_filter(event))
7660 /* don't bother with children, they don't have their own filters */
7664 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
7666 list_splice_init(&event->addr_filters.list, &list);
7668 list_splice(head, &event->addr_filters.list);
7670 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
7672 free_filters_list(&list);
7676 * Scan through mm's vmas and see if one of them matches the
7677 * @filter; if so, adjust filter's address range.
7678 * Called with mm::mmap_sem down for reading.
7680 static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
7681 struct mm_struct *mm)
7683 struct vm_area_struct *vma;
7685 for (vma = mm->mmap; vma; vma = vma->vm_next) {
7686 struct file *file = vma->vm_file;
7687 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
7688 unsigned long vma_size = vma->vm_end - vma->vm_start;
7693 if (!perf_addr_filter_match(filter, file, off, vma_size))
7696 return vma->vm_start;
7703 * Update event's address range filters based on the
7704 * task's existing mappings, if any.
7706 static void perf_event_addr_filters_apply(struct perf_event *event)
7708 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7709 struct task_struct *task = READ_ONCE(event->ctx->task);
7710 struct perf_addr_filter *filter;
7711 struct mm_struct *mm = NULL;
7712 unsigned int count = 0;
7713 unsigned long flags;
7716 * We may observe TASK_TOMBSTONE, which means that the event tear-down
7717 * will stop on the parent's child_mutex that our caller is also holding
7719 if (task == TASK_TOMBSTONE)
7722 mm = get_task_mm(event->ctx->task);
7726 down_read(&mm->mmap_sem);
7728 raw_spin_lock_irqsave(&ifh->lock, flags);
7729 list_for_each_entry(filter, &ifh->list, entry) {
7730 event->addr_filters_offs[count] = 0;
7732 if (perf_addr_filter_needs_mmap(filter))
7733 event->addr_filters_offs[count] =
7734 perf_addr_filter_apply(filter, mm);
7739 event->addr_filters_gen++;
7740 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7742 up_read(&mm->mmap_sem);
7747 perf_event_restart(event);
7751 * Address range filtering: limiting the data to certain
7752 * instruction address ranges. Filters are ioctl()ed to us from
7753 * userspace as ascii strings.
7755 * Filter string format:
7758 * where ACTION is one of the
7759 * * "filter": limit the trace to this region
7760 * * "start": start tracing from this address
7761 * * "stop": stop tracing at this address/region;
7763 * * for kernel addresses: <start address>[/<size>]
7764 * * for object files: <start address>[/<size>]@</path/to/object/file>
7766 * if <size> is not specified, the range is treated as a single address.
7779 IF_STATE_ACTION = 0,
7784 static const match_table_t if_tokens = {
7785 { IF_ACT_FILTER, "filter" },
7786 { IF_ACT_START, "start" },
7787 { IF_ACT_STOP, "stop" },
7788 { IF_SRC_FILE, "%u/%u@%s" },
7789 { IF_SRC_KERNEL, "%u/%u" },
7790 { IF_SRC_FILEADDR, "%u@%s" },
7791 { IF_SRC_KERNELADDR, "%u" },
7795 * Address filter string parser
7798 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
7799 struct list_head *filters)
7801 struct perf_addr_filter *filter = NULL;
7802 char *start, *orig, *filename = NULL;
7804 substring_t args[MAX_OPT_ARGS];
7805 int state = IF_STATE_ACTION, token;
7806 unsigned int kernel = 0;
7809 orig = fstr = kstrdup(fstr, GFP_KERNEL);
7813 while ((start = strsep(&fstr, " ,\n")) != NULL) {
7819 /* filter definition begins */
7820 if (state == IF_STATE_ACTION) {
7821 filter = perf_addr_filter_new(event, filters);
7826 token = match_token(start, if_tokens, args);
7833 if (state != IF_STATE_ACTION)
7836 state = IF_STATE_SOURCE;
7839 case IF_SRC_KERNELADDR:
7843 case IF_SRC_FILEADDR:
7845 if (state != IF_STATE_SOURCE)
7848 if (token == IF_SRC_FILE || token == IF_SRC_KERNEL)
7852 ret = kstrtoul(args[0].from, 0, &filter->offset);
7856 if (filter->range) {
7858 ret = kstrtoul(args[1].from, 0, &filter->size);
7863 if (token == IF_SRC_FILE) {
7864 filename = match_strdup(&args[2]);
7871 state = IF_STATE_END;
7879 * Filter definition is fully parsed, validate and install it.
7880 * Make sure that it doesn't contradict itself or the event's
7883 if (state == IF_STATE_END) {
7884 if (kernel && event->attr.exclude_kernel)
7891 /* look up the path and grab its inode */
7892 ret = kern_path(filename, LOOKUP_FOLLOW, &path);
7894 goto fail_free_name;
7896 filter->inode = igrab(d_inode(path.dentry));
7902 if (!filter->inode ||
7903 !S_ISREG(filter->inode->i_mode))
7904 /* free_filters_list() will iput() */
7908 /* ready to consume more filters */
7909 state = IF_STATE_ACTION;
7914 if (state != IF_STATE_ACTION)
7924 free_filters_list(filters);
7931 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
7937 * Since this is called in perf_ioctl() path, we're already holding
7940 lockdep_assert_held(&event->ctx->mutex);
7942 if (WARN_ON_ONCE(event->parent))
7946 * For now, we only support filtering in per-task events; doing so
7947 * for CPU-wide events requires additional context switching trickery,
7948 * since same object code will be mapped at different virtual
7949 * addresses in different processes.
7951 if (!event->ctx->task)
7954 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
7958 ret = event->pmu->addr_filters_validate(&filters);
7960 free_filters_list(&filters);
7964 /* remove existing filters, if any */
7965 perf_addr_filters_splice(event, &filters);
7967 /* install new filters */
7968 perf_event_for_each_child(event, perf_event_addr_filters_apply);
7973 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7978 if ((event->attr.type != PERF_TYPE_TRACEPOINT ||
7979 !IS_ENABLED(CONFIG_EVENT_TRACING)) &&
7980 !has_addr_filter(event))
7983 filter_str = strndup_user(arg, PAGE_SIZE);
7984 if (IS_ERR(filter_str))
7985 return PTR_ERR(filter_str);
7987 if (IS_ENABLED(CONFIG_EVENT_TRACING) &&
7988 event->attr.type == PERF_TYPE_TRACEPOINT)
7989 ret = ftrace_profile_set_filter(event, event->attr.config,
7991 else if (has_addr_filter(event))
7992 ret = perf_event_set_addr_filter(event, filter_str);
7999 * hrtimer based swevent callback
8002 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
8004 enum hrtimer_restart ret = HRTIMER_RESTART;
8005 struct perf_sample_data data;
8006 struct pt_regs *regs;
8007 struct perf_event *event;
8010 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
8012 if (event->state != PERF_EVENT_STATE_ACTIVE)
8013 return HRTIMER_NORESTART;
8015 event->pmu->read(event);
8017 perf_sample_data_init(&data, 0, event->hw.last_period);
8018 regs = get_irq_regs();
8020 if (regs && !perf_exclude_event(event, regs)) {
8021 if (!(event->attr.exclude_idle && is_idle_task(current)))
8022 if (__perf_event_overflow(event, 1, &data, regs))
8023 ret = HRTIMER_NORESTART;
8026 period = max_t(u64, 10000, event->hw.sample_period);
8027 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
8032 static void perf_swevent_start_hrtimer(struct perf_event *event)
8034 struct hw_perf_event *hwc = &event->hw;
8037 if (!is_sampling_event(event))
8040 period = local64_read(&hwc->period_left);
8045 local64_set(&hwc->period_left, 0);
8047 period = max_t(u64, 10000, hwc->sample_period);
8049 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
8050 HRTIMER_MODE_REL_PINNED);
8053 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
8055 struct hw_perf_event *hwc = &event->hw;
8057 if (is_sampling_event(event)) {
8058 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
8059 local64_set(&hwc->period_left, ktime_to_ns(remaining));
8061 hrtimer_cancel(&hwc->hrtimer);
8065 static void perf_swevent_init_hrtimer(struct perf_event *event)
8067 struct hw_perf_event *hwc = &event->hw;
8069 if (!is_sampling_event(event))
8072 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
8073 hwc->hrtimer.function = perf_swevent_hrtimer;
8076 * Since hrtimers have a fixed rate, we can do a static freq->period
8077 * mapping and avoid the whole period adjust feedback stuff.
8079 if (event->attr.freq) {
8080 long freq = event->attr.sample_freq;
8082 event->attr.sample_period = NSEC_PER_SEC / freq;
8083 hwc->sample_period = event->attr.sample_period;
8084 local64_set(&hwc->period_left, hwc->sample_period);
8085 hwc->last_period = hwc->sample_period;
8086 event->attr.freq = 0;
8091 * Software event: cpu wall time clock
8094 static void cpu_clock_event_update(struct perf_event *event)
8099 now = local_clock();
8100 prev = local64_xchg(&event->hw.prev_count, now);
8101 local64_add(now - prev, &event->count);
8104 static void cpu_clock_event_start(struct perf_event *event, int flags)
8106 local64_set(&event->hw.prev_count, local_clock());
8107 perf_swevent_start_hrtimer(event);
8110 static void cpu_clock_event_stop(struct perf_event *event, int flags)
8112 perf_swevent_cancel_hrtimer(event);
8113 cpu_clock_event_update(event);
8116 static int cpu_clock_event_add(struct perf_event *event, int flags)
8118 if (flags & PERF_EF_START)
8119 cpu_clock_event_start(event, flags);
8120 perf_event_update_userpage(event);
8125 static void cpu_clock_event_del(struct perf_event *event, int flags)
8127 cpu_clock_event_stop(event, flags);
8130 static void cpu_clock_event_read(struct perf_event *event)
8132 cpu_clock_event_update(event);
8135 static int cpu_clock_event_init(struct perf_event *event)
8137 if (event->attr.type != PERF_TYPE_SOFTWARE)
8140 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
8144 * no branch sampling for software events
8146 if (has_branch_stack(event))
8149 perf_swevent_init_hrtimer(event);
8154 static struct pmu perf_cpu_clock = {
8155 .task_ctx_nr = perf_sw_context,
8157 .capabilities = PERF_PMU_CAP_NO_NMI,
8159 .event_init = cpu_clock_event_init,
8160 .add = cpu_clock_event_add,
8161 .del = cpu_clock_event_del,
8162 .start = cpu_clock_event_start,
8163 .stop = cpu_clock_event_stop,
8164 .read = cpu_clock_event_read,
8168 * Software event: task time clock
8171 static void task_clock_event_update(struct perf_event *event, u64 now)
8176 prev = local64_xchg(&event->hw.prev_count, now);
8178 local64_add(delta, &event->count);
8181 static void task_clock_event_start(struct perf_event *event, int flags)
8183 local64_set(&event->hw.prev_count, event->ctx->time);
8184 perf_swevent_start_hrtimer(event);
8187 static void task_clock_event_stop(struct perf_event *event, int flags)
8189 perf_swevent_cancel_hrtimer(event);
8190 task_clock_event_update(event, event->ctx->time);
8193 static int task_clock_event_add(struct perf_event *event, int flags)
8195 if (flags & PERF_EF_START)
8196 task_clock_event_start(event, flags);
8197 perf_event_update_userpage(event);
8202 static void task_clock_event_del(struct perf_event *event, int flags)
8204 task_clock_event_stop(event, PERF_EF_UPDATE);
8207 static void task_clock_event_read(struct perf_event *event)
8209 u64 now = perf_clock();
8210 u64 delta = now - event->ctx->timestamp;
8211 u64 time = event->ctx->time + delta;
8213 task_clock_event_update(event, time);
8216 static int task_clock_event_init(struct perf_event *event)
8218 if (event->attr.type != PERF_TYPE_SOFTWARE)
8221 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
8225 * no branch sampling for software events
8227 if (has_branch_stack(event))
8230 perf_swevent_init_hrtimer(event);
8235 static struct pmu perf_task_clock = {
8236 .task_ctx_nr = perf_sw_context,
8238 .capabilities = PERF_PMU_CAP_NO_NMI,
8240 .event_init = task_clock_event_init,
8241 .add = task_clock_event_add,
8242 .del = task_clock_event_del,
8243 .start = task_clock_event_start,
8244 .stop = task_clock_event_stop,
8245 .read = task_clock_event_read,
8248 static void perf_pmu_nop_void(struct pmu *pmu)
8252 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
8256 static int perf_pmu_nop_int(struct pmu *pmu)
8261 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
8263 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
8265 __this_cpu_write(nop_txn_flags, flags);
8267 if (flags & ~PERF_PMU_TXN_ADD)
8270 perf_pmu_disable(pmu);
8273 static int perf_pmu_commit_txn(struct pmu *pmu)
8275 unsigned int flags = __this_cpu_read(nop_txn_flags);
8277 __this_cpu_write(nop_txn_flags, 0);
8279 if (flags & ~PERF_PMU_TXN_ADD)
8282 perf_pmu_enable(pmu);
8286 static void perf_pmu_cancel_txn(struct pmu *pmu)
8288 unsigned int flags = __this_cpu_read(nop_txn_flags);
8290 __this_cpu_write(nop_txn_flags, 0);
8292 if (flags & ~PERF_PMU_TXN_ADD)
8295 perf_pmu_enable(pmu);
8298 static int perf_event_idx_default(struct perf_event *event)
8304 * Ensures all contexts with the same task_ctx_nr have the same
8305 * pmu_cpu_context too.
8307 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
8314 list_for_each_entry(pmu, &pmus, entry) {
8315 if (pmu->task_ctx_nr == ctxn)
8316 return pmu->pmu_cpu_context;
8322 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
8326 for_each_possible_cpu(cpu) {
8327 struct perf_cpu_context *cpuctx;
8329 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8331 if (cpuctx->unique_pmu == old_pmu)
8332 cpuctx->unique_pmu = pmu;
8336 static void free_pmu_context(struct pmu *pmu)
8340 mutex_lock(&pmus_lock);
8342 * Like a real lame refcount.
8344 list_for_each_entry(i, &pmus, entry) {
8345 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
8346 update_pmu_context(i, pmu);
8351 free_percpu(pmu->pmu_cpu_context);
8353 mutex_unlock(&pmus_lock);
8357 * Let userspace know that this PMU supports address range filtering:
8359 static ssize_t nr_addr_filters_show(struct device *dev,
8360 struct device_attribute *attr,
8363 struct pmu *pmu = dev_get_drvdata(dev);
8365 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
8367 DEVICE_ATTR_RO(nr_addr_filters);
8369 static struct idr pmu_idr;
8372 type_show(struct device *dev, struct device_attribute *attr, char *page)
8374 struct pmu *pmu = dev_get_drvdata(dev);
8376 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
8378 static DEVICE_ATTR_RO(type);
8381 perf_event_mux_interval_ms_show(struct device *dev,
8382 struct device_attribute *attr,
8385 struct pmu *pmu = dev_get_drvdata(dev);
8387 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
8390 static DEFINE_MUTEX(mux_interval_mutex);
8393 perf_event_mux_interval_ms_store(struct device *dev,
8394 struct device_attribute *attr,
8395 const char *buf, size_t count)
8397 struct pmu *pmu = dev_get_drvdata(dev);
8398 int timer, cpu, ret;
8400 ret = kstrtoint(buf, 0, &timer);
8407 /* same value, noting to do */
8408 if (timer == pmu->hrtimer_interval_ms)
8411 mutex_lock(&mux_interval_mutex);
8412 pmu->hrtimer_interval_ms = timer;
8414 /* update all cpuctx for this PMU */
8416 for_each_online_cpu(cpu) {
8417 struct perf_cpu_context *cpuctx;
8418 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8419 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
8421 cpu_function_call(cpu,
8422 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
8425 mutex_unlock(&mux_interval_mutex);
8429 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
8431 static struct attribute *pmu_dev_attrs[] = {
8432 &dev_attr_type.attr,
8433 &dev_attr_perf_event_mux_interval_ms.attr,
8436 ATTRIBUTE_GROUPS(pmu_dev);
8438 static int pmu_bus_running;
8439 static struct bus_type pmu_bus = {
8440 .name = "event_source",
8441 .dev_groups = pmu_dev_groups,
8444 static void pmu_dev_release(struct device *dev)
8449 static int pmu_dev_alloc(struct pmu *pmu)
8453 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
8457 pmu->dev->groups = pmu->attr_groups;
8458 device_initialize(pmu->dev);
8459 ret = dev_set_name(pmu->dev, "%s", pmu->name);
8463 dev_set_drvdata(pmu->dev, pmu);
8464 pmu->dev->bus = &pmu_bus;
8465 pmu->dev->release = pmu_dev_release;
8466 ret = device_add(pmu->dev);
8470 /* For PMUs with address filters, throw in an extra attribute: */
8471 if (pmu->nr_addr_filters)
8472 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
8481 device_del(pmu->dev);
8484 put_device(pmu->dev);
8488 static struct lock_class_key cpuctx_mutex;
8489 static struct lock_class_key cpuctx_lock;
8491 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
8495 mutex_lock(&pmus_lock);
8497 pmu->pmu_disable_count = alloc_percpu(int);
8498 if (!pmu->pmu_disable_count)
8507 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
8515 if (pmu_bus_running) {
8516 ret = pmu_dev_alloc(pmu);
8522 if (pmu->task_ctx_nr == perf_hw_context) {
8523 static int hw_context_taken = 0;
8526 * Other than systems with heterogeneous CPUs, it never makes
8527 * sense for two PMUs to share perf_hw_context. PMUs which are
8528 * uncore must use perf_invalid_context.
8530 if (WARN_ON_ONCE(hw_context_taken &&
8531 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
8532 pmu->task_ctx_nr = perf_invalid_context;
8534 hw_context_taken = 1;
8537 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
8538 if (pmu->pmu_cpu_context)
8539 goto got_cpu_context;
8542 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
8543 if (!pmu->pmu_cpu_context)
8546 for_each_possible_cpu(cpu) {
8547 struct perf_cpu_context *cpuctx;
8549 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8550 __perf_event_init_context(&cpuctx->ctx);
8551 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
8552 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
8553 cpuctx->ctx.pmu = pmu;
8555 __perf_mux_hrtimer_init(cpuctx, cpu);
8557 cpuctx->unique_pmu = pmu;
8561 if (!pmu->start_txn) {
8562 if (pmu->pmu_enable) {
8564 * If we have pmu_enable/pmu_disable calls, install
8565 * transaction stubs that use that to try and batch
8566 * hardware accesses.
8568 pmu->start_txn = perf_pmu_start_txn;
8569 pmu->commit_txn = perf_pmu_commit_txn;
8570 pmu->cancel_txn = perf_pmu_cancel_txn;
8572 pmu->start_txn = perf_pmu_nop_txn;
8573 pmu->commit_txn = perf_pmu_nop_int;
8574 pmu->cancel_txn = perf_pmu_nop_void;
8578 if (!pmu->pmu_enable) {
8579 pmu->pmu_enable = perf_pmu_nop_void;
8580 pmu->pmu_disable = perf_pmu_nop_void;
8583 if (!pmu->event_idx)
8584 pmu->event_idx = perf_event_idx_default;
8586 list_add_rcu(&pmu->entry, &pmus);
8587 atomic_set(&pmu->exclusive_cnt, 0);
8590 mutex_unlock(&pmus_lock);
8595 device_del(pmu->dev);
8596 put_device(pmu->dev);
8599 if (pmu->type >= PERF_TYPE_MAX)
8600 idr_remove(&pmu_idr, pmu->type);
8603 free_percpu(pmu->pmu_disable_count);
8606 EXPORT_SYMBOL_GPL(perf_pmu_register);
8608 void perf_pmu_unregister(struct pmu *pmu)
8610 mutex_lock(&pmus_lock);
8611 list_del_rcu(&pmu->entry);
8612 mutex_unlock(&pmus_lock);
8615 * We dereference the pmu list under both SRCU and regular RCU, so
8616 * synchronize against both of those.
8618 synchronize_srcu(&pmus_srcu);
8621 free_percpu(pmu->pmu_disable_count);
8622 if (pmu->type >= PERF_TYPE_MAX)
8623 idr_remove(&pmu_idr, pmu->type);
8624 if (pmu->nr_addr_filters)
8625 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
8626 device_del(pmu->dev);
8627 put_device(pmu->dev);
8628 free_pmu_context(pmu);
8630 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
8632 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
8634 struct perf_event_context *ctx = NULL;
8637 if (!try_module_get(pmu->module))
8640 if (event->group_leader != event) {
8642 * This ctx->mutex can nest when we're called through
8643 * inheritance. See the perf_event_ctx_lock_nested() comment.
8645 ctx = perf_event_ctx_lock_nested(event->group_leader,
8646 SINGLE_DEPTH_NESTING);
8651 ret = pmu->event_init(event);
8654 perf_event_ctx_unlock(event->group_leader, ctx);
8657 module_put(pmu->module);
8662 static struct pmu *perf_init_event(struct perf_event *event)
8664 struct pmu *pmu = NULL;
8668 idx = srcu_read_lock(&pmus_srcu);
8671 pmu = idr_find(&pmu_idr, event->attr.type);
8674 ret = perf_try_init_event(pmu, event);
8680 list_for_each_entry_rcu(pmu, &pmus, entry) {
8681 ret = perf_try_init_event(pmu, event);
8685 if (ret != -ENOENT) {
8690 pmu = ERR_PTR(-ENOENT);
8692 srcu_read_unlock(&pmus_srcu, idx);
8697 static void attach_sb_event(struct perf_event *event)
8699 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
8701 raw_spin_lock(&pel->lock);
8702 list_add_rcu(&event->sb_list, &pel->list);
8703 raw_spin_unlock(&pel->lock);
8707 * We keep a list of all !task (and therefore per-cpu) events
8708 * that need to receive side-band records.
8710 * This avoids having to scan all the various PMU per-cpu contexts
8713 static void account_pmu_sb_event(struct perf_event *event)
8715 if (is_sb_event(event))
8716 attach_sb_event(event);
8719 static void account_event_cpu(struct perf_event *event, int cpu)
8724 if (is_cgroup_event(event))
8725 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
8728 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
8729 static void account_freq_event_nohz(void)
8731 #ifdef CONFIG_NO_HZ_FULL
8732 /* Lock so we don't race with concurrent unaccount */
8733 spin_lock(&nr_freq_lock);
8734 if (atomic_inc_return(&nr_freq_events) == 1)
8735 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
8736 spin_unlock(&nr_freq_lock);
8740 static void account_freq_event(void)
8742 if (tick_nohz_full_enabled())
8743 account_freq_event_nohz();
8745 atomic_inc(&nr_freq_events);
8749 static void account_event(struct perf_event *event)
8756 if (event->attach_state & PERF_ATTACH_TASK)
8758 if (event->attr.mmap || event->attr.mmap_data)
8759 atomic_inc(&nr_mmap_events);
8760 if (event->attr.comm)
8761 atomic_inc(&nr_comm_events);
8762 if (event->attr.task)
8763 atomic_inc(&nr_task_events);
8764 if (event->attr.freq)
8765 account_freq_event();
8766 if (event->attr.context_switch) {
8767 atomic_inc(&nr_switch_events);
8770 if (has_branch_stack(event))
8772 if (is_cgroup_event(event))
8776 if (atomic_inc_not_zero(&perf_sched_count))
8779 mutex_lock(&perf_sched_mutex);
8780 if (!atomic_read(&perf_sched_count)) {
8781 static_branch_enable(&perf_sched_events);
8783 * Guarantee that all CPUs observe they key change and
8784 * call the perf scheduling hooks before proceeding to
8785 * install events that need them.
8787 synchronize_sched();
8790 * Now that we have waited for the sync_sched(), allow further
8791 * increments to by-pass the mutex.
8793 atomic_inc(&perf_sched_count);
8794 mutex_unlock(&perf_sched_mutex);
8798 account_event_cpu(event, event->cpu);
8800 account_pmu_sb_event(event);
8804 * Allocate and initialize a event structure
8806 static struct perf_event *
8807 perf_event_alloc(struct perf_event_attr *attr, int cpu,
8808 struct task_struct *task,
8809 struct perf_event *group_leader,
8810 struct perf_event *parent_event,
8811 perf_overflow_handler_t overflow_handler,
8812 void *context, int cgroup_fd)
8815 struct perf_event *event;
8816 struct hw_perf_event *hwc;
8819 if ((unsigned)cpu >= nr_cpu_ids) {
8820 if (!task || cpu != -1)
8821 return ERR_PTR(-EINVAL);
8824 event = kzalloc(sizeof(*event), GFP_KERNEL);
8826 return ERR_PTR(-ENOMEM);
8829 * Single events are their own group leaders, with an
8830 * empty sibling list:
8833 group_leader = event;
8835 mutex_init(&event->child_mutex);
8836 INIT_LIST_HEAD(&event->child_list);
8838 INIT_LIST_HEAD(&event->group_entry);
8839 INIT_LIST_HEAD(&event->event_entry);
8840 INIT_LIST_HEAD(&event->sibling_list);
8841 INIT_LIST_HEAD(&event->rb_entry);
8842 INIT_LIST_HEAD(&event->active_entry);
8843 INIT_LIST_HEAD(&event->addr_filters.list);
8844 INIT_HLIST_NODE(&event->hlist_entry);
8847 init_waitqueue_head(&event->waitq);
8848 init_irq_work(&event->pending, perf_pending_event);
8850 mutex_init(&event->mmap_mutex);
8851 raw_spin_lock_init(&event->addr_filters.lock);
8853 atomic_long_set(&event->refcount, 1);
8855 event->attr = *attr;
8856 event->group_leader = group_leader;
8860 event->parent = parent_event;
8862 event->ns = get_pid_ns(task_active_pid_ns(current));
8863 event->id = atomic64_inc_return(&perf_event_id);
8865 event->state = PERF_EVENT_STATE_INACTIVE;
8868 event->attach_state = PERF_ATTACH_TASK;
8870 * XXX pmu::event_init needs to know what task to account to
8871 * and we cannot use the ctx information because we need the
8872 * pmu before we get a ctx.
8874 event->hw.target = task;
8877 event->clock = &local_clock;
8879 event->clock = parent_event->clock;
8881 if (!overflow_handler && parent_event) {
8882 overflow_handler = parent_event->overflow_handler;
8883 context = parent_event->overflow_handler_context;
8886 if (overflow_handler) {
8887 event->overflow_handler = overflow_handler;
8888 event->overflow_handler_context = context;
8889 } else if (is_write_backward(event)){
8890 event->overflow_handler = perf_event_output_backward;
8891 event->overflow_handler_context = NULL;
8893 event->overflow_handler = perf_event_output_forward;
8894 event->overflow_handler_context = NULL;
8897 perf_event__state_init(event);
8902 hwc->sample_period = attr->sample_period;
8903 if (attr->freq && attr->sample_freq)
8904 hwc->sample_period = 1;
8905 hwc->last_period = hwc->sample_period;
8907 local64_set(&hwc->period_left, hwc->sample_period);
8910 * we currently do not support PERF_FORMAT_GROUP on inherited events
8912 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
8915 if (!has_branch_stack(event))
8916 event->attr.branch_sample_type = 0;
8918 if (cgroup_fd != -1) {
8919 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8924 pmu = perf_init_event(event);
8927 else if (IS_ERR(pmu)) {
8932 err = exclusive_event_init(event);
8936 if (has_addr_filter(event)) {
8937 event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
8938 sizeof(unsigned long),
8940 if (!event->addr_filters_offs)
8943 /* force hw sync on the address filters */
8944 event->addr_filters_gen = 1;
8947 if (!event->parent) {
8948 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8949 err = get_callchain_buffers(attr->sample_max_stack);
8951 goto err_addr_filters;
8955 /* symmetric to unaccount_event() in _free_event() */
8956 account_event(event);
8961 kfree(event->addr_filters_offs);
8964 exclusive_event_destroy(event);
8968 event->destroy(event);
8969 module_put(pmu->module);
8971 if (is_cgroup_event(event))
8972 perf_detach_cgroup(event);
8974 put_pid_ns(event->ns);
8977 return ERR_PTR(err);
8980 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8981 struct perf_event_attr *attr)
8986 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8990 * zero the full structure, so that a short copy will be nice.
8992 memset(attr, 0, sizeof(*attr));
8994 ret = get_user(size, &uattr->size);
8998 if (size > PAGE_SIZE) /* silly large */
9001 if (!size) /* abi compat */
9002 size = PERF_ATTR_SIZE_VER0;
9004 if (size < PERF_ATTR_SIZE_VER0)
9008 * If we're handed a bigger struct than we know of,
9009 * ensure all the unknown bits are 0 - i.e. new
9010 * user-space does not rely on any kernel feature
9011 * extensions we dont know about yet.
9013 if (size > sizeof(*attr)) {
9014 unsigned char __user *addr;
9015 unsigned char __user *end;
9018 addr = (void __user *)uattr + sizeof(*attr);
9019 end = (void __user *)uattr + size;
9021 for (; addr < end; addr++) {
9022 ret = get_user(val, addr);
9028 size = sizeof(*attr);
9031 ret = copy_from_user(attr, uattr, size);
9035 if (attr->__reserved_1)
9038 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
9041 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
9044 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
9045 u64 mask = attr->branch_sample_type;
9047 /* only using defined bits */
9048 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
9051 /* at least one branch bit must be set */
9052 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
9055 /* propagate priv level, when not set for branch */
9056 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
9058 /* exclude_kernel checked on syscall entry */
9059 if (!attr->exclude_kernel)
9060 mask |= PERF_SAMPLE_BRANCH_KERNEL;
9062 if (!attr->exclude_user)
9063 mask |= PERF_SAMPLE_BRANCH_USER;
9065 if (!attr->exclude_hv)
9066 mask |= PERF_SAMPLE_BRANCH_HV;
9068 * adjust user setting (for HW filter setup)
9070 attr->branch_sample_type = mask;
9072 /* privileged levels capture (kernel, hv): check permissions */
9073 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
9074 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9078 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
9079 ret = perf_reg_validate(attr->sample_regs_user);
9084 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
9085 if (!arch_perf_have_user_stack_dump())
9089 * We have __u32 type for the size, but so far
9090 * we can only use __u16 as maximum due to the
9091 * __u16 sample size limit.
9093 if (attr->sample_stack_user >= USHRT_MAX)
9095 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
9099 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
9100 ret = perf_reg_validate(attr->sample_regs_intr);
9105 put_user(sizeof(*attr), &uattr->size);
9111 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
9113 struct ring_buffer *rb = NULL;
9119 /* don't allow circular references */
9120 if (event == output_event)
9124 * Don't allow cross-cpu buffers
9126 if (output_event->cpu != event->cpu)
9130 * If its not a per-cpu rb, it must be the same task.
9132 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
9136 * Mixing clocks in the same buffer is trouble you don't need.
9138 if (output_event->clock != event->clock)
9142 * Either writing ring buffer from beginning or from end.
9143 * Mixing is not allowed.
9145 if (is_write_backward(output_event) != is_write_backward(event))
9149 * If both events generate aux data, they must be on the same PMU
9151 if (has_aux(event) && has_aux(output_event) &&
9152 event->pmu != output_event->pmu)
9156 mutex_lock(&event->mmap_mutex);
9157 /* Can't redirect output if we've got an active mmap() */
9158 if (atomic_read(&event->mmap_count))
9162 /* get the rb we want to redirect to */
9163 rb = ring_buffer_get(output_event);
9168 ring_buffer_attach(event, rb);
9172 mutex_unlock(&event->mmap_mutex);
9178 static void mutex_lock_double(struct mutex *a, struct mutex *b)
9184 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
9187 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
9189 bool nmi_safe = false;
9192 case CLOCK_MONOTONIC:
9193 event->clock = &ktime_get_mono_fast_ns;
9197 case CLOCK_MONOTONIC_RAW:
9198 event->clock = &ktime_get_raw_fast_ns;
9202 case CLOCK_REALTIME:
9203 event->clock = &ktime_get_real_ns;
9206 case CLOCK_BOOTTIME:
9207 event->clock = &ktime_get_boot_ns;
9211 event->clock = &ktime_get_tai_ns;
9218 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
9225 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9227 * @attr_uptr: event_id type attributes for monitoring/sampling
9230 * @group_fd: group leader event fd
9232 SYSCALL_DEFINE5(perf_event_open,
9233 struct perf_event_attr __user *, attr_uptr,
9234 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
9236 struct perf_event *group_leader = NULL, *output_event = NULL;
9237 struct perf_event *event, *sibling;
9238 struct perf_event_attr attr;
9239 struct perf_event_context *ctx, *uninitialized_var(gctx);
9240 struct file *event_file = NULL;
9241 struct fd group = {NULL, 0};
9242 struct task_struct *task = NULL;
9247 int f_flags = O_RDWR;
9250 /* for future expandability... */
9251 if (flags & ~PERF_FLAG_ALL)
9254 err = perf_copy_attr(attr_uptr, &attr);
9258 if (!attr.exclude_kernel) {
9259 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9264 if (attr.sample_freq > sysctl_perf_event_sample_rate)
9267 if (attr.sample_period & (1ULL << 63))
9271 if (!attr.sample_max_stack)
9272 attr.sample_max_stack = sysctl_perf_event_max_stack;
9275 * In cgroup mode, the pid argument is used to pass the fd
9276 * opened to the cgroup directory in cgroupfs. The cpu argument
9277 * designates the cpu on which to monitor threads from that
9280 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
9283 if (flags & PERF_FLAG_FD_CLOEXEC)
9284 f_flags |= O_CLOEXEC;
9286 event_fd = get_unused_fd_flags(f_flags);
9290 if (group_fd != -1) {
9291 err = perf_fget_light(group_fd, &group);
9294 group_leader = group.file->private_data;
9295 if (flags & PERF_FLAG_FD_OUTPUT)
9296 output_event = group_leader;
9297 if (flags & PERF_FLAG_FD_NO_GROUP)
9298 group_leader = NULL;
9301 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
9302 task = find_lively_task_by_vpid(pid);
9304 err = PTR_ERR(task);
9309 if (task && group_leader &&
9310 group_leader->attr.inherit != attr.inherit) {
9318 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
9323 * Reuse ptrace permission checks for now.
9325 * We must hold cred_guard_mutex across this and any potential
9326 * perf_install_in_context() call for this new event to
9327 * serialize against exec() altering our credentials (and the
9328 * perf_event_exit_task() that could imply).
9331 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
9335 if (flags & PERF_FLAG_PID_CGROUP)
9338 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
9339 NULL, NULL, cgroup_fd);
9340 if (IS_ERR(event)) {
9341 err = PTR_ERR(event);
9345 if (is_sampling_event(event)) {
9346 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
9353 * Special case software events and allow them to be part of
9354 * any hardware group.
9358 if (attr.use_clockid) {
9359 err = perf_event_set_clock(event, attr.clockid);
9365 (is_software_event(event) != is_software_event(group_leader))) {
9366 if (is_software_event(event)) {
9368 * If event and group_leader are not both a software
9369 * event, and event is, then group leader is not.
9371 * Allow the addition of software events to !software
9372 * groups, this is safe because software events never
9375 pmu = group_leader->pmu;
9376 } else if (is_software_event(group_leader) &&
9377 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
9379 * In case the group is a pure software group, and we
9380 * try to add a hardware event, move the whole group to
9381 * the hardware context.
9388 * Get the target context (task or percpu):
9390 ctx = find_get_context(pmu, task, event);
9396 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
9402 * Look up the group leader (we will attach this event to it):
9408 * Do not allow a recursive hierarchy (this new sibling
9409 * becoming part of another group-sibling):
9411 if (group_leader->group_leader != group_leader)
9414 /* All events in a group should have the same clock */
9415 if (group_leader->clock != event->clock)
9419 * Do not allow to attach to a group in a different
9420 * task or CPU context:
9424 * Make sure we're both on the same task, or both
9427 if (group_leader->ctx->task != ctx->task)
9431 * Make sure we're both events for the same CPU;
9432 * grouping events for different CPUs is broken; since
9433 * you can never concurrently schedule them anyhow.
9435 if (group_leader->cpu != event->cpu)
9438 if (group_leader->ctx != ctx)
9443 * Only a group leader can be exclusive or pinned
9445 if (attr.exclusive || attr.pinned)
9450 err = perf_event_set_output(event, output_event);
9455 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
9457 if (IS_ERR(event_file)) {
9458 err = PTR_ERR(event_file);
9464 gctx = group_leader->ctx;
9465 mutex_lock_double(&gctx->mutex, &ctx->mutex);
9466 if (gctx->task == TASK_TOMBSTONE) {
9471 mutex_lock(&ctx->mutex);
9474 if (ctx->task == TASK_TOMBSTONE) {
9479 if (!perf_event_validate_size(event)) {
9485 * Must be under the same ctx::mutex as perf_install_in_context(),
9486 * because we need to serialize with concurrent event creation.
9488 if (!exclusive_event_installable(event, ctx)) {
9489 /* exclusive and group stuff are assumed mutually exclusive */
9490 WARN_ON_ONCE(move_group);
9496 WARN_ON_ONCE(ctx->parent_ctx);
9499 * This is the point on no return; we cannot fail hereafter. This is
9500 * where we start modifying current state.
9505 * See perf_event_ctx_lock() for comments on the details
9506 * of swizzling perf_event::ctx.
9508 perf_remove_from_context(group_leader, 0);
9510 list_for_each_entry(sibling, &group_leader->sibling_list,
9512 perf_remove_from_context(sibling, 0);
9517 * Wait for everybody to stop referencing the events through
9518 * the old lists, before installing it on new lists.
9523 * Install the group siblings before the group leader.
9525 * Because a group leader will try and install the entire group
9526 * (through the sibling list, which is still in-tact), we can
9527 * end up with siblings installed in the wrong context.
9529 * By installing siblings first we NO-OP because they're not
9530 * reachable through the group lists.
9532 list_for_each_entry(sibling, &group_leader->sibling_list,
9534 perf_event__state_init(sibling);
9535 perf_install_in_context(ctx, sibling, sibling->cpu);
9540 * Removing from the context ends up with disabled
9541 * event. What we want here is event in the initial
9542 * startup state, ready to be add into new context.
9544 perf_event__state_init(group_leader);
9545 perf_install_in_context(ctx, group_leader, group_leader->cpu);
9549 * Now that all events are installed in @ctx, nothing
9550 * references @gctx anymore, so drop the last reference we have
9557 * Precalculate sample_data sizes; do while holding ctx::mutex such
9558 * that we're serialized against further additions and before
9559 * perf_install_in_context() which is the point the event is active and
9560 * can use these values.
9562 perf_event__header_size(event);
9563 perf_event__id_header_size(event);
9565 event->owner = current;
9567 perf_install_in_context(ctx, event, event->cpu);
9568 perf_unpin_context(ctx);
9571 mutex_unlock(&gctx->mutex);
9572 mutex_unlock(&ctx->mutex);
9575 mutex_unlock(&task->signal->cred_guard_mutex);
9576 put_task_struct(task);
9581 mutex_lock(¤t->perf_event_mutex);
9582 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
9583 mutex_unlock(¤t->perf_event_mutex);
9586 * Drop the reference on the group_event after placing the
9587 * new event on the sibling_list. This ensures destruction
9588 * of the group leader will find the pointer to itself in
9589 * perf_group_detach().
9592 fd_install(event_fd, event_file);
9597 mutex_unlock(&gctx->mutex);
9598 mutex_unlock(&ctx->mutex);
9602 perf_unpin_context(ctx);
9606 * If event_file is set, the fput() above will have called ->release()
9607 * and that will take care of freeing the event.
9613 mutex_unlock(&task->signal->cred_guard_mutex);
9618 put_task_struct(task);
9622 put_unused_fd(event_fd);
9627 * perf_event_create_kernel_counter
9629 * @attr: attributes of the counter to create
9630 * @cpu: cpu in which the counter is bound
9631 * @task: task to profile (NULL for percpu)
9634 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
9635 struct task_struct *task,
9636 perf_overflow_handler_t overflow_handler,
9639 struct perf_event_context *ctx;
9640 struct perf_event *event;
9644 * Get the target context (task or percpu):
9647 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
9648 overflow_handler, context, -1);
9649 if (IS_ERR(event)) {
9650 err = PTR_ERR(event);
9654 /* Mark owner so we could distinguish it from user events. */
9655 event->owner = TASK_TOMBSTONE;
9657 ctx = find_get_context(event->pmu, task, event);
9663 WARN_ON_ONCE(ctx->parent_ctx);
9664 mutex_lock(&ctx->mutex);
9665 if (ctx->task == TASK_TOMBSTONE) {
9670 if (!exclusive_event_installable(event, ctx)) {
9675 perf_install_in_context(ctx, event, cpu);
9676 perf_unpin_context(ctx);
9677 mutex_unlock(&ctx->mutex);
9682 mutex_unlock(&ctx->mutex);
9683 perf_unpin_context(ctx);
9688 return ERR_PTR(err);
9690 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9692 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
9694 struct perf_event_context *src_ctx;
9695 struct perf_event_context *dst_ctx;
9696 struct perf_event *event, *tmp;
9699 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
9700 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
9703 * See perf_event_ctx_lock() for comments on the details
9704 * of swizzling perf_event::ctx.
9706 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
9707 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
9709 perf_remove_from_context(event, 0);
9710 unaccount_event_cpu(event, src_cpu);
9712 list_add(&event->migrate_entry, &events);
9716 * Wait for the events to quiesce before re-instating them.
9721 * Re-instate events in 2 passes.
9723 * Skip over group leaders and only install siblings on this first
9724 * pass, siblings will not get enabled without a leader, however a
9725 * leader will enable its siblings, even if those are still on the old
9728 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9729 if (event->group_leader == event)
9732 list_del(&event->migrate_entry);
9733 if (event->state >= PERF_EVENT_STATE_OFF)
9734 event->state = PERF_EVENT_STATE_INACTIVE;
9735 account_event_cpu(event, dst_cpu);
9736 perf_install_in_context(dst_ctx, event, dst_cpu);
9741 * Once all the siblings are setup properly, install the group leaders
9744 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9745 list_del(&event->migrate_entry);
9746 if (event->state >= PERF_EVENT_STATE_OFF)
9747 event->state = PERF_EVENT_STATE_INACTIVE;
9748 account_event_cpu(event, dst_cpu);
9749 perf_install_in_context(dst_ctx, event, dst_cpu);
9752 mutex_unlock(&dst_ctx->mutex);
9753 mutex_unlock(&src_ctx->mutex);
9755 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
9757 static void sync_child_event(struct perf_event *child_event,
9758 struct task_struct *child)
9760 struct perf_event *parent_event = child_event->parent;
9763 if (child_event->attr.inherit_stat)
9764 perf_event_read_event(child_event, child);
9766 child_val = perf_event_count(child_event);
9769 * Add back the child's count to the parent's count:
9771 atomic64_add(child_val, &parent_event->child_count);
9772 atomic64_add(child_event->total_time_enabled,
9773 &parent_event->child_total_time_enabled);
9774 atomic64_add(child_event->total_time_running,
9775 &parent_event->child_total_time_running);
9779 perf_event_exit_event(struct perf_event *child_event,
9780 struct perf_event_context *child_ctx,
9781 struct task_struct *child)
9783 struct perf_event *parent_event = child_event->parent;
9786 * Do not destroy the 'original' grouping; because of the context
9787 * switch optimization the original events could've ended up in a
9788 * random child task.
9790 * If we were to destroy the original group, all group related
9791 * operations would cease to function properly after this random
9794 * Do destroy all inherited groups, we don't care about those
9795 * and being thorough is better.
9797 raw_spin_lock_irq(&child_ctx->lock);
9798 WARN_ON_ONCE(child_ctx->is_active);
9801 perf_group_detach(child_event);
9802 list_del_event(child_event, child_ctx);
9803 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
9804 raw_spin_unlock_irq(&child_ctx->lock);
9807 * Parent events are governed by their filedesc, retain them.
9809 if (!parent_event) {
9810 perf_event_wakeup(child_event);
9814 * Child events can be cleaned up.
9817 sync_child_event(child_event, child);
9820 * Remove this event from the parent's list
9822 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9823 mutex_lock(&parent_event->child_mutex);
9824 list_del_init(&child_event->child_list);
9825 mutex_unlock(&parent_event->child_mutex);
9828 * Kick perf_poll() for is_event_hup().
9830 perf_event_wakeup(parent_event);
9831 free_event(child_event);
9832 put_event(parent_event);
9835 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9837 struct perf_event_context *child_ctx, *clone_ctx = NULL;
9838 struct perf_event *child_event, *next;
9840 WARN_ON_ONCE(child != current);
9842 child_ctx = perf_pin_task_context(child, ctxn);
9847 * In order to reduce the amount of tricky in ctx tear-down, we hold
9848 * ctx::mutex over the entire thing. This serializes against almost
9849 * everything that wants to access the ctx.
9851 * The exception is sys_perf_event_open() /
9852 * perf_event_create_kernel_count() which does find_get_context()
9853 * without ctx::mutex (it cannot because of the move_group double mutex
9854 * lock thing). See the comments in perf_install_in_context().
9856 mutex_lock(&child_ctx->mutex);
9859 * In a single ctx::lock section, de-schedule the events and detach the
9860 * context from the task such that we cannot ever get it scheduled back
9863 raw_spin_lock_irq(&child_ctx->lock);
9864 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
9867 * Now that the context is inactive, destroy the task <-> ctx relation
9868 * and mark the context dead.
9870 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
9871 put_ctx(child_ctx); /* cannot be last */
9872 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
9873 put_task_struct(current); /* cannot be last */
9875 clone_ctx = unclone_ctx(child_ctx);
9876 raw_spin_unlock_irq(&child_ctx->lock);
9882 * Report the task dead after unscheduling the events so that we
9883 * won't get any samples after PERF_RECORD_EXIT. We can however still
9884 * get a few PERF_RECORD_READ events.
9886 perf_event_task(child, child_ctx, 0);
9888 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9889 perf_event_exit_event(child_event, child_ctx, child);
9891 mutex_unlock(&child_ctx->mutex);
9897 * When a child task exits, feed back event values to parent events.
9899 * Can be called with cred_guard_mutex held when called from
9900 * install_exec_creds().
9902 void perf_event_exit_task(struct task_struct *child)
9904 struct perf_event *event, *tmp;
9907 mutex_lock(&child->perf_event_mutex);
9908 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9910 list_del_init(&event->owner_entry);
9913 * Ensure the list deletion is visible before we clear
9914 * the owner, closes a race against perf_release() where
9915 * we need to serialize on the owner->perf_event_mutex.
9917 smp_store_release(&event->owner, NULL);
9919 mutex_unlock(&child->perf_event_mutex);
9921 for_each_task_context_nr(ctxn)
9922 perf_event_exit_task_context(child, ctxn);
9925 * The perf_event_exit_task_context calls perf_event_task
9926 * with child's task_ctx, which generates EXIT events for
9927 * child contexts and sets child->perf_event_ctxp[] to NULL.
9928 * At this point we need to send EXIT events to cpu contexts.
9930 perf_event_task(child, NULL, 0);
9933 static void perf_free_event(struct perf_event *event,
9934 struct perf_event_context *ctx)
9936 struct perf_event *parent = event->parent;
9938 if (WARN_ON_ONCE(!parent))
9941 mutex_lock(&parent->child_mutex);
9942 list_del_init(&event->child_list);
9943 mutex_unlock(&parent->child_mutex);
9947 raw_spin_lock_irq(&ctx->lock);
9948 perf_group_detach(event);
9949 list_del_event(event, ctx);
9950 raw_spin_unlock_irq(&ctx->lock);
9955 * Free an unexposed, unused context as created by inheritance by
9956 * perf_event_init_task below, used by fork() in case of fail.
9958 * Not all locks are strictly required, but take them anyway to be nice and
9959 * help out with the lockdep assertions.
9961 void perf_event_free_task(struct task_struct *task)
9963 struct perf_event_context *ctx;
9964 struct perf_event *event, *tmp;
9967 for_each_task_context_nr(ctxn) {
9968 ctx = task->perf_event_ctxp[ctxn];
9972 mutex_lock(&ctx->mutex);
9974 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9976 perf_free_event(event, ctx);
9978 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9980 perf_free_event(event, ctx);
9982 if (!list_empty(&ctx->pinned_groups) ||
9983 !list_empty(&ctx->flexible_groups))
9986 mutex_unlock(&ctx->mutex);
9992 void perf_event_delayed_put(struct task_struct *task)
9996 for_each_task_context_nr(ctxn)
9997 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
10000 struct file *perf_event_get(unsigned int fd)
10004 file = fget_raw(fd);
10006 return ERR_PTR(-EBADF);
10008 if (file->f_op != &perf_fops) {
10010 return ERR_PTR(-EBADF);
10016 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
10019 return ERR_PTR(-EINVAL);
10021 return &event->attr;
10025 * inherit a event from parent task to child task:
10027 static struct perf_event *
10028 inherit_event(struct perf_event *parent_event,
10029 struct task_struct *parent,
10030 struct perf_event_context *parent_ctx,
10031 struct task_struct *child,
10032 struct perf_event *group_leader,
10033 struct perf_event_context *child_ctx)
10035 enum perf_event_active_state parent_state = parent_event->state;
10036 struct perf_event *child_event;
10037 unsigned long flags;
10040 * Instead of creating recursive hierarchies of events,
10041 * we link inherited events back to the original parent,
10042 * which has a filp for sure, which we use as the reference
10045 if (parent_event->parent)
10046 parent_event = parent_event->parent;
10048 child_event = perf_event_alloc(&parent_event->attr,
10051 group_leader, parent_event,
10053 if (IS_ERR(child_event))
10054 return child_event;
10057 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
10058 * must be under the same lock in order to serialize against
10059 * perf_event_release_kernel(), such that either we must observe
10060 * is_orphaned_event() or they will observe us on the child_list.
10062 mutex_lock(&parent_event->child_mutex);
10063 if (is_orphaned_event(parent_event) ||
10064 !atomic_long_inc_not_zero(&parent_event->refcount)) {
10065 mutex_unlock(&parent_event->child_mutex);
10066 free_event(child_event);
10070 get_ctx(child_ctx);
10073 * Make the child state follow the state of the parent event,
10074 * not its attr.disabled bit. We hold the parent's mutex,
10075 * so we won't race with perf_event_{en, dis}able_family.
10077 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
10078 child_event->state = PERF_EVENT_STATE_INACTIVE;
10080 child_event->state = PERF_EVENT_STATE_OFF;
10082 if (parent_event->attr.freq) {
10083 u64 sample_period = parent_event->hw.sample_period;
10084 struct hw_perf_event *hwc = &child_event->hw;
10086 hwc->sample_period = sample_period;
10087 hwc->last_period = sample_period;
10089 local64_set(&hwc->period_left, sample_period);
10092 child_event->ctx = child_ctx;
10093 child_event->overflow_handler = parent_event->overflow_handler;
10094 child_event->overflow_handler_context
10095 = parent_event->overflow_handler_context;
10098 * Precalculate sample_data sizes
10100 perf_event__header_size(child_event);
10101 perf_event__id_header_size(child_event);
10104 * Link it up in the child's context:
10106 raw_spin_lock_irqsave(&child_ctx->lock, flags);
10107 add_event_to_ctx(child_event, child_ctx);
10108 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
10111 * Link this into the parent event's child list
10113 list_add_tail(&child_event->child_list, &parent_event->child_list);
10114 mutex_unlock(&parent_event->child_mutex);
10116 return child_event;
10119 static int inherit_group(struct perf_event *parent_event,
10120 struct task_struct *parent,
10121 struct perf_event_context *parent_ctx,
10122 struct task_struct *child,
10123 struct perf_event_context *child_ctx)
10125 struct perf_event *leader;
10126 struct perf_event *sub;
10127 struct perf_event *child_ctr;
10129 leader = inherit_event(parent_event, parent, parent_ctx,
10130 child, NULL, child_ctx);
10131 if (IS_ERR(leader))
10132 return PTR_ERR(leader);
10133 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
10134 child_ctr = inherit_event(sub, parent, parent_ctx,
10135 child, leader, child_ctx);
10136 if (IS_ERR(child_ctr))
10137 return PTR_ERR(child_ctr);
10143 inherit_task_group(struct perf_event *event, struct task_struct *parent,
10144 struct perf_event_context *parent_ctx,
10145 struct task_struct *child, int ctxn,
10146 int *inherited_all)
10149 struct perf_event_context *child_ctx;
10151 if (!event->attr.inherit) {
10152 *inherited_all = 0;
10156 child_ctx = child->perf_event_ctxp[ctxn];
10159 * This is executed from the parent task context, so
10160 * inherit events that have been marked for cloning.
10161 * First allocate and initialize a context for the
10165 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
10169 child->perf_event_ctxp[ctxn] = child_ctx;
10172 ret = inherit_group(event, parent, parent_ctx,
10176 *inherited_all = 0;
10182 * Initialize the perf_event context in task_struct
10184 static int perf_event_init_context(struct task_struct *child, int ctxn)
10186 struct perf_event_context *child_ctx, *parent_ctx;
10187 struct perf_event_context *cloned_ctx;
10188 struct perf_event *event;
10189 struct task_struct *parent = current;
10190 int inherited_all = 1;
10191 unsigned long flags;
10194 if (likely(!parent->perf_event_ctxp[ctxn]))
10198 * If the parent's context is a clone, pin it so it won't get
10199 * swapped under us.
10201 parent_ctx = perf_pin_task_context(parent, ctxn);
10206 * No need to check if parent_ctx != NULL here; since we saw
10207 * it non-NULL earlier, the only reason for it to become NULL
10208 * is if we exit, and since we're currently in the middle of
10209 * a fork we can't be exiting at the same time.
10213 * Lock the parent list. No need to lock the child - not PID
10214 * hashed yet and not running, so nobody can access it.
10216 mutex_lock(&parent_ctx->mutex);
10219 * We dont have to disable NMIs - we are only looking at
10220 * the list, not manipulating it:
10222 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
10223 ret = inherit_task_group(event, parent, parent_ctx,
10224 child, ctxn, &inherited_all);
10230 * We can't hold ctx->lock when iterating the ->flexible_group list due
10231 * to allocations, but we need to prevent rotation because
10232 * rotate_ctx() will change the list from interrupt context.
10234 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10235 parent_ctx->rotate_disable = 1;
10236 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10238 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
10239 ret = inherit_task_group(event, parent, parent_ctx,
10240 child, ctxn, &inherited_all);
10245 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10246 parent_ctx->rotate_disable = 0;
10248 child_ctx = child->perf_event_ctxp[ctxn];
10250 if (child_ctx && inherited_all) {
10252 * Mark the child context as a clone of the parent
10253 * context, or of whatever the parent is a clone of.
10255 * Note that if the parent is a clone, the holding of
10256 * parent_ctx->lock avoids it from being uncloned.
10258 cloned_ctx = parent_ctx->parent_ctx;
10260 child_ctx->parent_ctx = cloned_ctx;
10261 child_ctx->parent_gen = parent_ctx->parent_gen;
10263 child_ctx->parent_ctx = parent_ctx;
10264 child_ctx->parent_gen = parent_ctx->generation;
10266 get_ctx(child_ctx->parent_ctx);
10269 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10270 mutex_unlock(&parent_ctx->mutex);
10272 perf_unpin_context(parent_ctx);
10273 put_ctx(parent_ctx);
10279 * Initialize the perf_event context in task_struct
10281 int perf_event_init_task(struct task_struct *child)
10285 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
10286 mutex_init(&child->perf_event_mutex);
10287 INIT_LIST_HEAD(&child->perf_event_list);
10289 for_each_task_context_nr(ctxn) {
10290 ret = perf_event_init_context(child, ctxn);
10292 perf_event_free_task(child);
10300 static void __init perf_event_init_all_cpus(void)
10302 struct swevent_htable *swhash;
10305 for_each_possible_cpu(cpu) {
10306 swhash = &per_cpu(swevent_htable, cpu);
10307 mutex_init(&swhash->hlist_mutex);
10308 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
10310 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
10311 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
10315 static void perf_event_init_cpu(int cpu)
10317 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10319 mutex_lock(&swhash->hlist_mutex);
10320 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
10321 struct swevent_hlist *hlist;
10323 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
10325 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10327 mutex_unlock(&swhash->hlist_mutex);
10330 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
10331 static void __perf_event_exit_context(void *__info)
10333 struct perf_event_context *ctx = __info;
10334 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
10335 struct perf_event *event;
10337 raw_spin_lock(&ctx->lock);
10338 list_for_each_entry(event, &ctx->event_list, event_entry)
10339 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
10340 raw_spin_unlock(&ctx->lock);
10343 static void perf_event_exit_cpu_context(int cpu)
10345 struct perf_event_context *ctx;
10349 idx = srcu_read_lock(&pmus_srcu);
10350 list_for_each_entry_rcu(pmu, &pmus, entry) {
10351 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
10353 mutex_lock(&ctx->mutex);
10354 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
10355 mutex_unlock(&ctx->mutex);
10357 srcu_read_unlock(&pmus_srcu, idx);
10360 static void perf_event_exit_cpu(int cpu)
10362 perf_event_exit_cpu_context(cpu);
10365 static inline void perf_event_exit_cpu(int cpu) { }
10369 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
10373 for_each_online_cpu(cpu)
10374 perf_event_exit_cpu(cpu);
10380 * Run the perf reboot notifier at the very last possible moment so that
10381 * the generic watchdog code runs as long as possible.
10383 static struct notifier_block perf_reboot_notifier = {
10384 .notifier_call = perf_reboot,
10385 .priority = INT_MIN,
10389 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
10391 unsigned int cpu = (long)hcpu;
10393 switch (action & ~CPU_TASKS_FROZEN) {
10395 case CPU_UP_PREPARE:
10397 * This must be done before the CPU comes alive, because the
10398 * moment we can run tasks we can encounter (software) events.
10400 * Specifically, someone can have inherited events on kthreadd
10401 * or a pre-existing worker thread that gets re-bound.
10403 perf_event_init_cpu(cpu);
10406 case CPU_DOWN_PREPARE:
10408 * This must be done before the CPU dies because after that an
10409 * active event might want to IPI the CPU and that'll not work
10410 * so great for dead CPUs.
10412 * XXX smp_call_function_single() return -ENXIO without a warn
10413 * so we could possibly deal with this.
10415 * This is safe against new events arriving because
10416 * sys_perf_event_open() serializes against hotplug using
10417 * get_online_cpus().
10419 perf_event_exit_cpu(cpu);
10428 void __init perf_event_init(void)
10432 idr_init(&pmu_idr);
10434 perf_event_init_all_cpus();
10435 init_srcu_struct(&pmus_srcu);
10436 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
10437 perf_pmu_register(&perf_cpu_clock, NULL, -1);
10438 perf_pmu_register(&perf_task_clock, NULL, -1);
10439 perf_tp_register();
10440 perf_cpu_notifier(perf_cpu_notify);
10441 register_reboot_notifier(&perf_reboot_notifier);
10443 ret = init_hw_breakpoint();
10444 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
10447 * Build time assertion that we keep the data_head at the intended
10448 * location. IOW, validation we got the __reserved[] size right.
10450 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
10454 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
10457 struct perf_pmu_events_attr *pmu_attr =
10458 container_of(attr, struct perf_pmu_events_attr, attr);
10460 if (pmu_attr->event_str)
10461 return sprintf(page, "%s\n", pmu_attr->event_str);
10465 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
10467 static int __init perf_event_sysfs_init(void)
10472 mutex_lock(&pmus_lock);
10474 ret = bus_register(&pmu_bus);
10478 list_for_each_entry(pmu, &pmus, entry) {
10479 if (!pmu->name || pmu->type < 0)
10482 ret = pmu_dev_alloc(pmu);
10483 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
10485 pmu_bus_running = 1;
10489 mutex_unlock(&pmus_lock);
10493 device_initcall(perf_event_sysfs_init);
10495 #ifdef CONFIG_CGROUP_PERF
10496 static struct cgroup_subsys_state *
10497 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10499 struct perf_cgroup *jc;
10501 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
10503 return ERR_PTR(-ENOMEM);
10505 jc->info = alloc_percpu(struct perf_cgroup_info);
10508 return ERR_PTR(-ENOMEM);
10514 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
10516 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
10518 free_percpu(jc->info);
10522 static int __perf_cgroup_move(void *info)
10524 struct task_struct *task = info;
10526 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
10531 static void perf_cgroup_attach(struct cgroup_taskset *tset)
10533 struct task_struct *task;
10534 struct cgroup_subsys_state *css;
10536 cgroup_taskset_for_each(task, css, tset)
10537 task_function_call(task, __perf_cgroup_move, task);
10540 struct cgroup_subsys perf_event_cgrp_subsys = {
10541 .css_alloc = perf_cgroup_css_alloc,
10542 .css_free = perf_cgroup_css_free,
10543 .attach = perf_cgroup_attach,
10545 #endif /* CONFIG_CGROUP_PERF */