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_call(struct perf_event *event, event_f func, void *data)
247 struct perf_event_context *ctx = event->ctx;
248 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
249 struct event_function_struct efs = {
255 if (!event->parent) {
257 * If this is a !child event, we must hold ctx::mutex to
258 * stabilize the the event->ctx relation. See
259 * perf_event_ctx_lock().
261 lockdep_assert_held(&ctx->mutex);
265 cpu_function_call(event->cpu, event_function, &efs);
269 if (task == TASK_TOMBSTONE)
273 if (!task_function_call(task, event_function, &efs))
276 raw_spin_lock_irq(&ctx->lock);
278 * Reload the task pointer, it might have been changed by
279 * a concurrent perf_event_context_sched_out().
282 if (task == TASK_TOMBSTONE) {
283 raw_spin_unlock_irq(&ctx->lock);
286 if (ctx->is_active) {
287 raw_spin_unlock_irq(&ctx->lock);
290 func(event, NULL, ctx, data);
291 raw_spin_unlock_irq(&ctx->lock);
295 * Similar to event_function_call() + event_function(), but hard assumes IRQs
296 * are already disabled and we're on the right CPU.
298 static void event_function_local(struct perf_event *event, event_f func, void *data)
300 struct perf_event_context *ctx = event->ctx;
301 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
302 struct task_struct *task = READ_ONCE(ctx->task);
303 struct perf_event_context *task_ctx = NULL;
305 WARN_ON_ONCE(!irqs_disabled());
308 if (task == TASK_TOMBSTONE)
314 perf_ctx_lock(cpuctx, task_ctx);
317 if (task == TASK_TOMBSTONE)
322 * We must be either inactive or active and the right task,
323 * otherwise we're screwed, since we cannot IPI to somewhere
326 if (ctx->is_active) {
327 if (WARN_ON_ONCE(task != current))
330 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
334 WARN_ON_ONCE(&cpuctx->ctx != ctx);
337 func(event, cpuctx, ctx, data);
339 perf_ctx_unlock(cpuctx, task_ctx);
342 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
343 PERF_FLAG_FD_OUTPUT |\
344 PERF_FLAG_PID_CGROUP |\
345 PERF_FLAG_FD_CLOEXEC)
348 * branch priv levels that need permission checks
350 #define PERF_SAMPLE_BRANCH_PERM_PLM \
351 (PERF_SAMPLE_BRANCH_KERNEL |\
352 PERF_SAMPLE_BRANCH_HV)
355 EVENT_FLEXIBLE = 0x1,
358 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
362 * perf_sched_events : >0 events exist
363 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
366 static void perf_sched_delayed(struct work_struct *work);
367 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
368 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
369 static DEFINE_MUTEX(perf_sched_mutex);
370 static atomic_t perf_sched_count;
372 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
373 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
374 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
376 static atomic_t nr_mmap_events __read_mostly;
377 static atomic_t nr_comm_events __read_mostly;
378 static atomic_t nr_task_events __read_mostly;
379 static atomic_t nr_freq_events __read_mostly;
380 static atomic_t nr_switch_events __read_mostly;
382 static LIST_HEAD(pmus);
383 static DEFINE_MUTEX(pmus_lock);
384 static struct srcu_struct pmus_srcu;
387 * perf event paranoia level:
388 * -1 - not paranoid at all
389 * 0 - disallow raw tracepoint access for unpriv
390 * 1 - disallow cpu events for unpriv
391 * 2 - disallow kernel profiling for unpriv
393 int sysctl_perf_event_paranoid __read_mostly = 2;
395 /* Minimum for 512 kiB + 1 user control page */
396 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
399 * max perf event sample rate
401 #define DEFAULT_MAX_SAMPLE_RATE 100000
402 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
403 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
405 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
407 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
408 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
410 static int perf_sample_allowed_ns __read_mostly =
411 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
413 static void update_perf_cpu_limits(void)
415 u64 tmp = perf_sample_period_ns;
417 tmp *= sysctl_perf_cpu_time_max_percent;
418 tmp = div_u64(tmp, 100);
422 WRITE_ONCE(perf_sample_allowed_ns, tmp);
425 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
427 int perf_proc_update_handler(struct ctl_table *table, int write,
428 void __user *buffer, size_t *lenp,
431 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
437 * If throttling is disabled don't allow the write:
439 if (sysctl_perf_cpu_time_max_percent == 100 ||
440 sysctl_perf_cpu_time_max_percent == 0)
443 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
444 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
445 update_perf_cpu_limits();
450 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
452 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
453 void __user *buffer, size_t *lenp,
456 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
461 if (sysctl_perf_cpu_time_max_percent == 100 ||
462 sysctl_perf_cpu_time_max_percent == 0) {
464 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
465 WRITE_ONCE(perf_sample_allowed_ns, 0);
467 update_perf_cpu_limits();
474 * perf samples are done in some very critical code paths (NMIs).
475 * If they take too much CPU time, the system can lock up and not
476 * get any real work done. This will drop the sample rate when
477 * we detect that events are taking too long.
479 #define NR_ACCUMULATED_SAMPLES 128
480 static DEFINE_PER_CPU(u64, running_sample_length);
482 static u64 __report_avg;
483 static u64 __report_allowed;
485 static void perf_duration_warn(struct irq_work *w)
487 printk_ratelimited(KERN_INFO
488 "perf: interrupt took too long (%lld > %lld), lowering "
489 "kernel.perf_event_max_sample_rate to %d\n",
490 __report_avg, __report_allowed,
491 sysctl_perf_event_sample_rate);
494 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
496 void perf_sample_event_took(u64 sample_len_ns)
498 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
506 /* Decay the counter by 1 average sample. */
507 running_len = __this_cpu_read(running_sample_length);
508 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
509 running_len += sample_len_ns;
510 __this_cpu_write(running_sample_length, running_len);
513 * Note: this will be biased artifically low until we have
514 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
515 * from having to maintain a count.
517 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
518 if (avg_len <= max_len)
521 __report_avg = avg_len;
522 __report_allowed = max_len;
525 * Compute a throttle threshold 25% below the current duration.
527 avg_len += avg_len / 4;
528 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
534 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
535 WRITE_ONCE(max_samples_per_tick, max);
537 sysctl_perf_event_sample_rate = max * HZ;
538 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
540 if (!irq_work_queue(&perf_duration_work)) {
541 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
542 "kernel.perf_event_max_sample_rate to %d\n",
543 __report_avg, __report_allowed,
544 sysctl_perf_event_sample_rate);
548 static atomic64_t perf_event_id;
550 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
551 enum event_type_t event_type);
553 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
554 enum event_type_t event_type,
555 struct task_struct *task);
557 static void update_context_time(struct perf_event_context *ctx);
558 static u64 perf_event_time(struct perf_event *event);
560 void __weak perf_event_print_debug(void) { }
562 extern __weak const char *perf_pmu_name(void)
567 static inline u64 perf_clock(void)
569 return local_clock();
572 static inline u64 perf_event_clock(struct perf_event *event)
574 return event->clock();
577 #ifdef CONFIG_CGROUP_PERF
580 perf_cgroup_match(struct perf_event *event)
582 struct perf_event_context *ctx = event->ctx;
583 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
585 /* @event doesn't care about cgroup */
589 /* wants specific cgroup scope but @cpuctx isn't associated with any */
594 * Cgroup scoping is recursive. An event enabled for a cgroup is
595 * also enabled for all its descendant cgroups. If @cpuctx's
596 * cgroup is a descendant of @event's (the test covers identity
597 * case), it's a match.
599 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
600 event->cgrp->css.cgroup);
603 static inline void perf_detach_cgroup(struct perf_event *event)
605 css_put(&event->cgrp->css);
609 static inline int is_cgroup_event(struct perf_event *event)
611 return event->cgrp != NULL;
614 static inline u64 perf_cgroup_event_time(struct perf_event *event)
616 struct perf_cgroup_info *t;
618 t = per_cpu_ptr(event->cgrp->info, event->cpu);
622 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
624 struct perf_cgroup_info *info;
629 info = this_cpu_ptr(cgrp->info);
631 info->time += now - info->timestamp;
632 info->timestamp = now;
635 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
637 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
639 __update_cgrp_time(cgrp_out);
642 static inline void update_cgrp_time_from_event(struct perf_event *event)
644 struct perf_cgroup *cgrp;
647 * ensure we access cgroup data only when needed and
648 * when we know the cgroup is pinned (css_get)
650 if (!is_cgroup_event(event))
653 cgrp = perf_cgroup_from_task(current, event->ctx);
655 * Do not update time when cgroup is not active
657 if (cgrp == event->cgrp)
658 __update_cgrp_time(event->cgrp);
662 perf_cgroup_set_timestamp(struct task_struct *task,
663 struct perf_event_context *ctx)
665 struct perf_cgroup *cgrp;
666 struct perf_cgroup_info *info;
669 * ctx->lock held by caller
670 * ensure we do not access cgroup data
671 * unless we have the cgroup pinned (css_get)
673 if (!task || !ctx->nr_cgroups)
676 cgrp = perf_cgroup_from_task(task, ctx);
677 info = this_cpu_ptr(cgrp->info);
678 info->timestamp = ctx->timestamp;
681 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
682 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
685 * reschedule events based on the cgroup constraint of task.
687 * mode SWOUT : schedule out everything
688 * mode SWIN : schedule in based on cgroup for next
690 static void perf_cgroup_switch(struct task_struct *task, int mode)
692 struct perf_cpu_context *cpuctx;
697 * disable interrupts to avoid geting nr_cgroup
698 * changes via __perf_event_disable(). Also
701 local_irq_save(flags);
704 * we reschedule only in the presence of cgroup
705 * constrained events.
708 list_for_each_entry_rcu(pmu, &pmus, entry) {
709 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
710 if (cpuctx->unique_pmu != pmu)
711 continue; /* ensure we process each cpuctx once */
714 * perf_cgroup_events says at least one
715 * context on this CPU has cgroup events.
717 * ctx->nr_cgroups reports the number of cgroup
718 * events for a context.
720 if (cpuctx->ctx.nr_cgroups > 0) {
721 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
722 perf_pmu_disable(cpuctx->ctx.pmu);
724 if (mode & PERF_CGROUP_SWOUT) {
725 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
727 * must not be done before ctxswout due
728 * to event_filter_match() in event_sched_out()
733 if (mode & PERF_CGROUP_SWIN) {
734 WARN_ON_ONCE(cpuctx->cgrp);
736 * set cgrp before ctxsw in to allow
737 * event_filter_match() to not have to pass
739 * we pass the cpuctx->ctx to perf_cgroup_from_task()
740 * because cgorup events are only per-cpu
742 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
743 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
745 perf_pmu_enable(cpuctx->ctx.pmu);
746 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
750 local_irq_restore(flags);
753 static inline void perf_cgroup_sched_out(struct task_struct *task,
754 struct task_struct *next)
756 struct perf_cgroup *cgrp1;
757 struct perf_cgroup *cgrp2 = NULL;
761 * we come here when we know perf_cgroup_events > 0
762 * we do not need to pass the ctx here because we know
763 * we are holding the rcu lock
765 cgrp1 = perf_cgroup_from_task(task, NULL);
766 cgrp2 = perf_cgroup_from_task(next, NULL);
769 * only schedule out current cgroup events if we know
770 * that we are switching to a different cgroup. Otherwise,
771 * do no touch the cgroup events.
774 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
779 static inline void perf_cgroup_sched_in(struct task_struct *prev,
780 struct task_struct *task)
782 struct perf_cgroup *cgrp1;
783 struct perf_cgroup *cgrp2 = NULL;
787 * we come here when we know perf_cgroup_events > 0
788 * we do not need to pass the ctx here because we know
789 * we are holding the rcu lock
791 cgrp1 = perf_cgroup_from_task(task, NULL);
792 cgrp2 = perf_cgroup_from_task(prev, NULL);
795 * only need to schedule in cgroup events if we are changing
796 * cgroup during ctxsw. Cgroup events were not scheduled
797 * out of ctxsw out if that was not the case.
800 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
805 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
806 struct perf_event_attr *attr,
807 struct perf_event *group_leader)
809 struct perf_cgroup *cgrp;
810 struct cgroup_subsys_state *css;
811 struct fd f = fdget(fd);
817 css = css_tryget_online_from_dir(f.file->f_path.dentry,
818 &perf_event_cgrp_subsys);
824 cgrp = container_of(css, struct perf_cgroup, css);
828 * all events in a group must monitor
829 * the same cgroup because a task belongs
830 * to only one perf cgroup at a time
832 if (group_leader && group_leader->cgrp != cgrp) {
833 perf_detach_cgroup(event);
842 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
844 struct perf_cgroup_info *t;
845 t = per_cpu_ptr(event->cgrp->info, event->cpu);
846 event->shadow_ctx_time = now - t->timestamp;
850 perf_cgroup_defer_enabled(struct perf_event *event)
853 * when the current task's perf cgroup does not match
854 * the event's, we need to remember to call the
855 * perf_mark_enable() function the first time a task with
856 * a matching perf cgroup is scheduled in.
858 if (is_cgroup_event(event) && !perf_cgroup_match(event))
859 event->cgrp_defer_enabled = 1;
863 perf_cgroup_mark_enabled(struct perf_event *event,
864 struct perf_event_context *ctx)
866 struct perf_event *sub;
867 u64 tstamp = perf_event_time(event);
869 if (!event->cgrp_defer_enabled)
872 event->cgrp_defer_enabled = 0;
874 event->tstamp_enabled = tstamp - event->total_time_enabled;
875 list_for_each_entry(sub, &event->sibling_list, group_entry) {
876 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
877 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
878 sub->cgrp_defer_enabled = 0;
884 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
885 * cleared when last cgroup event is removed.
888 list_update_cgroup_event(struct perf_event *event,
889 struct perf_event_context *ctx, bool add)
891 struct perf_cpu_context *cpuctx;
893 if (!is_cgroup_event(event))
896 if (add && ctx->nr_cgroups++)
898 else if (!add && --ctx->nr_cgroups)
901 * Because cgroup events are always per-cpu events,
902 * this will always be called from the right CPU.
904 cpuctx = __get_cpu_context(ctx);
905 cpuctx->cgrp = add ? event->cgrp : NULL;
908 #else /* !CONFIG_CGROUP_PERF */
911 perf_cgroup_match(struct perf_event *event)
916 static inline void perf_detach_cgroup(struct perf_event *event)
919 static inline int is_cgroup_event(struct perf_event *event)
924 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
929 static inline void update_cgrp_time_from_event(struct perf_event *event)
933 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
937 static inline void perf_cgroup_sched_out(struct task_struct *task,
938 struct task_struct *next)
942 static inline void perf_cgroup_sched_in(struct task_struct *prev,
943 struct task_struct *task)
947 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
948 struct perf_event_attr *attr,
949 struct perf_event *group_leader)
955 perf_cgroup_set_timestamp(struct task_struct *task,
956 struct perf_event_context *ctx)
961 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
966 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
970 static inline u64 perf_cgroup_event_time(struct perf_event *event)
976 perf_cgroup_defer_enabled(struct perf_event *event)
981 perf_cgroup_mark_enabled(struct perf_event *event,
982 struct perf_event_context *ctx)
987 list_update_cgroup_event(struct perf_event *event,
988 struct perf_event_context *ctx, bool add)
995 * set default to be dependent on timer tick just
998 #define PERF_CPU_HRTIMER (1000 / HZ)
1000 * function must be called with interrupts disbled
1002 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1004 struct perf_cpu_context *cpuctx;
1007 WARN_ON(!irqs_disabled());
1009 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1010 rotations = perf_rotate_context(cpuctx);
1012 raw_spin_lock(&cpuctx->hrtimer_lock);
1014 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1016 cpuctx->hrtimer_active = 0;
1017 raw_spin_unlock(&cpuctx->hrtimer_lock);
1019 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1022 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1024 struct hrtimer *timer = &cpuctx->hrtimer;
1025 struct pmu *pmu = cpuctx->ctx.pmu;
1028 /* no multiplexing needed for SW PMU */
1029 if (pmu->task_ctx_nr == perf_sw_context)
1033 * check default is sane, if not set then force to
1034 * default interval (1/tick)
1036 interval = pmu->hrtimer_interval_ms;
1038 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1040 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1042 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1043 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
1044 timer->function = perf_mux_hrtimer_handler;
1047 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1049 struct hrtimer *timer = &cpuctx->hrtimer;
1050 struct pmu *pmu = cpuctx->ctx.pmu;
1051 unsigned long flags;
1053 /* not for SW PMU */
1054 if (pmu->task_ctx_nr == perf_sw_context)
1057 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1058 if (!cpuctx->hrtimer_active) {
1059 cpuctx->hrtimer_active = 1;
1060 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1061 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
1063 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1068 void perf_pmu_disable(struct pmu *pmu)
1070 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1072 pmu->pmu_disable(pmu);
1075 void perf_pmu_enable(struct pmu *pmu)
1077 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1079 pmu->pmu_enable(pmu);
1082 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1085 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1086 * perf_event_task_tick() are fully serialized because they're strictly cpu
1087 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1088 * disabled, while perf_event_task_tick is called from IRQ context.
1090 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1092 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1094 WARN_ON(!irqs_disabled());
1096 WARN_ON(!list_empty(&ctx->active_ctx_list));
1098 list_add(&ctx->active_ctx_list, head);
1101 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1103 WARN_ON(!irqs_disabled());
1105 WARN_ON(list_empty(&ctx->active_ctx_list));
1107 list_del_init(&ctx->active_ctx_list);
1110 static void get_ctx(struct perf_event_context *ctx)
1112 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1115 static void free_ctx(struct rcu_head *head)
1117 struct perf_event_context *ctx;
1119 ctx = container_of(head, struct perf_event_context, rcu_head);
1120 kfree(ctx->task_ctx_data);
1124 static void put_ctx(struct perf_event_context *ctx)
1126 if (atomic_dec_and_test(&ctx->refcount)) {
1127 if (ctx->parent_ctx)
1128 put_ctx(ctx->parent_ctx);
1129 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1130 put_task_struct(ctx->task);
1131 call_rcu(&ctx->rcu_head, free_ctx);
1136 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1137 * perf_pmu_migrate_context() we need some magic.
1139 * Those places that change perf_event::ctx will hold both
1140 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1142 * Lock ordering is by mutex address. There are two other sites where
1143 * perf_event_context::mutex nests and those are:
1145 * - perf_event_exit_task_context() [ child , 0 ]
1146 * perf_event_exit_event()
1147 * put_event() [ parent, 1 ]
1149 * - perf_event_init_context() [ parent, 0 ]
1150 * inherit_task_group()
1153 * perf_event_alloc()
1155 * perf_try_init_event() [ child , 1 ]
1157 * While it appears there is an obvious deadlock here -- the parent and child
1158 * nesting levels are inverted between the two. This is in fact safe because
1159 * life-time rules separate them. That is an exiting task cannot fork, and a
1160 * spawning task cannot (yet) exit.
1162 * But remember that that these are parent<->child context relations, and
1163 * migration does not affect children, therefore these two orderings should not
1166 * The change in perf_event::ctx does not affect children (as claimed above)
1167 * because the sys_perf_event_open() case will install a new event and break
1168 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1169 * concerned with cpuctx and that doesn't have children.
1171 * The places that change perf_event::ctx will issue:
1173 * perf_remove_from_context();
1174 * synchronize_rcu();
1175 * perf_install_in_context();
1177 * to affect the change. The remove_from_context() + synchronize_rcu() should
1178 * quiesce the event, after which we can install it in the new location. This
1179 * means that only external vectors (perf_fops, prctl) can perturb the event
1180 * while in transit. Therefore all such accessors should also acquire
1181 * perf_event_context::mutex to serialize against this.
1183 * However; because event->ctx can change while we're waiting to acquire
1184 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1189 * task_struct::perf_event_mutex
1190 * perf_event_context::mutex
1191 * perf_event::child_mutex;
1192 * perf_event_context::lock
1193 * perf_event::mmap_mutex
1196 static struct perf_event_context *
1197 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1199 struct perf_event_context *ctx;
1203 ctx = ACCESS_ONCE(event->ctx);
1204 if (!atomic_inc_not_zero(&ctx->refcount)) {
1210 mutex_lock_nested(&ctx->mutex, nesting);
1211 if (event->ctx != ctx) {
1212 mutex_unlock(&ctx->mutex);
1220 static inline struct perf_event_context *
1221 perf_event_ctx_lock(struct perf_event *event)
1223 return perf_event_ctx_lock_nested(event, 0);
1226 static void perf_event_ctx_unlock(struct perf_event *event,
1227 struct perf_event_context *ctx)
1229 mutex_unlock(&ctx->mutex);
1234 * This must be done under the ctx->lock, such as to serialize against
1235 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1236 * calling scheduler related locks and ctx->lock nests inside those.
1238 static __must_check struct perf_event_context *
1239 unclone_ctx(struct perf_event_context *ctx)
1241 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1243 lockdep_assert_held(&ctx->lock);
1246 ctx->parent_ctx = NULL;
1252 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1255 * only top level events have the pid namespace they were created in
1258 event = event->parent;
1260 return task_tgid_nr_ns(p, event->ns);
1263 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1266 * only top level events have the pid namespace they were created in
1269 event = event->parent;
1271 return task_pid_nr_ns(p, event->ns);
1275 * If we inherit events we want to return the parent event id
1278 static u64 primary_event_id(struct perf_event *event)
1283 id = event->parent->id;
1289 * Get the perf_event_context for a task and lock it.
1291 * This has to cope with with the fact that until it is locked,
1292 * the context could get moved to another task.
1294 static struct perf_event_context *
1295 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1297 struct perf_event_context *ctx;
1301 * One of the few rules of preemptible RCU is that one cannot do
1302 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1303 * part of the read side critical section was irqs-enabled -- see
1304 * rcu_read_unlock_special().
1306 * Since ctx->lock nests under rq->lock we must ensure the entire read
1307 * side critical section has interrupts disabled.
1309 local_irq_save(*flags);
1311 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1314 * If this context is a clone of another, it might
1315 * get swapped for another underneath us by
1316 * perf_event_task_sched_out, though the
1317 * rcu_read_lock() protects us from any context
1318 * getting freed. Lock the context and check if it
1319 * got swapped before we could get the lock, and retry
1320 * if so. If we locked the right context, then it
1321 * can't get swapped on us any more.
1323 raw_spin_lock(&ctx->lock);
1324 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1325 raw_spin_unlock(&ctx->lock);
1327 local_irq_restore(*flags);
1331 if (ctx->task == TASK_TOMBSTONE ||
1332 !atomic_inc_not_zero(&ctx->refcount)) {
1333 raw_spin_unlock(&ctx->lock);
1336 WARN_ON_ONCE(ctx->task != task);
1341 local_irq_restore(*flags);
1346 * Get the context for a task and increment its pin_count so it
1347 * can't get swapped to another task. This also increments its
1348 * reference count so that the context can't get freed.
1350 static struct perf_event_context *
1351 perf_pin_task_context(struct task_struct *task, int ctxn)
1353 struct perf_event_context *ctx;
1354 unsigned long flags;
1356 ctx = perf_lock_task_context(task, ctxn, &flags);
1359 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1364 static void perf_unpin_context(struct perf_event_context *ctx)
1366 unsigned long flags;
1368 raw_spin_lock_irqsave(&ctx->lock, flags);
1370 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1374 * Update the record of the current time in a context.
1376 static void update_context_time(struct perf_event_context *ctx)
1378 u64 now = perf_clock();
1380 ctx->time += now - ctx->timestamp;
1381 ctx->timestamp = now;
1384 static u64 perf_event_time(struct perf_event *event)
1386 struct perf_event_context *ctx = event->ctx;
1388 if (is_cgroup_event(event))
1389 return perf_cgroup_event_time(event);
1391 return ctx ? ctx->time : 0;
1395 * Update the total_time_enabled and total_time_running fields for a event.
1397 static void update_event_times(struct perf_event *event)
1399 struct perf_event_context *ctx = event->ctx;
1402 lockdep_assert_held(&ctx->lock);
1404 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1405 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1409 * in cgroup mode, time_enabled represents
1410 * the time the event was enabled AND active
1411 * tasks were in the monitored cgroup. This is
1412 * independent of the activity of the context as
1413 * there may be a mix of cgroup and non-cgroup events.
1415 * That is why we treat cgroup events differently
1418 if (is_cgroup_event(event))
1419 run_end = perf_cgroup_event_time(event);
1420 else if (ctx->is_active)
1421 run_end = ctx->time;
1423 run_end = event->tstamp_stopped;
1425 event->total_time_enabled = run_end - event->tstamp_enabled;
1427 if (event->state == PERF_EVENT_STATE_INACTIVE)
1428 run_end = event->tstamp_stopped;
1430 run_end = perf_event_time(event);
1432 event->total_time_running = run_end - event->tstamp_running;
1437 * Update total_time_enabled and total_time_running for all events in a group.
1439 static void update_group_times(struct perf_event *leader)
1441 struct perf_event *event;
1443 update_event_times(leader);
1444 list_for_each_entry(event, &leader->sibling_list, group_entry)
1445 update_event_times(event);
1448 static struct list_head *
1449 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1451 if (event->attr.pinned)
1452 return &ctx->pinned_groups;
1454 return &ctx->flexible_groups;
1458 * Add a event from the lists for its context.
1459 * Must be called with ctx->mutex and ctx->lock held.
1462 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1465 lockdep_assert_held(&ctx->lock);
1467 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1468 event->attach_state |= PERF_ATTACH_CONTEXT;
1471 * If we're a stand alone event or group leader, we go to the context
1472 * list, group events are kept attached to the group so that
1473 * perf_group_detach can, at all times, locate all siblings.
1475 if (event->group_leader == event) {
1476 struct list_head *list;
1478 event->group_caps = event->event_caps;
1480 list = ctx_group_list(event, ctx);
1481 list_add_tail(&event->group_entry, list);
1484 list_update_cgroup_event(event, ctx, true);
1486 list_add_rcu(&event->event_entry, &ctx->event_list);
1488 if (event->attr.inherit_stat)
1495 * Initialize event state based on the perf_event_attr::disabled.
1497 static inline void perf_event__state_init(struct perf_event *event)
1499 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1500 PERF_EVENT_STATE_INACTIVE;
1503 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1505 int entry = sizeof(u64); /* value */
1509 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1510 size += sizeof(u64);
1512 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1513 size += sizeof(u64);
1515 if (event->attr.read_format & PERF_FORMAT_ID)
1516 entry += sizeof(u64);
1518 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1520 size += sizeof(u64);
1524 event->read_size = size;
1527 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1529 struct perf_sample_data *data;
1532 if (sample_type & PERF_SAMPLE_IP)
1533 size += sizeof(data->ip);
1535 if (sample_type & PERF_SAMPLE_ADDR)
1536 size += sizeof(data->addr);
1538 if (sample_type & PERF_SAMPLE_PERIOD)
1539 size += sizeof(data->period);
1541 if (sample_type & PERF_SAMPLE_WEIGHT)
1542 size += sizeof(data->weight);
1544 if (sample_type & PERF_SAMPLE_READ)
1545 size += event->read_size;
1547 if (sample_type & PERF_SAMPLE_DATA_SRC)
1548 size += sizeof(data->data_src.val);
1550 if (sample_type & PERF_SAMPLE_TRANSACTION)
1551 size += sizeof(data->txn);
1553 event->header_size = size;
1557 * Called at perf_event creation and when events are attached/detached from a
1560 static void perf_event__header_size(struct perf_event *event)
1562 __perf_event_read_size(event,
1563 event->group_leader->nr_siblings);
1564 __perf_event_header_size(event, event->attr.sample_type);
1567 static void perf_event__id_header_size(struct perf_event *event)
1569 struct perf_sample_data *data;
1570 u64 sample_type = event->attr.sample_type;
1573 if (sample_type & PERF_SAMPLE_TID)
1574 size += sizeof(data->tid_entry);
1576 if (sample_type & PERF_SAMPLE_TIME)
1577 size += sizeof(data->time);
1579 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1580 size += sizeof(data->id);
1582 if (sample_type & PERF_SAMPLE_ID)
1583 size += sizeof(data->id);
1585 if (sample_type & PERF_SAMPLE_STREAM_ID)
1586 size += sizeof(data->stream_id);
1588 if (sample_type & PERF_SAMPLE_CPU)
1589 size += sizeof(data->cpu_entry);
1591 event->id_header_size = size;
1594 static bool perf_event_validate_size(struct perf_event *event)
1597 * The values computed here will be over-written when we actually
1600 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1601 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1602 perf_event__id_header_size(event);
1605 * Sum the lot; should not exceed the 64k limit we have on records.
1606 * Conservative limit to allow for callchains and other variable fields.
1608 if (event->read_size + event->header_size +
1609 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1615 static void perf_group_attach(struct perf_event *event)
1617 struct perf_event *group_leader = event->group_leader, *pos;
1620 * We can have double attach due to group movement in perf_event_open.
1622 if (event->attach_state & PERF_ATTACH_GROUP)
1625 event->attach_state |= PERF_ATTACH_GROUP;
1627 if (group_leader == event)
1630 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1632 group_leader->group_caps &= event->event_caps;
1634 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1635 group_leader->nr_siblings++;
1637 perf_event__header_size(group_leader);
1639 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1640 perf_event__header_size(pos);
1644 * Remove a event from the lists for its context.
1645 * Must be called with ctx->mutex and ctx->lock held.
1648 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1650 WARN_ON_ONCE(event->ctx != ctx);
1651 lockdep_assert_held(&ctx->lock);
1654 * We can have double detach due to exit/hot-unplug + close.
1656 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1659 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1661 list_update_cgroup_event(event, ctx, false);
1664 if (event->attr.inherit_stat)
1667 list_del_rcu(&event->event_entry);
1669 if (event->group_leader == event)
1670 list_del_init(&event->group_entry);
1672 update_group_times(event);
1675 * If event was in error state, then keep it
1676 * that way, otherwise bogus counts will be
1677 * returned on read(). The only way to get out
1678 * of error state is by explicit re-enabling
1681 if (event->state > PERF_EVENT_STATE_OFF)
1682 event->state = PERF_EVENT_STATE_OFF;
1687 static void perf_group_detach(struct perf_event *event)
1689 struct perf_event *sibling, *tmp;
1690 struct list_head *list = NULL;
1693 * We can have double detach due to exit/hot-unplug + close.
1695 if (!(event->attach_state & PERF_ATTACH_GROUP))
1698 event->attach_state &= ~PERF_ATTACH_GROUP;
1701 * If this is a sibling, remove it from its group.
1703 if (event->group_leader != event) {
1704 list_del_init(&event->group_entry);
1705 event->group_leader->nr_siblings--;
1709 if (!list_empty(&event->group_entry))
1710 list = &event->group_entry;
1713 * If this was a group event with sibling events then
1714 * upgrade the siblings to singleton events by adding them
1715 * to whatever list we are on.
1717 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1719 list_move_tail(&sibling->group_entry, list);
1720 sibling->group_leader = sibling;
1722 /* Inherit group flags from the previous leader */
1723 sibling->group_caps = event->group_caps;
1725 WARN_ON_ONCE(sibling->ctx != event->ctx);
1729 perf_event__header_size(event->group_leader);
1731 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1732 perf_event__header_size(tmp);
1735 static bool is_orphaned_event(struct perf_event *event)
1737 return event->state == PERF_EVENT_STATE_DEAD;
1740 static inline int __pmu_filter_match(struct perf_event *event)
1742 struct pmu *pmu = event->pmu;
1743 return pmu->filter_match ? pmu->filter_match(event) : 1;
1747 * Check whether we should attempt to schedule an event group based on
1748 * PMU-specific filtering. An event group can consist of HW and SW events,
1749 * potentially with a SW leader, so we must check all the filters, to
1750 * determine whether a group is schedulable:
1752 static inline int pmu_filter_match(struct perf_event *event)
1754 struct perf_event *child;
1756 if (!__pmu_filter_match(event))
1759 list_for_each_entry(child, &event->sibling_list, group_entry) {
1760 if (!__pmu_filter_match(child))
1768 event_filter_match(struct perf_event *event)
1770 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
1771 perf_cgroup_match(event) && pmu_filter_match(event);
1775 event_sched_out(struct perf_event *event,
1776 struct perf_cpu_context *cpuctx,
1777 struct perf_event_context *ctx)
1779 u64 tstamp = perf_event_time(event);
1782 WARN_ON_ONCE(event->ctx != ctx);
1783 lockdep_assert_held(&ctx->lock);
1786 * An event which could not be activated because of
1787 * filter mismatch still needs to have its timings
1788 * maintained, otherwise bogus information is return
1789 * via read() for time_enabled, time_running:
1791 if (event->state == PERF_EVENT_STATE_INACTIVE &&
1792 !event_filter_match(event)) {
1793 delta = tstamp - event->tstamp_stopped;
1794 event->tstamp_running += delta;
1795 event->tstamp_stopped = tstamp;
1798 if (event->state != PERF_EVENT_STATE_ACTIVE)
1801 perf_pmu_disable(event->pmu);
1803 event->tstamp_stopped = tstamp;
1804 event->pmu->del(event, 0);
1806 event->state = PERF_EVENT_STATE_INACTIVE;
1807 if (event->pending_disable) {
1808 event->pending_disable = 0;
1809 event->state = PERF_EVENT_STATE_OFF;
1812 if (!is_software_event(event))
1813 cpuctx->active_oncpu--;
1814 if (!--ctx->nr_active)
1815 perf_event_ctx_deactivate(ctx);
1816 if (event->attr.freq && event->attr.sample_freq)
1818 if (event->attr.exclusive || !cpuctx->active_oncpu)
1819 cpuctx->exclusive = 0;
1821 perf_pmu_enable(event->pmu);
1825 group_sched_out(struct perf_event *group_event,
1826 struct perf_cpu_context *cpuctx,
1827 struct perf_event_context *ctx)
1829 struct perf_event *event;
1830 int state = group_event->state;
1832 perf_pmu_disable(ctx->pmu);
1834 event_sched_out(group_event, cpuctx, ctx);
1837 * Schedule out siblings (if any):
1839 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1840 event_sched_out(event, cpuctx, ctx);
1842 perf_pmu_enable(ctx->pmu);
1844 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1845 cpuctx->exclusive = 0;
1848 #define DETACH_GROUP 0x01UL
1851 * Cross CPU call to remove a performance event
1853 * We disable the event on the hardware level first. After that we
1854 * remove it from the context list.
1857 __perf_remove_from_context(struct perf_event *event,
1858 struct perf_cpu_context *cpuctx,
1859 struct perf_event_context *ctx,
1862 unsigned long flags = (unsigned long)info;
1864 event_sched_out(event, cpuctx, ctx);
1865 if (flags & DETACH_GROUP)
1866 perf_group_detach(event);
1867 list_del_event(event, ctx);
1869 if (!ctx->nr_events && ctx->is_active) {
1872 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1873 cpuctx->task_ctx = NULL;
1879 * Remove the event from a task's (or a CPU's) list of events.
1881 * If event->ctx is a cloned context, callers must make sure that
1882 * every task struct that event->ctx->task could possibly point to
1883 * remains valid. This is OK when called from perf_release since
1884 * that only calls us on the top-level context, which can't be a clone.
1885 * When called from perf_event_exit_task, it's OK because the
1886 * context has been detached from its task.
1888 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1890 lockdep_assert_held(&event->ctx->mutex);
1892 event_function_call(event, __perf_remove_from_context, (void *)flags);
1896 * Cross CPU call to disable a performance event
1898 static void __perf_event_disable(struct perf_event *event,
1899 struct perf_cpu_context *cpuctx,
1900 struct perf_event_context *ctx,
1903 if (event->state < PERF_EVENT_STATE_INACTIVE)
1906 update_context_time(ctx);
1907 update_cgrp_time_from_event(event);
1908 update_group_times(event);
1909 if (event == event->group_leader)
1910 group_sched_out(event, cpuctx, ctx);
1912 event_sched_out(event, cpuctx, ctx);
1913 event->state = PERF_EVENT_STATE_OFF;
1919 * If event->ctx is a cloned context, callers must make sure that
1920 * every task struct that event->ctx->task could possibly point to
1921 * remains valid. This condition is satisifed when called through
1922 * perf_event_for_each_child or perf_event_for_each because they
1923 * hold the top-level event's child_mutex, so any descendant that
1924 * goes to exit will block in perf_event_exit_event().
1926 * When called from perf_pending_event it's OK because event->ctx
1927 * is the current context on this CPU and preemption is disabled,
1928 * hence we can't get into perf_event_task_sched_out for this context.
1930 static void _perf_event_disable(struct perf_event *event)
1932 struct perf_event_context *ctx = event->ctx;
1934 raw_spin_lock_irq(&ctx->lock);
1935 if (event->state <= PERF_EVENT_STATE_OFF) {
1936 raw_spin_unlock_irq(&ctx->lock);
1939 raw_spin_unlock_irq(&ctx->lock);
1941 event_function_call(event, __perf_event_disable, NULL);
1944 void perf_event_disable_local(struct perf_event *event)
1946 event_function_local(event, __perf_event_disable, NULL);
1950 * Strictly speaking kernel users cannot create groups and therefore this
1951 * interface does not need the perf_event_ctx_lock() magic.
1953 void perf_event_disable(struct perf_event *event)
1955 struct perf_event_context *ctx;
1957 ctx = perf_event_ctx_lock(event);
1958 _perf_event_disable(event);
1959 perf_event_ctx_unlock(event, ctx);
1961 EXPORT_SYMBOL_GPL(perf_event_disable);
1963 void perf_event_disable_inatomic(struct perf_event *event)
1965 event->pending_disable = 1;
1966 irq_work_queue(&event->pending);
1969 static void perf_set_shadow_time(struct perf_event *event,
1970 struct perf_event_context *ctx,
1974 * use the correct time source for the time snapshot
1976 * We could get by without this by leveraging the
1977 * fact that to get to this function, the caller
1978 * has most likely already called update_context_time()
1979 * and update_cgrp_time_xx() and thus both timestamp
1980 * are identical (or very close). Given that tstamp is,
1981 * already adjusted for cgroup, we could say that:
1982 * tstamp - ctx->timestamp
1984 * tstamp - cgrp->timestamp.
1986 * Then, in perf_output_read(), the calculation would
1987 * work with no changes because:
1988 * - event is guaranteed scheduled in
1989 * - no scheduled out in between
1990 * - thus the timestamp would be the same
1992 * But this is a bit hairy.
1994 * So instead, we have an explicit cgroup call to remain
1995 * within the time time source all along. We believe it
1996 * is cleaner and simpler to understand.
1998 if (is_cgroup_event(event))
1999 perf_cgroup_set_shadow_time(event, tstamp);
2001 event->shadow_ctx_time = tstamp - ctx->timestamp;
2004 #define MAX_INTERRUPTS (~0ULL)
2006 static void perf_log_throttle(struct perf_event *event, int enable);
2007 static void perf_log_itrace_start(struct perf_event *event);
2010 event_sched_in(struct perf_event *event,
2011 struct perf_cpu_context *cpuctx,
2012 struct perf_event_context *ctx)
2014 u64 tstamp = perf_event_time(event);
2017 lockdep_assert_held(&ctx->lock);
2019 if (event->state <= PERF_EVENT_STATE_OFF)
2022 WRITE_ONCE(event->oncpu, smp_processor_id());
2024 * Order event::oncpu write to happen before the ACTIVE state
2028 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
2031 * Unthrottle events, since we scheduled we might have missed several
2032 * ticks already, also for a heavily scheduling task there is little
2033 * guarantee it'll get a tick in a timely manner.
2035 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2036 perf_log_throttle(event, 1);
2037 event->hw.interrupts = 0;
2041 * The new state must be visible before we turn it on in the hardware:
2045 perf_pmu_disable(event->pmu);
2047 perf_set_shadow_time(event, ctx, tstamp);
2049 perf_log_itrace_start(event);
2051 if (event->pmu->add(event, PERF_EF_START)) {
2052 event->state = PERF_EVENT_STATE_INACTIVE;
2058 event->tstamp_running += tstamp - event->tstamp_stopped;
2060 if (!is_software_event(event))
2061 cpuctx->active_oncpu++;
2062 if (!ctx->nr_active++)
2063 perf_event_ctx_activate(ctx);
2064 if (event->attr.freq && event->attr.sample_freq)
2067 if (event->attr.exclusive)
2068 cpuctx->exclusive = 1;
2071 perf_pmu_enable(event->pmu);
2077 group_sched_in(struct perf_event *group_event,
2078 struct perf_cpu_context *cpuctx,
2079 struct perf_event_context *ctx)
2081 struct perf_event *event, *partial_group = NULL;
2082 struct pmu *pmu = ctx->pmu;
2083 u64 now = ctx->time;
2084 bool simulate = false;
2086 if (group_event->state == PERF_EVENT_STATE_OFF)
2089 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2091 if (event_sched_in(group_event, cpuctx, ctx)) {
2092 pmu->cancel_txn(pmu);
2093 perf_mux_hrtimer_restart(cpuctx);
2098 * Schedule in siblings as one group (if any):
2100 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2101 if (event_sched_in(event, cpuctx, ctx)) {
2102 partial_group = event;
2107 if (!pmu->commit_txn(pmu))
2112 * Groups can be scheduled in as one unit only, so undo any
2113 * partial group before returning:
2114 * The events up to the failed event are scheduled out normally,
2115 * tstamp_stopped will be updated.
2117 * The failed events and the remaining siblings need to have
2118 * their timings updated as if they had gone thru event_sched_in()
2119 * and event_sched_out(). This is required to get consistent timings
2120 * across the group. This also takes care of the case where the group
2121 * could never be scheduled by ensuring tstamp_stopped is set to mark
2122 * the time the event was actually stopped, such that time delta
2123 * calculation in update_event_times() is correct.
2125 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2126 if (event == partial_group)
2130 event->tstamp_running += now - event->tstamp_stopped;
2131 event->tstamp_stopped = now;
2133 event_sched_out(event, cpuctx, ctx);
2136 event_sched_out(group_event, cpuctx, ctx);
2138 pmu->cancel_txn(pmu);
2140 perf_mux_hrtimer_restart(cpuctx);
2146 * Work out whether we can put this event group on the CPU now.
2148 static int group_can_go_on(struct perf_event *event,
2149 struct perf_cpu_context *cpuctx,
2153 * Groups consisting entirely of software events can always go on.
2155 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2158 * If an exclusive group is already on, no other hardware
2161 if (cpuctx->exclusive)
2164 * If this group is exclusive and there are already
2165 * events on the CPU, it can't go on.
2167 if (event->attr.exclusive && cpuctx->active_oncpu)
2170 * Otherwise, try to add it if all previous groups were able
2176 static void add_event_to_ctx(struct perf_event *event,
2177 struct perf_event_context *ctx)
2179 u64 tstamp = perf_event_time(event);
2181 list_add_event(event, ctx);
2182 perf_group_attach(event);
2183 event->tstamp_enabled = tstamp;
2184 event->tstamp_running = tstamp;
2185 event->tstamp_stopped = tstamp;
2188 static void ctx_sched_out(struct perf_event_context *ctx,
2189 struct perf_cpu_context *cpuctx,
2190 enum event_type_t event_type);
2192 ctx_sched_in(struct perf_event_context *ctx,
2193 struct perf_cpu_context *cpuctx,
2194 enum event_type_t event_type,
2195 struct task_struct *task);
2197 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2198 struct perf_event_context *ctx)
2200 if (!cpuctx->task_ctx)
2203 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2206 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2209 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2210 struct perf_event_context *ctx,
2211 struct task_struct *task)
2213 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2215 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2216 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2218 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2221 static void ctx_resched(struct perf_cpu_context *cpuctx,
2222 struct perf_event_context *task_ctx)
2224 perf_pmu_disable(cpuctx->ctx.pmu);
2226 task_ctx_sched_out(cpuctx, task_ctx);
2227 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2228 perf_event_sched_in(cpuctx, task_ctx, current);
2229 perf_pmu_enable(cpuctx->ctx.pmu);
2233 * Cross CPU call to install and enable a performance event
2235 * Very similar to remote_function() + event_function() but cannot assume that
2236 * things like ctx->is_active and cpuctx->task_ctx are set.
2238 static int __perf_install_in_context(void *info)
2240 struct perf_event *event = info;
2241 struct perf_event_context *ctx = event->ctx;
2242 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2243 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2244 bool activate = true;
2247 raw_spin_lock(&cpuctx->ctx.lock);
2249 raw_spin_lock(&ctx->lock);
2252 /* If we're on the wrong CPU, try again */
2253 if (task_cpu(ctx->task) != smp_processor_id()) {
2259 * If we're on the right CPU, see if the task we target is
2260 * current, if not we don't have to activate the ctx, a future
2261 * context switch will do that for us.
2263 if (ctx->task != current)
2266 WARN_ON_ONCE(cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2268 } else if (task_ctx) {
2269 raw_spin_lock(&task_ctx->lock);
2273 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2274 add_event_to_ctx(event, ctx);
2275 ctx_resched(cpuctx, task_ctx);
2277 add_event_to_ctx(event, ctx);
2281 perf_ctx_unlock(cpuctx, task_ctx);
2287 * Attach a performance event to a context.
2289 * Very similar to event_function_call, see comment there.
2292 perf_install_in_context(struct perf_event_context *ctx,
2293 struct perf_event *event,
2296 struct task_struct *task = READ_ONCE(ctx->task);
2298 lockdep_assert_held(&ctx->mutex);
2300 if (event->cpu != -1)
2304 * Ensures that if we can observe event->ctx, both the event and ctx
2305 * will be 'complete'. See perf_iterate_sb_cpu().
2307 smp_store_release(&event->ctx, ctx);
2310 cpu_function_call(cpu, __perf_install_in_context, event);
2315 * Should not happen, we validate the ctx is still alive before calling.
2317 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2321 * Installing events is tricky because we cannot rely on ctx->is_active
2322 * to be set in case this is the nr_events 0 -> 1 transition.
2326 * Cannot use task_function_call() because we need to run on the task's
2327 * CPU regardless of whether its current or not.
2329 if (!cpu_function_call(task_cpu(task), __perf_install_in_context, event))
2332 raw_spin_lock_irq(&ctx->lock);
2334 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2336 * Cannot happen because we already checked above (which also
2337 * cannot happen), and we hold ctx->mutex, which serializes us
2338 * against perf_event_exit_task_context().
2340 raw_spin_unlock_irq(&ctx->lock);
2343 raw_spin_unlock_irq(&ctx->lock);
2345 * Since !ctx->is_active doesn't mean anything, we must IPI
2352 * Put a event into inactive state and update time fields.
2353 * Enabling the leader of a group effectively enables all
2354 * the group members that aren't explicitly disabled, so we
2355 * have to update their ->tstamp_enabled also.
2356 * Note: this works for group members as well as group leaders
2357 * since the non-leader members' sibling_lists will be empty.
2359 static void __perf_event_mark_enabled(struct perf_event *event)
2361 struct perf_event *sub;
2362 u64 tstamp = perf_event_time(event);
2364 event->state = PERF_EVENT_STATE_INACTIVE;
2365 event->tstamp_enabled = tstamp - event->total_time_enabled;
2366 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2367 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2368 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2373 * Cross CPU call to enable a performance event
2375 static void __perf_event_enable(struct perf_event *event,
2376 struct perf_cpu_context *cpuctx,
2377 struct perf_event_context *ctx,
2380 struct perf_event *leader = event->group_leader;
2381 struct perf_event_context *task_ctx;
2383 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2384 event->state <= PERF_EVENT_STATE_ERROR)
2388 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2390 __perf_event_mark_enabled(event);
2392 if (!ctx->is_active)
2395 if (!event_filter_match(event)) {
2396 if (is_cgroup_event(event))
2397 perf_cgroup_defer_enabled(event);
2398 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2403 * If the event is in a group and isn't the group leader,
2404 * then don't put it on unless the group is on.
2406 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2407 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2411 task_ctx = cpuctx->task_ctx;
2413 WARN_ON_ONCE(task_ctx != ctx);
2415 ctx_resched(cpuctx, task_ctx);
2421 * If event->ctx is a cloned context, callers must make sure that
2422 * every task struct that event->ctx->task could possibly point to
2423 * remains valid. This condition is satisfied when called through
2424 * perf_event_for_each_child or perf_event_for_each as described
2425 * for perf_event_disable.
2427 static void _perf_event_enable(struct perf_event *event)
2429 struct perf_event_context *ctx = event->ctx;
2431 raw_spin_lock_irq(&ctx->lock);
2432 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2433 event->state < PERF_EVENT_STATE_ERROR) {
2434 raw_spin_unlock_irq(&ctx->lock);
2439 * If the event is in error state, clear that first.
2441 * That way, if we see the event in error state below, we know that it
2442 * has gone back into error state, as distinct from the task having
2443 * been scheduled away before the cross-call arrived.
2445 if (event->state == PERF_EVENT_STATE_ERROR)
2446 event->state = PERF_EVENT_STATE_OFF;
2447 raw_spin_unlock_irq(&ctx->lock);
2449 event_function_call(event, __perf_event_enable, NULL);
2453 * See perf_event_disable();
2455 void perf_event_enable(struct perf_event *event)
2457 struct perf_event_context *ctx;
2459 ctx = perf_event_ctx_lock(event);
2460 _perf_event_enable(event);
2461 perf_event_ctx_unlock(event, ctx);
2463 EXPORT_SYMBOL_GPL(perf_event_enable);
2465 struct stop_event_data {
2466 struct perf_event *event;
2467 unsigned int restart;
2470 static int __perf_event_stop(void *info)
2472 struct stop_event_data *sd = info;
2473 struct perf_event *event = sd->event;
2475 /* if it's already INACTIVE, do nothing */
2476 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2479 /* matches smp_wmb() in event_sched_in() */
2483 * There is a window with interrupts enabled before we get here,
2484 * so we need to check again lest we try to stop another CPU's event.
2486 if (READ_ONCE(event->oncpu) != smp_processor_id())
2489 event->pmu->stop(event, PERF_EF_UPDATE);
2492 * May race with the actual stop (through perf_pmu_output_stop()),
2493 * but it is only used for events with AUX ring buffer, and such
2494 * events will refuse to restart because of rb::aux_mmap_count==0,
2495 * see comments in perf_aux_output_begin().
2497 * Since this is happening on a event-local CPU, no trace is lost
2501 event->pmu->start(event, 0);
2506 static int perf_event_stop(struct perf_event *event, int restart)
2508 struct stop_event_data sd = {
2515 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2518 /* matches smp_wmb() in event_sched_in() */
2522 * We only want to restart ACTIVE events, so if the event goes
2523 * inactive here (event->oncpu==-1), there's nothing more to do;
2524 * fall through with ret==-ENXIO.
2526 ret = cpu_function_call(READ_ONCE(event->oncpu),
2527 __perf_event_stop, &sd);
2528 } while (ret == -EAGAIN);
2534 * In order to contain the amount of racy and tricky in the address filter
2535 * configuration management, it is a two part process:
2537 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2538 * we update the addresses of corresponding vmas in
2539 * event::addr_filters_offs array and bump the event::addr_filters_gen;
2540 * (p2) when an event is scheduled in (pmu::add), it calls
2541 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2542 * if the generation has changed since the previous call.
2544 * If (p1) happens while the event is active, we restart it to force (p2).
2546 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2547 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2549 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2550 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2552 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2555 void perf_event_addr_filters_sync(struct perf_event *event)
2557 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2559 if (!has_addr_filter(event))
2562 raw_spin_lock(&ifh->lock);
2563 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2564 event->pmu->addr_filters_sync(event);
2565 event->hw.addr_filters_gen = event->addr_filters_gen;
2567 raw_spin_unlock(&ifh->lock);
2569 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2571 static int _perf_event_refresh(struct perf_event *event, int refresh)
2574 * not supported on inherited events
2576 if (event->attr.inherit || !is_sampling_event(event))
2579 atomic_add(refresh, &event->event_limit);
2580 _perf_event_enable(event);
2586 * See perf_event_disable()
2588 int perf_event_refresh(struct perf_event *event, int refresh)
2590 struct perf_event_context *ctx;
2593 ctx = perf_event_ctx_lock(event);
2594 ret = _perf_event_refresh(event, refresh);
2595 perf_event_ctx_unlock(event, ctx);
2599 EXPORT_SYMBOL_GPL(perf_event_refresh);
2601 static void ctx_sched_out(struct perf_event_context *ctx,
2602 struct perf_cpu_context *cpuctx,
2603 enum event_type_t event_type)
2605 int is_active = ctx->is_active;
2606 struct perf_event *event;
2608 lockdep_assert_held(&ctx->lock);
2610 if (likely(!ctx->nr_events)) {
2612 * See __perf_remove_from_context().
2614 WARN_ON_ONCE(ctx->is_active);
2616 WARN_ON_ONCE(cpuctx->task_ctx);
2620 ctx->is_active &= ~event_type;
2621 if (!(ctx->is_active & EVENT_ALL))
2625 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2626 if (!ctx->is_active)
2627 cpuctx->task_ctx = NULL;
2631 * Always update time if it was set; not only when it changes.
2632 * Otherwise we can 'forget' to update time for any but the last
2633 * context we sched out. For example:
2635 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2636 * ctx_sched_out(.event_type = EVENT_PINNED)
2638 * would only update time for the pinned events.
2640 if (is_active & EVENT_TIME) {
2641 /* update (and stop) ctx time */
2642 update_context_time(ctx);
2643 update_cgrp_time_from_cpuctx(cpuctx);
2646 is_active ^= ctx->is_active; /* changed bits */
2648 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2651 perf_pmu_disable(ctx->pmu);
2652 if (is_active & EVENT_PINNED) {
2653 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2654 group_sched_out(event, cpuctx, ctx);
2657 if (is_active & EVENT_FLEXIBLE) {
2658 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2659 group_sched_out(event, cpuctx, ctx);
2661 perf_pmu_enable(ctx->pmu);
2665 * Test whether two contexts are equivalent, i.e. whether they have both been
2666 * cloned from the same version of the same context.
2668 * Equivalence is measured using a generation number in the context that is
2669 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2670 * and list_del_event().
2672 static int context_equiv(struct perf_event_context *ctx1,
2673 struct perf_event_context *ctx2)
2675 lockdep_assert_held(&ctx1->lock);
2676 lockdep_assert_held(&ctx2->lock);
2678 /* Pinning disables the swap optimization */
2679 if (ctx1->pin_count || ctx2->pin_count)
2682 /* If ctx1 is the parent of ctx2 */
2683 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2686 /* If ctx2 is the parent of ctx1 */
2687 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2691 * If ctx1 and ctx2 have the same parent; we flatten the parent
2692 * hierarchy, see perf_event_init_context().
2694 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2695 ctx1->parent_gen == ctx2->parent_gen)
2702 static void __perf_event_sync_stat(struct perf_event *event,
2703 struct perf_event *next_event)
2707 if (!event->attr.inherit_stat)
2711 * Update the event value, we cannot use perf_event_read()
2712 * because we're in the middle of a context switch and have IRQs
2713 * disabled, which upsets smp_call_function_single(), however
2714 * we know the event must be on the current CPU, therefore we
2715 * don't need to use it.
2717 switch (event->state) {
2718 case PERF_EVENT_STATE_ACTIVE:
2719 event->pmu->read(event);
2722 case PERF_EVENT_STATE_INACTIVE:
2723 update_event_times(event);
2731 * In order to keep per-task stats reliable we need to flip the event
2732 * values when we flip the contexts.
2734 value = local64_read(&next_event->count);
2735 value = local64_xchg(&event->count, value);
2736 local64_set(&next_event->count, value);
2738 swap(event->total_time_enabled, next_event->total_time_enabled);
2739 swap(event->total_time_running, next_event->total_time_running);
2742 * Since we swizzled the values, update the user visible data too.
2744 perf_event_update_userpage(event);
2745 perf_event_update_userpage(next_event);
2748 static void perf_event_sync_stat(struct perf_event_context *ctx,
2749 struct perf_event_context *next_ctx)
2751 struct perf_event *event, *next_event;
2756 update_context_time(ctx);
2758 event = list_first_entry(&ctx->event_list,
2759 struct perf_event, event_entry);
2761 next_event = list_first_entry(&next_ctx->event_list,
2762 struct perf_event, event_entry);
2764 while (&event->event_entry != &ctx->event_list &&
2765 &next_event->event_entry != &next_ctx->event_list) {
2767 __perf_event_sync_stat(event, next_event);
2769 event = list_next_entry(event, event_entry);
2770 next_event = list_next_entry(next_event, event_entry);
2774 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2775 struct task_struct *next)
2777 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2778 struct perf_event_context *next_ctx;
2779 struct perf_event_context *parent, *next_parent;
2780 struct perf_cpu_context *cpuctx;
2786 cpuctx = __get_cpu_context(ctx);
2787 if (!cpuctx->task_ctx)
2791 next_ctx = next->perf_event_ctxp[ctxn];
2795 parent = rcu_dereference(ctx->parent_ctx);
2796 next_parent = rcu_dereference(next_ctx->parent_ctx);
2798 /* If neither context have a parent context; they cannot be clones. */
2799 if (!parent && !next_parent)
2802 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2804 * Looks like the two contexts are clones, so we might be
2805 * able to optimize the context switch. We lock both
2806 * contexts and check that they are clones under the
2807 * lock (including re-checking that neither has been
2808 * uncloned in the meantime). It doesn't matter which
2809 * order we take the locks because no other cpu could
2810 * be trying to lock both of these tasks.
2812 raw_spin_lock(&ctx->lock);
2813 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2814 if (context_equiv(ctx, next_ctx)) {
2815 WRITE_ONCE(ctx->task, next);
2816 WRITE_ONCE(next_ctx->task, task);
2818 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2821 * RCU_INIT_POINTER here is safe because we've not
2822 * modified the ctx and the above modification of
2823 * ctx->task and ctx->task_ctx_data are immaterial
2824 * since those values are always verified under
2825 * ctx->lock which we're now holding.
2827 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2828 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2832 perf_event_sync_stat(ctx, next_ctx);
2834 raw_spin_unlock(&next_ctx->lock);
2835 raw_spin_unlock(&ctx->lock);
2841 raw_spin_lock(&ctx->lock);
2842 task_ctx_sched_out(cpuctx, ctx);
2843 raw_spin_unlock(&ctx->lock);
2847 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
2849 void perf_sched_cb_dec(struct pmu *pmu)
2851 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2853 this_cpu_dec(perf_sched_cb_usages);
2855 if (!--cpuctx->sched_cb_usage)
2856 list_del(&cpuctx->sched_cb_entry);
2860 void perf_sched_cb_inc(struct pmu *pmu)
2862 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2864 if (!cpuctx->sched_cb_usage++)
2865 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
2867 this_cpu_inc(perf_sched_cb_usages);
2871 * This function provides the context switch callback to the lower code
2872 * layer. It is invoked ONLY when the context switch callback is enabled.
2874 * This callback is relevant even to per-cpu events; for example multi event
2875 * PEBS requires this to provide PID/TID information. This requires we flush
2876 * all queued PEBS records before we context switch to a new task.
2878 static void perf_pmu_sched_task(struct task_struct *prev,
2879 struct task_struct *next,
2882 struct perf_cpu_context *cpuctx;
2888 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
2889 pmu = cpuctx->unique_pmu; /* software PMUs will not have sched_task */
2891 if (WARN_ON_ONCE(!pmu->sched_task))
2894 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2895 perf_pmu_disable(pmu);
2897 pmu->sched_task(cpuctx->task_ctx, sched_in);
2899 perf_pmu_enable(pmu);
2900 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2904 static void perf_event_switch(struct task_struct *task,
2905 struct task_struct *next_prev, bool sched_in);
2907 #define for_each_task_context_nr(ctxn) \
2908 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2911 * Called from scheduler to remove the events of the current task,
2912 * with interrupts disabled.
2914 * We stop each event and update the event value in event->count.
2916 * This does not protect us against NMI, but disable()
2917 * sets the disabled bit in the control field of event _before_
2918 * accessing the event control register. If a NMI hits, then it will
2919 * not restart the event.
2921 void __perf_event_task_sched_out(struct task_struct *task,
2922 struct task_struct *next)
2926 if (__this_cpu_read(perf_sched_cb_usages))
2927 perf_pmu_sched_task(task, next, false);
2929 if (atomic_read(&nr_switch_events))
2930 perf_event_switch(task, next, false);
2932 for_each_task_context_nr(ctxn)
2933 perf_event_context_sched_out(task, ctxn, next);
2936 * if cgroup events exist on this CPU, then we need
2937 * to check if we have to switch out PMU state.
2938 * cgroup event are system-wide mode only
2940 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2941 perf_cgroup_sched_out(task, next);
2945 * Called with IRQs disabled
2947 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2948 enum event_type_t event_type)
2950 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2954 ctx_pinned_sched_in(struct perf_event_context *ctx,
2955 struct perf_cpu_context *cpuctx)
2957 struct perf_event *event;
2959 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2960 if (event->state <= PERF_EVENT_STATE_OFF)
2962 if (!event_filter_match(event))
2965 /* may need to reset tstamp_enabled */
2966 if (is_cgroup_event(event))
2967 perf_cgroup_mark_enabled(event, ctx);
2969 if (group_can_go_on(event, cpuctx, 1))
2970 group_sched_in(event, cpuctx, ctx);
2973 * If this pinned group hasn't been scheduled,
2974 * put it in error state.
2976 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2977 update_group_times(event);
2978 event->state = PERF_EVENT_STATE_ERROR;
2984 ctx_flexible_sched_in(struct perf_event_context *ctx,
2985 struct perf_cpu_context *cpuctx)
2987 struct perf_event *event;
2990 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2991 /* Ignore events in OFF or ERROR state */
2992 if (event->state <= PERF_EVENT_STATE_OFF)
2995 * Listen to the 'cpu' scheduling filter constraint
2998 if (!event_filter_match(event))
3001 /* may need to reset tstamp_enabled */
3002 if (is_cgroup_event(event))
3003 perf_cgroup_mark_enabled(event, ctx);
3005 if (group_can_go_on(event, cpuctx, can_add_hw)) {
3006 if (group_sched_in(event, cpuctx, ctx))
3013 ctx_sched_in(struct perf_event_context *ctx,
3014 struct perf_cpu_context *cpuctx,
3015 enum event_type_t event_type,
3016 struct task_struct *task)
3018 int is_active = ctx->is_active;
3021 lockdep_assert_held(&ctx->lock);
3023 if (likely(!ctx->nr_events))
3026 ctx->is_active |= (event_type | EVENT_TIME);
3029 cpuctx->task_ctx = ctx;
3031 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3034 is_active ^= ctx->is_active; /* changed bits */
3036 if (is_active & EVENT_TIME) {
3037 /* start ctx time */
3039 ctx->timestamp = now;
3040 perf_cgroup_set_timestamp(task, ctx);
3044 * First go through the list and put on any pinned groups
3045 * in order to give them the best chance of going on.
3047 if (is_active & EVENT_PINNED)
3048 ctx_pinned_sched_in(ctx, cpuctx);
3050 /* Then walk through the lower prio flexible groups */
3051 if (is_active & EVENT_FLEXIBLE)
3052 ctx_flexible_sched_in(ctx, cpuctx);
3055 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3056 enum event_type_t event_type,
3057 struct task_struct *task)
3059 struct perf_event_context *ctx = &cpuctx->ctx;
3061 ctx_sched_in(ctx, cpuctx, event_type, task);
3064 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3065 struct task_struct *task)
3067 struct perf_cpu_context *cpuctx;
3069 cpuctx = __get_cpu_context(ctx);
3070 if (cpuctx->task_ctx == ctx)
3073 perf_ctx_lock(cpuctx, ctx);
3074 perf_pmu_disable(ctx->pmu);
3076 * We want to keep the following priority order:
3077 * cpu pinned (that don't need to move), task pinned,
3078 * cpu flexible, task flexible.
3080 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3081 perf_event_sched_in(cpuctx, ctx, task);
3082 perf_pmu_enable(ctx->pmu);
3083 perf_ctx_unlock(cpuctx, ctx);
3087 * Called from scheduler to add the events of the current task
3088 * with interrupts disabled.
3090 * We restore the event value and then enable it.
3092 * This does not protect us against NMI, but enable()
3093 * sets the enabled bit in the control field of event _before_
3094 * accessing the event control register. If a NMI hits, then it will
3095 * keep the event running.
3097 void __perf_event_task_sched_in(struct task_struct *prev,
3098 struct task_struct *task)
3100 struct perf_event_context *ctx;
3104 * If cgroup events exist on this CPU, then we need to check if we have
3105 * to switch in PMU state; cgroup event are system-wide mode only.
3107 * Since cgroup events are CPU events, we must schedule these in before
3108 * we schedule in the task events.
3110 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3111 perf_cgroup_sched_in(prev, task);
3113 for_each_task_context_nr(ctxn) {
3114 ctx = task->perf_event_ctxp[ctxn];
3118 perf_event_context_sched_in(ctx, task);
3121 if (atomic_read(&nr_switch_events))
3122 perf_event_switch(task, prev, true);
3124 if (__this_cpu_read(perf_sched_cb_usages))
3125 perf_pmu_sched_task(prev, task, true);
3128 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3130 u64 frequency = event->attr.sample_freq;
3131 u64 sec = NSEC_PER_SEC;
3132 u64 divisor, dividend;
3134 int count_fls, nsec_fls, frequency_fls, sec_fls;
3136 count_fls = fls64(count);
3137 nsec_fls = fls64(nsec);
3138 frequency_fls = fls64(frequency);
3142 * We got @count in @nsec, with a target of sample_freq HZ
3143 * the target period becomes:
3146 * period = -------------------
3147 * @nsec * sample_freq
3152 * Reduce accuracy by one bit such that @a and @b converge
3153 * to a similar magnitude.
3155 #define REDUCE_FLS(a, b) \
3157 if (a##_fls > b##_fls) { \
3167 * Reduce accuracy until either term fits in a u64, then proceed with
3168 * the other, so that finally we can do a u64/u64 division.
3170 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3171 REDUCE_FLS(nsec, frequency);
3172 REDUCE_FLS(sec, count);
3175 if (count_fls + sec_fls > 64) {
3176 divisor = nsec * frequency;
3178 while (count_fls + sec_fls > 64) {
3179 REDUCE_FLS(count, sec);
3183 dividend = count * sec;
3185 dividend = count * sec;
3187 while (nsec_fls + frequency_fls > 64) {
3188 REDUCE_FLS(nsec, frequency);
3192 divisor = nsec * frequency;
3198 return div64_u64(dividend, divisor);
3201 static DEFINE_PER_CPU(int, perf_throttled_count);
3202 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3204 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3206 struct hw_perf_event *hwc = &event->hw;
3207 s64 period, sample_period;
3210 period = perf_calculate_period(event, nsec, count);
3212 delta = (s64)(period - hwc->sample_period);
3213 delta = (delta + 7) / 8; /* low pass filter */
3215 sample_period = hwc->sample_period + delta;
3220 hwc->sample_period = sample_period;
3222 if (local64_read(&hwc->period_left) > 8*sample_period) {
3224 event->pmu->stop(event, PERF_EF_UPDATE);
3226 local64_set(&hwc->period_left, 0);
3229 event->pmu->start(event, PERF_EF_RELOAD);
3234 * combine freq adjustment with unthrottling to avoid two passes over the
3235 * events. At the same time, make sure, having freq events does not change
3236 * the rate of unthrottling as that would introduce bias.
3238 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3241 struct perf_event *event;
3242 struct hw_perf_event *hwc;
3243 u64 now, period = TICK_NSEC;
3247 * only need to iterate over all events iff:
3248 * - context have events in frequency mode (needs freq adjust)
3249 * - there are events to unthrottle on this cpu
3251 if (!(ctx->nr_freq || needs_unthr))
3254 raw_spin_lock(&ctx->lock);
3255 perf_pmu_disable(ctx->pmu);
3257 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3258 if (event->state != PERF_EVENT_STATE_ACTIVE)
3261 if (!event_filter_match(event))
3264 perf_pmu_disable(event->pmu);
3268 if (hwc->interrupts == MAX_INTERRUPTS) {
3269 hwc->interrupts = 0;
3270 perf_log_throttle(event, 1);
3271 event->pmu->start(event, 0);
3274 if (!event->attr.freq || !event->attr.sample_freq)
3278 * stop the event and update event->count
3280 event->pmu->stop(event, PERF_EF_UPDATE);
3282 now = local64_read(&event->count);
3283 delta = now - hwc->freq_count_stamp;
3284 hwc->freq_count_stamp = now;
3288 * reload only if value has changed
3289 * we have stopped the event so tell that
3290 * to perf_adjust_period() to avoid stopping it
3294 perf_adjust_period(event, period, delta, false);
3296 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3298 perf_pmu_enable(event->pmu);
3301 perf_pmu_enable(ctx->pmu);
3302 raw_spin_unlock(&ctx->lock);
3306 * Round-robin a context's events:
3308 static void rotate_ctx(struct perf_event_context *ctx)
3311 * Rotate the first entry last of non-pinned groups. Rotation might be
3312 * disabled by the inheritance code.
3314 if (!ctx->rotate_disable)
3315 list_rotate_left(&ctx->flexible_groups);
3318 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3320 struct perf_event_context *ctx = NULL;
3323 if (cpuctx->ctx.nr_events) {
3324 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3328 ctx = cpuctx->task_ctx;
3329 if (ctx && ctx->nr_events) {
3330 if (ctx->nr_events != ctx->nr_active)
3337 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3338 perf_pmu_disable(cpuctx->ctx.pmu);
3340 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3342 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3344 rotate_ctx(&cpuctx->ctx);
3348 perf_event_sched_in(cpuctx, ctx, current);
3350 perf_pmu_enable(cpuctx->ctx.pmu);
3351 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3357 void perf_event_task_tick(void)
3359 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3360 struct perf_event_context *ctx, *tmp;
3363 WARN_ON(!irqs_disabled());
3365 __this_cpu_inc(perf_throttled_seq);
3366 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3367 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3369 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3370 perf_adjust_freq_unthr_context(ctx, throttled);
3373 static int event_enable_on_exec(struct perf_event *event,
3374 struct perf_event_context *ctx)
3376 if (!event->attr.enable_on_exec)
3379 event->attr.enable_on_exec = 0;
3380 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3383 __perf_event_mark_enabled(event);
3389 * Enable all of a task's events that have been marked enable-on-exec.
3390 * This expects task == current.
3392 static void perf_event_enable_on_exec(int ctxn)
3394 struct perf_event_context *ctx, *clone_ctx = NULL;
3395 struct perf_cpu_context *cpuctx;
3396 struct perf_event *event;
3397 unsigned long flags;
3400 local_irq_save(flags);
3401 ctx = current->perf_event_ctxp[ctxn];
3402 if (!ctx || !ctx->nr_events)
3405 cpuctx = __get_cpu_context(ctx);
3406 perf_ctx_lock(cpuctx, ctx);
3407 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3408 list_for_each_entry(event, &ctx->event_list, event_entry)
3409 enabled |= event_enable_on_exec(event, ctx);
3412 * Unclone and reschedule this context if we enabled any event.
3415 clone_ctx = unclone_ctx(ctx);
3416 ctx_resched(cpuctx, ctx);
3418 perf_ctx_unlock(cpuctx, ctx);
3421 local_irq_restore(flags);
3427 struct perf_read_data {
3428 struct perf_event *event;
3433 static int find_cpu_to_read(struct perf_event *event, int local_cpu)
3435 int event_cpu = event->oncpu;
3436 u16 local_pkg, event_pkg;
3438 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
3439 event_pkg = topology_physical_package_id(event_cpu);
3440 local_pkg = topology_physical_package_id(local_cpu);
3442 if (event_pkg == local_pkg)
3450 * Cross CPU call to read the hardware event
3452 static void __perf_event_read(void *info)
3454 struct perf_read_data *data = info;
3455 struct perf_event *sub, *event = data->event;
3456 struct perf_event_context *ctx = event->ctx;
3457 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3458 struct pmu *pmu = event->pmu;
3461 * If this is a task context, we need to check whether it is
3462 * the current task context of this cpu. If not it has been
3463 * scheduled out before the smp call arrived. In that case
3464 * event->count would have been updated to a recent sample
3465 * when the event was scheduled out.
3467 if (ctx->task && cpuctx->task_ctx != ctx)
3470 raw_spin_lock(&ctx->lock);
3471 if (ctx->is_active) {
3472 update_context_time(ctx);
3473 update_cgrp_time_from_event(event);
3476 update_event_times(event);
3477 if (event->state != PERF_EVENT_STATE_ACTIVE)
3486 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3490 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3491 update_event_times(sub);
3492 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3494 * Use sibling's PMU rather than @event's since
3495 * sibling could be on different (eg: software) PMU.
3497 sub->pmu->read(sub);
3501 data->ret = pmu->commit_txn(pmu);
3504 raw_spin_unlock(&ctx->lock);
3507 static inline u64 perf_event_count(struct perf_event *event)
3509 if (event->pmu->count)
3510 return event->pmu->count(event);
3512 return __perf_event_count(event);
3516 * NMI-safe method to read a local event, that is an event that
3518 * - either for the current task, or for this CPU
3519 * - does not have inherit set, for inherited task events
3520 * will not be local and we cannot read them atomically
3521 * - must not have a pmu::count method
3523 u64 perf_event_read_local(struct perf_event *event)
3525 unsigned long flags;
3529 * Disabling interrupts avoids all counter scheduling (context
3530 * switches, timer based rotation and IPIs).
3532 local_irq_save(flags);
3534 /* If this is a per-task event, it must be for current */
3535 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3536 event->hw.target != current);
3538 /* If this is a per-CPU event, it must be for this CPU */
3539 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3540 event->cpu != smp_processor_id());
3543 * It must not be an event with inherit set, we cannot read
3544 * all child counters from atomic context.
3546 WARN_ON_ONCE(event->attr.inherit);
3549 * It must not have a pmu::count method, those are not
3552 WARN_ON_ONCE(event->pmu->count);
3555 * If the event is currently on this CPU, its either a per-task event,
3556 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3559 if (event->oncpu == smp_processor_id())
3560 event->pmu->read(event);
3562 val = local64_read(&event->count);
3563 local_irq_restore(flags);
3568 static int perf_event_read(struct perf_event *event, bool group)
3570 int ret = 0, cpu_to_read, local_cpu;
3573 * If event is enabled and currently active on a CPU, update the
3574 * value in the event structure:
3576 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3577 struct perf_read_data data = {
3583 local_cpu = get_cpu();
3584 cpu_to_read = find_cpu_to_read(event, local_cpu);
3588 * Purposely ignore the smp_call_function_single() return
3591 * If event->oncpu isn't a valid CPU it means the event got
3592 * scheduled out and that will have updated the event count.
3594 * Therefore, either way, we'll have an up-to-date event count
3597 (void)smp_call_function_single(cpu_to_read, __perf_event_read, &data, 1);
3599 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3600 struct perf_event_context *ctx = event->ctx;
3601 unsigned long flags;
3603 raw_spin_lock_irqsave(&ctx->lock, flags);
3605 * may read while context is not active
3606 * (e.g., thread is blocked), in that case
3607 * we cannot update context time
3609 if (ctx->is_active) {
3610 update_context_time(ctx);
3611 update_cgrp_time_from_event(event);
3614 update_group_times(event);
3616 update_event_times(event);
3617 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3624 * Initialize the perf_event context in a task_struct:
3626 static void __perf_event_init_context(struct perf_event_context *ctx)
3628 raw_spin_lock_init(&ctx->lock);
3629 mutex_init(&ctx->mutex);
3630 INIT_LIST_HEAD(&ctx->active_ctx_list);
3631 INIT_LIST_HEAD(&ctx->pinned_groups);
3632 INIT_LIST_HEAD(&ctx->flexible_groups);
3633 INIT_LIST_HEAD(&ctx->event_list);
3634 atomic_set(&ctx->refcount, 1);
3637 static struct perf_event_context *
3638 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3640 struct perf_event_context *ctx;
3642 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3646 __perf_event_init_context(ctx);
3649 get_task_struct(task);
3656 static struct task_struct *
3657 find_lively_task_by_vpid(pid_t vpid)
3659 struct task_struct *task;
3665 task = find_task_by_vpid(vpid);
3667 get_task_struct(task);
3671 return ERR_PTR(-ESRCH);
3677 * Returns a matching context with refcount and pincount.
3679 static struct perf_event_context *
3680 find_get_context(struct pmu *pmu, struct task_struct *task,
3681 struct perf_event *event)
3683 struct perf_event_context *ctx, *clone_ctx = NULL;
3684 struct perf_cpu_context *cpuctx;
3685 void *task_ctx_data = NULL;
3686 unsigned long flags;
3688 int cpu = event->cpu;
3691 /* Must be root to operate on a CPU event: */
3692 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3693 return ERR_PTR(-EACCES);
3696 * We could be clever and allow to attach a event to an
3697 * offline CPU and activate it when the CPU comes up, but
3700 if (!cpu_online(cpu))
3701 return ERR_PTR(-ENODEV);
3703 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3712 ctxn = pmu->task_ctx_nr;
3716 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3717 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3718 if (!task_ctx_data) {
3725 ctx = perf_lock_task_context(task, ctxn, &flags);
3727 clone_ctx = unclone_ctx(ctx);
3730 if (task_ctx_data && !ctx->task_ctx_data) {
3731 ctx->task_ctx_data = task_ctx_data;
3732 task_ctx_data = NULL;
3734 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3739 ctx = alloc_perf_context(pmu, task);
3744 if (task_ctx_data) {
3745 ctx->task_ctx_data = task_ctx_data;
3746 task_ctx_data = NULL;
3750 mutex_lock(&task->perf_event_mutex);
3752 * If it has already passed perf_event_exit_task().
3753 * we must see PF_EXITING, it takes this mutex too.
3755 if (task->flags & PF_EXITING)
3757 else if (task->perf_event_ctxp[ctxn])
3762 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3764 mutex_unlock(&task->perf_event_mutex);
3766 if (unlikely(err)) {
3775 kfree(task_ctx_data);
3779 kfree(task_ctx_data);
3780 return ERR_PTR(err);
3783 static void perf_event_free_filter(struct perf_event *event);
3784 static void perf_event_free_bpf_prog(struct perf_event *event);
3786 static void free_event_rcu(struct rcu_head *head)
3788 struct perf_event *event;
3790 event = container_of(head, struct perf_event, rcu_head);
3792 put_pid_ns(event->ns);
3793 perf_event_free_filter(event);
3797 static void ring_buffer_attach(struct perf_event *event,
3798 struct ring_buffer *rb);
3800 static void detach_sb_event(struct perf_event *event)
3802 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
3804 raw_spin_lock(&pel->lock);
3805 list_del_rcu(&event->sb_list);
3806 raw_spin_unlock(&pel->lock);
3809 static bool is_sb_event(struct perf_event *event)
3811 struct perf_event_attr *attr = &event->attr;
3816 if (event->attach_state & PERF_ATTACH_TASK)
3819 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
3820 attr->comm || attr->comm_exec ||
3822 attr->context_switch)
3827 static void unaccount_pmu_sb_event(struct perf_event *event)
3829 if (is_sb_event(event))
3830 detach_sb_event(event);
3833 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3838 if (is_cgroup_event(event))
3839 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3842 #ifdef CONFIG_NO_HZ_FULL
3843 static DEFINE_SPINLOCK(nr_freq_lock);
3846 static void unaccount_freq_event_nohz(void)
3848 #ifdef CONFIG_NO_HZ_FULL
3849 spin_lock(&nr_freq_lock);
3850 if (atomic_dec_and_test(&nr_freq_events))
3851 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
3852 spin_unlock(&nr_freq_lock);
3856 static void unaccount_freq_event(void)
3858 if (tick_nohz_full_enabled())
3859 unaccount_freq_event_nohz();
3861 atomic_dec(&nr_freq_events);
3864 static void unaccount_event(struct perf_event *event)
3871 if (event->attach_state & PERF_ATTACH_TASK)
3873 if (event->attr.mmap || event->attr.mmap_data)
3874 atomic_dec(&nr_mmap_events);
3875 if (event->attr.comm)
3876 atomic_dec(&nr_comm_events);
3877 if (event->attr.task)
3878 atomic_dec(&nr_task_events);
3879 if (event->attr.freq)
3880 unaccount_freq_event();
3881 if (event->attr.context_switch) {
3883 atomic_dec(&nr_switch_events);
3885 if (is_cgroup_event(event))
3887 if (has_branch_stack(event))
3891 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3892 schedule_delayed_work(&perf_sched_work, HZ);
3895 unaccount_event_cpu(event, event->cpu);
3897 unaccount_pmu_sb_event(event);
3900 static void perf_sched_delayed(struct work_struct *work)
3902 mutex_lock(&perf_sched_mutex);
3903 if (atomic_dec_and_test(&perf_sched_count))
3904 static_branch_disable(&perf_sched_events);
3905 mutex_unlock(&perf_sched_mutex);
3909 * The following implement mutual exclusion of events on "exclusive" pmus
3910 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3911 * at a time, so we disallow creating events that might conflict, namely:
3913 * 1) cpu-wide events in the presence of per-task events,
3914 * 2) per-task events in the presence of cpu-wide events,
3915 * 3) two matching events on the same context.
3917 * The former two cases are handled in the allocation path (perf_event_alloc(),
3918 * _free_event()), the latter -- before the first perf_install_in_context().
3920 static int exclusive_event_init(struct perf_event *event)
3922 struct pmu *pmu = event->pmu;
3924 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3928 * Prevent co-existence of per-task and cpu-wide events on the
3929 * same exclusive pmu.
3931 * Negative pmu::exclusive_cnt means there are cpu-wide
3932 * events on this "exclusive" pmu, positive means there are
3935 * Since this is called in perf_event_alloc() path, event::ctx
3936 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3937 * to mean "per-task event", because unlike other attach states it
3938 * never gets cleared.
3940 if (event->attach_state & PERF_ATTACH_TASK) {
3941 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3944 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3951 static void exclusive_event_destroy(struct perf_event *event)
3953 struct pmu *pmu = event->pmu;
3955 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3958 /* see comment in exclusive_event_init() */
3959 if (event->attach_state & PERF_ATTACH_TASK)
3960 atomic_dec(&pmu->exclusive_cnt);
3962 atomic_inc(&pmu->exclusive_cnt);
3965 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3967 if ((e1->pmu == e2->pmu) &&
3968 (e1->cpu == e2->cpu ||
3975 /* Called under the same ctx::mutex as perf_install_in_context() */
3976 static bool exclusive_event_installable(struct perf_event *event,
3977 struct perf_event_context *ctx)
3979 struct perf_event *iter_event;
3980 struct pmu *pmu = event->pmu;
3982 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3985 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3986 if (exclusive_event_match(iter_event, event))
3993 static void perf_addr_filters_splice(struct perf_event *event,
3994 struct list_head *head);
3996 static void _free_event(struct perf_event *event)
3998 irq_work_sync(&event->pending);
4000 unaccount_event(event);
4004 * Can happen when we close an event with re-directed output.
4006 * Since we have a 0 refcount, perf_mmap_close() will skip
4007 * over us; possibly making our ring_buffer_put() the last.
4009 mutex_lock(&event->mmap_mutex);
4010 ring_buffer_attach(event, NULL);
4011 mutex_unlock(&event->mmap_mutex);
4014 if (is_cgroup_event(event))
4015 perf_detach_cgroup(event);
4017 if (!event->parent) {
4018 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4019 put_callchain_buffers();
4022 perf_event_free_bpf_prog(event);
4023 perf_addr_filters_splice(event, NULL);
4024 kfree(event->addr_filters_offs);
4027 event->destroy(event);
4030 put_ctx(event->ctx);
4032 exclusive_event_destroy(event);
4033 module_put(event->pmu->module);
4035 call_rcu(&event->rcu_head, free_event_rcu);
4039 * Used to free events which have a known refcount of 1, such as in error paths
4040 * where the event isn't exposed yet and inherited events.
4042 static void free_event(struct perf_event *event)
4044 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4045 "unexpected event refcount: %ld; ptr=%p\n",
4046 atomic_long_read(&event->refcount), event)) {
4047 /* leak to avoid use-after-free */
4055 * Remove user event from the owner task.
4057 static void perf_remove_from_owner(struct perf_event *event)
4059 struct task_struct *owner;
4063 * Matches the smp_store_release() in perf_event_exit_task(). If we
4064 * observe !owner it means the list deletion is complete and we can
4065 * indeed free this event, otherwise we need to serialize on
4066 * owner->perf_event_mutex.
4068 owner = lockless_dereference(event->owner);
4071 * Since delayed_put_task_struct() also drops the last
4072 * task reference we can safely take a new reference
4073 * while holding the rcu_read_lock().
4075 get_task_struct(owner);
4081 * If we're here through perf_event_exit_task() we're already
4082 * holding ctx->mutex which would be an inversion wrt. the
4083 * normal lock order.
4085 * However we can safely take this lock because its the child
4088 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4091 * We have to re-check the event->owner field, if it is cleared
4092 * we raced with perf_event_exit_task(), acquiring the mutex
4093 * ensured they're done, and we can proceed with freeing the
4097 list_del_init(&event->owner_entry);
4098 smp_store_release(&event->owner, NULL);
4100 mutex_unlock(&owner->perf_event_mutex);
4101 put_task_struct(owner);
4105 static void put_event(struct perf_event *event)
4107 if (!atomic_long_dec_and_test(&event->refcount))
4114 * Kill an event dead; while event:refcount will preserve the event
4115 * object, it will not preserve its functionality. Once the last 'user'
4116 * gives up the object, we'll destroy the thing.
4118 int perf_event_release_kernel(struct perf_event *event)
4120 struct perf_event_context *ctx = event->ctx;
4121 struct perf_event *child, *tmp;
4124 * If we got here through err_file: fput(event_file); we will not have
4125 * attached to a context yet.
4128 WARN_ON_ONCE(event->attach_state &
4129 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4133 if (!is_kernel_event(event))
4134 perf_remove_from_owner(event);
4136 ctx = perf_event_ctx_lock(event);
4137 WARN_ON_ONCE(ctx->parent_ctx);
4138 perf_remove_from_context(event, DETACH_GROUP);
4140 raw_spin_lock_irq(&ctx->lock);
4142 * Mark this even as STATE_DEAD, there is no external reference to it
4145 * Anybody acquiring event->child_mutex after the below loop _must_
4146 * also see this, most importantly inherit_event() which will avoid
4147 * placing more children on the list.
4149 * Thus this guarantees that we will in fact observe and kill _ALL_
4152 event->state = PERF_EVENT_STATE_DEAD;
4153 raw_spin_unlock_irq(&ctx->lock);
4155 perf_event_ctx_unlock(event, ctx);
4158 mutex_lock(&event->child_mutex);
4159 list_for_each_entry(child, &event->child_list, child_list) {
4162 * Cannot change, child events are not migrated, see the
4163 * comment with perf_event_ctx_lock_nested().
4165 ctx = lockless_dereference(child->ctx);
4167 * Since child_mutex nests inside ctx::mutex, we must jump
4168 * through hoops. We start by grabbing a reference on the ctx.
4170 * Since the event cannot get freed while we hold the
4171 * child_mutex, the context must also exist and have a !0
4177 * Now that we have a ctx ref, we can drop child_mutex, and
4178 * acquire ctx::mutex without fear of it going away. Then we
4179 * can re-acquire child_mutex.
4181 mutex_unlock(&event->child_mutex);
4182 mutex_lock(&ctx->mutex);
4183 mutex_lock(&event->child_mutex);
4186 * Now that we hold ctx::mutex and child_mutex, revalidate our
4187 * state, if child is still the first entry, it didn't get freed
4188 * and we can continue doing so.
4190 tmp = list_first_entry_or_null(&event->child_list,
4191 struct perf_event, child_list);
4193 perf_remove_from_context(child, DETACH_GROUP);
4194 list_del(&child->child_list);
4197 * This matches the refcount bump in inherit_event();
4198 * this can't be the last reference.
4203 mutex_unlock(&event->child_mutex);
4204 mutex_unlock(&ctx->mutex);
4208 mutex_unlock(&event->child_mutex);
4211 put_event(event); /* Must be the 'last' reference */
4214 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4217 * Called when the last reference to the file is gone.
4219 static int perf_release(struct inode *inode, struct file *file)
4221 perf_event_release_kernel(file->private_data);
4225 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4227 struct perf_event *child;
4233 mutex_lock(&event->child_mutex);
4235 (void)perf_event_read(event, false);
4236 total += perf_event_count(event);
4238 *enabled += event->total_time_enabled +
4239 atomic64_read(&event->child_total_time_enabled);
4240 *running += event->total_time_running +
4241 atomic64_read(&event->child_total_time_running);
4243 list_for_each_entry(child, &event->child_list, child_list) {
4244 (void)perf_event_read(child, false);
4245 total += perf_event_count(child);
4246 *enabled += child->total_time_enabled;
4247 *running += child->total_time_running;
4249 mutex_unlock(&event->child_mutex);
4253 EXPORT_SYMBOL_GPL(perf_event_read_value);
4255 static int __perf_read_group_add(struct perf_event *leader,
4256 u64 read_format, u64 *values)
4258 struct perf_event *sub;
4259 int n = 1; /* skip @nr */
4262 ret = perf_event_read(leader, true);
4267 * Since we co-schedule groups, {enabled,running} times of siblings
4268 * will be identical to those of the leader, so we only publish one
4271 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4272 values[n++] += leader->total_time_enabled +
4273 atomic64_read(&leader->child_total_time_enabled);
4276 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4277 values[n++] += leader->total_time_running +
4278 atomic64_read(&leader->child_total_time_running);
4282 * Write {count,id} tuples for every sibling.
4284 values[n++] += perf_event_count(leader);
4285 if (read_format & PERF_FORMAT_ID)
4286 values[n++] = primary_event_id(leader);
4288 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4289 values[n++] += perf_event_count(sub);
4290 if (read_format & PERF_FORMAT_ID)
4291 values[n++] = primary_event_id(sub);
4297 static int perf_read_group(struct perf_event *event,
4298 u64 read_format, char __user *buf)
4300 struct perf_event *leader = event->group_leader, *child;
4301 struct perf_event_context *ctx = leader->ctx;
4305 lockdep_assert_held(&ctx->mutex);
4307 values = kzalloc(event->read_size, GFP_KERNEL);
4311 values[0] = 1 + leader->nr_siblings;
4314 * By locking the child_mutex of the leader we effectively
4315 * lock the child list of all siblings.. XXX explain how.
4317 mutex_lock(&leader->child_mutex);
4319 ret = __perf_read_group_add(leader, read_format, values);
4323 list_for_each_entry(child, &leader->child_list, child_list) {
4324 ret = __perf_read_group_add(child, read_format, values);
4329 mutex_unlock(&leader->child_mutex);
4331 ret = event->read_size;
4332 if (copy_to_user(buf, values, event->read_size))
4337 mutex_unlock(&leader->child_mutex);
4343 static int perf_read_one(struct perf_event *event,
4344 u64 read_format, char __user *buf)
4346 u64 enabled, running;
4350 values[n++] = perf_event_read_value(event, &enabled, &running);
4351 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4352 values[n++] = enabled;
4353 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4354 values[n++] = running;
4355 if (read_format & PERF_FORMAT_ID)
4356 values[n++] = primary_event_id(event);
4358 if (copy_to_user(buf, values, n * sizeof(u64)))
4361 return n * sizeof(u64);
4364 static bool is_event_hup(struct perf_event *event)
4368 if (event->state > PERF_EVENT_STATE_EXIT)
4371 mutex_lock(&event->child_mutex);
4372 no_children = list_empty(&event->child_list);
4373 mutex_unlock(&event->child_mutex);
4378 * Read the performance event - simple non blocking version for now
4381 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4383 u64 read_format = event->attr.read_format;
4387 * Return end-of-file for a read on a event that is in
4388 * error state (i.e. because it was pinned but it couldn't be
4389 * scheduled on to the CPU at some point).
4391 if (event->state == PERF_EVENT_STATE_ERROR)
4394 if (count < event->read_size)
4397 WARN_ON_ONCE(event->ctx->parent_ctx);
4398 if (read_format & PERF_FORMAT_GROUP)
4399 ret = perf_read_group(event, read_format, buf);
4401 ret = perf_read_one(event, read_format, buf);
4407 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4409 struct perf_event *event = file->private_data;
4410 struct perf_event_context *ctx;
4413 ctx = perf_event_ctx_lock(event);
4414 ret = __perf_read(event, buf, count);
4415 perf_event_ctx_unlock(event, ctx);
4420 static unsigned int perf_poll(struct file *file, poll_table *wait)
4422 struct perf_event *event = file->private_data;
4423 struct ring_buffer *rb;
4424 unsigned int events = POLLHUP;
4426 poll_wait(file, &event->waitq, wait);
4428 if (is_event_hup(event))
4432 * Pin the event->rb by taking event->mmap_mutex; otherwise
4433 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4435 mutex_lock(&event->mmap_mutex);
4438 events = atomic_xchg(&rb->poll, 0);
4439 mutex_unlock(&event->mmap_mutex);
4443 static void _perf_event_reset(struct perf_event *event)
4445 (void)perf_event_read(event, false);
4446 local64_set(&event->count, 0);
4447 perf_event_update_userpage(event);
4451 * Holding the top-level event's child_mutex means that any
4452 * descendant process that has inherited this event will block
4453 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4454 * task existence requirements of perf_event_enable/disable.
4456 static void perf_event_for_each_child(struct perf_event *event,
4457 void (*func)(struct perf_event *))
4459 struct perf_event *child;
4461 WARN_ON_ONCE(event->ctx->parent_ctx);
4463 mutex_lock(&event->child_mutex);
4465 list_for_each_entry(child, &event->child_list, child_list)
4467 mutex_unlock(&event->child_mutex);
4470 static void perf_event_for_each(struct perf_event *event,
4471 void (*func)(struct perf_event *))
4473 struct perf_event_context *ctx = event->ctx;
4474 struct perf_event *sibling;
4476 lockdep_assert_held(&ctx->mutex);
4478 event = event->group_leader;
4480 perf_event_for_each_child(event, func);
4481 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4482 perf_event_for_each_child(sibling, func);
4485 static void __perf_event_period(struct perf_event *event,
4486 struct perf_cpu_context *cpuctx,
4487 struct perf_event_context *ctx,
4490 u64 value = *((u64 *)info);
4493 if (event->attr.freq) {
4494 event->attr.sample_freq = value;
4496 event->attr.sample_period = value;
4497 event->hw.sample_period = value;
4500 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4502 perf_pmu_disable(ctx->pmu);
4504 * We could be throttled; unthrottle now to avoid the tick
4505 * trying to unthrottle while we already re-started the event.
4507 if (event->hw.interrupts == MAX_INTERRUPTS) {
4508 event->hw.interrupts = 0;
4509 perf_log_throttle(event, 1);
4511 event->pmu->stop(event, PERF_EF_UPDATE);
4514 local64_set(&event->hw.period_left, 0);
4517 event->pmu->start(event, PERF_EF_RELOAD);
4518 perf_pmu_enable(ctx->pmu);
4522 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4526 if (!is_sampling_event(event))
4529 if (copy_from_user(&value, arg, sizeof(value)))
4535 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4538 event_function_call(event, __perf_event_period, &value);
4543 static const struct file_operations perf_fops;
4545 static inline int perf_fget_light(int fd, struct fd *p)
4547 struct fd f = fdget(fd);
4551 if (f.file->f_op != &perf_fops) {
4559 static int perf_event_set_output(struct perf_event *event,
4560 struct perf_event *output_event);
4561 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4562 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4564 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4566 void (*func)(struct perf_event *);
4570 case PERF_EVENT_IOC_ENABLE:
4571 func = _perf_event_enable;
4573 case PERF_EVENT_IOC_DISABLE:
4574 func = _perf_event_disable;
4576 case PERF_EVENT_IOC_RESET:
4577 func = _perf_event_reset;
4580 case PERF_EVENT_IOC_REFRESH:
4581 return _perf_event_refresh(event, arg);
4583 case PERF_EVENT_IOC_PERIOD:
4584 return perf_event_period(event, (u64 __user *)arg);
4586 case PERF_EVENT_IOC_ID:
4588 u64 id = primary_event_id(event);
4590 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4595 case PERF_EVENT_IOC_SET_OUTPUT:
4599 struct perf_event *output_event;
4601 ret = perf_fget_light(arg, &output);
4604 output_event = output.file->private_data;
4605 ret = perf_event_set_output(event, output_event);
4608 ret = perf_event_set_output(event, NULL);
4613 case PERF_EVENT_IOC_SET_FILTER:
4614 return perf_event_set_filter(event, (void __user *)arg);
4616 case PERF_EVENT_IOC_SET_BPF:
4617 return perf_event_set_bpf_prog(event, arg);
4619 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
4620 struct ring_buffer *rb;
4623 rb = rcu_dereference(event->rb);
4624 if (!rb || !rb->nr_pages) {
4628 rb_toggle_paused(rb, !!arg);
4636 if (flags & PERF_IOC_FLAG_GROUP)
4637 perf_event_for_each(event, func);
4639 perf_event_for_each_child(event, func);
4644 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4646 struct perf_event *event = file->private_data;
4647 struct perf_event_context *ctx;
4650 ctx = perf_event_ctx_lock(event);
4651 ret = _perf_ioctl(event, cmd, arg);
4652 perf_event_ctx_unlock(event, ctx);
4657 #ifdef CONFIG_COMPAT
4658 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4661 switch (_IOC_NR(cmd)) {
4662 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4663 case _IOC_NR(PERF_EVENT_IOC_ID):
4664 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4665 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4666 cmd &= ~IOCSIZE_MASK;
4667 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4671 return perf_ioctl(file, cmd, arg);
4674 # define perf_compat_ioctl NULL
4677 int perf_event_task_enable(void)
4679 struct perf_event_context *ctx;
4680 struct perf_event *event;
4682 mutex_lock(¤t->perf_event_mutex);
4683 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4684 ctx = perf_event_ctx_lock(event);
4685 perf_event_for_each_child(event, _perf_event_enable);
4686 perf_event_ctx_unlock(event, ctx);
4688 mutex_unlock(¤t->perf_event_mutex);
4693 int perf_event_task_disable(void)
4695 struct perf_event_context *ctx;
4696 struct perf_event *event;
4698 mutex_lock(¤t->perf_event_mutex);
4699 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4700 ctx = perf_event_ctx_lock(event);
4701 perf_event_for_each_child(event, _perf_event_disable);
4702 perf_event_ctx_unlock(event, ctx);
4704 mutex_unlock(¤t->perf_event_mutex);
4709 static int perf_event_index(struct perf_event *event)
4711 if (event->hw.state & PERF_HES_STOPPED)
4714 if (event->state != PERF_EVENT_STATE_ACTIVE)
4717 return event->pmu->event_idx(event);
4720 static void calc_timer_values(struct perf_event *event,
4727 *now = perf_clock();
4728 ctx_time = event->shadow_ctx_time + *now;
4729 *enabled = ctx_time - event->tstamp_enabled;
4730 *running = ctx_time - event->tstamp_running;
4733 static void perf_event_init_userpage(struct perf_event *event)
4735 struct perf_event_mmap_page *userpg;
4736 struct ring_buffer *rb;
4739 rb = rcu_dereference(event->rb);
4743 userpg = rb->user_page;
4745 /* Allow new userspace to detect that bit 0 is deprecated */
4746 userpg->cap_bit0_is_deprecated = 1;
4747 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4748 userpg->data_offset = PAGE_SIZE;
4749 userpg->data_size = perf_data_size(rb);
4755 void __weak arch_perf_update_userpage(
4756 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4761 * Callers need to ensure there can be no nesting of this function, otherwise
4762 * the seqlock logic goes bad. We can not serialize this because the arch
4763 * code calls this from NMI context.
4765 void perf_event_update_userpage(struct perf_event *event)
4767 struct perf_event_mmap_page *userpg;
4768 struct ring_buffer *rb;
4769 u64 enabled, running, now;
4772 rb = rcu_dereference(event->rb);
4777 * compute total_time_enabled, total_time_running
4778 * based on snapshot values taken when the event
4779 * was last scheduled in.
4781 * we cannot simply called update_context_time()
4782 * because of locking issue as we can be called in
4785 calc_timer_values(event, &now, &enabled, &running);
4787 userpg = rb->user_page;
4789 * Disable preemption so as to not let the corresponding user-space
4790 * spin too long if we get preempted.
4795 userpg->index = perf_event_index(event);
4796 userpg->offset = perf_event_count(event);
4798 userpg->offset -= local64_read(&event->hw.prev_count);
4800 userpg->time_enabled = enabled +
4801 atomic64_read(&event->child_total_time_enabled);
4803 userpg->time_running = running +
4804 atomic64_read(&event->child_total_time_running);
4806 arch_perf_update_userpage(event, userpg, now);
4815 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4817 struct perf_event *event = vma->vm_file->private_data;
4818 struct ring_buffer *rb;
4819 int ret = VM_FAULT_SIGBUS;
4821 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4822 if (vmf->pgoff == 0)
4828 rb = rcu_dereference(event->rb);
4832 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4835 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4839 get_page(vmf->page);
4840 vmf->page->mapping = vma->vm_file->f_mapping;
4841 vmf->page->index = vmf->pgoff;
4850 static void ring_buffer_attach(struct perf_event *event,
4851 struct ring_buffer *rb)
4853 struct ring_buffer *old_rb = NULL;
4854 unsigned long flags;
4858 * Should be impossible, we set this when removing
4859 * event->rb_entry and wait/clear when adding event->rb_entry.
4861 WARN_ON_ONCE(event->rcu_pending);
4864 spin_lock_irqsave(&old_rb->event_lock, flags);
4865 list_del_rcu(&event->rb_entry);
4866 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4868 event->rcu_batches = get_state_synchronize_rcu();
4869 event->rcu_pending = 1;
4873 if (event->rcu_pending) {
4874 cond_synchronize_rcu(event->rcu_batches);
4875 event->rcu_pending = 0;
4878 spin_lock_irqsave(&rb->event_lock, flags);
4879 list_add_rcu(&event->rb_entry, &rb->event_list);
4880 spin_unlock_irqrestore(&rb->event_lock, flags);
4884 * Avoid racing with perf_mmap_close(AUX): stop the event
4885 * before swizzling the event::rb pointer; if it's getting
4886 * unmapped, its aux_mmap_count will be 0 and it won't
4887 * restart. See the comment in __perf_pmu_output_stop().
4889 * Data will inevitably be lost when set_output is done in
4890 * mid-air, but then again, whoever does it like this is
4891 * not in for the data anyway.
4894 perf_event_stop(event, 0);
4896 rcu_assign_pointer(event->rb, rb);
4899 ring_buffer_put(old_rb);
4901 * Since we detached before setting the new rb, so that we
4902 * could attach the new rb, we could have missed a wakeup.
4905 wake_up_all(&event->waitq);
4909 static void ring_buffer_wakeup(struct perf_event *event)
4911 struct ring_buffer *rb;
4914 rb = rcu_dereference(event->rb);
4916 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4917 wake_up_all(&event->waitq);
4922 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4924 struct ring_buffer *rb;
4927 rb = rcu_dereference(event->rb);
4929 if (!atomic_inc_not_zero(&rb->refcount))
4937 void ring_buffer_put(struct ring_buffer *rb)
4939 if (!atomic_dec_and_test(&rb->refcount))
4942 WARN_ON_ONCE(!list_empty(&rb->event_list));
4944 call_rcu(&rb->rcu_head, rb_free_rcu);
4947 static void perf_mmap_open(struct vm_area_struct *vma)
4949 struct perf_event *event = vma->vm_file->private_data;
4951 atomic_inc(&event->mmap_count);
4952 atomic_inc(&event->rb->mmap_count);
4955 atomic_inc(&event->rb->aux_mmap_count);
4957 if (event->pmu->event_mapped)
4958 event->pmu->event_mapped(event);
4961 static void perf_pmu_output_stop(struct perf_event *event);
4964 * A buffer can be mmap()ed multiple times; either directly through the same
4965 * event, or through other events by use of perf_event_set_output().
4967 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4968 * the buffer here, where we still have a VM context. This means we need
4969 * to detach all events redirecting to us.
4971 static void perf_mmap_close(struct vm_area_struct *vma)
4973 struct perf_event *event = vma->vm_file->private_data;
4975 struct ring_buffer *rb = ring_buffer_get(event);
4976 struct user_struct *mmap_user = rb->mmap_user;
4977 int mmap_locked = rb->mmap_locked;
4978 unsigned long size = perf_data_size(rb);
4980 if (event->pmu->event_unmapped)
4981 event->pmu->event_unmapped(event);
4984 * rb->aux_mmap_count will always drop before rb->mmap_count and
4985 * event->mmap_count, so it is ok to use event->mmap_mutex to
4986 * serialize with perf_mmap here.
4988 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4989 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4991 * Stop all AUX events that are writing to this buffer,
4992 * so that we can free its AUX pages and corresponding PMU
4993 * data. Note that after rb::aux_mmap_count dropped to zero,
4994 * they won't start any more (see perf_aux_output_begin()).
4996 perf_pmu_output_stop(event);
4998 /* now it's safe to free the pages */
4999 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
5000 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
5002 /* this has to be the last one */
5004 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
5006 mutex_unlock(&event->mmap_mutex);
5009 atomic_dec(&rb->mmap_count);
5011 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5014 ring_buffer_attach(event, NULL);
5015 mutex_unlock(&event->mmap_mutex);
5017 /* If there's still other mmap()s of this buffer, we're done. */
5018 if (atomic_read(&rb->mmap_count))
5022 * No other mmap()s, detach from all other events that might redirect
5023 * into the now unreachable buffer. Somewhat complicated by the
5024 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5028 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5029 if (!atomic_long_inc_not_zero(&event->refcount)) {
5031 * This event is en-route to free_event() which will
5032 * detach it and remove it from the list.
5038 mutex_lock(&event->mmap_mutex);
5040 * Check we didn't race with perf_event_set_output() which can
5041 * swizzle the rb from under us while we were waiting to
5042 * acquire mmap_mutex.
5044 * If we find a different rb; ignore this event, a next
5045 * iteration will no longer find it on the list. We have to
5046 * still restart the iteration to make sure we're not now
5047 * iterating the wrong list.
5049 if (event->rb == rb)
5050 ring_buffer_attach(event, NULL);
5052 mutex_unlock(&event->mmap_mutex);
5056 * Restart the iteration; either we're on the wrong list or
5057 * destroyed its integrity by doing a deletion.
5064 * It could be there's still a few 0-ref events on the list; they'll
5065 * get cleaned up by free_event() -- they'll also still have their
5066 * ref on the rb and will free it whenever they are done with it.
5068 * Aside from that, this buffer is 'fully' detached and unmapped,
5069 * undo the VM accounting.
5072 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
5073 vma->vm_mm->pinned_vm -= mmap_locked;
5074 free_uid(mmap_user);
5077 ring_buffer_put(rb); /* could be last */
5080 static const struct vm_operations_struct perf_mmap_vmops = {
5081 .open = perf_mmap_open,
5082 .close = perf_mmap_close, /* non mergable */
5083 .fault = perf_mmap_fault,
5084 .page_mkwrite = perf_mmap_fault,
5087 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5089 struct perf_event *event = file->private_data;
5090 unsigned long user_locked, user_lock_limit;
5091 struct user_struct *user = current_user();
5092 unsigned long locked, lock_limit;
5093 struct ring_buffer *rb = NULL;
5094 unsigned long vma_size;
5095 unsigned long nr_pages;
5096 long user_extra = 0, extra = 0;
5097 int ret = 0, flags = 0;
5100 * Don't allow mmap() of inherited per-task counters. This would
5101 * create a performance issue due to all children writing to the
5104 if (event->cpu == -1 && event->attr.inherit)
5107 if (!(vma->vm_flags & VM_SHARED))
5110 vma_size = vma->vm_end - vma->vm_start;
5112 if (vma->vm_pgoff == 0) {
5113 nr_pages = (vma_size / PAGE_SIZE) - 1;
5116 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5117 * mapped, all subsequent mappings should have the same size
5118 * and offset. Must be above the normal perf buffer.
5120 u64 aux_offset, aux_size;
5125 nr_pages = vma_size / PAGE_SIZE;
5127 mutex_lock(&event->mmap_mutex);
5134 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
5135 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
5137 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5140 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5143 /* already mapped with a different offset */
5144 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5147 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5150 /* already mapped with a different size */
5151 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5154 if (!is_power_of_2(nr_pages))
5157 if (!atomic_inc_not_zero(&rb->mmap_count))
5160 if (rb_has_aux(rb)) {
5161 atomic_inc(&rb->aux_mmap_count);
5166 atomic_set(&rb->aux_mmap_count, 1);
5167 user_extra = nr_pages;
5173 * If we have rb pages ensure they're a power-of-two number, so we
5174 * can do bitmasks instead of modulo.
5176 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5179 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5182 WARN_ON_ONCE(event->ctx->parent_ctx);
5184 mutex_lock(&event->mmap_mutex);
5186 if (event->rb->nr_pages != nr_pages) {
5191 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5193 * Raced against perf_mmap_close() through
5194 * perf_event_set_output(). Try again, hope for better
5197 mutex_unlock(&event->mmap_mutex);
5204 user_extra = nr_pages + 1;
5207 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5210 * Increase the limit linearly with more CPUs:
5212 user_lock_limit *= num_online_cpus();
5214 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5216 if (user_locked > user_lock_limit)
5217 extra = user_locked - user_lock_limit;
5219 lock_limit = rlimit(RLIMIT_MEMLOCK);
5220 lock_limit >>= PAGE_SHIFT;
5221 locked = vma->vm_mm->pinned_vm + extra;
5223 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5224 !capable(CAP_IPC_LOCK)) {
5229 WARN_ON(!rb && event->rb);
5231 if (vma->vm_flags & VM_WRITE)
5232 flags |= RING_BUFFER_WRITABLE;
5235 rb = rb_alloc(nr_pages,
5236 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5244 atomic_set(&rb->mmap_count, 1);
5245 rb->mmap_user = get_current_user();
5246 rb->mmap_locked = extra;
5248 ring_buffer_attach(event, rb);
5250 perf_event_init_userpage(event);
5251 perf_event_update_userpage(event);
5253 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5254 event->attr.aux_watermark, flags);
5256 rb->aux_mmap_locked = extra;
5261 atomic_long_add(user_extra, &user->locked_vm);
5262 vma->vm_mm->pinned_vm += extra;
5264 atomic_inc(&event->mmap_count);
5266 atomic_dec(&rb->mmap_count);
5269 mutex_unlock(&event->mmap_mutex);
5272 * Since pinned accounting is per vm we cannot allow fork() to copy our
5275 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5276 vma->vm_ops = &perf_mmap_vmops;
5278 if (event->pmu->event_mapped)
5279 event->pmu->event_mapped(event);
5284 static int perf_fasync(int fd, struct file *filp, int on)
5286 struct inode *inode = file_inode(filp);
5287 struct perf_event *event = filp->private_data;
5291 retval = fasync_helper(fd, filp, on, &event->fasync);
5292 inode_unlock(inode);
5300 static const struct file_operations perf_fops = {
5301 .llseek = no_llseek,
5302 .release = perf_release,
5305 .unlocked_ioctl = perf_ioctl,
5306 .compat_ioctl = perf_compat_ioctl,
5308 .fasync = perf_fasync,
5314 * If there's data, ensure we set the poll() state and publish everything
5315 * to user-space before waking everybody up.
5318 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5320 /* only the parent has fasync state */
5322 event = event->parent;
5323 return &event->fasync;
5326 void perf_event_wakeup(struct perf_event *event)
5328 ring_buffer_wakeup(event);
5330 if (event->pending_kill) {
5331 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5332 event->pending_kill = 0;
5336 static void perf_pending_event(struct irq_work *entry)
5338 struct perf_event *event = container_of(entry,
5339 struct perf_event, pending);
5342 rctx = perf_swevent_get_recursion_context();
5344 * If we 'fail' here, that's OK, it means recursion is already disabled
5345 * and we won't recurse 'further'.
5348 if (event->pending_disable) {
5349 event->pending_disable = 0;
5350 perf_event_disable_local(event);
5353 if (event->pending_wakeup) {
5354 event->pending_wakeup = 0;
5355 perf_event_wakeup(event);
5359 perf_swevent_put_recursion_context(rctx);
5363 * We assume there is only KVM supporting the callbacks.
5364 * Later on, we might change it to a list if there is
5365 * another virtualization implementation supporting the callbacks.
5367 struct perf_guest_info_callbacks *perf_guest_cbs;
5369 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5371 perf_guest_cbs = cbs;
5374 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5376 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5378 perf_guest_cbs = NULL;
5381 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5384 perf_output_sample_regs(struct perf_output_handle *handle,
5385 struct pt_regs *regs, u64 mask)
5388 DECLARE_BITMAP(_mask, 64);
5390 bitmap_from_u64(_mask, mask);
5391 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
5394 val = perf_reg_value(regs, bit);
5395 perf_output_put(handle, val);
5399 static void perf_sample_regs_user(struct perf_regs *regs_user,
5400 struct pt_regs *regs,
5401 struct pt_regs *regs_user_copy)
5403 if (user_mode(regs)) {
5404 regs_user->abi = perf_reg_abi(current);
5405 regs_user->regs = regs;
5406 } else if (current->mm) {
5407 perf_get_regs_user(regs_user, regs, regs_user_copy);
5409 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5410 regs_user->regs = NULL;
5414 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5415 struct pt_regs *regs)
5417 regs_intr->regs = regs;
5418 regs_intr->abi = perf_reg_abi(current);
5423 * Get remaining task size from user stack pointer.
5425 * It'd be better to take stack vma map and limit this more
5426 * precisly, but there's no way to get it safely under interrupt,
5427 * so using TASK_SIZE as limit.
5429 static u64 perf_ustack_task_size(struct pt_regs *regs)
5431 unsigned long addr = perf_user_stack_pointer(regs);
5433 if (!addr || addr >= TASK_SIZE)
5436 return TASK_SIZE - addr;
5440 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5441 struct pt_regs *regs)
5445 /* No regs, no stack pointer, no dump. */
5450 * Check if we fit in with the requested stack size into the:
5452 * If we don't, we limit the size to the TASK_SIZE.
5454 * - remaining sample size
5455 * If we don't, we customize the stack size to
5456 * fit in to the remaining sample size.
5459 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5460 stack_size = min(stack_size, (u16) task_size);
5462 /* Current header size plus static size and dynamic size. */
5463 header_size += 2 * sizeof(u64);
5465 /* Do we fit in with the current stack dump size? */
5466 if ((u16) (header_size + stack_size) < header_size) {
5468 * If we overflow the maximum size for the sample,
5469 * we customize the stack dump size to fit in.
5471 stack_size = USHRT_MAX - header_size - sizeof(u64);
5472 stack_size = round_up(stack_size, sizeof(u64));
5479 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5480 struct pt_regs *regs)
5482 /* Case of a kernel thread, nothing to dump */
5485 perf_output_put(handle, size);
5494 * - the size requested by user or the best one we can fit
5495 * in to the sample max size
5497 * - user stack dump data
5499 * - the actual dumped size
5503 perf_output_put(handle, dump_size);
5506 sp = perf_user_stack_pointer(regs);
5507 rem = __output_copy_user(handle, (void *) sp, dump_size);
5508 dyn_size = dump_size - rem;
5510 perf_output_skip(handle, rem);
5513 perf_output_put(handle, dyn_size);
5517 static void __perf_event_header__init_id(struct perf_event_header *header,
5518 struct perf_sample_data *data,
5519 struct perf_event *event)
5521 u64 sample_type = event->attr.sample_type;
5523 data->type = sample_type;
5524 header->size += event->id_header_size;
5526 if (sample_type & PERF_SAMPLE_TID) {
5527 /* namespace issues */
5528 data->tid_entry.pid = perf_event_pid(event, current);
5529 data->tid_entry.tid = perf_event_tid(event, current);
5532 if (sample_type & PERF_SAMPLE_TIME)
5533 data->time = perf_event_clock(event);
5535 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5536 data->id = primary_event_id(event);
5538 if (sample_type & PERF_SAMPLE_STREAM_ID)
5539 data->stream_id = event->id;
5541 if (sample_type & PERF_SAMPLE_CPU) {
5542 data->cpu_entry.cpu = raw_smp_processor_id();
5543 data->cpu_entry.reserved = 0;
5547 void perf_event_header__init_id(struct perf_event_header *header,
5548 struct perf_sample_data *data,
5549 struct perf_event *event)
5551 if (event->attr.sample_id_all)
5552 __perf_event_header__init_id(header, data, event);
5555 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5556 struct perf_sample_data *data)
5558 u64 sample_type = data->type;
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_ID)
5567 perf_output_put(handle, data->id);
5569 if (sample_type & PERF_SAMPLE_STREAM_ID)
5570 perf_output_put(handle, data->stream_id);
5572 if (sample_type & PERF_SAMPLE_CPU)
5573 perf_output_put(handle, data->cpu_entry);
5575 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5576 perf_output_put(handle, data->id);
5579 void perf_event__output_id_sample(struct perf_event *event,
5580 struct perf_output_handle *handle,
5581 struct perf_sample_data *sample)
5583 if (event->attr.sample_id_all)
5584 __perf_event__output_id_sample(handle, sample);
5587 static void perf_output_read_one(struct perf_output_handle *handle,
5588 struct perf_event *event,
5589 u64 enabled, u64 running)
5591 u64 read_format = event->attr.read_format;
5595 values[n++] = perf_event_count(event);
5596 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5597 values[n++] = enabled +
5598 atomic64_read(&event->child_total_time_enabled);
5600 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5601 values[n++] = running +
5602 atomic64_read(&event->child_total_time_running);
5604 if (read_format & PERF_FORMAT_ID)
5605 values[n++] = primary_event_id(event);
5607 __output_copy(handle, values, n * sizeof(u64));
5611 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5613 static void perf_output_read_group(struct perf_output_handle *handle,
5614 struct perf_event *event,
5615 u64 enabled, u64 running)
5617 struct perf_event *leader = event->group_leader, *sub;
5618 u64 read_format = event->attr.read_format;
5622 values[n++] = 1 + leader->nr_siblings;
5624 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5625 values[n++] = enabled;
5627 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5628 values[n++] = running;
5630 if (leader != event)
5631 leader->pmu->read(leader);
5633 values[n++] = perf_event_count(leader);
5634 if (read_format & PERF_FORMAT_ID)
5635 values[n++] = primary_event_id(leader);
5637 __output_copy(handle, values, n * sizeof(u64));
5639 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5642 if ((sub != event) &&
5643 (sub->state == PERF_EVENT_STATE_ACTIVE))
5644 sub->pmu->read(sub);
5646 values[n++] = perf_event_count(sub);
5647 if (read_format & PERF_FORMAT_ID)
5648 values[n++] = primary_event_id(sub);
5650 __output_copy(handle, values, n * sizeof(u64));
5654 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5655 PERF_FORMAT_TOTAL_TIME_RUNNING)
5657 static void perf_output_read(struct perf_output_handle *handle,
5658 struct perf_event *event)
5660 u64 enabled = 0, running = 0, now;
5661 u64 read_format = event->attr.read_format;
5664 * compute total_time_enabled, total_time_running
5665 * based on snapshot values taken when the event
5666 * was last scheduled in.
5668 * we cannot simply called update_context_time()
5669 * because of locking issue as we are called in
5672 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5673 calc_timer_values(event, &now, &enabled, &running);
5675 if (event->attr.read_format & PERF_FORMAT_GROUP)
5676 perf_output_read_group(handle, event, enabled, running);
5678 perf_output_read_one(handle, event, enabled, running);
5681 void perf_output_sample(struct perf_output_handle *handle,
5682 struct perf_event_header *header,
5683 struct perf_sample_data *data,
5684 struct perf_event *event)
5686 u64 sample_type = data->type;
5688 perf_output_put(handle, *header);
5690 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5691 perf_output_put(handle, data->id);
5693 if (sample_type & PERF_SAMPLE_IP)
5694 perf_output_put(handle, data->ip);
5696 if (sample_type & PERF_SAMPLE_TID)
5697 perf_output_put(handle, data->tid_entry);
5699 if (sample_type & PERF_SAMPLE_TIME)
5700 perf_output_put(handle, data->time);
5702 if (sample_type & PERF_SAMPLE_ADDR)
5703 perf_output_put(handle, data->addr);
5705 if (sample_type & PERF_SAMPLE_ID)
5706 perf_output_put(handle, data->id);
5708 if (sample_type & PERF_SAMPLE_STREAM_ID)
5709 perf_output_put(handle, data->stream_id);
5711 if (sample_type & PERF_SAMPLE_CPU)
5712 perf_output_put(handle, data->cpu_entry);
5714 if (sample_type & PERF_SAMPLE_PERIOD)
5715 perf_output_put(handle, data->period);
5717 if (sample_type & PERF_SAMPLE_READ)
5718 perf_output_read(handle, event);
5720 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5721 if (data->callchain) {
5724 if (data->callchain)
5725 size += data->callchain->nr;
5727 size *= sizeof(u64);
5729 __output_copy(handle, data->callchain, size);
5732 perf_output_put(handle, nr);
5736 if (sample_type & PERF_SAMPLE_RAW) {
5737 struct perf_raw_record *raw = data->raw;
5740 struct perf_raw_frag *frag = &raw->frag;
5742 perf_output_put(handle, raw->size);
5745 __output_custom(handle, frag->copy,
5746 frag->data, frag->size);
5748 __output_copy(handle, frag->data,
5751 if (perf_raw_frag_last(frag))
5756 __output_skip(handle, NULL, frag->pad);
5762 .size = sizeof(u32),
5765 perf_output_put(handle, raw);
5769 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5770 if (data->br_stack) {
5773 size = data->br_stack->nr
5774 * sizeof(struct perf_branch_entry);
5776 perf_output_put(handle, data->br_stack->nr);
5777 perf_output_copy(handle, data->br_stack->entries, size);
5780 * we always store at least the value of nr
5783 perf_output_put(handle, nr);
5787 if (sample_type & PERF_SAMPLE_REGS_USER) {
5788 u64 abi = data->regs_user.abi;
5791 * If there are no regs to dump, notice it through
5792 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5794 perf_output_put(handle, abi);
5797 u64 mask = event->attr.sample_regs_user;
5798 perf_output_sample_regs(handle,
5799 data->regs_user.regs,
5804 if (sample_type & PERF_SAMPLE_STACK_USER) {
5805 perf_output_sample_ustack(handle,
5806 data->stack_user_size,
5807 data->regs_user.regs);
5810 if (sample_type & PERF_SAMPLE_WEIGHT)
5811 perf_output_put(handle, data->weight);
5813 if (sample_type & PERF_SAMPLE_DATA_SRC)
5814 perf_output_put(handle, data->data_src.val);
5816 if (sample_type & PERF_SAMPLE_TRANSACTION)
5817 perf_output_put(handle, data->txn);
5819 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5820 u64 abi = data->regs_intr.abi;
5822 * If there are no regs to dump, notice it through
5823 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5825 perf_output_put(handle, abi);
5828 u64 mask = event->attr.sample_regs_intr;
5830 perf_output_sample_regs(handle,
5831 data->regs_intr.regs,
5836 if (!event->attr.watermark) {
5837 int wakeup_events = event->attr.wakeup_events;
5839 if (wakeup_events) {
5840 struct ring_buffer *rb = handle->rb;
5841 int events = local_inc_return(&rb->events);
5843 if (events >= wakeup_events) {
5844 local_sub(wakeup_events, &rb->events);
5845 local_inc(&rb->wakeup);
5851 void perf_prepare_sample(struct perf_event_header *header,
5852 struct perf_sample_data *data,
5853 struct perf_event *event,
5854 struct pt_regs *regs)
5856 u64 sample_type = event->attr.sample_type;
5858 header->type = PERF_RECORD_SAMPLE;
5859 header->size = sizeof(*header) + event->header_size;
5862 header->misc |= perf_misc_flags(regs);
5864 __perf_event_header__init_id(header, data, event);
5866 if (sample_type & PERF_SAMPLE_IP)
5867 data->ip = perf_instruction_pointer(regs);
5869 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5872 data->callchain = perf_callchain(event, regs);
5874 if (data->callchain)
5875 size += data->callchain->nr;
5877 header->size += size * sizeof(u64);
5880 if (sample_type & PERF_SAMPLE_RAW) {
5881 struct perf_raw_record *raw = data->raw;
5885 struct perf_raw_frag *frag = &raw->frag;
5890 if (perf_raw_frag_last(frag))
5895 size = round_up(sum + sizeof(u32), sizeof(u64));
5896 raw->size = size - sizeof(u32);
5897 frag->pad = raw->size - sum;
5902 header->size += size;
5905 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5906 int size = sizeof(u64); /* nr */
5907 if (data->br_stack) {
5908 size += data->br_stack->nr
5909 * sizeof(struct perf_branch_entry);
5911 header->size += size;
5914 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5915 perf_sample_regs_user(&data->regs_user, regs,
5916 &data->regs_user_copy);
5918 if (sample_type & PERF_SAMPLE_REGS_USER) {
5919 /* regs dump ABI info */
5920 int size = sizeof(u64);
5922 if (data->regs_user.regs) {
5923 u64 mask = event->attr.sample_regs_user;
5924 size += hweight64(mask) * sizeof(u64);
5927 header->size += size;
5930 if (sample_type & PERF_SAMPLE_STACK_USER) {
5932 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5933 * processed as the last one or have additional check added
5934 * in case new sample type is added, because we could eat
5935 * up the rest of the sample size.
5937 u16 stack_size = event->attr.sample_stack_user;
5938 u16 size = sizeof(u64);
5940 stack_size = perf_sample_ustack_size(stack_size, header->size,
5941 data->regs_user.regs);
5944 * If there is something to dump, add space for the dump
5945 * itself and for the field that tells the dynamic size,
5946 * which is how many have been actually dumped.
5949 size += sizeof(u64) + stack_size;
5951 data->stack_user_size = stack_size;
5952 header->size += size;
5955 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5956 /* regs dump ABI info */
5957 int size = sizeof(u64);
5959 perf_sample_regs_intr(&data->regs_intr, regs);
5961 if (data->regs_intr.regs) {
5962 u64 mask = event->attr.sample_regs_intr;
5964 size += hweight64(mask) * sizeof(u64);
5967 header->size += size;
5971 static void __always_inline
5972 __perf_event_output(struct perf_event *event,
5973 struct perf_sample_data *data,
5974 struct pt_regs *regs,
5975 int (*output_begin)(struct perf_output_handle *,
5976 struct perf_event *,
5979 struct perf_output_handle handle;
5980 struct perf_event_header header;
5982 /* protect the callchain buffers */
5985 perf_prepare_sample(&header, data, event, regs);
5987 if (output_begin(&handle, event, header.size))
5990 perf_output_sample(&handle, &header, data, event);
5992 perf_output_end(&handle);
5999 perf_event_output_forward(struct perf_event *event,
6000 struct perf_sample_data *data,
6001 struct pt_regs *regs)
6003 __perf_event_output(event, data, regs, perf_output_begin_forward);
6007 perf_event_output_backward(struct perf_event *event,
6008 struct perf_sample_data *data,
6009 struct pt_regs *regs)
6011 __perf_event_output(event, data, regs, perf_output_begin_backward);
6015 perf_event_output(struct perf_event *event,
6016 struct perf_sample_data *data,
6017 struct pt_regs *regs)
6019 __perf_event_output(event, data, regs, perf_output_begin);
6026 struct perf_read_event {
6027 struct perf_event_header header;
6034 perf_event_read_event(struct perf_event *event,
6035 struct task_struct *task)
6037 struct perf_output_handle handle;
6038 struct perf_sample_data sample;
6039 struct perf_read_event read_event = {
6041 .type = PERF_RECORD_READ,
6043 .size = sizeof(read_event) + event->read_size,
6045 .pid = perf_event_pid(event, task),
6046 .tid = perf_event_tid(event, task),
6050 perf_event_header__init_id(&read_event.header, &sample, event);
6051 ret = perf_output_begin(&handle, event, read_event.header.size);
6055 perf_output_put(&handle, read_event);
6056 perf_output_read(&handle, event);
6057 perf_event__output_id_sample(event, &handle, &sample);
6059 perf_output_end(&handle);
6062 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
6065 perf_iterate_ctx(struct perf_event_context *ctx,
6066 perf_iterate_f output,
6067 void *data, bool all)
6069 struct perf_event *event;
6071 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6073 if (event->state < PERF_EVENT_STATE_INACTIVE)
6075 if (!event_filter_match(event))
6079 output(event, data);
6083 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
6085 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
6086 struct perf_event *event;
6088 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6090 * Skip events that are not fully formed yet; ensure that
6091 * if we observe event->ctx, both event and ctx will be
6092 * complete enough. See perf_install_in_context().
6094 if (!smp_load_acquire(&event->ctx))
6097 if (event->state < PERF_EVENT_STATE_INACTIVE)
6099 if (!event_filter_match(event))
6101 output(event, data);
6106 * Iterate all events that need to receive side-band events.
6108 * For new callers; ensure that account_pmu_sb_event() includes
6109 * your event, otherwise it might not get delivered.
6112 perf_iterate_sb(perf_iterate_f output, void *data,
6113 struct perf_event_context *task_ctx)
6115 struct perf_event_context *ctx;
6122 * If we have task_ctx != NULL we only notify the task context itself.
6123 * The task_ctx is set only for EXIT events before releasing task
6127 perf_iterate_ctx(task_ctx, output, data, false);
6131 perf_iterate_sb_cpu(output, data);
6133 for_each_task_context_nr(ctxn) {
6134 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6136 perf_iterate_ctx(ctx, output, data, false);
6144 * Clear all file-based filters at exec, they'll have to be
6145 * re-instated when/if these objects are mmapped again.
6147 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6149 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6150 struct perf_addr_filter *filter;
6151 unsigned int restart = 0, count = 0;
6152 unsigned long flags;
6154 if (!has_addr_filter(event))
6157 raw_spin_lock_irqsave(&ifh->lock, flags);
6158 list_for_each_entry(filter, &ifh->list, entry) {
6159 if (filter->inode) {
6160 event->addr_filters_offs[count] = 0;
6168 event->addr_filters_gen++;
6169 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6172 perf_event_stop(event, 1);
6175 void perf_event_exec(void)
6177 struct perf_event_context *ctx;
6181 for_each_task_context_nr(ctxn) {
6182 ctx = current->perf_event_ctxp[ctxn];
6186 perf_event_enable_on_exec(ctxn);
6188 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6194 struct remote_output {
6195 struct ring_buffer *rb;
6199 static void __perf_event_output_stop(struct perf_event *event, void *data)
6201 struct perf_event *parent = event->parent;
6202 struct remote_output *ro = data;
6203 struct ring_buffer *rb = ro->rb;
6204 struct stop_event_data sd = {
6208 if (!has_aux(event))
6215 * In case of inheritance, it will be the parent that links to the
6216 * ring-buffer, but it will be the child that's actually using it.
6218 * We are using event::rb to determine if the event should be stopped,
6219 * however this may race with ring_buffer_attach() (through set_output),
6220 * which will make us skip the event that actually needs to be stopped.
6221 * So ring_buffer_attach() has to stop an aux event before re-assigning
6224 if (rcu_dereference(parent->rb) == rb)
6225 ro->err = __perf_event_stop(&sd);
6228 static int __perf_pmu_output_stop(void *info)
6230 struct perf_event *event = info;
6231 struct pmu *pmu = event->pmu;
6232 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6233 struct remote_output ro = {
6238 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6239 if (cpuctx->task_ctx)
6240 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6247 static void perf_pmu_output_stop(struct perf_event *event)
6249 struct perf_event *iter;
6254 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6256 * For per-CPU events, we need to make sure that neither they
6257 * nor their children are running; for cpu==-1 events it's
6258 * sufficient to stop the event itself if it's active, since
6259 * it can't have children.
6263 cpu = READ_ONCE(iter->oncpu);
6268 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6269 if (err == -EAGAIN) {
6278 * task tracking -- fork/exit
6280 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6283 struct perf_task_event {
6284 struct task_struct *task;
6285 struct perf_event_context *task_ctx;
6288 struct perf_event_header header;
6298 static int perf_event_task_match(struct perf_event *event)
6300 return event->attr.comm || event->attr.mmap ||
6301 event->attr.mmap2 || event->attr.mmap_data ||
6305 static void perf_event_task_output(struct perf_event *event,
6308 struct perf_task_event *task_event = data;
6309 struct perf_output_handle handle;
6310 struct perf_sample_data sample;
6311 struct task_struct *task = task_event->task;
6312 int ret, size = task_event->event_id.header.size;
6314 if (!perf_event_task_match(event))
6317 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6319 ret = perf_output_begin(&handle, event,
6320 task_event->event_id.header.size);
6324 task_event->event_id.pid = perf_event_pid(event, task);
6325 task_event->event_id.ppid = perf_event_pid(event, current);
6327 task_event->event_id.tid = perf_event_tid(event, task);
6328 task_event->event_id.ptid = perf_event_tid(event, current);
6330 task_event->event_id.time = perf_event_clock(event);
6332 perf_output_put(&handle, task_event->event_id);
6334 perf_event__output_id_sample(event, &handle, &sample);
6336 perf_output_end(&handle);
6338 task_event->event_id.header.size = size;
6341 static void perf_event_task(struct task_struct *task,
6342 struct perf_event_context *task_ctx,
6345 struct perf_task_event task_event;
6347 if (!atomic_read(&nr_comm_events) &&
6348 !atomic_read(&nr_mmap_events) &&
6349 !atomic_read(&nr_task_events))
6352 task_event = (struct perf_task_event){
6354 .task_ctx = task_ctx,
6357 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6359 .size = sizeof(task_event.event_id),
6369 perf_iterate_sb(perf_event_task_output,
6374 void perf_event_fork(struct task_struct *task)
6376 perf_event_task(task, NULL, 1);
6383 struct perf_comm_event {
6384 struct task_struct *task;
6389 struct perf_event_header header;
6396 static int perf_event_comm_match(struct perf_event *event)
6398 return event->attr.comm;
6401 static void perf_event_comm_output(struct perf_event *event,
6404 struct perf_comm_event *comm_event = data;
6405 struct perf_output_handle handle;
6406 struct perf_sample_data sample;
6407 int size = comm_event->event_id.header.size;
6410 if (!perf_event_comm_match(event))
6413 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6414 ret = perf_output_begin(&handle, event,
6415 comm_event->event_id.header.size);
6420 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6421 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6423 perf_output_put(&handle, comm_event->event_id);
6424 __output_copy(&handle, comm_event->comm,
6425 comm_event->comm_size);
6427 perf_event__output_id_sample(event, &handle, &sample);
6429 perf_output_end(&handle);
6431 comm_event->event_id.header.size = size;
6434 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6436 char comm[TASK_COMM_LEN];
6439 memset(comm, 0, sizeof(comm));
6440 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6441 size = ALIGN(strlen(comm)+1, sizeof(u64));
6443 comm_event->comm = comm;
6444 comm_event->comm_size = size;
6446 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6448 perf_iterate_sb(perf_event_comm_output,
6453 void perf_event_comm(struct task_struct *task, bool exec)
6455 struct perf_comm_event comm_event;
6457 if (!atomic_read(&nr_comm_events))
6460 comm_event = (struct perf_comm_event){
6466 .type = PERF_RECORD_COMM,
6467 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6475 perf_event_comm_event(&comm_event);
6482 struct perf_mmap_event {
6483 struct vm_area_struct *vma;
6485 const char *file_name;
6493 struct perf_event_header header;
6503 static int perf_event_mmap_match(struct perf_event *event,
6506 struct perf_mmap_event *mmap_event = data;
6507 struct vm_area_struct *vma = mmap_event->vma;
6508 int executable = vma->vm_flags & VM_EXEC;
6510 return (!executable && event->attr.mmap_data) ||
6511 (executable && (event->attr.mmap || event->attr.mmap2));
6514 static void perf_event_mmap_output(struct perf_event *event,
6517 struct perf_mmap_event *mmap_event = data;
6518 struct perf_output_handle handle;
6519 struct perf_sample_data sample;
6520 int size = mmap_event->event_id.header.size;
6523 if (!perf_event_mmap_match(event, data))
6526 if (event->attr.mmap2) {
6527 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6528 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6529 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6530 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6531 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6532 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6533 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6536 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6537 ret = perf_output_begin(&handle, event,
6538 mmap_event->event_id.header.size);
6542 mmap_event->event_id.pid = perf_event_pid(event, current);
6543 mmap_event->event_id.tid = perf_event_tid(event, current);
6545 perf_output_put(&handle, mmap_event->event_id);
6547 if (event->attr.mmap2) {
6548 perf_output_put(&handle, mmap_event->maj);
6549 perf_output_put(&handle, mmap_event->min);
6550 perf_output_put(&handle, mmap_event->ino);
6551 perf_output_put(&handle, mmap_event->ino_generation);
6552 perf_output_put(&handle, mmap_event->prot);
6553 perf_output_put(&handle, mmap_event->flags);
6556 __output_copy(&handle, mmap_event->file_name,
6557 mmap_event->file_size);
6559 perf_event__output_id_sample(event, &handle, &sample);
6561 perf_output_end(&handle);
6563 mmap_event->event_id.header.size = size;
6566 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6568 struct vm_area_struct *vma = mmap_event->vma;
6569 struct file *file = vma->vm_file;
6570 int maj = 0, min = 0;
6571 u64 ino = 0, gen = 0;
6572 u32 prot = 0, flags = 0;
6579 struct inode *inode;
6582 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6588 * d_path() works from the end of the rb backwards, so we
6589 * need to add enough zero bytes after the string to handle
6590 * the 64bit alignment we do later.
6592 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6597 inode = file_inode(vma->vm_file);
6598 dev = inode->i_sb->s_dev;
6600 gen = inode->i_generation;
6604 if (vma->vm_flags & VM_READ)
6606 if (vma->vm_flags & VM_WRITE)
6608 if (vma->vm_flags & VM_EXEC)
6611 if (vma->vm_flags & VM_MAYSHARE)
6614 flags = MAP_PRIVATE;
6616 if (vma->vm_flags & VM_DENYWRITE)
6617 flags |= MAP_DENYWRITE;
6618 if (vma->vm_flags & VM_MAYEXEC)
6619 flags |= MAP_EXECUTABLE;
6620 if (vma->vm_flags & VM_LOCKED)
6621 flags |= MAP_LOCKED;
6622 if (vma->vm_flags & VM_HUGETLB)
6623 flags |= MAP_HUGETLB;
6627 if (vma->vm_ops && vma->vm_ops->name) {
6628 name = (char *) vma->vm_ops->name(vma);
6633 name = (char *)arch_vma_name(vma);
6637 if (vma->vm_start <= vma->vm_mm->start_brk &&
6638 vma->vm_end >= vma->vm_mm->brk) {
6642 if (vma->vm_start <= vma->vm_mm->start_stack &&
6643 vma->vm_end >= vma->vm_mm->start_stack) {
6653 strlcpy(tmp, name, sizeof(tmp));
6657 * Since our buffer works in 8 byte units we need to align our string
6658 * size to a multiple of 8. However, we must guarantee the tail end is
6659 * zero'd out to avoid leaking random bits to userspace.
6661 size = strlen(name)+1;
6662 while (!IS_ALIGNED(size, sizeof(u64)))
6663 name[size++] = '\0';
6665 mmap_event->file_name = name;
6666 mmap_event->file_size = size;
6667 mmap_event->maj = maj;
6668 mmap_event->min = min;
6669 mmap_event->ino = ino;
6670 mmap_event->ino_generation = gen;
6671 mmap_event->prot = prot;
6672 mmap_event->flags = flags;
6674 if (!(vma->vm_flags & VM_EXEC))
6675 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6677 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6679 perf_iterate_sb(perf_event_mmap_output,
6687 * Check whether inode and address range match filter criteria.
6689 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
6690 struct file *file, unsigned long offset,
6693 if (filter->inode != file->f_inode)
6696 if (filter->offset > offset + size)
6699 if (filter->offset + filter->size < offset)
6705 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
6707 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6708 struct vm_area_struct *vma = data;
6709 unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
6710 struct file *file = vma->vm_file;
6711 struct perf_addr_filter *filter;
6712 unsigned int restart = 0, count = 0;
6714 if (!has_addr_filter(event))
6720 raw_spin_lock_irqsave(&ifh->lock, flags);
6721 list_for_each_entry(filter, &ifh->list, entry) {
6722 if (perf_addr_filter_match(filter, file, off,
6723 vma->vm_end - vma->vm_start)) {
6724 event->addr_filters_offs[count] = vma->vm_start;
6732 event->addr_filters_gen++;
6733 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6736 perf_event_stop(event, 1);
6740 * Adjust all task's events' filters to the new vma
6742 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
6744 struct perf_event_context *ctx;
6748 * Data tracing isn't supported yet and as such there is no need
6749 * to keep track of anything that isn't related to executable code:
6751 if (!(vma->vm_flags & VM_EXEC))
6755 for_each_task_context_nr(ctxn) {
6756 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6760 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
6765 void perf_event_mmap(struct vm_area_struct *vma)
6767 struct perf_mmap_event mmap_event;
6769 if (!atomic_read(&nr_mmap_events))
6772 mmap_event = (struct perf_mmap_event){
6778 .type = PERF_RECORD_MMAP,
6779 .misc = PERF_RECORD_MISC_USER,
6784 .start = vma->vm_start,
6785 .len = vma->vm_end - vma->vm_start,
6786 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6788 /* .maj (attr_mmap2 only) */
6789 /* .min (attr_mmap2 only) */
6790 /* .ino (attr_mmap2 only) */
6791 /* .ino_generation (attr_mmap2 only) */
6792 /* .prot (attr_mmap2 only) */
6793 /* .flags (attr_mmap2 only) */
6796 perf_addr_filters_adjust(vma);
6797 perf_event_mmap_event(&mmap_event);
6800 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6801 unsigned long size, u64 flags)
6803 struct perf_output_handle handle;
6804 struct perf_sample_data sample;
6805 struct perf_aux_event {
6806 struct perf_event_header header;
6812 .type = PERF_RECORD_AUX,
6814 .size = sizeof(rec),
6822 perf_event_header__init_id(&rec.header, &sample, event);
6823 ret = perf_output_begin(&handle, event, rec.header.size);
6828 perf_output_put(&handle, rec);
6829 perf_event__output_id_sample(event, &handle, &sample);
6831 perf_output_end(&handle);
6835 * Lost/dropped samples logging
6837 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6839 struct perf_output_handle handle;
6840 struct perf_sample_data sample;
6844 struct perf_event_header header;
6846 } lost_samples_event = {
6848 .type = PERF_RECORD_LOST_SAMPLES,
6850 .size = sizeof(lost_samples_event),
6855 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6857 ret = perf_output_begin(&handle, event,
6858 lost_samples_event.header.size);
6862 perf_output_put(&handle, lost_samples_event);
6863 perf_event__output_id_sample(event, &handle, &sample);
6864 perf_output_end(&handle);
6868 * context_switch tracking
6871 struct perf_switch_event {
6872 struct task_struct *task;
6873 struct task_struct *next_prev;
6876 struct perf_event_header header;
6882 static int perf_event_switch_match(struct perf_event *event)
6884 return event->attr.context_switch;
6887 static void perf_event_switch_output(struct perf_event *event, void *data)
6889 struct perf_switch_event *se = data;
6890 struct perf_output_handle handle;
6891 struct perf_sample_data sample;
6894 if (!perf_event_switch_match(event))
6897 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6898 if (event->ctx->task) {
6899 se->event_id.header.type = PERF_RECORD_SWITCH;
6900 se->event_id.header.size = sizeof(se->event_id.header);
6902 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6903 se->event_id.header.size = sizeof(se->event_id);
6904 se->event_id.next_prev_pid =
6905 perf_event_pid(event, se->next_prev);
6906 se->event_id.next_prev_tid =
6907 perf_event_tid(event, se->next_prev);
6910 perf_event_header__init_id(&se->event_id.header, &sample, event);
6912 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6916 if (event->ctx->task)
6917 perf_output_put(&handle, se->event_id.header);
6919 perf_output_put(&handle, se->event_id);
6921 perf_event__output_id_sample(event, &handle, &sample);
6923 perf_output_end(&handle);
6926 static void perf_event_switch(struct task_struct *task,
6927 struct task_struct *next_prev, bool sched_in)
6929 struct perf_switch_event switch_event;
6931 /* N.B. caller checks nr_switch_events != 0 */
6933 switch_event = (struct perf_switch_event){
6935 .next_prev = next_prev,
6939 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6942 /* .next_prev_pid */
6943 /* .next_prev_tid */
6947 perf_iterate_sb(perf_event_switch_output,
6953 * IRQ throttle logging
6956 static void perf_log_throttle(struct perf_event *event, int enable)
6958 struct perf_output_handle handle;
6959 struct perf_sample_data sample;
6963 struct perf_event_header header;
6967 } throttle_event = {
6969 .type = PERF_RECORD_THROTTLE,
6971 .size = sizeof(throttle_event),
6973 .time = perf_event_clock(event),
6974 .id = primary_event_id(event),
6975 .stream_id = event->id,
6979 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6981 perf_event_header__init_id(&throttle_event.header, &sample, event);
6983 ret = perf_output_begin(&handle, event,
6984 throttle_event.header.size);
6988 perf_output_put(&handle, throttle_event);
6989 perf_event__output_id_sample(event, &handle, &sample);
6990 perf_output_end(&handle);
6993 static void perf_log_itrace_start(struct perf_event *event)
6995 struct perf_output_handle handle;
6996 struct perf_sample_data sample;
6997 struct perf_aux_event {
6998 struct perf_event_header header;
7005 event = event->parent;
7007 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
7008 event->hw.itrace_started)
7011 rec.header.type = PERF_RECORD_ITRACE_START;
7012 rec.header.misc = 0;
7013 rec.header.size = sizeof(rec);
7014 rec.pid = perf_event_pid(event, current);
7015 rec.tid = perf_event_tid(event, current);
7017 perf_event_header__init_id(&rec.header, &sample, event);
7018 ret = perf_output_begin(&handle, event, rec.header.size);
7023 perf_output_put(&handle, rec);
7024 perf_event__output_id_sample(event, &handle, &sample);
7026 perf_output_end(&handle);
7030 * Generic event overflow handling, sampling.
7033 static int __perf_event_overflow(struct perf_event *event,
7034 int throttle, struct perf_sample_data *data,
7035 struct pt_regs *regs)
7037 int events = atomic_read(&event->event_limit);
7038 struct hw_perf_event *hwc = &event->hw;
7043 * Non-sampling counters might still use the PMI to fold short
7044 * hardware counters, ignore those.
7046 if (unlikely(!is_sampling_event(event)))
7049 seq = __this_cpu_read(perf_throttled_seq);
7050 if (seq != hwc->interrupts_seq) {
7051 hwc->interrupts_seq = seq;
7052 hwc->interrupts = 1;
7055 if (unlikely(throttle
7056 && hwc->interrupts >= max_samples_per_tick)) {
7057 __this_cpu_inc(perf_throttled_count);
7058 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
7059 hwc->interrupts = MAX_INTERRUPTS;
7060 perf_log_throttle(event, 0);
7065 if (event->attr.freq) {
7066 u64 now = perf_clock();
7067 s64 delta = now - hwc->freq_time_stamp;
7069 hwc->freq_time_stamp = now;
7071 if (delta > 0 && delta < 2*TICK_NSEC)
7072 perf_adjust_period(event, delta, hwc->last_period, true);
7076 * XXX event_limit might not quite work as expected on inherited
7080 event->pending_kill = POLL_IN;
7081 if (events && atomic_dec_and_test(&event->event_limit)) {
7083 event->pending_kill = POLL_HUP;
7085 perf_event_disable_inatomic(event);
7088 READ_ONCE(event->overflow_handler)(event, data, regs);
7090 if (*perf_event_fasync(event) && event->pending_kill) {
7091 event->pending_wakeup = 1;
7092 irq_work_queue(&event->pending);
7098 int perf_event_overflow(struct perf_event *event,
7099 struct perf_sample_data *data,
7100 struct pt_regs *regs)
7102 return __perf_event_overflow(event, 1, data, regs);
7106 * Generic software event infrastructure
7109 struct swevent_htable {
7110 struct swevent_hlist *swevent_hlist;
7111 struct mutex hlist_mutex;
7114 /* Recursion avoidance in each contexts */
7115 int recursion[PERF_NR_CONTEXTS];
7118 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
7121 * We directly increment event->count and keep a second value in
7122 * event->hw.period_left to count intervals. This period event
7123 * is kept in the range [-sample_period, 0] so that we can use the
7127 u64 perf_swevent_set_period(struct perf_event *event)
7129 struct hw_perf_event *hwc = &event->hw;
7130 u64 period = hwc->last_period;
7134 hwc->last_period = hwc->sample_period;
7137 old = val = local64_read(&hwc->period_left);
7141 nr = div64_u64(period + val, period);
7142 offset = nr * period;
7144 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7150 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
7151 struct perf_sample_data *data,
7152 struct pt_regs *regs)
7154 struct hw_perf_event *hwc = &event->hw;
7158 overflow = perf_swevent_set_period(event);
7160 if (hwc->interrupts == MAX_INTERRUPTS)
7163 for (; overflow; overflow--) {
7164 if (__perf_event_overflow(event, throttle,
7167 * We inhibit the overflow from happening when
7168 * hwc->interrupts == MAX_INTERRUPTS.
7176 static void perf_swevent_event(struct perf_event *event, u64 nr,
7177 struct perf_sample_data *data,
7178 struct pt_regs *regs)
7180 struct hw_perf_event *hwc = &event->hw;
7182 local64_add(nr, &event->count);
7187 if (!is_sampling_event(event))
7190 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
7192 return perf_swevent_overflow(event, 1, data, regs);
7194 data->period = event->hw.last_period;
7196 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
7197 return perf_swevent_overflow(event, 1, data, regs);
7199 if (local64_add_negative(nr, &hwc->period_left))
7202 perf_swevent_overflow(event, 0, data, regs);
7205 static int perf_exclude_event(struct perf_event *event,
7206 struct pt_regs *regs)
7208 if (event->hw.state & PERF_HES_STOPPED)
7212 if (event->attr.exclude_user && user_mode(regs))
7215 if (event->attr.exclude_kernel && !user_mode(regs))
7222 static int perf_swevent_match(struct perf_event *event,
7223 enum perf_type_id type,
7225 struct perf_sample_data *data,
7226 struct pt_regs *regs)
7228 if (event->attr.type != type)
7231 if (event->attr.config != event_id)
7234 if (perf_exclude_event(event, regs))
7240 static inline u64 swevent_hash(u64 type, u32 event_id)
7242 u64 val = event_id | (type << 32);
7244 return hash_64(val, SWEVENT_HLIST_BITS);
7247 static inline struct hlist_head *
7248 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
7250 u64 hash = swevent_hash(type, event_id);
7252 return &hlist->heads[hash];
7255 /* For the read side: events when they trigger */
7256 static inline struct hlist_head *
7257 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
7259 struct swevent_hlist *hlist;
7261 hlist = rcu_dereference(swhash->swevent_hlist);
7265 return __find_swevent_head(hlist, type, event_id);
7268 /* For the event head insertion and removal in the hlist */
7269 static inline struct hlist_head *
7270 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
7272 struct swevent_hlist *hlist;
7273 u32 event_id = event->attr.config;
7274 u64 type = event->attr.type;
7277 * Event scheduling is always serialized against hlist allocation
7278 * and release. Which makes the protected version suitable here.
7279 * The context lock guarantees that.
7281 hlist = rcu_dereference_protected(swhash->swevent_hlist,
7282 lockdep_is_held(&event->ctx->lock));
7286 return __find_swevent_head(hlist, type, event_id);
7289 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
7291 struct perf_sample_data *data,
7292 struct pt_regs *regs)
7294 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7295 struct perf_event *event;
7296 struct hlist_head *head;
7299 head = find_swevent_head_rcu(swhash, type, event_id);
7303 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7304 if (perf_swevent_match(event, type, event_id, data, regs))
7305 perf_swevent_event(event, nr, data, regs);
7311 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
7313 int perf_swevent_get_recursion_context(void)
7315 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7317 return get_recursion_context(swhash->recursion);
7319 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
7321 void perf_swevent_put_recursion_context(int rctx)
7323 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7325 put_recursion_context(swhash->recursion, rctx);
7328 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7330 struct perf_sample_data data;
7332 if (WARN_ON_ONCE(!regs))
7335 perf_sample_data_init(&data, addr, 0);
7336 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
7339 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7343 preempt_disable_notrace();
7344 rctx = perf_swevent_get_recursion_context();
7345 if (unlikely(rctx < 0))
7348 ___perf_sw_event(event_id, nr, regs, addr);
7350 perf_swevent_put_recursion_context(rctx);
7352 preempt_enable_notrace();
7355 static void perf_swevent_read(struct perf_event *event)
7359 static int perf_swevent_add(struct perf_event *event, int flags)
7361 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7362 struct hw_perf_event *hwc = &event->hw;
7363 struct hlist_head *head;
7365 if (is_sampling_event(event)) {
7366 hwc->last_period = hwc->sample_period;
7367 perf_swevent_set_period(event);
7370 hwc->state = !(flags & PERF_EF_START);
7372 head = find_swevent_head(swhash, event);
7373 if (WARN_ON_ONCE(!head))
7376 hlist_add_head_rcu(&event->hlist_entry, head);
7377 perf_event_update_userpage(event);
7382 static void perf_swevent_del(struct perf_event *event, int flags)
7384 hlist_del_rcu(&event->hlist_entry);
7387 static void perf_swevent_start(struct perf_event *event, int flags)
7389 event->hw.state = 0;
7392 static void perf_swevent_stop(struct perf_event *event, int flags)
7394 event->hw.state = PERF_HES_STOPPED;
7397 /* Deref the hlist from the update side */
7398 static inline struct swevent_hlist *
7399 swevent_hlist_deref(struct swevent_htable *swhash)
7401 return rcu_dereference_protected(swhash->swevent_hlist,
7402 lockdep_is_held(&swhash->hlist_mutex));
7405 static void swevent_hlist_release(struct swevent_htable *swhash)
7407 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7412 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7413 kfree_rcu(hlist, rcu_head);
7416 static void swevent_hlist_put_cpu(int cpu)
7418 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7420 mutex_lock(&swhash->hlist_mutex);
7422 if (!--swhash->hlist_refcount)
7423 swevent_hlist_release(swhash);
7425 mutex_unlock(&swhash->hlist_mutex);
7428 static void swevent_hlist_put(void)
7432 for_each_possible_cpu(cpu)
7433 swevent_hlist_put_cpu(cpu);
7436 static int swevent_hlist_get_cpu(int cpu)
7438 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7441 mutex_lock(&swhash->hlist_mutex);
7442 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7443 struct swevent_hlist *hlist;
7445 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7450 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7452 swhash->hlist_refcount++;
7454 mutex_unlock(&swhash->hlist_mutex);
7459 static int swevent_hlist_get(void)
7461 int err, cpu, failed_cpu;
7464 for_each_possible_cpu(cpu) {
7465 err = swevent_hlist_get_cpu(cpu);
7475 for_each_possible_cpu(cpu) {
7476 if (cpu == failed_cpu)
7478 swevent_hlist_put_cpu(cpu);
7485 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7487 static void sw_perf_event_destroy(struct perf_event *event)
7489 u64 event_id = event->attr.config;
7491 WARN_ON(event->parent);
7493 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7494 swevent_hlist_put();
7497 static int perf_swevent_init(struct perf_event *event)
7499 u64 event_id = event->attr.config;
7501 if (event->attr.type != PERF_TYPE_SOFTWARE)
7505 * no branch sampling for software events
7507 if (has_branch_stack(event))
7511 case PERF_COUNT_SW_CPU_CLOCK:
7512 case PERF_COUNT_SW_TASK_CLOCK:
7519 if (event_id >= PERF_COUNT_SW_MAX)
7522 if (!event->parent) {
7525 err = swevent_hlist_get();
7529 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7530 event->destroy = sw_perf_event_destroy;
7536 static struct pmu perf_swevent = {
7537 .task_ctx_nr = perf_sw_context,
7539 .capabilities = PERF_PMU_CAP_NO_NMI,
7541 .event_init = perf_swevent_init,
7542 .add = perf_swevent_add,
7543 .del = perf_swevent_del,
7544 .start = perf_swevent_start,
7545 .stop = perf_swevent_stop,
7546 .read = perf_swevent_read,
7549 #ifdef CONFIG_EVENT_TRACING
7551 static int perf_tp_filter_match(struct perf_event *event,
7552 struct perf_sample_data *data)
7554 void *record = data->raw->frag.data;
7556 /* only top level events have filters set */
7558 event = event->parent;
7560 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7565 static int perf_tp_event_match(struct perf_event *event,
7566 struct perf_sample_data *data,
7567 struct pt_regs *regs)
7569 if (event->hw.state & PERF_HES_STOPPED)
7572 * All tracepoints are from kernel-space.
7574 if (event->attr.exclude_kernel)
7577 if (!perf_tp_filter_match(event, data))
7583 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
7584 struct trace_event_call *call, u64 count,
7585 struct pt_regs *regs, struct hlist_head *head,
7586 struct task_struct *task)
7588 struct bpf_prog *prog = call->prog;
7591 *(struct pt_regs **)raw_data = regs;
7592 if (!trace_call_bpf(prog, raw_data) || hlist_empty(head)) {
7593 perf_swevent_put_recursion_context(rctx);
7597 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
7600 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
7602 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
7603 struct pt_regs *regs, struct hlist_head *head, int rctx,
7604 struct task_struct *task)
7606 struct perf_sample_data data;
7607 struct perf_event *event;
7609 struct perf_raw_record raw = {
7616 perf_sample_data_init(&data, 0, 0);
7619 perf_trace_buf_update(record, event_type);
7621 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7622 if (perf_tp_event_match(event, &data, regs))
7623 perf_swevent_event(event, count, &data, regs);
7627 * If we got specified a target task, also iterate its context and
7628 * deliver this event there too.
7630 if (task && task != current) {
7631 struct perf_event_context *ctx;
7632 struct trace_entry *entry = record;
7635 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7639 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7640 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7642 if (event->attr.config != entry->type)
7644 if (perf_tp_event_match(event, &data, regs))
7645 perf_swevent_event(event, count, &data, regs);
7651 perf_swevent_put_recursion_context(rctx);
7653 EXPORT_SYMBOL_GPL(perf_tp_event);
7655 static void tp_perf_event_destroy(struct perf_event *event)
7657 perf_trace_destroy(event);
7660 static int perf_tp_event_init(struct perf_event *event)
7664 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7668 * no branch sampling for tracepoint events
7670 if (has_branch_stack(event))
7673 err = perf_trace_init(event);
7677 event->destroy = tp_perf_event_destroy;
7682 static struct pmu perf_tracepoint = {
7683 .task_ctx_nr = perf_sw_context,
7685 .event_init = perf_tp_event_init,
7686 .add = perf_trace_add,
7687 .del = perf_trace_del,
7688 .start = perf_swevent_start,
7689 .stop = perf_swevent_stop,
7690 .read = perf_swevent_read,
7693 static inline void perf_tp_register(void)
7695 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7698 static void perf_event_free_filter(struct perf_event *event)
7700 ftrace_profile_free_filter(event);
7703 #ifdef CONFIG_BPF_SYSCALL
7704 static void bpf_overflow_handler(struct perf_event *event,
7705 struct perf_sample_data *data,
7706 struct pt_regs *regs)
7708 struct bpf_perf_event_data_kern ctx = {
7715 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
7718 ret = BPF_PROG_RUN(event->prog, (void *)&ctx);
7721 __this_cpu_dec(bpf_prog_active);
7726 event->orig_overflow_handler(event, data, regs);
7729 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
7731 struct bpf_prog *prog;
7733 if (event->overflow_handler_context)
7734 /* hw breakpoint or kernel counter */
7740 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
7742 return PTR_ERR(prog);
7745 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
7746 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
7750 static void perf_event_free_bpf_handler(struct perf_event *event)
7752 struct bpf_prog *prog = event->prog;
7757 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
7762 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
7766 static void perf_event_free_bpf_handler(struct perf_event *event)
7771 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7773 bool is_kprobe, is_tracepoint;
7774 struct bpf_prog *prog;
7776 if (event->attr.type == PERF_TYPE_HARDWARE ||
7777 event->attr.type == PERF_TYPE_SOFTWARE)
7778 return perf_event_set_bpf_handler(event, prog_fd);
7780 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7783 if (event->tp_event->prog)
7786 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
7787 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
7788 if (!is_kprobe && !is_tracepoint)
7789 /* bpf programs can only be attached to u/kprobe or tracepoint */
7792 prog = bpf_prog_get(prog_fd);
7794 return PTR_ERR(prog);
7796 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
7797 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
7798 /* valid fd, but invalid bpf program type */
7803 if (is_tracepoint) {
7804 int off = trace_event_get_offsets(event->tp_event);
7806 if (prog->aux->max_ctx_offset > off) {
7811 event->tp_event->prog = prog;
7816 static void perf_event_free_bpf_prog(struct perf_event *event)
7818 struct bpf_prog *prog;
7820 perf_event_free_bpf_handler(event);
7822 if (!event->tp_event)
7825 prog = event->tp_event->prog;
7827 event->tp_event->prog = NULL;
7834 static inline void perf_tp_register(void)
7838 static void perf_event_free_filter(struct perf_event *event)
7842 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7847 static void perf_event_free_bpf_prog(struct perf_event *event)
7850 #endif /* CONFIG_EVENT_TRACING */
7852 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7853 void perf_bp_event(struct perf_event *bp, void *data)
7855 struct perf_sample_data sample;
7856 struct pt_regs *regs = data;
7858 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7860 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7861 perf_swevent_event(bp, 1, &sample, regs);
7866 * Allocate a new address filter
7868 static struct perf_addr_filter *
7869 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
7871 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
7872 struct perf_addr_filter *filter;
7874 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
7878 INIT_LIST_HEAD(&filter->entry);
7879 list_add_tail(&filter->entry, filters);
7884 static void free_filters_list(struct list_head *filters)
7886 struct perf_addr_filter *filter, *iter;
7888 list_for_each_entry_safe(filter, iter, filters, entry) {
7890 iput(filter->inode);
7891 list_del(&filter->entry);
7897 * Free existing address filters and optionally install new ones
7899 static void perf_addr_filters_splice(struct perf_event *event,
7900 struct list_head *head)
7902 unsigned long flags;
7905 if (!has_addr_filter(event))
7908 /* don't bother with children, they don't have their own filters */
7912 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
7914 list_splice_init(&event->addr_filters.list, &list);
7916 list_splice(head, &event->addr_filters.list);
7918 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
7920 free_filters_list(&list);
7924 * Scan through mm's vmas and see if one of them matches the
7925 * @filter; if so, adjust filter's address range.
7926 * Called with mm::mmap_sem down for reading.
7928 static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
7929 struct mm_struct *mm)
7931 struct vm_area_struct *vma;
7933 for (vma = mm->mmap; vma; vma = vma->vm_next) {
7934 struct file *file = vma->vm_file;
7935 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
7936 unsigned long vma_size = vma->vm_end - vma->vm_start;
7941 if (!perf_addr_filter_match(filter, file, off, vma_size))
7944 return vma->vm_start;
7951 * Update event's address range filters based on the
7952 * task's existing mappings, if any.
7954 static void perf_event_addr_filters_apply(struct perf_event *event)
7956 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7957 struct task_struct *task = READ_ONCE(event->ctx->task);
7958 struct perf_addr_filter *filter;
7959 struct mm_struct *mm = NULL;
7960 unsigned int count = 0;
7961 unsigned long flags;
7964 * We may observe TASK_TOMBSTONE, which means that the event tear-down
7965 * will stop on the parent's child_mutex that our caller is also holding
7967 if (task == TASK_TOMBSTONE)
7970 mm = get_task_mm(event->ctx->task);
7974 down_read(&mm->mmap_sem);
7976 raw_spin_lock_irqsave(&ifh->lock, flags);
7977 list_for_each_entry(filter, &ifh->list, entry) {
7978 event->addr_filters_offs[count] = 0;
7981 * Adjust base offset if the filter is associated to a binary
7982 * that needs to be mapped:
7985 event->addr_filters_offs[count] =
7986 perf_addr_filter_apply(filter, mm);
7991 event->addr_filters_gen++;
7992 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7994 up_read(&mm->mmap_sem);
7999 perf_event_stop(event, 1);
8003 * Address range filtering: limiting the data to certain
8004 * instruction address ranges. Filters are ioctl()ed to us from
8005 * userspace as ascii strings.
8007 * Filter string format:
8010 * where ACTION is one of the
8011 * * "filter": limit the trace to this region
8012 * * "start": start tracing from this address
8013 * * "stop": stop tracing at this address/region;
8015 * * for kernel addresses: <start address>[/<size>]
8016 * * for object files: <start address>[/<size>]@</path/to/object/file>
8018 * if <size> is not specified, the range is treated as a single address.
8031 IF_STATE_ACTION = 0,
8036 static const match_table_t if_tokens = {
8037 { IF_ACT_FILTER, "filter" },
8038 { IF_ACT_START, "start" },
8039 { IF_ACT_STOP, "stop" },
8040 { IF_SRC_FILE, "%u/%u@%s" },
8041 { IF_SRC_KERNEL, "%u/%u" },
8042 { IF_SRC_FILEADDR, "%u@%s" },
8043 { IF_SRC_KERNELADDR, "%u" },
8047 * Address filter string parser
8050 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
8051 struct list_head *filters)
8053 struct perf_addr_filter *filter = NULL;
8054 char *start, *orig, *filename = NULL;
8056 substring_t args[MAX_OPT_ARGS];
8057 int state = IF_STATE_ACTION, token;
8058 unsigned int kernel = 0;
8061 orig = fstr = kstrdup(fstr, GFP_KERNEL);
8065 while ((start = strsep(&fstr, " ,\n")) != NULL) {
8071 /* filter definition begins */
8072 if (state == IF_STATE_ACTION) {
8073 filter = perf_addr_filter_new(event, filters);
8078 token = match_token(start, if_tokens, args);
8085 if (state != IF_STATE_ACTION)
8088 state = IF_STATE_SOURCE;
8091 case IF_SRC_KERNELADDR:
8095 case IF_SRC_FILEADDR:
8097 if (state != IF_STATE_SOURCE)
8100 if (token == IF_SRC_FILE || token == IF_SRC_KERNEL)
8104 ret = kstrtoul(args[0].from, 0, &filter->offset);
8108 if (filter->range) {
8110 ret = kstrtoul(args[1].from, 0, &filter->size);
8115 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
8116 int fpos = filter->range ? 2 : 1;
8118 filename = match_strdup(&args[fpos]);
8125 state = IF_STATE_END;
8133 * Filter definition is fully parsed, validate and install it.
8134 * Make sure that it doesn't contradict itself or the event's
8137 if (state == IF_STATE_END) {
8138 if (kernel && event->attr.exclude_kernel)
8145 /* look up the path and grab its inode */
8146 ret = kern_path(filename, LOOKUP_FOLLOW, &path);
8148 goto fail_free_name;
8150 filter->inode = igrab(d_inode(path.dentry));
8156 if (!filter->inode ||
8157 !S_ISREG(filter->inode->i_mode))
8158 /* free_filters_list() will iput() */
8162 /* ready to consume more filters */
8163 state = IF_STATE_ACTION;
8168 if (state != IF_STATE_ACTION)
8178 free_filters_list(filters);
8185 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
8191 * Since this is called in perf_ioctl() path, we're already holding
8194 lockdep_assert_held(&event->ctx->mutex);
8196 if (WARN_ON_ONCE(event->parent))
8200 * For now, we only support filtering in per-task events; doing so
8201 * for CPU-wide events requires additional context switching trickery,
8202 * since same object code will be mapped at different virtual
8203 * addresses in different processes.
8205 if (!event->ctx->task)
8208 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
8212 ret = event->pmu->addr_filters_validate(&filters);
8214 free_filters_list(&filters);
8218 /* remove existing filters, if any */
8219 perf_addr_filters_splice(event, &filters);
8221 /* install new filters */
8222 perf_event_for_each_child(event, perf_event_addr_filters_apply);
8227 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
8232 if ((event->attr.type != PERF_TYPE_TRACEPOINT ||
8233 !IS_ENABLED(CONFIG_EVENT_TRACING)) &&
8234 !has_addr_filter(event))
8237 filter_str = strndup_user(arg, PAGE_SIZE);
8238 if (IS_ERR(filter_str))
8239 return PTR_ERR(filter_str);
8241 if (IS_ENABLED(CONFIG_EVENT_TRACING) &&
8242 event->attr.type == PERF_TYPE_TRACEPOINT)
8243 ret = ftrace_profile_set_filter(event, event->attr.config,
8245 else if (has_addr_filter(event))
8246 ret = perf_event_set_addr_filter(event, filter_str);
8253 * hrtimer based swevent callback
8256 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
8258 enum hrtimer_restart ret = HRTIMER_RESTART;
8259 struct perf_sample_data data;
8260 struct pt_regs *regs;
8261 struct perf_event *event;
8264 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
8266 if (event->state != PERF_EVENT_STATE_ACTIVE)
8267 return HRTIMER_NORESTART;
8269 event->pmu->read(event);
8271 perf_sample_data_init(&data, 0, event->hw.last_period);
8272 regs = get_irq_regs();
8274 if (regs && !perf_exclude_event(event, regs)) {
8275 if (!(event->attr.exclude_idle && is_idle_task(current)))
8276 if (__perf_event_overflow(event, 1, &data, regs))
8277 ret = HRTIMER_NORESTART;
8280 period = max_t(u64, 10000, event->hw.sample_period);
8281 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
8286 static void perf_swevent_start_hrtimer(struct perf_event *event)
8288 struct hw_perf_event *hwc = &event->hw;
8291 if (!is_sampling_event(event))
8294 period = local64_read(&hwc->period_left);
8299 local64_set(&hwc->period_left, 0);
8301 period = max_t(u64, 10000, hwc->sample_period);
8303 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
8304 HRTIMER_MODE_REL_PINNED);
8307 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
8309 struct hw_perf_event *hwc = &event->hw;
8311 if (is_sampling_event(event)) {
8312 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
8313 local64_set(&hwc->period_left, ktime_to_ns(remaining));
8315 hrtimer_cancel(&hwc->hrtimer);
8319 static void perf_swevent_init_hrtimer(struct perf_event *event)
8321 struct hw_perf_event *hwc = &event->hw;
8323 if (!is_sampling_event(event))
8326 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
8327 hwc->hrtimer.function = perf_swevent_hrtimer;
8330 * Since hrtimers have a fixed rate, we can do a static freq->period
8331 * mapping and avoid the whole period adjust feedback stuff.
8333 if (event->attr.freq) {
8334 long freq = event->attr.sample_freq;
8336 event->attr.sample_period = NSEC_PER_SEC / freq;
8337 hwc->sample_period = event->attr.sample_period;
8338 local64_set(&hwc->period_left, hwc->sample_period);
8339 hwc->last_period = hwc->sample_period;
8340 event->attr.freq = 0;
8345 * Software event: cpu wall time clock
8348 static void cpu_clock_event_update(struct perf_event *event)
8353 now = local_clock();
8354 prev = local64_xchg(&event->hw.prev_count, now);
8355 local64_add(now - prev, &event->count);
8358 static void cpu_clock_event_start(struct perf_event *event, int flags)
8360 local64_set(&event->hw.prev_count, local_clock());
8361 perf_swevent_start_hrtimer(event);
8364 static void cpu_clock_event_stop(struct perf_event *event, int flags)
8366 perf_swevent_cancel_hrtimer(event);
8367 cpu_clock_event_update(event);
8370 static int cpu_clock_event_add(struct perf_event *event, int flags)
8372 if (flags & PERF_EF_START)
8373 cpu_clock_event_start(event, flags);
8374 perf_event_update_userpage(event);
8379 static void cpu_clock_event_del(struct perf_event *event, int flags)
8381 cpu_clock_event_stop(event, flags);
8384 static void cpu_clock_event_read(struct perf_event *event)
8386 cpu_clock_event_update(event);
8389 static int cpu_clock_event_init(struct perf_event *event)
8391 if (event->attr.type != PERF_TYPE_SOFTWARE)
8394 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
8398 * no branch sampling for software events
8400 if (has_branch_stack(event))
8403 perf_swevent_init_hrtimer(event);
8408 static struct pmu perf_cpu_clock = {
8409 .task_ctx_nr = perf_sw_context,
8411 .capabilities = PERF_PMU_CAP_NO_NMI,
8413 .event_init = cpu_clock_event_init,
8414 .add = cpu_clock_event_add,
8415 .del = cpu_clock_event_del,
8416 .start = cpu_clock_event_start,
8417 .stop = cpu_clock_event_stop,
8418 .read = cpu_clock_event_read,
8422 * Software event: task time clock
8425 static void task_clock_event_update(struct perf_event *event, u64 now)
8430 prev = local64_xchg(&event->hw.prev_count, now);
8432 local64_add(delta, &event->count);
8435 static void task_clock_event_start(struct perf_event *event, int flags)
8437 local64_set(&event->hw.prev_count, event->ctx->time);
8438 perf_swevent_start_hrtimer(event);
8441 static void task_clock_event_stop(struct perf_event *event, int flags)
8443 perf_swevent_cancel_hrtimer(event);
8444 task_clock_event_update(event, event->ctx->time);
8447 static int task_clock_event_add(struct perf_event *event, int flags)
8449 if (flags & PERF_EF_START)
8450 task_clock_event_start(event, flags);
8451 perf_event_update_userpage(event);
8456 static void task_clock_event_del(struct perf_event *event, int flags)
8458 task_clock_event_stop(event, PERF_EF_UPDATE);
8461 static void task_clock_event_read(struct perf_event *event)
8463 u64 now = perf_clock();
8464 u64 delta = now - event->ctx->timestamp;
8465 u64 time = event->ctx->time + delta;
8467 task_clock_event_update(event, time);
8470 static int task_clock_event_init(struct perf_event *event)
8472 if (event->attr.type != PERF_TYPE_SOFTWARE)
8475 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
8479 * no branch sampling for software events
8481 if (has_branch_stack(event))
8484 perf_swevent_init_hrtimer(event);
8489 static struct pmu perf_task_clock = {
8490 .task_ctx_nr = perf_sw_context,
8492 .capabilities = PERF_PMU_CAP_NO_NMI,
8494 .event_init = task_clock_event_init,
8495 .add = task_clock_event_add,
8496 .del = task_clock_event_del,
8497 .start = task_clock_event_start,
8498 .stop = task_clock_event_stop,
8499 .read = task_clock_event_read,
8502 static void perf_pmu_nop_void(struct pmu *pmu)
8506 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
8510 static int perf_pmu_nop_int(struct pmu *pmu)
8515 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
8517 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
8519 __this_cpu_write(nop_txn_flags, flags);
8521 if (flags & ~PERF_PMU_TXN_ADD)
8524 perf_pmu_disable(pmu);
8527 static int perf_pmu_commit_txn(struct pmu *pmu)
8529 unsigned int flags = __this_cpu_read(nop_txn_flags);
8531 __this_cpu_write(nop_txn_flags, 0);
8533 if (flags & ~PERF_PMU_TXN_ADD)
8536 perf_pmu_enable(pmu);
8540 static void perf_pmu_cancel_txn(struct pmu *pmu)
8542 unsigned int flags = __this_cpu_read(nop_txn_flags);
8544 __this_cpu_write(nop_txn_flags, 0);
8546 if (flags & ~PERF_PMU_TXN_ADD)
8549 perf_pmu_enable(pmu);
8552 static int perf_event_idx_default(struct perf_event *event)
8558 * Ensures all contexts with the same task_ctx_nr have the same
8559 * pmu_cpu_context too.
8561 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
8568 list_for_each_entry(pmu, &pmus, entry) {
8569 if (pmu->task_ctx_nr == ctxn)
8570 return pmu->pmu_cpu_context;
8576 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
8580 for_each_possible_cpu(cpu) {
8581 struct perf_cpu_context *cpuctx;
8583 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8585 if (cpuctx->unique_pmu == old_pmu)
8586 cpuctx->unique_pmu = pmu;
8590 static void free_pmu_context(struct pmu *pmu)
8594 mutex_lock(&pmus_lock);
8596 * Like a real lame refcount.
8598 list_for_each_entry(i, &pmus, entry) {
8599 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
8600 update_pmu_context(i, pmu);
8605 free_percpu(pmu->pmu_cpu_context);
8607 mutex_unlock(&pmus_lock);
8611 * Let userspace know that this PMU supports address range filtering:
8613 static ssize_t nr_addr_filters_show(struct device *dev,
8614 struct device_attribute *attr,
8617 struct pmu *pmu = dev_get_drvdata(dev);
8619 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
8621 DEVICE_ATTR_RO(nr_addr_filters);
8623 static struct idr pmu_idr;
8626 type_show(struct device *dev, struct device_attribute *attr, char *page)
8628 struct pmu *pmu = dev_get_drvdata(dev);
8630 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
8632 static DEVICE_ATTR_RO(type);
8635 perf_event_mux_interval_ms_show(struct device *dev,
8636 struct device_attribute *attr,
8639 struct pmu *pmu = dev_get_drvdata(dev);
8641 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
8644 static DEFINE_MUTEX(mux_interval_mutex);
8647 perf_event_mux_interval_ms_store(struct device *dev,
8648 struct device_attribute *attr,
8649 const char *buf, size_t count)
8651 struct pmu *pmu = dev_get_drvdata(dev);
8652 int timer, cpu, ret;
8654 ret = kstrtoint(buf, 0, &timer);
8661 /* same value, noting to do */
8662 if (timer == pmu->hrtimer_interval_ms)
8665 mutex_lock(&mux_interval_mutex);
8666 pmu->hrtimer_interval_ms = timer;
8668 /* update all cpuctx for this PMU */
8670 for_each_online_cpu(cpu) {
8671 struct perf_cpu_context *cpuctx;
8672 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8673 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
8675 cpu_function_call(cpu,
8676 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
8679 mutex_unlock(&mux_interval_mutex);
8683 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
8685 static struct attribute *pmu_dev_attrs[] = {
8686 &dev_attr_type.attr,
8687 &dev_attr_perf_event_mux_interval_ms.attr,
8690 ATTRIBUTE_GROUPS(pmu_dev);
8692 static int pmu_bus_running;
8693 static struct bus_type pmu_bus = {
8694 .name = "event_source",
8695 .dev_groups = pmu_dev_groups,
8698 static void pmu_dev_release(struct device *dev)
8703 static int pmu_dev_alloc(struct pmu *pmu)
8707 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
8711 pmu->dev->groups = pmu->attr_groups;
8712 device_initialize(pmu->dev);
8713 ret = dev_set_name(pmu->dev, "%s", pmu->name);
8717 dev_set_drvdata(pmu->dev, pmu);
8718 pmu->dev->bus = &pmu_bus;
8719 pmu->dev->release = pmu_dev_release;
8720 ret = device_add(pmu->dev);
8724 /* For PMUs with address filters, throw in an extra attribute: */
8725 if (pmu->nr_addr_filters)
8726 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
8735 device_del(pmu->dev);
8738 put_device(pmu->dev);
8742 static struct lock_class_key cpuctx_mutex;
8743 static struct lock_class_key cpuctx_lock;
8745 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
8749 mutex_lock(&pmus_lock);
8751 pmu->pmu_disable_count = alloc_percpu(int);
8752 if (!pmu->pmu_disable_count)
8761 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
8769 if (pmu_bus_running) {
8770 ret = pmu_dev_alloc(pmu);
8776 if (pmu->task_ctx_nr == perf_hw_context) {
8777 static int hw_context_taken = 0;
8780 * Other than systems with heterogeneous CPUs, it never makes
8781 * sense for two PMUs to share perf_hw_context. PMUs which are
8782 * uncore must use perf_invalid_context.
8784 if (WARN_ON_ONCE(hw_context_taken &&
8785 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
8786 pmu->task_ctx_nr = perf_invalid_context;
8788 hw_context_taken = 1;
8791 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
8792 if (pmu->pmu_cpu_context)
8793 goto got_cpu_context;
8796 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
8797 if (!pmu->pmu_cpu_context)
8800 for_each_possible_cpu(cpu) {
8801 struct perf_cpu_context *cpuctx;
8803 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8804 __perf_event_init_context(&cpuctx->ctx);
8805 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
8806 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
8807 cpuctx->ctx.pmu = pmu;
8809 __perf_mux_hrtimer_init(cpuctx, cpu);
8811 cpuctx->unique_pmu = pmu;
8815 if (!pmu->start_txn) {
8816 if (pmu->pmu_enable) {
8818 * If we have pmu_enable/pmu_disable calls, install
8819 * transaction stubs that use that to try and batch
8820 * hardware accesses.
8822 pmu->start_txn = perf_pmu_start_txn;
8823 pmu->commit_txn = perf_pmu_commit_txn;
8824 pmu->cancel_txn = perf_pmu_cancel_txn;
8826 pmu->start_txn = perf_pmu_nop_txn;
8827 pmu->commit_txn = perf_pmu_nop_int;
8828 pmu->cancel_txn = perf_pmu_nop_void;
8832 if (!pmu->pmu_enable) {
8833 pmu->pmu_enable = perf_pmu_nop_void;
8834 pmu->pmu_disable = perf_pmu_nop_void;
8837 if (!pmu->event_idx)
8838 pmu->event_idx = perf_event_idx_default;
8840 list_add_rcu(&pmu->entry, &pmus);
8841 atomic_set(&pmu->exclusive_cnt, 0);
8844 mutex_unlock(&pmus_lock);
8849 device_del(pmu->dev);
8850 put_device(pmu->dev);
8853 if (pmu->type >= PERF_TYPE_MAX)
8854 idr_remove(&pmu_idr, pmu->type);
8857 free_percpu(pmu->pmu_disable_count);
8860 EXPORT_SYMBOL_GPL(perf_pmu_register);
8862 void perf_pmu_unregister(struct pmu *pmu)
8866 mutex_lock(&pmus_lock);
8867 remove_device = pmu_bus_running;
8868 list_del_rcu(&pmu->entry);
8869 mutex_unlock(&pmus_lock);
8872 * We dereference the pmu list under both SRCU and regular RCU, so
8873 * synchronize against both of those.
8875 synchronize_srcu(&pmus_srcu);
8878 free_percpu(pmu->pmu_disable_count);
8879 if (pmu->type >= PERF_TYPE_MAX)
8880 idr_remove(&pmu_idr, pmu->type);
8881 if (remove_device) {
8882 if (pmu->nr_addr_filters)
8883 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
8884 device_del(pmu->dev);
8885 put_device(pmu->dev);
8887 free_pmu_context(pmu);
8889 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
8891 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
8893 struct perf_event_context *ctx = NULL;
8896 if (!try_module_get(pmu->module))
8899 if (event->group_leader != event) {
8901 * This ctx->mutex can nest when we're called through
8902 * inheritance. See the perf_event_ctx_lock_nested() comment.
8904 ctx = perf_event_ctx_lock_nested(event->group_leader,
8905 SINGLE_DEPTH_NESTING);
8910 ret = pmu->event_init(event);
8913 perf_event_ctx_unlock(event->group_leader, ctx);
8916 module_put(pmu->module);
8921 static struct pmu *perf_init_event(struct perf_event *event)
8923 struct pmu *pmu = NULL;
8927 idx = srcu_read_lock(&pmus_srcu);
8930 pmu = idr_find(&pmu_idr, event->attr.type);
8933 ret = perf_try_init_event(pmu, event);
8939 list_for_each_entry_rcu(pmu, &pmus, entry) {
8940 ret = perf_try_init_event(pmu, event);
8944 if (ret != -ENOENT) {
8949 pmu = ERR_PTR(-ENOENT);
8951 srcu_read_unlock(&pmus_srcu, idx);
8956 static void attach_sb_event(struct perf_event *event)
8958 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
8960 raw_spin_lock(&pel->lock);
8961 list_add_rcu(&event->sb_list, &pel->list);
8962 raw_spin_unlock(&pel->lock);
8966 * We keep a list of all !task (and therefore per-cpu) events
8967 * that need to receive side-band records.
8969 * This avoids having to scan all the various PMU per-cpu contexts
8972 static void account_pmu_sb_event(struct perf_event *event)
8974 if (is_sb_event(event))
8975 attach_sb_event(event);
8978 static void account_event_cpu(struct perf_event *event, int cpu)
8983 if (is_cgroup_event(event))
8984 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
8987 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
8988 static void account_freq_event_nohz(void)
8990 #ifdef CONFIG_NO_HZ_FULL
8991 /* Lock so we don't race with concurrent unaccount */
8992 spin_lock(&nr_freq_lock);
8993 if (atomic_inc_return(&nr_freq_events) == 1)
8994 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
8995 spin_unlock(&nr_freq_lock);
8999 static void account_freq_event(void)
9001 if (tick_nohz_full_enabled())
9002 account_freq_event_nohz();
9004 atomic_inc(&nr_freq_events);
9008 static void account_event(struct perf_event *event)
9015 if (event->attach_state & PERF_ATTACH_TASK)
9017 if (event->attr.mmap || event->attr.mmap_data)
9018 atomic_inc(&nr_mmap_events);
9019 if (event->attr.comm)
9020 atomic_inc(&nr_comm_events);
9021 if (event->attr.task)
9022 atomic_inc(&nr_task_events);
9023 if (event->attr.freq)
9024 account_freq_event();
9025 if (event->attr.context_switch) {
9026 atomic_inc(&nr_switch_events);
9029 if (has_branch_stack(event))
9031 if (is_cgroup_event(event))
9035 if (atomic_inc_not_zero(&perf_sched_count))
9038 mutex_lock(&perf_sched_mutex);
9039 if (!atomic_read(&perf_sched_count)) {
9040 static_branch_enable(&perf_sched_events);
9042 * Guarantee that all CPUs observe they key change and
9043 * call the perf scheduling hooks before proceeding to
9044 * install events that need them.
9046 synchronize_sched();
9049 * Now that we have waited for the sync_sched(), allow further
9050 * increments to by-pass the mutex.
9052 atomic_inc(&perf_sched_count);
9053 mutex_unlock(&perf_sched_mutex);
9057 account_event_cpu(event, event->cpu);
9059 account_pmu_sb_event(event);
9063 * Allocate and initialize a event structure
9065 static struct perf_event *
9066 perf_event_alloc(struct perf_event_attr *attr, int cpu,
9067 struct task_struct *task,
9068 struct perf_event *group_leader,
9069 struct perf_event *parent_event,
9070 perf_overflow_handler_t overflow_handler,
9071 void *context, int cgroup_fd)
9074 struct perf_event *event;
9075 struct hw_perf_event *hwc;
9078 if ((unsigned)cpu >= nr_cpu_ids) {
9079 if (!task || cpu != -1)
9080 return ERR_PTR(-EINVAL);
9083 event = kzalloc(sizeof(*event), GFP_KERNEL);
9085 return ERR_PTR(-ENOMEM);
9088 * Single events are their own group leaders, with an
9089 * empty sibling list:
9092 group_leader = event;
9094 mutex_init(&event->child_mutex);
9095 INIT_LIST_HEAD(&event->child_list);
9097 INIT_LIST_HEAD(&event->group_entry);
9098 INIT_LIST_HEAD(&event->event_entry);
9099 INIT_LIST_HEAD(&event->sibling_list);
9100 INIT_LIST_HEAD(&event->rb_entry);
9101 INIT_LIST_HEAD(&event->active_entry);
9102 INIT_LIST_HEAD(&event->addr_filters.list);
9103 INIT_HLIST_NODE(&event->hlist_entry);
9106 init_waitqueue_head(&event->waitq);
9107 init_irq_work(&event->pending, perf_pending_event);
9109 mutex_init(&event->mmap_mutex);
9110 raw_spin_lock_init(&event->addr_filters.lock);
9112 atomic_long_set(&event->refcount, 1);
9114 event->attr = *attr;
9115 event->group_leader = group_leader;
9119 event->parent = parent_event;
9121 event->ns = get_pid_ns(task_active_pid_ns(current));
9122 event->id = atomic64_inc_return(&perf_event_id);
9124 event->state = PERF_EVENT_STATE_INACTIVE;
9127 event->attach_state = PERF_ATTACH_TASK;
9129 * XXX pmu::event_init needs to know what task to account to
9130 * and we cannot use the ctx information because we need the
9131 * pmu before we get a ctx.
9133 event->hw.target = task;
9136 event->clock = &local_clock;
9138 event->clock = parent_event->clock;
9140 if (!overflow_handler && parent_event) {
9141 overflow_handler = parent_event->overflow_handler;
9142 context = parent_event->overflow_handler_context;
9143 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
9144 if (overflow_handler == bpf_overflow_handler) {
9145 struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
9148 err = PTR_ERR(prog);
9152 event->orig_overflow_handler =
9153 parent_event->orig_overflow_handler;
9158 if (overflow_handler) {
9159 event->overflow_handler = overflow_handler;
9160 event->overflow_handler_context = context;
9161 } else if (is_write_backward(event)){
9162 event->overflow_handler = perf_event_output_backward;
9163 event->overflow_handler_context = NULL;
9165 event->overflow_handler = perf_event_output_forward;
9166 event->overflow_handler_context = NULL;
9169 perf_event__state_init(event);
9174 hwc->sample_period = attr->sample_period;
9175 if (attr->freq && attr->sample_freq)
9176 hwc->sample_period = 1;
9177 hwc->last_period = hwc->sample_period;
9179 local64_set(&hwc->period_left, hwc->sample_period);
9182 * we currently do not support PERF_FORMAT_GROUP on inherited events
9184 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
9187 if (!has_branch_stack(event))
9188 event->attr.branch_sample_type = 0;
9190 if (cgroup_fd != -1) {
9191 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
9196 pmu = perf_init_event(event);
9199 else if (IS_ERR(pmu)) {
9204 err = exclusive_event_init(event);
9208 if (has_addr_filter(event)) {
9209 event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
9210 sizeof(unsigned long),
9212 if (!event->addr_filters_offs)
9215 /* force hw sync on the address filters */
9216 event->addr_filters_gen = 1;
9219 if (!event->parent) {
9220 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
9221 err = get_callchain_buffers(attr->sample_max_stack);
9223 goto err_addr_filters;
9227 /* symmetric to unaccount_event() in _free_event() */
9228 account_event(event);
9233 kfree(event->addr_filters_offs);
9236 exclusive_event_destroy(event);
9240 event->destroy(event);
9241 module_put(pmu->module);
9243 if (is_cgroup_event(event))
9244 perf_detach_cgroup(event);
9246 put_pid_ns(event->ns);
9249 return ERR_PTR(err);
9252 static int perf_copy_attr(struct perf_event_attr __user *uattr,
9253 struct perf_event_attr *attr)
9258 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
9262 * zero the full structure, so that a short copy will be nice.
9264 memset(attr, 0, sizeof(*attr));
9266 ret = get_user(size, &uattr->size);
9270 if (size > PAGE_SIZE) /* silly large */
9273 if (!size) /* abi compat */
9274 size = PERF_ATTR_SIZE_VER0;
9276 if (size < PERF_ATTR_SIZE_VER0)
9280 * If we're handed a bigger struct than we know of,
9281 * ensure all the unknown bits are 0 - i.e. new
9282 * user-space does not rely on any kernel feature
9283 * extensions we dont know about yet.
9285 if (size > sizeof(*attr)) {
9286 unsigned char __user *addr;
9287 unsigned char __user *end;
9290 addr = (void __user *)uattr + sizeof(*attr);
9291 end = (void __user *)uattr + size;
9293 for (; addr < end; addr++) {
9294 ret = get_user(val, addr);
9300 size = sizeof(*attr);
9303 ret = copy_from_user(attr, uattr, size);
9307 if (attr->__reserved_1)
9310 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
9313 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
9316 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
9317 u64 mask = attr->branch_sample_type;
9319 /* only using defined bits */
9320 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
9323 /* at least one branch bit must be set */
9324 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
9327 /* propagate priv level, when not set for branch */
9328 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
9330 /* exclude_kernel checked on syscall entry */
9331 if (!attr->exclude_kernel)
9332 mask |= PERF_SAMPLE_BRANCH_KERNEL;
9334 if (!attr->exclude_user)
9335 mask |= PERF_SAMPLE_BRANCH_USER;
9337 if (!attr->exclude_hv)
9338 mask |= PERF_SAMPLE_BRANCH_HV;
9340 * adjust user setting (for HW filter setup)
9342 attr->branch_sample_type = mask;
9344 /* privileged levels capture (kernel, hv): check permissions */
9345 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
9346 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9350 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
9351 ret = perf_reg_validate(attr->sample_regs_user);
9356 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
9357 if (!arch_perf_have_user_stack_dump())
9361 * We have __u32 type for the size, but so far
9362 * we can only use __u16 as maximum due to the
9363 * __u16 sample size limit.
9365 if (attr->sample_stack_user >= USHRT_MAX)
9367 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
9371 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
9372 ret = perf_reg_validate(attr->sample_regs_intr);
9377 put_user(sizeof(*attr), &uattr->size);
9383 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
9385 struct ring_buffer *rb = NULL;
9391 /* don't allow circular references */
9392 if (event == output_event)
9396 * Don't allow cross-cpu buffers
9398 if (output_event->cpu != event->cpu)
9402 * If its not a per-cpu rb, it must be the same task.
9404 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
9408 * Mixing clocks in the same buffer is trouble you don't need.
9410 if (output_event->clock != event->clock)
9414 * Either writing ring buffer from beginning or from end.
9415 * Mixing is not allowed.
9417 if (is_write_backward(output_event) != is_write_backward(event))
9421 * If both events generate aux data, they must be on the same PMU
9423 if (has_aux(event) && has_aux(output_event) &&
9424 event->pmu != output_event->pmu)
9428 mutex_lock(&event->mmap_mutex);
9429 /* Can't redirect output if we've got an active mmap() */
9430 if (atomic_read(&event->mmap_count))
9434 /* get the rb we want to redirect to */
9435 rb = ring_buffer_get(output_event);
9440 ring_buffer_attach(event, rb);
9444 mutex_unlock(&event->mmap_mutex);
9450 static void mutex_lock_double(struct mutex *a, struct mutex *b)
9456 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
9459 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
9461 bool nmi_safe = false;
9464 case CLOCK_MONOTONIC:
9465 event->clock = &ktime_get_mono_fast_ns;
9469 case CLOCK_MONOTONIC_RAW:
9470 event->clock = &ktime_get_raw_fast_ns;
9474 case CLOCK_REALTIME:
9475 event->clock = &ktime_get_real_ns;
9478 case CLOCK_BOOTTIME:
9479 event->clock = &ktime_get_boot_ns;
9483 event->clock = &ktime_get_tai_ns;
9490 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
9497 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9499 * @attr_uptr: event_id type attributes for monitoring/sampling
9502 * @group_fd: group leader event fd
9504 SYSCALL_DEFINE5(perf_event_open,
9505 struct perf_event_attr __user *, attr_uptr,
9506 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
9508 struct perf_event *group_leader = NULL, *output_event = NULL;
9509 struct perf_event *event, *sibling;
9510 struct perf_event_attr attr;
9511 struct perf_event_context *ctx, *uninitialized_var(gctx);
9512 struct file *event_file = NULL;
9513 struct fd group = {NULL, 0};
9514 struct task_struct *task = NULL;
9519 int f_flags = O_RDWR;
9522 /* for future expandability... */
9523 if (flags & ~PERF_FLAG_ALL)
9526 err = perf_copy_attr(attr_uptr, &attr);
9530 if (!attr.exclude_kernel) {
9531 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9536 if (attr.sample_freq > sysctl_perf_event_sample_rate)
9539 if (attr.sample_period & (1ULL << 63))
9543 if (!attr.sample_max_stack)
9544 attr.sample_max_stack = sysctl_perf_event_max_stack;
9547 * In cgroup mode, the pid argument is used to pass the fd
9548 * opened to the cgroup directory in cgroupfs. The cpu argument
9549 * designates the cpu on which to monitor threads from that
9552 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
9555 if (flags & PERF_FLAG_FD_CLOEXEC)
9556 f_flags |= O_CLOEXEC;
9558 event_fd = get_unused_fd_flags(f_flags);
9562 if (group_fd != -1) {
9563 err = perf_fget_light(group_fd, &group);
9566 group_leader = group.file->private_data;
9567 if (flags & PERF_FLAG_FD_OUTPUT)
9568 output_event = group_leader;
9569 if (flags & PERF_FLAG_FD_NO_GROUP)
9570 group_leader = NULL;
9573 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
9574 task = find_lively_task_by_vpid(pid);
9576 err = PTR_ERR(task);
9581 if (task && group_leader &&
9582 group_leader->attr.inherit != attr.inherit) {
9590 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
9595 * Reuse ptrace permission checks for now.
9597 * We must hold cred_guard_mutex across this and any potential
9598 * perf_install_in_context() call for this new event to
9599 * serialize against exec() altering our credentials (and the
9600 * perf_event_exit_task() that could imply).
9603 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
9607 if (flags & PERF_FLAG_PID_CGROUP)
9610 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
9611 NULL, NULL, cgroup_fd);
9612 if (IS_ERR(event)) {
9613 err = PTR_ERR(event);
9617 if (is_sampling_event(event)) {
9618 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
9625 * Special case software events and allow them to be part of
9626 * any hardware group.
9630 if (attr.use_clockid) {
9631 err = perf_event_set_clock(event, attr.clockid);
9636 if (pmu->task_ctx_nr == perf_sw_context)
9637 event->event_caps |= PERF_EV_CAP_SOFTWARE;
9640 (is_software_event(event) != is_software_event(group_leader))) {
9641 if (is_software_event(event)) {
9643 * If event and group_leader are not both a software
9644 * event, and event is, then group leader is not.
9646 * Allow the addition of software events to !software
9647 * groups, this is safe because software events never
9650 pmu = group_leader->pmu;
9651 } else if (is_software_event(group_leader) &&
9652 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
9654 * In case the group is a pure software group, and we
9655 * try to add a hardware event, move the whole group to
9656 * the hardware context.
9663 * Get the target context (task or percpu):
9665 ctx = find_get_context(pmu, task, event);
9671 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
9677 * Look up the group leader (we will attach this event to it):
9683 * Do not allow a recursive hierarchy (this new sibling
9684 * becoming part of another group-sibling):
9686 if (group_leader->group_leader != group_leader)
9689 /* All events in a group should have the same clock */
9690 if (group_leader->clock != event->clock)
9694 * Do not allow to attach to a group in a different
9695 * task or CPU context:
9699 * Make sure we're both on the same task, or both
9702 if (group_leader->ctx->task != ctx->task)
9706 * Make sure we're both events for the same CPU;
9707 * grouping events for different CPUs is broken; since
9708 * you can never concurrently schedule them anyhow.
9710 if (group_leader->cpu != event->cpu)
9713 if (group_leader->ctx != ctx)
9718 * Only a group leader can be exclusive or pinned
9720 if (attr.exclusive || attr.pinned)
9725 err = perf_event_set_output(event, output_event);
9730 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
9732 if (IS_ERR(event_file)) {
9733 err = PTR_ERR(event_file);
9739 gctx = group_leader->ctx;
9740 mutex_lock_double(&gctx->mutex, &ctx->mutex);
9741 if (gctx->task == TASK_TOMBSTONE) {
9746 mutex_lock(&ctx->mutex);
9749 if (ctx->task == TASK_TOMBSTONE) {
9754 if (!perf_event_validate_size(event)) {
9760 * Must be under the same ctx::mutex as perf_install_in_context(),
9761 * because we need to serialize with concurrent event creation.
9763 if (!exclusive_event_installable(event, ctx)) {
9764 /* exclusive and group stuff are assumed mutually exclusive */
9765 WARN_ON_ONCE(move_group);
9771 WARN_ON_ONCE(ctx->parent_ctx);
9774 * This is the point on no return; we cannot fail hereafter. This is
9775 * where we start modifying current state.
9780 * See perf_event_ctx_lock() for comments on the details
9781 * of swizzling perf_event::ctx.
9783 perf_remove_from_context(group_leader, 0);
9785 list_for_each_entry(sibling, &group_leader->sibling_list,
9787 perf_remove_from_context(sibling, 0);
9792 * Wait for everybody to stop referencing the events through
9793 * the old lists, before installing it on new lists.
9798 * Install the group siblings before the group leader.
9800 * Because a group leader will try and install the entire group
9801 * (through the sibling list, which is still in-tact), we can
9802 * end up with siblings installed in the wrong context.
9804 * By installing siblings first we NO-OP because they're not
9805 * reachable through the group lists.
9807 list_for_each_entry(sibling, &group_leader->sibling_list,
9809 perf_event__state_init(sibling);
9810 perf_install_in_context(ctx, sibling, sibling->cpu);
9815 * Removing from the context ends up with disabled
9816 * event. What we want here is event in the initial
9817 * startup state, ready to be add into new context.
9819 perf_event__state_init(group_leader);
9820 perf_install_in_context(ctx, group_leader, group_leader->cpu);
9824 * Now that all events are installed in @ctx, nothing
9825 * references @gctx anymore, so drop the last reference we have
9832 * Precalculate sample_data sizes; do while holding ctx::mutex such
9833 * that we're serialized against further additions and before
9834 * perf_install_in_context() which is the point the event is active and
9835 * can use these values.
9837 perf_event__header_size(event);
9838 perf_event__id_header_size(event);
9840 event->owner = current;
9842 perf_install_in_context(ctx, event, event->cpu);
9843 perf_unpin_context(ctx);
9846 mutex_unlock(&gctx->mutex);
9847 mutex_unlock(&ctx->mutex);
9850 mutex_unlock(&task->signal->cred_guard_mutex);
9851 put_task_struct(task);
9856 mutex_lock(¤t->perf_event_mutex);
9857 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
9858 mutex_unlock(¤t->perf_event_mutex);
9861 * Drop the reference on the group_event after placing the
9862 * new event on the sibling_list. This ensures destruction
9863 * of the group leader will find the pointer to itself in
9864 * perf_group_detach().
9867 fd_install(event_fd, event_file);
9872 mutex_unlock(&gctx->mutex);
9873 mutex_unlock(&ctx->mutex);
9877 perf_unpin_context(ctx);
9881 * If event_file is set, the fput() above will have called ->release()
9882 * and that will take care of freeing the event.
9888 mutex_unlock(&task->signal->cred_guard_mutex);
9893 put_task_struct(task);
9897 put_unused_fd(event_fd);
9902 * perf_event_create_kernel_counter
9904 * @attr: attributes of the counter to create
9905 * @cpu: cpu in which the counter is bound
9906 * @task: task to profile (NULL for percpu)
9909 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
9910 struct task_struct *task,
9911 perf_overflow_handler_t overflow_handler,
9914 struct perf_event_context *ctx;
9915 struct perf_event *event;
9919 * Get the target context (task or percpu):
9922 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
9923 overflow_handler, context, -1);
9924 if (IS_ERR(event)) {
9925 err = PTR_ERR(event);
9929 /* Mark owner so we could distinguish it from user events. */
9930 event->owner = TASK_TOMBSTONE;
9932 ctx = find_get_context(event->pmu, task, event);
9938 WARN_ON_ONCE(ctx->parent_ctx);
9939 mutex_lock(&ctx->mutex);
9940 if (ctx->task == TASK_TOMBSTONE) {
9945 if (!exclusive_event_installable(event, ctx)) {
9950 perf_install_in_context(ctx, event, cpu);
9951 perf_unpin_context(ctx);
9952 mutex_unlock(&ctx->mutex);
9957 mutex_unlock(&ctx->mutex);
9958 perf_unpin_context(ctx);
9963 return ERR_PTR(err);
9965 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9967 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
9969 struct perf_event_context *src_ctx;
9970 struct perf_event_context *dst_ctx;
9971 struct perf_event *event, *tmp;
9974 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
9975 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
9978 * See perf_event_ctx_lock() for comments on the details
9979 * of swizzling perf_event::ctx.
9981 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
9982 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
9984 perf_remove_from_context(event, 0);
9985 unaccount_event_cpu(event, src_cpu);
9987 list_add(&event->migrate_entry, &events);
9991 * Wait for the events to quiesce before re-instating them.
9996 * Re-instate events in 2 passes.
9998 * Skip over group leaders and only install siblings on this first
9999 * pass, siblings will not get enabled without a leader, however a
10000 * leader will enable its siblings, even if those are still on the old
10003 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10004 if (event->group_leader == event)
10007 list_del(&event->migrate_entry);
10008 if (event->state >= PERF_EVENT_STATE_OFF)
10009 event->state = PERF_EVENT_STATE_INACTIVE;
10010 account_event_cpu(event, dst_cpu);
10011 perf_install_in_context(dst_ctx, event, dst_cpu);
10016 * Once all the siblings are setup properly, install the group leaders
10019 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10020 list_del(&event->migrate_entry);
10021 if (event->state >= PERF_EVENT_STATE_OFF)
10022 event->state = PERF_EVENT_STATE_INACTIVE;
10023 account_event_cpu(event, dst_cpu);
10024 perf_install_in_context(dst_ctx, event, dst_cpu);
10027 mutex_unlock(&dst_ctx->mutex);
10028 mutex_unlock(&src_ctx->mutex);
10030 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
10032 static void sync_child_event(struct perf_event *child_event,
10033 struct task_struct *child)
10035 struct perf_event *parent_event = child_event->parent;
10038 if (child_event->attr.inherit_stat)
10039 perf_event_read_event(child_event, child);
10041 child_val = perf_event_count(child_event);
10044 * Add back the child's count to the parent's count:
10046 atomic64_add(child_val, &parent_event->child_count);
10047 atomic64_add(child_event->total_time_enabled,
10048 &parent_event->child_total_time_enabled);
10049 atomic64_add(child_event->total_time_running,
10050 &parent_event->child_total_time_running);
10054 perf_event_exit_event(struct perf_event *child_event,
10055 struct perf_event_context *child_ctx,
10056 struct task_struct *child)
10058 struct perf_event *parent_event = child_event->parent;
10061 * Do not destroy the 'original' grouping; because of the context
10062 * switch optimization the original events could've ended up in a
10063 * random child task.
10065 * If we were to destroy the original group, all group related
10066 * operations would cease to function properly after this random
10069 * Do destroy all inherited groups, we don't care about those
10070 * and being thorough is better.
10072 raw_spin_lock_irq(&child_ctx->lock);
10073 WARN_ON_ONCE(child_ctx->is_active);
10076 perf_group_detach(child_event);
10077 list_del_event(child_event, child_ctx);
10078 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
10079 raw_spin_unlock_irq(&child_ctx->lock);
10082 * Parent events are governed by their filedesc, retain them.
10084 if (!parent_event) {
10085 perf_event_wakeup(child_event);
10089 * Child events can be cleaned up.
10092 sync_child_event(child_event, child);
10095 * Remove this event from the parent's list
10097 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
10098 mutex_lock(&parent_event->child_mutex);
10099 list_del_init(&child_event->child_list);
10100 mutex_unlock(&parent_event->child_mutex);
10103 * Kick perf_poll() for is_event_hup().
10105 perf_event_wakeup(parent_event);
10106 free_event(child_event);
10107 put_event(parent_event);
10110 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
10112 struct perf_event_context *child_ctx, *clone_ctx = NULL;
10113 struct perf_event *child_event, *next;
10115 WARN_ON_ONCE(child != current);
10117 child_ctx = perf_pin_task_context(child, ctxn);
10122 * In order to reduce the amount of tricky in ctx tear-down, we hold
10123 * ctx::mutex over the entire thing. This serializes against almost
10124 * everything that wants to access the ctx.
10126 * The exception is sys_perf_event_open() /
10127 * perf_event_create_kernel_count() which does find_get_context()
10128 * without ctx::mutex (it cannot because of the move_group double mutex
10129 * lock thing). See the comments in perf_install_in_context().
10131 mutex_lock(&child_ctx->mutex);
10134 * In a single ctx::lock section, de-schedule the events and detach the
10135 * context from the task such that we cannot ever get it scheduled back
10138 raw_spin_lock_irq(&child_ctx->lock);
10139 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
10142 * Now that the context is inactive, destroy the task <-> ctx relation
10143 * and mark the context dead.
10145 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
10146 put_ctx(child_ctx); /* cannot be last */
10147 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
10148 put_task_struct(current); /* cannot be last */
10150 clone_ctx = unclone_ctx(child_ctx);
10151 raw_spin_unlock_irq(&child_ctx->lock);
10154 put_ctx(clone_ctx);
10157 * Report the task dead after unscheduling the events so that we
10158 * won't get any samples after PERF_RECORD_EXIT. We can however still
10159 * get a few PERF_RECORD_READ events.
10161 perf_event_task(child, child_ctx, 0);
10163 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
10164 perf_event_exit_event(child_event, child_ctx, child);
10166 mutex_unlock(&child_ctx->mutex);
10168 put_ctx(child_ctx);
10172 * When a child task exits, feed back event values to parent events.
10174 * Can be called with cred_guard_mutex held when called from
10175 * install_exec_creds().
10177 void perf_event_exit_task(struct task_struct *child)
10179 struct perf_event *event, *tmp;
10182 mutex_lock(&child->perf_event_mutex);
10183 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
10185 list_del_init(&event->owner_entry);
10188 * Ensure the list deletion is visible before we clear
10189 * the owner, closes a race against perf_release() where
10190 * we need to serialize on the owner->perf_event_mutex.
10192 smp_store_release(&event->owner, NULL);
10194 mutex_unlock(&child->perf_event_mutex);
10196 for_each_task_context_nr(ctxn)
10197 perf_event_exit_task_context(child, ctxn);
10200 * The perf_event_exit_task_context calls perf_event_task
10201 * with child's task_ctx, which generates EXIT events for
10202 * child contexts and sets child->perf_event_ctxp[] to NULL.
10203 * At this point we need to send EXIT events to cpu contexts.
10205 perf_event_task(child, NULL, 0);
10208 static void perf_free_event(struct perf_event *event,
10209 struct perf_event_context *ctx)
10211 struct perf_event *parent = event->parent;
10213 if (WARN_ON_ONCE(!parent))
10216 mutex_lock(&parent->child_mutex);
10217 list_del_init(&event->child_list);
10218 mutex_unlock(&parent->child_mutex);
10222 raw_spin_lock_irq(&ctx->lock);
10223 perf_group_detach(event);
10224 list_del_event(event, ctx);
10225 raw_spin_unlock_irq(&ctx->lock);
10230 * Free an unexposed, unused context as created by inheritance by
10231 * perf_event_init_task below, used by fork() in case of fail.
10233 * Not all locks are strictly required, but take them anyway to be nice and
10234 * help out with the lockdep assertions.
10236 void perf_event_free_task(struct task_struct *task)
10238 struct perf_event_context *ctx;
10239 struct perf_event *event, *tmp;
10242 for_each_task_context_nr(ctxn) {
10243 ctx = task->perf_event_ctxp[ctxn];
10247 mutex_lock(&ctx->mutex);
10249 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
10251 perf_free_event(event, ctx);
10253 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
10255 perf_free_event(event, ctx);
10257 if (!list_empty(&ctx->pinned_groups) ||
10258 !list_empty(&ctx->flexible_groups))
10261 mutex_unlock(&ctx->mutex);
10267 void perf_event_delayed_put(struct task_struct *task)
10271 for_each_task_context_nr(ctxn)
10272 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
10275 struct file *perf_event_get(unsigned int fd)
10279 file = fget_raw(fd);
10281 return ERR_PTR(-EBADF);
10283 if (file->f_op != &perf_fops) {
10285 return ERR_PTR(-EBADF);
10291 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
10294 return ERR_PTR(-EINVAL);
10296 return &event->attr;
10300 * inherit a event from parent task to child task:
10302 static struct perf_event *
10303 inherit_event(struct perf_event *parent_event,
10304 struct task_struct *parent,
10305 struct perf_event_context *parent_ctx,
10306 struct task_struct *child,
10307 struct perf_event *group_leader,
10308 struct perf_event_context *child_ctx)
10310 enum perf_event_active_state parent_state = parent_event->state;
10311 struct perf_event *child_event;
10312 unsigned long flags;
10315 * Instead of creating recursive hierarchies of events,
10316 * we link inherited events back to the original parent,
10317 * which has a filp for sure, which we use as the reference
10320 if (parent_event->parent)
10321 parent_event = parent_event->parent;
10323 child_event = perf_event_alloc(&parent_event->attr,
10326 group_leader, parent_event,
10328 if (IS_ERR(child_event))
10329 return child_event;
10332 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
10333 * must be under the same lock in order to serialize against
10334 * perf_event_release_kernel(), such that either we must observe
10335 * is_orphaned_event() or they will observe us on the child_list.
10337 mutex_lock(&parent_event->child_mutex);
10338 if (is_orphaned_event(parent_event) ||
10339 !atomic_long_inc_not_zero(&parent_event->refcount)) {
10340 mutex_unlock(&parent_event->child_mutex);
10341 free_event(child_event);
10345 get_ctx(child_ctx);
10348 * Make the child state follow the state of the parent event,
10349 * not its attr.disabled bit. We hold the parent's mutex,
10350 * so we won't race with perf_event_{en, dis}able_family.
10352 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
10353 child_event->state = PERF_EVENT_STATE_INACTIVE;
10355 child_event->state = PERF_EVENT_STATE_OFF;
10357 if (parent_event->attr.freq) {
10358 u64 sample_period = parent_event->hw.sample_period;
10359 struct hw_perf_event *hwc = &child_event->hw;
10361 hwc->sample_period = sample_period;
10362 hwc->last_period = sample_period;
10364 local64_set(&hwc->period_left, sample_period);
10367 child_event->ctx = child_ctx;
10368 child_event->overflow_handler = parent_event->overflow_handler;
10369 child_event->overflow_handler_context
10370 = parent_event->overflow_handler_context;
10373 * Precalculate sample_data sizes
10375 perf_event__header_size(child_event);
10376 perf_event__id_header_size(child_event);
10379 * Link it up in the child's context:
10381 raw_spin_lock_irqsave(&child_ctx->lock, flags);
10382 add_event_to_ctx(child_event, child_ctx);
10383 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
10386 * Link this into the parent event's child list
10388 list_add_tail(&child_event->child_list, &parent_event->child_list);
10389 mutex_unlock(&parent_event->child_mutex);
10391 return child_event;
10394 static int inherit_group(struct perf_event *parent_event,
10395 struct task_struct *parent,
10396 struct perf_event_context *parent_ctx,
10397 struct task_struct *child,
10398 struct perf_event_context *child_ctx)
10400 struct perf_event *leader;
10401 struct perf_event *sub;
10402 struct perf_event *child_ctr;
10404 leader = inherit_event(parent_event, parent, parent_ctx,
10405 child, NULL, child_ctx);
10406 if (IS_ERR(leader))
10407 return PTR_ERR(leader);
10408 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
10409 child_ctr = inherit_event(sub, parent, parent_ctx,
10410 child, leader, child_ctx);
10411 if (IS_ERR(child_ctr))
10412 return PTR_ERR(child_ctr);
10418 inherit_task_group(struct perf_event *event, struct task_struct *parent,
10419 struct perf_event_context *parent_ctx,
10420 struct task_struct *child, int ctxn,
10421 int *inherited_all)
10424 struct perf_event_context *child_ctx;
10426 if (!event->attr.inherit) {
10427 *inherited_all = 0;
10431 child_ctx = child->perf_event_ctxp[ctxn];
10434 * This is executed from the parent task context, so
10435 * inherit events that have been marked for cloning.
10436 * First allocate and initialize a context for the
10440 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
10444 child->perf_event_ctxp[ctxn] = child_ctx;
10447 ret = inherit_group(event, parent, parent_ctx,
10451 *inherited_all = 0;
10457 * Initialize the perf_event context in task_struct
10459 static int perf_event_init_context(struct task_struct *child, int ctxn)
10461 struct perf_event_context *child_ctx, *parent_ctx;
10462 struct perf_event_context *cloned_ctx;
10463 struct perf_event *event;
10464 struct task_struct *parent = current;
10465 int inherited_all = 1;
10466 unsigned long flags;
10469 if (likely(!parent->perf_event_ctxp[ctxn]))
10473 * If the parent's context is a clone, pin it so it won't get
10474 * swapped under us.
10476 parent_ctx = perf_pin_task_context(parent, ctxn);
10481 * No need to check if parent_ctx != NULL here; since we saw
10482 * it non-NULL earlier, the only reason for it to become NULL
10483 * is if we exit, and since we're currently in the middle of
10484 * a fork we can't be exiting at the same time.
10488 * Lock the parent list. No need to lock the child - not PID
10489 * hashed yet and not running, so nobody can access it.
10491 mutex_lock(&parent_ctx->mutex);
10494 * We dont have to disable NMIs - we are only looking at
10495 * the list, not manipulating it:
10497 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
10498 ret = inherit_task_group(event, parent, parent_ctx,
10499 child, ctxn, &inherited_all);
10505 * We can't hold ctx->lock when iterating the ->flexible_group list due
10506 * to allocations, but we need to prevent rotation because
10507 * rotate_ctx() will change the list from interrupt context.
10509 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10510 parent_ctx->rotate_disable = 1;
10511 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10513 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
10514 ret = inherit_task_group(event, parent, parent_ctx,
10515 child, ctxn, &inherited_all);
10520 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10521 parent_ctx->rotate_disable = 0;
10523 child_ctx = child->perf_event_ctxp[ctxn];
10525 if (child_ctx && inherited_all) {
10527 * Mark the child context as a clone of the parent
10528 * context, or of whatever the parent is a clone of.
10530 * Note that if the parent is a clone, the holding of
10531 * parent_ctx->lock avoids it from being uncloned.
10533 cloned_ctx = parent_ctx->parent_ctx;
10535 child_ctx->parent_ctx = cloned_ctx;
10536 child_ctx->parent_gen = parent_ctx->parent_gen;
10538 child_ctx->parent_ctx = parent_ctx;
10539 child_ctx->parent_gen = parent_ctx->generation;
10541 get_ctx(child_ctx->parent_ctx);
10544 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10545 mutex_unlock(&parent_ctx->mutex);
10547 perf_unpin_context(parent_ctx);
10548 put_ctx(parent_ctx);
10554 * Initialize the perf_event context in task_struct
10556 int perf_event_init_task(struct task_struct *child)
10560 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
10561 mutex_init(&child->perf_event_mutex);
10562 INIT_LIST_HEAD(&child->perf_event_list);
10564 for_each_task_context_nr(ctxn) {
10565 ret = perf_event_init_context(child, ctxn);
10567 perf_event_free_task(child);
10575 static void __init perf_event_init_all_cpus(void)
10577 struct swevent_htable *swhash;
10580 for_each_possible_cpu(cpu) {
10581 swhash = &per_cpu(swevent_htable, cpu);
10582 mutex_init(&swhash->hlist_mutex);
10583 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
10585 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
10586 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
10588 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
10592 int perf_event_init_cpu(unsigned int cpu)
10594 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10596 mutex_lock(&swhash->hlist_mutex);
10597 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
10598 struct swevent_hlist *hlist;
10600 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
10602 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10604 mutex_unlock(&swhash->hlist_mutex);
10608 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
10609 static void __perf_event_exit_context(void *__info)
10611 struct perf_event_context *ctx = __info;
10612 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
10613 struct perf_event *event;
10615 raw_spin_lock(&ctx->lock);
10616 list_for_each_entry(event, &ctx->event_list, event_entry)
10617 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
10618 raw_spin_unlock(&ctx->lock);
10621 static void perf_event_exit_cpu_context(int cpu)
10623 struct perf_event_context *ctx;
10627 idx = srcu_read_lock(&pmus_srcu);
10628 list_for_each_entry_rcu(pmu, &pmus, entry) {
10629 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
10631 mutex_lock(&ctx->mutex);
10632 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
10633 mutex_unlock(&ctx->mutex);
10635 srcu_read_unlock(&pmus_srcu, idx);
10639 static void perf_event_exit_cpu_context(int cpu) { }
10643 int perf_event_exit_cpu(unsigned int cpu)
10645 perf_event_exit_cpu_context(cpu);
10650 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
10654 for_each_online_cpu(cpu)
10655 perf_event_exit_cpu(cpu);
10661 * Run the perf reboot notifier at the very last possible moment so that
10662 * the generic watchdog code runs as long as possible.
10664 static struct notifier_block perf_reboot_notifier = {
10665 .notifier_call = perf_reboot,
10666 .priority = INT_MIN,
10669 void __init perf_event_init(void)
10673 idr_init(&pmu_idr);
10675 perf_event_init_all_cpus();
10676 init_srcu_struct(&pmus_srcu);
10677 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
10678 perf_pmu_register(&perf_cpu_clock, NULL, -1);
10679 perf_pmu_register(&perf_task_clock, NULL, -1);
10680 perf_tp_register();
10681 perf_event_init_cpu(smp_processor_id());
10682 register_reboot_notifier(&perf_reboot_notifier);
10684 ret = init_hw_breakpoint();
10685 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
10688 * Build time assertion that we keep the data_head at the intended
10689 * location. IOW, validation we got the __reserved[] size right.
10691 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
10695 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
10698 struct perf_pmu_events_attr *pmu_attr =
10699 container_of(attr, struct perf_pmu_events_attr, attr);
10701 if (pmu_attr->event_str)
10702 return sprintf(page, "%s\n", pmu_attr->event_str);
10706 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
10708 static int __init perf_event_sysfs_init(void)
10713 mutex_lock(&pmus_lock);
10715 ret = bus_register(&pmu_bus);
10719 list_for_each_entry(pmu, &pmus, entry) {
10720 if (!pmu->name || pmu->type < 0)
10723 ret = pmu_dev_alloc(pmu);
10724 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
10726 pmu_bus_running = 1;
10730 mutex_unlock(&pmus_lock);
10734 device_initcall(perf_event_sysfs_init);
10736 #ifdef CONFIG_CGROUP_PERF
10737 static struct cgroup_subsys_state *
10738 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10740 struct perf_cgroup *jc;
10742 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
10744 return ERR_PTR(-ENOMEM);
10746 jc->info = alloc_percpu(struct perf_cgroup_info);
10749 return ERR_PTR(-ENOMEM);
10755 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
10757 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
10759 free_percpu(jc->info);
10763 static int __perf_cgroup_move(void *info)
10765 struct task_struct *task = info;
10767 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
10772 static void perf_cgroup_attach(struct cgroup_taskset *tset)
10774 struct task_struct *task;
10775 struct cgroup_subsys_state *css;
10777 cgroup_taskset_for_each(task, css, tset)
10778 task_function_call(task, __perf_cgroup_move, task);
10781 struct cgroup_subsys perf_event_cgrp_subsys = {
10782 .css_alloc = perf_cgroup_css_alloc,
10783 .css_free = perf_cgroup_css_free,
10784 .attach = perf_cgroup_attach,
10786 #endif /* CONFIG_CGROUP_PERF */