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. This will
94 * retry due to any failures in smp_call_function_single(), such as if the
95 * task_cpu() goes offline concurrently.
97 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
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,
126 * cpu_function_call - call a function on the cpu
127 * @func: the function to be called
128 * @info: the function call argument
130 * Calls the function @func on the remote cpu.
132 * returns: @func return value or -ENXIO when the cpu is offline
134 static int cpu_function_call(int cpu, remote_function_f func, void *info)
136 struct remote_function_call data = {
140 .ret = -ENXIO, /* No such CPU */
143 smp_call_function_single(cpu, remote_function, &data, 1);
148 static inline struct perf_cpu_context *
149 __get_cpu_context(struct perf_event_context *ctx)
151 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
154 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
155 struct perf_event_context *ctx)
157 raw_spin_lock(&cpuctx->ctx.lock);
159 raw_spin_lock(&ctx->lock);
162 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
163 struct perf_event_context *ctx)
166 raw_spin_unlock(&ctx->lock);
167 raw_spin_unlock(&cpuctx->ctx.lock);
170 #define TASK_TOMBSTONE ((void *)-1L)
172 static bool is_kernel_event(struct perf_event *event)
174 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
178 * On task ctx scheduling...
180 * When !ctx->nr_events a task context will not be scheduled. This means
181 * we can disable the scheduler hooks (for performance) without leaving
182 * pending task ctx state.
184 * This however results in two special cases:
186 * - removing the last event from a task ctx; this is relatively straight
187 * forward and is done in __perf_remove_from_context.
189 * - adding the first event to a task ctx; this is tricky because we cannot
190 * rely on ctx->is_active and therefore cannot use event_function_call().
191 * See perf_install_in_context().
193 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
196 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
197 struct perf_event_context *, void *);
199 struct event_function_struct {
200 struct perf_event *event;
205 static int event_function(void *info)
207 struct event_function_struct *efs = info;
208 struct perf_event *event = efs->event;
209 struct perf_event_context *ctx = event->ctx;
210 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
211 struct perf_event_context *task_ctx = cpuctx->task_ctx;
214 WARN_ON_ONCE(!irqs_disabled());
216 perf_ctx_lock(cpuctx, task_ctx);
218 * Since we do the IPI call without holding ctx->lock things can have
219 * changed, double check we hit the task we set out to hit.
222 if (ctx->task != current) {
228 * We only use event_function_call() on established contexts,
229 * and event_function() is only ever called when active (or
230 * rather, we'll have bailed in task_function_call() or the
231 * above ctx->task != current test), therefore we must have
232 * ctx->is_active here.
234 WARN_ON_ONCE(!ctx->is_active);
236 * And since we have ctx->is_active, cpuctx->task_ctx must
239 WARN_ON_ONCE(task_ctx != ctx);
241 WARN_ON_ONCE(&cpuctx->ctx != ctx);
244 efs->func(event, cpuctx, ctx, efs->data);
246 perf_ctx_unlock(cpuctx, task_ctx);
251 static void event_function_call(struct perf_event *event, event_f func, void *data)
253 struct perf_event_context *ctx = event->ctx;
254 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
255 struct event_function_struct efs = {
261 if (!event->parent) {
263 * If this is a !child event, we must hold ctx::mutex to
264 * stabilize the the event->ctx relation. See
265 * perf_event_ctx_lock().
267 lockdep_assert_held(&ctx->mutex);
271 cpu_function_call(event->cpu, event_function, &efs);
275 if (task == TASK_TOMBSTONE)
279 if (!task_function_call(task, event_function, &efs))
282 raw_spin_lock_irq(&ctx->lock);
284 * Reload the task pointer, it might have been changed by
285 * a concurrent perf_event_context_sched_out().
288 if (task == TASK_TOMBSTONE) {
289 raw_spin_unlock_irq(&ctx->lock);
292 if (ctx->is_active) {
293 raw_spin_unlock_irq(&ctx->lock);
296 func(event, NULL, ctx, data);
297 raw_spin_unlock_irq(&ctx->lock);
301 * Similar to event_function_call() + event_function(), but hard assumes IRQs
302 * are already disabled and we're on the right CPU.
304 static void event_function_local(struct perf_event *event, event_f func, void *data)
306 struct perf_event_context *ctx = event->ctx;
307 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
308 struct task_struct *task = READ_ONCE(ctx->task);
309 struct perf_event_context *task_ctx = NULL;
311 WARN_ON_ONCE(!irqs_disabled());
314 if (task == TASK_TOMBSTONE)
320 perf_ctx_lock(cpuctx, task_ctx);
323 if (task == TASK_TOMBSTONE)
328 * We must be either inactive or active and the right task,
329 * otherwise we're screwed, since we cannot IPI to somewhere
332 if (ctx->is_active) {
333 if (WARN_ON_ONCE(task != current))
336 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
340 WARN_ON_ONCE(&cpuctx->ctx != ctx);
343 func(event, cpuctx, ctx, data);
345 perf_ctx_unlock(cpuctx, task_ctx);
348 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
349 PERF_FLAG_FD_OUTPUT |\
350 PERF_FLAG_PID_CGROUP |\
351 PERF_FLAG_FD_CLOEXEC)
354 * branch priv levels that need permission checks
356 #define PERF_SAMPLE_BRANCH_PERM_PLM \
357 (PERF_SAMPLE_BRANCH_KERNEL |\
358 PERF_SAMPLE_BRANCH_HV)
361 EVENT_FLEXIBLE = 0x1,
364 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
368 * perf_sched_events : >0 events exist
369 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
372 static void perf_sched_delayed(struct work_struct *work);
373 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
374 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
375 static DEFINE_MUTEX(perf_sched_mutex);
376 static atomic_t perf_sched_count;
378 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
379 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
380 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
382 static atomic_t nr_mmap_events __read_mostly;
383 static atomic_t nr_comm_events __read_mostly;
384 static atomic_t nr_task_events __read_mostly;
385 static atomic_t nr_freq_events __read_mostly;
386 static atomic_t nr_switch_events __read_mostly;
388 static LIST_HEAD(pmus);
389 static DEFINE_MUTEX(pmus_lock);
390 static struct srcu_struct pmus_srcu;
393 * perf event paranoia level:
394 * -1 - not paranoid at all
395 * 0 - disallow raw tracepoint access for unpriv
396 * 1 - disallow cpu events for unpriv
397 * 2 - disallow kernel profiling for unpriv
399 int sysctl_perf_event_paranoid __read_mostly = 2;
401 /* Minimum for 512 kiB + 1 user control page */
402 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
405 * max perf event sample rate
407 #define DEFAULT_MAX_SAMPLE_RATE 100000
408 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
409 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
411 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
413 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
414 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
416 static int perf_sample_allowed_ns __read_mostly =
417 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
419 static void update_perf_cpu_limits(void)
421 u64 tmp = perf_sample_period_ns;
423 tmp *= sysctl_perf_cpu_time_max_percent;
424 tmp = div_u64(tmp, 100);
428 WRITE_ONCE(perf_sample_allowed_ns, tmp);
431 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
433 int perf_proc_update_handler(struct ctl_table *table, int write,
434 void __user *buffer, size_t *lenp,
438 int perf_cpu = sysctl_perf_cpu_time_max_percent;
440 * If throttling is disabled don't allow the write:
442 if (write && (perf_cpu == 100 || perf_cpu == 0))
445 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
449 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
450 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
451 update_perf_cpu_limits();
456 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
458 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
459 void __user *buffer, size_t *lenp,
462 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
467 if (sysctl_perf_cpu_time_max_percent == 100 ||
468 sysctl_perf_cpu_time_max_percent == 0) {
470 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
471 WRITE_ONCE(perf_sample_allowed_ns, 0);
473 update_perf_cpu_limits();
480 * perf samples are done in some very critical code paths (NMIs).
481 * If they take too much CPU time, the system can lock up and not
482 * get any real work done. This will drop the sample rate when
483 * we detect that events are taking too long.
485 #define NR_ACCUMULATED_SAMPLES 128
486 static DEFINE_PER_CPU(u64, running_sample_length);
488 static u64 __report_avg;
489 static u64 __report_allowed;
491 static void perf_duration_warn(struct irq_work *w)
493 printk_ratelimited(KERN_INFO
494 "perf: interrupt took too long (%lld > %lld), lowering "
495 "kernel.perf_event_max_sample_rate to %d\n",
496 __report_avg, __report_allowed,
497 sysctl_perf_event_sample_rate);
500 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
502 void perf_sample_event_took(u64 sample_len_ns)
504 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
512 /* Decay the counter by 1 average sample. */
513 running_len = __this_cpu_read(running_sample_length);
514 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
515 running_len += sample_len_ns;
516 __this_cpu_write(running_sample_length, running_len);
519 * Note: this will be biased artifically low until we have
520 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
521 * from having to maintain a count.
523 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
524 if (avg_len <= max_len)
527 __report_avg = avg_len;
528 __report_allowed = max_len;
531 * Compute a throttle threshold 25% below the current duration.
533 avg_len += avg_len / 4;
534 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
540 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
541 WRITE_ONCE(max_samples_per_tick, max);
543 sysctl_perf_event_sample_rate = max * HZ;
544 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
546 if (!irq_work_queue(&perf_duration_work)) {
547 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
548 "kernel.perf_event_max_sample_rate to %d\n",
549 __report_avg, __report_allowed,
550 sysctl_perf_event_sample_rate);
554 static atomic64_t perf_event_id;
556 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
557 enum event_type_t event_type);
559 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
560 enum event_type_t event_type,
561 struct task_struct *task);
563 static void update_context_time(struct perf_event_context *ctx);
564 static u64 perf_event_time(struct perf_event *event);
566 void __weak perf_event_print_debug(void) { }
568 extern __weak const char *perf_pmu_name(void)
573 static inline u64 perf_clock(void)
575 return local_clock();
578 static inline u64 perf_event_clock(struct perf_event *event)
580 return event->clock();
583 #ifdef CONFIG_CGROUP_PERF
586 perf_cgroup_match(struct perf_event *event)
588 struct perf_event_context *ctx = event->ctx;
589 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
591 /* @event doesn't care about cgroup */
595 /* wants specific cgroup scope but @cpuctx isn't associated with any */
600 * Cgroup scoping is recursive. An event enabled for a cgroup is
601 * also enabled for all its descendant cgroups. If @cpuctx's
602 * cgroup is a descendant of @event's (the test covers identity
603 * case), it's a match.
605 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
606 event->cgrp->css.cgroup);
609 static inline void perf_detach_cgroup(struct perf_event *event)
611 css_put(&event->cgrp->css);
615 static inline int is_cgroup_event(struct perf_event *event)
617 return event->cgrp != NULL;
620 static inline u64 perf_cgroup_event_time(struct perf_event *event)
622 struct perf_cgroup_info *t;
624 t = per_cpu_ptr(event->cgrp->info, event->cpu);
628 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
630 struct perf_cgroup_info *info;
635 info = this_cpu_ptr(cgrp->info);
637 info->time += now - info->timestamp;
638 info->timestamp = now;
641 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
643 struct perf_cgroup *cgrp = cpuctx->cgrp;
644 struct cgroup_subsys_state *css;
647 for (css = &cgrp->css; css; css = css->parent) {
648 cgrp = container_of(css, struct perf_cgroup, css);
649 __update_cgrp_time(cgrp);
654 static inline void update_cgrp_time_from_event(struct perf_event *event)
656 struct perf_cgroup *cgrp;
659 * ensure we access cgroup data only when needed and
660 * when we know the cgroup is pinned (css_get)
662 if (!is_cgroup_event(event))
665 cgrp = perf_cgroup_from_task(current, event->ctx);
667 * Do not update time when cgroup is not active
669 if (cgrp == event->cgrp)
670 __update_cgrp_time(event->cgrp);
674 perf_cgroup_set_timestamp(struct task_struct *task,
675 struct perf_event_context *ctx)
677 struct perf_cgroup *cgrp;
678 struct perf_cgroup_info *info;
679 struct cgroup_subsys_state *css;
682 * ctx->lock held by caller
683 * ensure we do not access cgroup data
684 * unless we have the cgroup pinned (css_get)
686 if (!task || !ctx->nr_cgroups)
689 cgrp = perf_cgroup_from_task(task, ctx);
691 for (css = &cgrp->css; css; css = css->parent) {
692 cgrp = container_of(css, struct perf_cgroup, css);
693 info = this_cpu_ptr(cgrp->info);
694 info->timestamp = ctx->timestamp;
698 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
699 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
702 * reschedule events based on the cgroup constraint of task.
704 * mode SWOUT : schedule out everything
705 * mode SWIN : schedule in based on cgroup for next
707 static void perf_cgroup_switch(struct task_struct *task, int mode)
709 struct perf_cpu_context *cpuctx;
714 * disable interrupts to avoid geting nr_cgroup
715 * changes via __perf_event_disable(). Also
718 local_irq_save(flags);
721 * we reschedule only in the presence of cgroup
722 * constrained events.
725 list_for_each_entry_rcu(pmu, &pmus, entry) {
726 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
727 if (cpuctx->unique_pmu != pmu)
728 continue; /* ensure we process each cpuctx once */
731 * perf_cgroup_events says at least one
732 * context on this CPU has cgroup events.
734 * ctx->nr_cgroups reports the number of cgroup
735 * events for a context.
737 if (cpuctx->ctx.nr_cgroups > 0) {
738 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
739 perf_pmu_disable(cpuctx->ctx.pmu);
741 if (mode & PERF_CGROUP_SWOUT) {
742 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
744 * must not be done before ctxswout due
745 * to event_filter_match() in event_sched_out()
750 if (mode & PERF_CGROUP_SWIN) {
751 WARN_ON_ONCE(cpuctx->cgrp);
753 * set cgrp before ctxsw in to allow
754 * event_filter_match() to not have to pass
756 * we pass the cpuctx->ctx to perf_cgroup_from_task()
757 * because cgorup events are only per-cpu
759 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
760 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
762 perf_pmu_enable(cpuctx->ctx.pmu);
763 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
767 local_irq_restore(flags);
770 static inline void perf_cgroup_sched_out(struct task_struct *task,
771 struct task_struct *next)
773 struct perf_cgroup *cgrp1;
774 struct perf_cgroup *cgrp2 = NULL;
778 * we come here when we know perf_cgroup_events > 0
779 * we do not need to pass the ctx here because we know
780 * we are holding the rcu lock
782 cgrp1 = perf_cgroup_from_task(task, NULL);
783 cgrp2 = perf_cgroup_from_task(next, NULL);
786 * only schedule out current cgroup events if we know
787 * that we are switching to a different cgroup. Otherwise,
788 * do no touch the cgroup events.
791 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
796 static inline void perf_cgroup_sched_in(struct task_struct *prev,
797 struct task_struct *task)
799 struct perf_cgroup *cgrp1;
800 struct perf_cgroup *cgrp2 = NULL;
804 * we come here when we know perf_cgroup_events > 0
805 * we do not need to pass the ctx here because we know
806 * we are holding the rcu lock
808 cgrp1 = perf_cgroup_from_task(task, NULL);
809 cgrp2 = perf_cgroup_from_task(prev, NULL);
812 * only need to schedule in cgroup events if we are changing
813 * cgroup during ctxsw. Cgroup events were not scheduled
814 * out of ctxsw out if that was not the case.
817 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
822 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
823 struct perf_event_attr *attr,
824 struct perf_event *group_leader)
826 struct perf_cgroup *cgrp;
827 struct cgroup_subsys_state *css;
828 struct fd f = fdget(fd);
834 css = css_tryget_online_from_dir(f.file->f_path.dentry,
835 &perf_event_cgrp_subsys);
841 cgrp = container_of(css, struct perf_cgroup, css);
845 * all events in a group must monitor
846 * the same cgroup because a task belongs
847 * to only one perf cgroup at a time
849 if (group_leader && group_leader->cgrp != cgrp) {
850 perf_detach_cgroup(event);
859 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
861 struct perf_cgroup_info *t;
862 t = per_cpu_ptr(event->cgrp->info, event->cpu);
863 event->shadow_ctx_time = now - t->timestamp;
867 perf_cgroup_defer_enabled(struct perf_event *event)
870 * when the current task's perf cgroup does not match
871 * the event's, we need to remember to call the
872 * perf_mark_enable() function the first time a task with
873 * a matching perf cgroup is scheduled in.
875 if (is_cgroup_event(event) && !perf_cgroup_match(event))
876 event->cgrp_defer_enabled = 1;
880 perf_cgroup_mark_enabled(struct perf_event *event,
881 struct perf_event_context *ctx)
883 struct perf_event *sub;
884 u64 tstamp = perf_event_time(event);
886 if (!event->cgrp_defer_enabled)
889 event->cgrp_defer_enabled = 0;
891 event->tstamp_enabled = tstamp - event->total_time_enabled;
892 list_for_each_entry(sub, &event->sibling_list, group_entry) {
893 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
894 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
895 sub->cgrp_defer_enabled = 0;
901 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
902 * cleared when last cgroup event is removed.
905 list_update_cgroup_event(struct perf_event *event,
906 struct perf_event_context *ctx, bool add)
908 struct perf_cpu_context *cpuctx;
910 if (!is_cgroup_event(event))
913 if (add && ctx->nr_cgroups++)
915 else if (!add && --ctx->nr_cgroups)
918 * Because cgroup events are always per-cpu events,
919 * this will always be called from the right CPU.
921 cpuctx = __get_cpu_context(ctx);
924 * cpuctx->cgrp is NULL until a cgroup event is sched in or
925 * ctx->nr_cgroup == 0 .
927 if (add && perf_cgroup_from_task(current, ctx) == event->cgrp)
928 cpuctx->cgrp = event->cgrp;
933 #else /* !CONFIG_CGROUP_PERF */
936 perf_cgroup_match(struct perf_event *event)
941 static inline void perf_detach_cgroup(struct perf_event *event)
944 static inline int is_cgroup_event(struct perf_event *event)
949 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
954 static inline void update_cgrp_time_from_event(struct perf_event *event)
958 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
962 static inline void perf_cgroup_sched_out(struct task_struct *task,
963 struct task_struct *next)
967 static inline void perf_cgroup_sched_in(struct task_struct *prev,
968 struct task_struct *task)
972 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
973 struct perf_event_attr *attr,
974 struct perf_event *group_leader)
980 perf_cgroup_set_timestamp(struct task_struct *task,
981 struct perf_event_context *ctx)
986 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
991 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
995 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1001 perf_cgroup_defer_enabled(struct perf_event *event)
1006 perf_cgroup_mark_enabled(struct perf_event *event,
1007 struct perf_event_context *ctx)
1012 list_update_cgroup_event(struct perf_event *event,
1013 struct perf_event_context *ctx, bool add)
1020 * set default to be dependent on timer tick just
1021 * like original code
1023 #define PERF_CPU_HRTIMER (1000 / HZ)
1025 * function must be called with interrupts disbled
1027 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1029 struct perf_cpu_context *cpuctx;
1032 WARN_ON(!irqs_disabled());
1034 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1035 rotations = perf_rotate_context(cpuctx);
1037 raw_spin_lock(&cpuctx->hrtimer_lock);
1039 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1041 cpuctx->hrtimer_active = 0;
1042 raw_spin_unlock(&cpuctx->hrtimer_lock);
1044 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1047 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1049 struct hrtimer *timer = &cpuctx->hrtimer;
1050 struct pmu *pmu = cpuctx->ctx.pmu;
1053 /* no multiplexing needed for SW PMU */
1054 if (pmu->task_ctx_nr == perf_sw_context)
1058 * check default is sane, if not set then force to
1059 * default interval (1/tick)
1061 interval = pmu->hrtimer_interval_ms;
1063 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1065 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1067 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1068 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
1069 timer->function = perf_mux_hrtimer_handler;
1072 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1074 struct hrtimer *timer = &cpuctx->hrtimer;
1075 struct pmu *pmu = cpuctx->ctx.pmu;
1076 unsigned long flags;
1078 /* not for SW PMU */
1079 if (pmu->task_ctx_nr == perf_sw_context)
1082 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1083 if (!cpuctx->hrtimer_active) {
1084 cpuctx->hrtimer_active = 1;
1085 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1086 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
1088 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1093 void perf_pmu_disable(struct pmu *pmu)
1095 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1097 pmu->pmu_disable(pmu);
1100 void perf_pmu_enable(struct pmu *pmu)
1102 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1104 pmu->pmu_enable(pmu);
1107 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1110 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1111 * perf_event_task_tick() are fully serialized because they're strictly cpu
1112 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1113 * disabled, while perf_event_task_tick is called from IRQ context.
1115 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1117 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1119 WARN_ON(!irqs_disabled());
1121 WARN_ON(!list_empty(&ctx->active_ctx_list));
1123 list_add(&ctx->active_ctx_list, head);
1126 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1128 WARN_ON(!irqs_disabled());
1130 WARN_ON(list_empty(&ctx->active_ctx_list));
1132 list_del_init(&ctx->active_ctx_list);
1135 static void get_ctx(struct perf_event_context *ctx)
1137 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1140 static void free_ctx(struct rcu_head *head)
1142 struct perf_event_context *ctx;
1144 ctx = container_of(head, struct perf_event_context, rcu_head);
1145 kfree(ctx->task_ctx_data);
1149 static void put_ctx(struct perf_event_context *ctx)
1151 if (atomic_dec_and_test(&ctx->refcount)) {
1152 if (ctx->parent_ctx)
1153 put_ctx(ctx->parent_ctx);
1154 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1155 put_task_struct(ctx->task);
1156 call_rcu(&ctx->rcu_head, free_ctx);
1161 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1162 * perf_pmu_migrate_context() we need some magic.
1164 * Those places that change perf_event::ctx will hold both
1165 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1167 * Lock ordering is by mutex address. There are two other sites where
1168 * perf_event_context::mutex nests and those are:
1170 * - perf_event_exit_task_context() [ child , 0 ]
1171 * perf_event_exit_event()
1172 * put_event() [ parent, 1 ]
1174 * - perf_event_init_context() [ parent, 0 ]
1175 * inherit_task_group()
1178 * perf_event_alloc()
1180 * perf_try_init_event() [ child , 1 ]
1182 * While it appears there is an obvious deadlock here -- the parent and child
1183 * nesting levels are inverted between the two. This is in fact safe because
1184 * life-time rules separate them. That is an exiting task cannot fork, and a
1185 * spawning task cannot (yet) exit.
1187 * But remember that that these are parent<->child context relations, and
1188 * migration does not affect children, therefore these two orderings should not
1191 * The change in perf_event::ctx does not affect children (as claimed above)
1192 * because the sys_perf_event_open() case will install a new event and break
1193 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1194 * concerned with cpuctx and that doesn't have children.
1196 * The places that change perf_event::ctx will issue:
1198 * perf_remove_from_context();
1199 * synchronize_rcu();
1200 * perf_install_in_context();
1202 * to affect the change. The remove_from_context() + synchronize_rcu() should
1203 * quiesce the event, after which we can install it in the new location. This
1204 * means that only external vectors (perf_fops, prctl) can perturb the event
1205 * while in transit. Therefore all such accessors should also acquire
1206 * perf_event_context::mutex to serialize against this.
1208 * However; because event->ctx can change while we're waiting to acquire
1209 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1214 * task_struct::perf_event_mutex
1215 * perf_event_context::mutex
1216 * perf_event::child_mutex;
1217 * perf_event_context::lock
1218 * perf_event::mmap_mutex
1221 static struct perf_event_context *
1222 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1224 struct perf_event_context *ctx;
1228 ctx = ACCESS_ONCE(event->ctx);
1229 if (!atomic_inc_not_zero(&ctx->refcount)) {
1235 mutex_lock_nested(&ctx->mutex, nesting);
1236 if (event->ctx != ctx) {
1237 mutex_unlock(&ctx->mutex);
1245 static inline struct perf_event_context *
1246 perf_event_ctx_lock(struct perf_event *event)
1248 return perf_event_ctx_lock_nested(event, 0);
1251 static void perf_event_ctx_unlock(struct perf_event *event,
1252 struct perf_event_context *ctx)
1254 mutex_unlock(&ctx->mutex);
1259 * This must be done under the ctx->lock, such as to serialize against
1260 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1261 * calling scheduler related locks and ctx->lock nests inside those.
1263 static __must_check struct perf_event_context *
1264 unclone_ctx(struct perf_event_context *ctx)
1266 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1268 lockdep_assert_held(&ctx->lock);
1271 ctx->parent_ctx = NULL;
1277 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1280 * only top level events have the pid namespace they were created in
1283 event = event->parent;
1285 return task_tgid_nr_ns(p, event->ns);
1288 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1291 * only top level events have the pid namespace they were created in
1294 event = event->parent;
1296 return task_pid_nr_ns(p, event->ns);
1300 * If we inherit events we want to return the parent event id
1303 static u64 primary_event_id(struct perf_event *event)
1308 id = event->parent->id;
1314 * Get the perf_event_context for a task and lock it.
1316 * This has to cope with with the fact that until it is locked,
1317 * the context could get moved to another task.
1319 static struct perf_event_context *
1320 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1322 struct perf_event_context *ctx;
1326 * One of the few rules of preemptible RCU is that one cannot do
1327 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1328 * part of the read side critical section was irqs-enabled -- see
1329 * rcu_read_unlock_special().
1331 * Since ctx->lock nests under rq->lock we must ensure the entire read
1332 * side critical section has interrupts disabled.
1334 local_irq_save(*flags);
1336 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1339 * If this context is a clone of another, it might
1340 * get swapped for another underneath us by
1341 * perf_event_task_sched_out, though the
1342 * rcu_read_lock() protects us from any context
1343 * getting freed. Lock the context and check if it
1344 * got swapped before we could get the lock, and retry
1345 * if so. If we locked the right context, then it
1346 * can't get swapped on us any more.
1348 raw_spin_lock(&ctx->lock);
1349 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1350 raw_spin_unlock(&ctx->lock);
1352 local_irq_restore(*flags);
1356 if (ctx->task == TASK_TOMBSTONE ||
1357 !atomic_inc_not_zero(&ctx->refcount)) {
1358 raw_spin_unlock(&ctx->lock);
1361 WARN_ON_ONCE(ctx->task != task);
1366 local_irq_restore(*flags);
1371 * Get the context for a task and increment its pin_count so it
1372 * can't get swapped to another task. This also increments its
1373 * reference count so that the context can't get freed.
1375 static struct perf_event_context *
1376 perf_pin_task_context(struct task_struct *task, int ctxn)
1378 struct perf_event_context *ctx;
1379 unsigned long flags;
1381 ctx = perf_lock_task_context(task, ctxn, &flags);
1384 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1389 static void perf_unpin_context(struct perf_event_context *ctx)
1391 unsigned long flags;
1393 raw_spin_lock_irqsave(&ctx->lock, flags);
1395 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1399 * Update the record of the current time in a context.
1401 static void update_context_time(struct perf_event_context *ctx)
1403 u64 now = perf_clock();
1405 ctx->time += now - ctx->timestamp;
1406 ctx->timestamp = now;
1409 static u64 perf_event_time(struct perf_event *event)
1411 struct perf_event_context *ctx = event->ctx;
1413 if (is_cgroup_event(event))
1414 return perf_cgroup_event_time(event);
1416 return ctx ? ctx->time : 0;
1420 * Update the total_time_enabled and total_time_running fields for a event.
1422 static void update_event_times(struct perf_event *event)
1424 struct perf_event_context *ctx = event->ctx;
1427 lockdep_assert_held(&ctx->lock);
1429 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1430 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1434 * in cgroup mode, time_enabled represents
1435 * the time the event was enabled AND active
1436 * tasks were in the monitored cgroup. This is
1437 * independent of the activity of the context as
1438 * there may be a mix of cgroup and non-cgroup events.
1440 * That is why we treat cgroup events differently
1443 if (is_cgroup_event(event))
1444 run_end = perf_cgroup_event_time(event);
1445 else if (ctx->is_active)
1446 run_end = ctx->time;
1448 run_end = event->tstamp_stopped;
1450 event->total_time_enabled = run_end - event->tstamp_enabled;
1452 if (event->state == PERF_EVENT_STATE_INACTIVE)
1453 run_end = event->tstamp_stopped;
1455 run_end = perf_event_time(event);
1457 event->total_time_running = run_end - event->tstamp_running;
1462 * Update total_time_enabled and total_time_running for all events in a group.
1464 static void update_group_times(struct perf_event *leader)
1466 struct perf_event *event;
1468 update_event_times(leader);
1469 list_for_each_entry(event, &leader->sibling_list, group_entry)
1470 update_event_times(event);
1473 static struct list_head *
1474 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1476 if (event->attr.pinned)
1477 return &ctx->pinned_groups;
1479 return &ctx->flexible_groups;
1483 * Add a event from the lists for its context.
1484 * Must be called with ctx->mutex and ctx->lock held.
1487 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1489 lockdep_assert_held(&ctx->lock);
1491 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1492 event->attach_state |= PERF_ATTACH_CONTEXT;
1495 * If we're a stand alone event or group leader, we go to the context
1496 * list, group events are kept attached to the group so that
1497 * perf_group_detach can, at all times, locate all siblings.
1499 if (event->group_leader == event) {
1500 struct list_head *list;
1502 event->group_caps = event->event_caps;
1504 list = ctx_group_list(event, ctx);
1505 list_add_tail(&event->group_entry, list);
1508 list_update_cgroup_event(event, ctx, true);
1510 list_add_rcu(&event->event_entry, &ctx->event_list);
1512 if (event->attr.inherit_stat)
1519 * Initialize event state based on the perf_event_attr::disabled.
1521 static inline void perf_event__state_init(struct perf_event *event)
1523 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1524 PERF_EVENT_STATE_INACTIVE;
1527 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1529 int entry = sizeof(u64); /* value */
1533 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1534 size += sizeof(u64);
1536 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1537 size += sizeof(u64);
1539 if (event->attr.read_format & PERF_FORMAT_ID)
1540 entry += sizeof(u64);
1542 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1544 size += sizeof(u64);
1548 event->read_size = size;
1551 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1553 struct perf_sample_data *data;
1556 if (sample_type & PERF_SAMPLE_IP)
1557 size += sizeof(data->ip);
1559 if (sample_type & PERF_SAMPLE_ADDR)
1560 size += sizeof(data->addr);
1562 if (sample_type & PERF_SAMPLE_PERIOD)
1563 size += sizeof(data->period);
1565 if (sample_type & PERF_SAMPLE_WEIGHT)
1566 size += sizeof(data->weight);
1568 if (sample_type & PERF_SAMPLE_READ)
1569 size += event->read_size;
1571 if (sample_type & PERF_SAMPLE_DATA_SRC)
1572 size += sizeof(data->data_src.val);
1574 if (sample_type & PERF_SAMPLE_TRANSACTION)
1575 size += sizeof(data->txn);
1577 event->header_size = size;
1581 * Called at perf_event creation and when events are attached/detached from a
1584 static void perf_event__header_size(struct perf_event *event)
1586 __perf_event_read_size(event,
1587 event->group_leader->nr_siblings);
1588 __perf_event_header_size(event, event->attr.sample_type);
1591 static void perf_event__id_header_size(struct perf_event *event)
1593 struct perf_sample_data *data;
1594 u64 sample_type = event->attr.sample_type;
1597 if (sample_type & PERF_SAMPLE_TID)
1598 size += sizeof(data->tid_entry);
1600 if (sample_type & PERF_SAMPLE_TIME)
1601 size += sizeof(data->time);
1603 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1604 size += sizeof(data->id);
1606 if (sample_type & PERF_SAMPLE_ID)
1607 size += sizeof(data->id);
1609 if (sample_type & PERF_SAMPLE_STREAM_ID)
1610 size += sizeof(data->stream_id);
1612 if (sample_type & PERF_SAMPLE_CPU)
1613 size += sizeof(data->cpu_entry);
1615 event->id_header_size = size;
1618 static bool perf_event_validate_size(struct perf_event *event)
1621 * The values computed here will be over-written when we actually
1624 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1625 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1626 perf_event__id_header_size(event);
1629 * Sum the lot; should not exceed the 64k limit we have on records.
1630 * Conservative limit to allow for callchains and other variable fields.
1632 if (event->read_size + event->header_size +
1633 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1639 static void perf_group_attach(struct perf_event *event)
1641 struct perf_event *group_leader = event->group_leader, *pos;
1643 lockdep_assert_held(&event->ctx->lock);
1646 * We can have double attach due to group movement in perf_event_open.
1648 if (event->attach_state & PERF_ATTACH_GROUP)
1651 event->attach_state |= PERF_ATTACH_GROUP;
1653 if (group_leader == event)
1656 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1658 group_leader->group_caps &= event->event_caps;
1660 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1661 group_leader->nr_siblings++;
1663 perf_event__header_size(group_leader);
1665 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1666 perf_event__header_size(pos);
1670 * Remove a event from the lists for its context.
1671 * Must be called with ctx->mutex and ctx->lock held.
1674 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1676 WARN_ON_ONCE(event->ctx != ctx);
1677 lockdep_assert_held(&ctx->lock);
1680 * We can have double detach due to exit/hot-unplug + close.
1682 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1685 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1687 list_update_cgroup_event(event, ctx, false);
1690 if (event->attr.inherit_stat)
1693 list_del_rcu(&event->event_entry);
1695 if (event->group_leader == event)
1696 list_del_init(&event->group_entry);
1698 update_group_times(event);
1701 * If event was in error state, then keep it
1702 * that way, otherwise bogus counts will be
1703 * returned on read(). The only way to get out
1704 * of error state is by explicit re-enabling
1707 if (event->state > PERF_EVENT_STATE_OFF)
1708 event->state = PERF_EVENT_STATE_OFF;
1713 static void perf_group_detach(struct perf_event *event)
1715 struct perf_event *sibling, *tmp;
1716 struct list_head *list = NULL;
1718 lockdep_assert_held(&event->ctx->lock);
1721 * We can have double detach due to exit/hot-unplug + close.
1723 if (!(event->attach_state & PERF_ATTACH_GROUP))
1726 event->attach_state &= ~PERF_ATTACH_GROUP;
1729 * If this is a sibling, remove it from its group.
1731 if (event->group_leader != event) {
1732 list_del_init(&event->group_entry);
1733 event->group_leader->nr_siblings--;
1737 if (!list_empty(&event->group_entry))
1738 list = &event->group_entry;
1741 * If this was a group event with sibling events then
1742 * upgrade the siblings to singleton events by adding them
1743 * to whatever list we are on.
1745 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1747 list_move_tail(&sibling->group_entry, list);
1748 sibling->group_leader = sibling;
1750 /* Inherit group flags from the previous leader */
1751 sibling->group_caps = event->group_caps;
1753 WARN_ON_ONCE(sibling->ctx != event->ctx);
1757 perf_event__header_size(event->group_leader);
1759 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1760 perf_event__header_size(tmp);
1763 static bool is_orphaned_event(struct perf_event *event)
1765 return event->state == PERF_EVENT_STATE_DEAD;
1768 static inline int __pmu_filter_match(struct perf_event *event)
1770 struct pmu *pmu = event->pmu;
1771 return pmu->filter_match ? pmu->filter_match(event) : 1;
1775 * Check whether we should attempt to schedule an event group based on
1776 * PMU-specific filtering. An event group can consist of HW and SW events,
1777 * potentially with a SW leader, so we must check all the filters, to
1778 * determine whether a group is schedulable:
1780 static inline int pmu_filter_match(struct perf_event *event)
1782 struct perf_event *child;
1784 if (!__pmu_filter_match(event))
1787 list_for_each_entry(child, &event->sibling_list, group_entry) {
1788 if (!__pmu_filter_match(child))
1796 event_filter_match(struct perf_event *event)
1798 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
1799 perf_cgroup_match(event) && pmu_filter_match(event);
1803 event_sched_out(struct perf_event *event,
1804 struct perf_cpu_context *cpuctx,
1805 struct perf_event_context *ctx)
1807 u64 tstamp = perf_event_time(event);
1810 WARN_ON_ONCE(event->ctx != ctx);
1811 lockdep_assert_held(&ctx->lock);
1814 * An event which could not be activated because of
1815 * filter mismatch still needs to have its timings
1816 * maintained, otherwise bogus information is return
1817 * via read() for time_enabled, time_running:
1819 if (event->state == PERF_EVENT_STATE_INACTIVE &&
1820 !event_filter_match(event)) {
1821 delta = tstamp - event->tstamp_stopped;
1822 event->tstamp_running += delta;
1823 event->tstamp_stopped = tstamp;
1826 if (event->state != PERF_EVENT_STATE_ACTIVE)
1829 perf_pmu_disable(event->pmu);
1831 event->tstamp_stopped = tstamp;
1832 event->pmu->del(event, 0);
1834 event->state = PERF_EVENT_STATE_INACTIVE;
1835 if (event->pending_disable) {
1836 event->pending_disable = 0;
1837 event->state = PERF_EVENT_STATE_OFF;
1840 if (!is_software_event(event))
1841 cpuctx->active_oncpu--;
1842 if (!--ctx->nr_active)
1843 perf_event_ctx_deactivate(ctx);
1844 if (event->attr.freq && event->attr.sample_freq)
1846 if (event->attr.exclusive || !cpuctx->active_oncpu)
1847 cpuctx->exclusive = 0;
1849 perf_pmu_enable(event->pmu);
1853 group_sched_out(struct perf_event *group_event,
1854 struct perf_cpu_context *cpuctx,
1855 struct perf_event_context *ctx)
1857 struct perf_event *event;
1858 int state = group_event->state;
1860 perf_pmu_disable(ctx->pmu);
1862 event_sched_out(group_event, cpuctx, ctx);
1865 * Schedule out siblings (if any):
1867 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1868 event_sched_out(event, cpuctx, ctx);
1870 perf_pmu_enable(ctx->pmu);
1872 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1873 cpuctx->exclusive = 0;
1876 #define DETACH_GROUP 0x01UL
1879 * Cross CPU call to remove a performance event
1881 * We disable the event on the hardware level first. After that we
1882 * remove it from the context list.
1885 __perf_remove_from_context(struct perf_event *event,
1886 struct perf_cpu_context *cpuctx,
1887 struct perf_event_context *ctx,
1890 unsigned long flags = (unsigned long)info;
1892 event_sched_out(event, cpuctx, ctx);
1893 if (flags & DETACH_GROUP)
1894 perf_group_detach(event);
1895 list_del_event(event, ctx);
1897 if (!ctx->nr_events && ctx->is_active) {
1900 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1901 cpuctx->task_ctx = NULL;
1907 * Remove the event from a task's (or a CPU's) list of events.
1909 * If event->ctx is a cloned context, callers must make sure that
1910 * every task struct that event->ctx->task could possibly point to
1911 * remains valid. This is OK when called from perf_release since
1912 * that only calls us on the top-level context, which can't be a clone.
1913 * When called from perf_event_exit_task, it's OK because the
1914 * context has been detached from its task.
1916 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1918 struct perf_event_context *ctx = event->ctx;
1920 lockdep_assert_held(&ctx->mutex);
1922 event_function_call(event, __perf_remove_from_context, (void *)flags);
1925 * The above event_function_call() can NO-OP when it hits
1926 * TASK_TOMBSTONE. In that case we must already have been detached
1927 * from the context (by perf_event_exit_event()) but the grouping
1928 * might still be in-tact.
1930 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1931 if ((flags & DETACH_GROUP) &&
1932 (event->attach_state & PERF_ATTACH_GROUP)) {
1934 * Since in that case we cannot possibly be scheduled, simply
1937 raw_spin_lock_irq(&ctx->lock);
1938 perf_group_detach(event);
1939 raw_spin_unlock_irq(&ctx->lock);
1944 * Cross CPU call to disable a performance event
1946 static void __perf_event_disable(struct perf_event *event,
1947 struct perf_cpu_context *cpuctx,
1948 struct perf_event_context *ctx,
1951 if (event->state < PERF_EVENT_STATE_INACTIVE)
1954 update_context_time(ctx);
1955 update_cgrp_time_from_event(event);
1956 update_group_times(event);
1957 if (event == event->group_leader)
1958 group_sched_out(event, cpuctx, ctx);
1960 event_sched_out(event, cpuctx, ctx);
1961 event->state = PERF_EVENT_STATE_OFF;
1967 * If event->ctx is a cloned context, callers must make sure that
1968 * every task struct that event->ctx->task could possibly point to
1969 * remains valid. This condition is satisifed when called through
1970 * perf_event_for_each_child or perf_event_for_each because they
1971 * hold the top-level event's child_mutex, so any descendant that
1972 * goes to exit will block in perf_event_exit_event().
1974 * When called from perf_pending_event it's OK because event->ctx
1975 * is the current context on this CPU and preemption is disabled,
1976 * hence we can't get into perf_event_task_sched_out for this context.
1978 static void _perf_event_disable(struct perf_event *event)
1980 struct perf_event_context *ctx = event->ctx;
1982 raw_spin_lock_irq(&ctx->lock);
1983 if (event->state <= PERF_EVENT_STATE_OFF) {
1984 raw_spin_unlock_irq(&ctx->lock);
1987 raw_spin_unlock_irq(&ctx->lock);
1989 event_function_call(event, __perf_event_disable, NULL);
1992 void perf_event_disable_local(struct perf_event *event)
1994 event_function_local(event, __perf_event_disable, NULL);
1998 * Strictly speaking kernel users cannot create groups and therefore this
1999 * interface does not need the perf_event_ctx_lock() magic.
2001 void perf_event_disable(struct perf_event *event)
2003 struct perf_event_context *ctx;
2005 ctx = perf_event_ctx_lock(event);
2006 _perf_event_disable(event);
2007 perf_event_ctx_unlock(event, ctx);
2009 EXPORT_SYMBOL_GPL(perf_event_disable);
2011 void perf_event_disable_inatomic(struct perf_event *event)
2013 event->pending_disable = 1;
2014 irq_work_queue(&event->pending);
2017 static void perf_set_shadow_time(struct perf_event *event,
2018 struct perf_event_context *ctx,
2022 * use the correct time source for the time snapshot
2024 * We could get by without this by leveraging the
2025 * fact that to get to this function, the caller
2026 * has most likely already called update_context_time()
2027 * and update_cgrp_time_xx() and thus both timestamp
2028 * are identical (or very close). Given that tstamp is,
2029 * already adjusted for cgroup, we could say that:
2030 * tstamp - ctx->timestamp
2032 * tstamp - cgrp->timestamp.
2034 * Then, in perf_output_read(), the calculation would
2035 * work with no changes because:
2036 * - event is guaranteed scheduled in
2037 * - no scheduled out in between
2038 * - thus the timestamp would be the same
2040 * But this is a bit hairy.
2042 * So instead, we have an explicit cgroup call to remain
2043 * within the time time source all along. We believe it
2044 * is cleaner and simpler to understand.
2046 if (is_cgroup_event(event))
2047 perf_cgroup_set_shadow_time(event, tstamp);
2049 event->shadow_ctx_time = tstamp - ctx->timestamp;
2052 #define MAX_INTERRUPTS (~0ULL)
2054 static void perf_log_throttle(struct perf_event *event, int enable);
2055 static void perf_log_itrace_start(struct perf_event *event);
2058 event_sched_in(struct perf_event *event,
2059 struct perf_cpu_context *cpuctx,
2060 struct perf_event_context *ctx)
2062 u64 tstamp = perf_event_time(event);
2065 lockdep_assert_held(&ctx->lock);
2067 if (event->state <= PERF_EVENT_STATE_OFF)
2070 WRITE_ONCE(event->oncpu, smp_processor_id());
2072 * Order event::oncpu write to happen before the ACTIVE state
2076 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
2079 * Unthrottle events, since we scheduled we might have missed several
2080 * ticks already, also for a heavily scheduling task there is little
2081 * guarantee it'll get a tick in a timely manner.
2083 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2084 perf_log_throttle(event, 1);
2085 event->hw.interrupts = 0;
2089 * The new state must be visible before we turn it on in the hardware:
2093 perf_pmu_disable(event->pmu);
2095 perf_set_shadow_time(event, ctx, tstamp);
2097 perf_log_itrace_start(event);
2099 if (event->pmu->add(event, PERF_EF_START)) {
2100 event->state = PERF_EVENT_STATE_INACTIVE;
2106 event->tstamp_running += tstamp - event->tstamp_stopped;
2108 if (!is_software_event(event))
2109 cpuctx->active_oncpu++;
2110 if (!ctx->nr_active++)
2111 perf_event_ctx_activate(ctx);
2112 if (event->attr.freq && event->attr.sample_freq)
2115 if (event->attr.exclusive)
2116 cpuctx->exclusive = 1;
2119 perf_pmu_enable(event->pmu);
2125 group_sched_in(struct perf_event *group_event,
2126 struct perf_cpu_context *cpuctx,
2127 struct perf_event_context *ctx)
2129 struct perf_event *event, *partial_group = NULL;
2130 struct pmu *pmu = ctx->pmu;
2131 u64 now = ctx->time;
2132 bool simulate = false;
2134 if (group_event->state == PERF_EVENT_STATE_OFF)
2137 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2139 if (event_sched_in(group_event, cpuctx, ctx)) {
2140 pmu->cancel_txn(pmu);
2141 perf_mux_hrtimer_restart(cpuctx);
2146 * Schedule in siblings as one group (if any):
2148 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2149 if (event_sched_in(event, cpuctx, ctx)) {
2150 partial_group = event;
2155 if (!pmu->commit_txn(pmu))
2160 * Groups can be scheduled in as one unit only, so undo any
2161 * partial group before returning:
2162 * The events up to the failed event are scheduled out normally,
2163 * tstamp_stopped will be updated.
2165 * The failed events and the remaining siblings need to have
2166 * their timings updated as if they had gone thru event_sched_in()
2167 * and event_sched_out(). This is required to get consistent timings
2168 * across the group. This also takes care of the case where the group
2169 * could never be scheduled by ensuring tstamp_stopped is set to mark
2170 * the time the event was actually stopped, such that time delta
2171 * calculation in update_event_times() is correct.
2173 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2174 if (event == partial_group)
2178 event->tstamp_running += now - event->tstamp_stopped;
2179 event->tstamp_stopped = now;
2181 event_sched_out(event, cpuctx, ctx);
2184 event_sched_out(group_event, cpuctx, ctx);
2186 pmu->cancel_txn(pmu);
2188 perf_mux_hrtimer_restart(cpuctx);
2194 * Work out whether we can put this event group on the CPU now.
2196 static int group_can_go_on(struct perf_event *event,
2197 struct perf_cpu_context *cpuctx,
2201 * Groups consisting entirely of software events can always go on.
2203 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2206 * If an exclusive group is already on, no other hardware
2209 if (cpuctx->exclusive)
2212 * If this group is exclusive and there are already
2213 * events on the CPU, it can't go on.
2215 if (event->attr.exclusive && cpuctx->active_oncpu)
2218 * Otherwise, try to add it if all previous groups were able
2224 static void add_event_to_ctx(struct perf_event *event,
2225 struct perf_event_context *ctx)
2227 u64 tstamp = perf_event_time(event);
2229 list_add_event(event, ctx);
2230 perf_group_attach(event);
2231 event->tstamp_enabled = tstamp;
2232 event->tstamp_running = tstamp;
2233 event->tstamp_stopped = tstamp;
2236 static void ctx_sched_out(struct perf_event_context *ctx,
2237 struct perf_cpu_context *cpuctx,
2238 enum event_type_t event_type);
2240 ctx_sched_in(struct perf_event_context *ctx,
2241 struct perf_cpu_context *cpuctx,
2242 enum event_type_t event_type,
2243 struct task_struct *task);
2245 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2246 struct perf_event_context *ctx)
2248 if (!cpuctx->task_ctx)
2251 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2254 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2257 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2258 struct perf_event_context *ctx,
2259 struct task_struct *task)
2261 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2263 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2264 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2266 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2269 static void ctx_resched(struct perf_cpu_context *cpuctx,
2270 struct perf_event_context *task_ctx)
2272 perf_pmu_disable(cpuctx->ctx.pmu);
2274 task_ctx_sched_out(cpuctx, task_ctx);
2275 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2276 perf_event_sched_in(cpuctx, task_ctx, current);
2277 perf_pmu_enable(cpuctx->ctx.pmu);
2281 * Cross CPU call to install and enable a performance event
2283 * Very similar to remote_function() + event_function() but cannot assume that
2284 * things like ctx->is_active and cpuctx->task_ctx are set.
2286 static int __perf_install_in_context(void *info)
2288 struct perf_event *event = info;
2289 struct perf_event_context *ctx = event->ctx;
2290 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2291 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2292 bool reprogram = true;
2295 raw_spin_lock(&cpuctx->ctx.lock);
2297 raw_spin_lock(&ctx->lock);
2300 reprogram = (ctx->task == current);
2303 * If the task is running, it must be running on this CPU,
2304 * otherwise we cannot reprogram things.
2306 * If its not running, we don't care, ctx->lock will
2307 * serialize against it becoming runnable.
2309 if (task_curr(ctx->task) && !reprogram) {
2314 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2315 } else if (task_ctx) {
2316 raw_spin_lock(&task_ctx->lock);
2320 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2321 add_event_to_ctx(event, ctx);
2322 ctx_resched(cpuctx, task_ctx);
2324 add_event_to_ctx(event, ctx);
2328 perf_ctx_unlock(cpuctx, task_ctx);
2334 * Attach a performance event to a context.
2336 * Very similar to event_function_call, see comment there.
2339 perf_install_in_context(struct perf_event_context *ctx,
2340 struct perf_event *event,
2343 struct task_struct *task = READ_ONCE(ctx->task);
2345 lockdep_assert_held(&ctx->mutex);
2347 if (event->cpu != -1)
2351 * Ensures that if we can observe event->ctx, both the event and ctx
2352 * will be 'complete'. See perf_iterate_sb_cpu().
2354 smp_store_release(&event->ctx, ctx);
2357 cpu_function_call(cpu, __perf_install_in_context, event);
2362 * Should not happen, we validate the ctx is still alive before calling.
2364 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2368 * Installing events is tricky because we cannot rely on ctx->is_active
2369 * to be set in case this is the nr_events 0 -> 1 transition.
2371 * Instead we use task_curr(), which tells us if the task is running.
2372 * However, since we use task_curr() outside of rq::lock, we can race
2373 * against the actual state. This means the result can be wrong.
2375 * If we get a false positive, we retry, this is harmless.
2377 * If we get a false negative, things are complicated. If we are after
2378 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2379 * value must be correct. If we're before, it doesn't matter since
2380 * perf_event_context_sched_in() will program the counter.
2382 * However, this hinges on the remote context switch having observed
2383 * our task->perf_event_ctxp[] store, such that it will in fact take
2384 * ctx::lock in perf_event_context_sched_in().
2386 * We do this by task_function_call(), if the IPI fails to hit the task
2387 * we know any future context switch of task must see the
2388 * perf_event_ctpx[] store.
2392 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2393 * task_cpu() load, such that if the IPI then does not find the task
2394 * running, a future context switch of that task must observe the
2399 if (!task_function_call(task, __perf_install_in_context, event))
2402 raw_spin_lock_irq(&ctx->lock);
2404 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2406 * Cannot happen because we already checked above (which also
2407 * cannot happen), and we hold ctx->mutex, which serializes us
2408 * against perf_event_exit_task_context().
2410 raw_spin_unlock_irq(&ctx->lock);
2414 * If the task is not running, ctx->lock will avoid it becoming so,
2415 * thus we can safely install the event.
2417 if (task_curr(task)) {
2418 raw_spin_unlock_irq(&ctx->lock);
2421 add_event_to_ctx(event, ctx);
2422 raw_spin_unlock_irq(&ctx->lock);
2426 * Put a event into inactive state and update time fields.
2427 * Enabling the leader of a group effectively enables all
2428 * the group members that aren't explicitly disabled, so we
2429 * have to update their ->tstamp_enabled also.
2430 * Note: this works for group members as well as group leaders
2431 * since the non-leader members' sibling_lists will be empty.
2433 static void __perf_event_mark_enabled(struct perf_event *event)
2435 struct perf_event *sub;
2436 u64 tstamp = perf_event_time(event);
2438 event->state = PERF_EVENT_STATE_INACTIVE;
2439 event->tstamp_enabled = tstamp - event->total_time_enabled;
2440 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2441 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2442 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2447 * Cross CPU call to enable a performance event
2449 static void __perf_event_enable(struct perf_event *event,
2450 struct perf_cpu_context *cpuctx,
2451 struct perf_event_context *ctx,
2454 struct perf_event *leader = event->group_leader;
2455 struct perf_event_context *task_ctx;
2457 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2458 event->state <= PERF_EVENT_STATE_ERROR)
2462 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2464 __perf_event_mark_enabled(event);
2466 if (!ctx->is_active)
2469 if (!event_filter_match(event)) {
2470 if (is_cgroup_event(event))
2471 perf_cgroup_defer_enabled(event);
2472 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2477 * If the event is in a group and isn't the group leader,
2478 * then don't put it on unless the group is on.
2480 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2481 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2485 task_ctx = cpuctx->task_ctx;
2487 WARN_ON_ONCE(task_ctx != ctx);
2489 ctx_resched(cpuctx, task_ctx);
2495 * If event->ctx is a cloned context, callers must make sure that
2496 * every task struct that event->ctx->task could possibly point to
2497 * remains valid. This condition is satisfied when called through
2498 * perf_event_for_each_child or perf_event_for_each as described
2499 * for perf_event_disable.
2501 static void _perf_event_enable(struct perf_event *event)
2503 struct perf_event_context *ctx = event->ctx;
2505 raw_spin_lock_irq(&ctx->lock);
2506 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2507 event->state < PERF_EVENT_STATE_ERROR) {
2508 raw_spin_unlock_irq(&ctx->lock);
2513 * If the event is in error state, clear that first.
2515 * That way, if we see the event in error state below, we know that it
2516 * has gone back into error state, as distinct from the task having
2517 * been scheduled away before the cross-call arrived.
2519 if (event->state == PERF_EVENT_STATE_ERROR)
2520 event->state = PERF_EVENT_STATE_OFF;
2521 raw_spin_unlock_irq(&ctx->lock);
2523 event_function_call(event, __perf_event_enable, NULL);
2527 * See perf_event_disable();
2529 void perf_event_enable(struct perf_event *event)
2531 struct perf_event_context *ctx;
2533 ctx = perf_event_ctx_lock(event);
2534 _perf_event_enable(event);
2535 perf_event_ctx_unlock(event, ctx);
2537 EXPORT_SYMBOL_GPL(perf_event_enable);
2539 struct stop_event_data {
2540 struct perf_event *event;
2541 unsigned int restart;
2544 static int __perf_event_stop(void *info)
2546 struct stop_event_data *sd = info;
2547 struct perf_event *event = sd->event;
2549 /* if it's already INACTIVE, do nothing */
2550 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2553 /* matches smp_wmb() in event_sched_in() */
2557 * There is a window with interrupts enabled before we get here,
2558 * so we need to check again lest we try to stop another CPU's event.
2560 if (READ_ONCE(event->oncpu) != smp_processor_id())
2563 event->pmu->stop(event, PERF_EF_UPDATE);
2566 * May race with the actual stop (through perf_pmu_output_stop()),
2567 * but it is only used for events with AUX ring buffer, and such
2568 * events will refuse to restart because of rb::aux_mmap_count==0,
2569 * see comments in perf_aux_output_begin().
2571 * Since this is happening on a event-local CPU, no trace is lost
2575 event->pmu->start(event, 0);
2580 static int perf_event_stop(struct perf_event *event, int restart)
2582 struct stop_event_data sd = {
2589 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2592 /* matches smp_wmb() in event_sched_in() */
2596 * We only want to restart ACTIVE events, so if the event goes
2597 * inactive here (event->oncpu==-1), there's nothing more to do;
2598 * fall through with ret==-ENXIO.
2600 ret = cpu_function_call(READ_ONCE(event->oncpu),
2601 __perf_event_stop, &sd);
2602 } while (ret == -EAGAIN);
2608 * In order to contain the amount of racy and tricky in the address filter
2609 * configuration management, it is a two part process:
2611 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2612 * we update the addresses of corresponding vmas in
2613 * event::addr_filters_offs array and bump the event::addr_filters_gen;
2614 * (p2) when an event is scheduled in (pmu::add), it calls
2615 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2616 * if the generation has changed since the previous call.
2618 * If (p1) happens while the event is active, we restart it to force (p2).
2620 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2621 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2623 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2624 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2626 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2629 void perf_event_addr_filters_sync(struct perf_event *event)
2631 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2633 if (!has_addr_filter(event))
2636 raw_spin_lock(&ifh->lock);
2637 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2638 event->pmu->addr_filters_sync(event);
2639 event->hw.addr_filters_gen = event->addr_filters_gen;
2641 raw_spin_unlock(&ifh->lock);
2643 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2645 static int _perf_event_refresh(struct perf_event *event, int refresh)
2648 * not supported on inherited events
2650 if (event->attr.inherit || !is_sampling_event(event))
2653 atomic_add(refresh, &event->event_limit);
2654 _perf_event_enable(event);
2660 * See perf_event_disable()
2662 int perf_event_refresh(struct perf_event *event, int refresh)
2664 struct perf_event_context *ctx;
2667 ctx = perf_event_ctx_lock(event);
2668 ret = _perf_event_refresh(event, refresh);
2669 perf_event_ctx_unlock(event, ctx);
2673 EXPORT_SYMBOL_GPL(perf_event_refresh);
2675 static void ctx_sched_out(struct perf_event_context *ctx,
2676 struct perf_cpu_context *cpuctx,
2677 enum event_type_t event_type)
2679 int is_active = ctx->is_active;
2680 struct perf_event *event;
2682 lockdep_assert_held(&ctx->lock);
2684 if (likely(!ctx->nr_events)) {
2686 * See __perf_remove_from_context().
2688 WARN_ON_ONCE(ctx->is_active);
2690 WARN_ON_ONCE(cpuctx->task_ctx);
2694 ctx->is_active &= ~event_type;
2695 if (!(ctx->is_active & EVENT_ALL))
2699 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2700 if (!ctx->is_active)
2701 cpuctx->task_ctx = NULL;
2705 * Always update time if it was set; not only when it changes.
2706 * Otherwise we can 'forget' to update time for any but the last
2707 * context we sched out. For example:
2709 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2710 * ctx_sched_out(.event_type = EVENT_PINNED)
2712 * would only update time for the pinned events.
2714 if (is_active & EVENT_TIME) {
2715 /* update (and stop) ctx time */
2716 update_context_time(ctx);
2717 update_cgrp_time_from_cpuctx(cpuctx);
2720 is_active ^= ctx->is_active; /* changed bits */
2722 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2725 perf_pmu_disable(ctx->pmu);
2726 if (is_active & EVENT_PINNED) {
2727 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2728 group_sched_out(event, cpuctx, ctx);
2731 if (is_active & EVENT_FLEXIBLE) {
2732 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2733 group_sched_out(event, cpuctx, ctx);
2735 perf_pmu_enable(ctx->pmu);
2739 * Test whether two contexts are equivalent, i.e. whether they have both been
2740 * cloned from the same version of the same context.
2742 * Equivalence is measured using a generation number in the context that is
2743 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2744 * and list_del_event().
2746 static int context_equiv(struct perf_event_context *ctx1,
2747 struct perf_event_context *ctx2)
2749 lockdep_assert_held(&ctx1->lock);
2750 lockdep_assert_held(&ctx2->lock);
2752 /* Pinning disables the swap optimization */
2753 if (ctx1->pin_count || ctx2->pin_count)
2756 /* If ctx1 is the parent of ctx2 */
2757 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2760 /* If ctx2 is the parent of ctx1 */
2761 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2765 * If ctx1 and ctx2 have the same parent; we flatten the parent
2766 * hierarchy, see perf_event_init_context().
2768 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2769 ctx1->parent_gen == ctx2->parent_gen)
2776 static void __perf_event_sync_stat(struct perf_event *event,
2777 struct perf_event *next_event)
2781 if (!event->attr.inherit_stat)
2785 * Update the event value, we cannot use perf_event_read()
2786 * because we're in the middle of a context switch and have IRQs
2787 * disabled, which upsets smp_call_function_single(), however
2788 * we know the event must be on the current CPU, therefore we
2789 * don't need to use it.
2791 switch (event->state) {
2792 case PERF_EVENT_STATE_ACTIVE:
2793 event->pmu->read(event);
2796 case PERF_EVENT_STATE_INACTIVE:
2797 update_event_times(event);
2805 * In order to keep per-task stats reliable we need to flip the event
2806 * values when we flip the contexts.
2808 value = local64_read(&next_event->count);
2809 value = local64_xchg(&event->count, value);
2810 local64_set(&next_event->count, value);
2812 swap(event->total_time_enabled, next_event->total_time_enabled);
2813 swap(event->total_time_running, next_event->total_time_running);
2816 * Since we swizzled the values, update the user visible data too.
2818 perf_event_update_userpage(event);
2819 perf_event_update_userpage(next_event);
2822 static void perf_event_sync_stat(struct perf_event_context *ctx,
2823 struct perf_event_context *next_ctx)
2825 struct perf_event *event, *next_event;
2830 update_context_time(ctx);
2832 event = list_first_entry(&ctx->event_list,
2833 struct perf_event, event_entry);
2835 next_event = list_first_entry(&next_ctx->event_list,
2836 struct perf_event, event_entry);
2838 while (&event->event_entry != &ctx->event_list &&
2839 &next_event->event_entry != &next_ctx->event_list) {
2841 __perf_event_sync_stat(event, next_event);
2843 event = list_next_entry(event, event_entry);
2844 next_event = list_next_entry(next_event, event_entry);
2848 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2849 struct task_struct *next)
2851 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2852 struct perf_event_context *next_ctx;
2853 struct perf_event_context *parent, *next_parent;
2854 struct perf_cpu_context *cpuctx;
2860 cpuctx = __get_cpu_context(ctx);
2861 if (!cpuctx->task_ctx)
2865 next_ctx = next->perf_event_ctxp[ctxn];
2869 parent = rcu_dereference(ctx->parent_ctx);
2870 next_parent = rcu_dereference(next_ctx->parent_ctx);
2872 /* If neither context have a parent context; they cannot be clones. */
2873 if (!parent && !next_parent)
2876 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2878 * Looks like the two contexts are clones, so we might be
2879 * able to optimize the context switch. We lock both
2880 * contexts and check that they are clones under the
2881 * lock (including re-checking that neither has been
2882 * uncloned in the meantime). It doesn't matter which
2883 * order we take the locks because no other cpu could
2884 * be trying to lock both of these tasks.
2886 raw_spin_lock(&ctx->lock);
2887 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2888 if (context_equiv(ctx, next_ctx)) {
2889 WRITE_ONCE(ctx->task, next);
2890 WRITE_ONCE(next_ctx->task, task);
2892 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2895 * RCU_INIT_POINTER here is safe because we've not
2896 * modified the ctx and the above modification of
2897 * ctx->task and ctx->task_ctx_data are immaterial
2898 * since those values are always verified under
2899 * ctx->lock which we're now holding.
2901 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2902 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2906 perf_event_sync_stat(ctx, next_ctx);
2908 raw_spin_unlock(&next_ctx->lock);
2909 raw_spin_unlock(&ctx->lock);
2915 raw_spin_lock(&ctx->lock);
2916 task_ctx_sched_out(cpuctx, ctx);
2917 raw_spin_unlock(&ctx->lock);
2921 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
2923 void perf_sched_cb_dec(struct pmu *pmu)
2925 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2927 this_cpu_dec(perf_sched_cb_usages);
2929 if (!--cpuctx->sched_cb_usage)
2930 list_del(&cpuctx->sched_cb_entry);
2934 void perf_sched_cb_inc(struct pmu *pmu)
2936 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2938 if (!cpuctx->sched_cb_usage++)
2939 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
2941 this_cpu_inc(perf_sched_cb_usages);
2945 * This function provides the context switch callback to the lower code
2946 * layer. It is invoked ONLY when the context switch callback is enabled.
2948 * This callback is relevant even to per-cpu events; for example multi event
2949 * PEBS requires this to provide PID/TID information. This requires we flush
2950 * all queued PEBS records before we context switch to a new task.
2952 static void perf_pmu_sched_task(struct task_struct *prev,
2953 struct task_struct *next,
2956 struct perf_cpu_context *cpuctx;
2962 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
2963 pmu = cpuctx->unique_pmu; /* software PMUs will not have sched_task */
2965 if (WARN_ON_ONCE(!pmu->sched_task))
2968 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2969 perf_pmu_disable(pmu);
2971 pmu->sched_task(cpuctx->task_ctx, sched_in);
2973 perf_pmu_enable(pmu);
2974 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2978 static void perf_event_switch(struct task_struct *task,
2979 struct task_struct *next_prev, bool sched_in);
2981 #define for_each_task_context_nr(ctxn) \
2982 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2985 * Called from scheduler to remove the events of the current task,
2986 * with interrupts disabled.
2988 * We stop each event and update the event value in event->count.
2990 * This does not protect us against NMI, but disable()
2991 * sets the disabled bit in the control field of event _before_
2992 * accessing the event control register. If a NMI hits, then it will
2993 * not restart the event.
2995 void __perf_event_task_sched_out(struct task_struct *task,
2996 struct task_struct *next)
3000 if (__this_cpu_read(perf_sched_cb_usages))
3001 perf_pmu_sched_task(task, next, false);
3003 if (atomic_read(&nr_switch_events))
3004 perf_event_switch(task, next, false);
3006 for_each_task_context_nr(ctxn)
3007 perf_event_context_sched_out(task, ctxn, next);
3010 * if cgroup events exist on this CPU, then we need
3011 * to check if we have to switch out PMU state.
3012 * cgroup event are system-wide mode only
3014 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3015 perf_cgroup_sched_out(task, next);
3019 * Called with IRQs disabled
3021 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3022 enum event_type_t event_type)
3024 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3028 ctx_pinned_sched_in(struct perf_event_context *ctx,
3029 struct perf_cpu_context *cpuctx)
3031 struct perf_event *event;
3033 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
3034 if (event->state <= PERF_EVENT_STATE_OFF)
3036 if (!event_filter_match(event))
3039 /* may need to reset tstamp_enabled */
3040 if (is_cgroup_event(event))
3041 perf_cgroup_mark_enabled(event, ctx);
3043 if (group_can_go_on(event, cpuctx, 1))
3044 group_sched_in(event, cpuctx, ctx);
3047 * If this pinned group hasn't been scheduled,
3048 * put it in error state.
3050 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3051 update_group_times(event);
3052 event->state = PERF_EVENT_STATE_ERROR;
3058 ctx_flexible_sched_in(struct perf_event_context *ctx,
3059 struct perf_cpu_context *cpuctx)
3061 struct perf_event *event;
3064 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
3065 /* Ignore events in OFF or ERROR state */
3066 if (event->state <= PERF_EVENT_STATE_OFF)
3069 * Listen to the 'cpu' scheduling filter constraint
3072 if (!event_filter_match(event))
3075 /* may need to reset tstamp_enabled */
3076 if (is_cgroup_event(event))
3077 perf_cgroup_mark_enabled(event, ctx);
3079 if (group_can_go_on(event, cpuctx, can_add_hw)) {
3080 if (group_sched_in(event, cpuctx, ctx))
3087 ctx_sched_in(struct perf_event_context *ctx,
3088 struct perf_cpu_context *cpuctx,
3089 enum event_type_t event_type,
3090 struct task_struct *task)
3092 int is_active = ctx->is_active;
3095 lockdep_assert_held(&ctx->lock);
3097 if (likely(!ctx->nr_events))
3100 ctx->is_active |= (event_type | EVENT_TIME);
3103 cpuctx->task_ctx = ctx;
3105 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3108 is_active ^= ctx->is_active; /* changed bits */
3110 if (is_active & EVENT_TIME) {
3111 /* start ctx time */
3113 ctx->timestamp = now;
3114 perf_cgroup_set_timestamp(task, ctx);
3118 * First go through the list and put on any pinned groups
3119 * in order to give them the best chance of going on.
3121 if (is_active & EVENT_PINNED)
3122 ctx_pinned_sched_in(ctx, cpuctx);
3124 /* Then walk through the lower prio flexible groups */
3125 if (is_active & EVENT_FLEXIBLE)
3126 ctx_flexible_sched_in(ctx, cpuctx);
3129 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3130 enum event_type_t event_type,
3131 struct task_struct *task)
3133 struct perf_event_context *ctx = &cpuctx->ctx;
3135 ctx_sched_in(ctx, cpuctx, event_type, task);
3138 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3139 struct task_struct *task)
3141 struct perf_cpu_context *cpuctx;
3143 cpuctx = __get_cpu_context(ctx);
3144 if (cpuctx->task_ctx == ctx)
3147 perf_ctx_lock(cpuctx, ctx);
3148 perf_pmu_disable(ctx->pmu);
3150 * We want to keep the following priority order:
3151 * cpu pinned (that don't need to move), task pinned,
3152 * cpu flexible, task flexible.
3154 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3155 perf_event_sched_in(cpuctx, ctx, task);
3156 perf_pmu_enable(ctx->pmu);
3157 perf_ctx_unlock(cpuctx, ctx);
3161 * Called from scheduler to add the events of the current task
3162 * with interrupts disabled.
3164 * We restore the event value and then enable it.
3166 * This does not protect us against NMI, but enable()
3167 * sets the enabled bit in the control field of event _before_
3168 * accessing the event control register. If a NMI hits, then it will
3169 * keep the event running.
3171 void __perf_event_task_sched_in(struct task_struct *prev,
3172 struct task_struct *task)
3174 struct perf_event_context *ctx;
3178 * If cgroup events exist on this CPU, then we need to check if we have
3179 * to switch in PMU state; cgroup event are system-wide mode only.
3181 * Since cgroup events are CPU events, we must schedule these in before
3182 * we schedule in the task events.
3184 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3185 perf_cgroup_sched_in(prev, task);
3187 for_each_task_context_nr(ctxn) {
3188 ctx = task->perf_event_ctxp[ctxn];
3192 perf_event_context_sched_in(ctx, task);
3195 if (atomic_read(&nr_switch_events))
3196 perf_event_switch(task, prev, true);
3198 if (__this_cpu_read(perf_sched_cb_usages))
3199 perf_pmu_sched_task(prev, task, true);
3202 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3204 u64 frequency = event->attr.sample_freq;
3205 u64 sec = NSEC_PER_SEC;
3206 u64 divisor, dividend;
3208 int count_fls, nsec_fls, frequency_fls, sec_fls;
3210 count_fls = fls64(count);
3211 nsec_fls = fls64(nsec);
3212 frequency_fls = fls64(frequency);
3216 * We got @count in @nsec, with a target of sample_freq HZ
3217 * the target period becomes:
3220 * period = -------------------
3221 * @nsec * sample_freq
3226 * Reduce accuracy by one bit such that @a and @b converge
3227 * to a similar magnitude.
3229 #define REDUCE_FLS(a, b) \
3231 if (a##_fls > b##_fls) { \
3241 * Reduce accuracy until either term fits in a u64, then proceed with
3242 * the other, so that finally we can do a u64/u64 division.
3244 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3245 REDUCE_FLS(nsec, frequency);
3246 REDUCE_FLS(sec, count);
3249 if (count_fls + sec_fls > 64) {
3250 divisor = nsec * frequency;
3252 while (count_fls + sec_fls > 64) {
3253 REDUCE_FLS(count, sec);
3257 dividend = count * sec;
3259 dividend = count * sec;
3261 while (nsec_fls + frequency_fls > 64) {
3262 REDUCE_FLS(nsec, frequency);
3266 divisor = nsec * frequency;
3272 return div64_u64(dividend, divisor);
3275 static DEFINE_PER_CPU(int, perf_throttled_count);
3276 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3278 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3280 struct hw_perf_event *hwc = &event->hw;
3281 s64 period, sample_period;
3284 period = perf_calculate_period(event, nsec, count);
3286 delta = (s64)(period - hwc->sample_period);
3287 delta = (delta + 7) / 8; /* low pass filter */
3289 sample_period = hwc->sample_period + delta;
3294 hwc->sample_period = sample_period;
3296 if (local64_read(&hwc->period_left) > 8*sample_period) {
3298 event->pmu->stop(event, PERF_EF_UPDATE);
3300 local64_set(&hwc->period_left, 0);
3303 event->pmu->start(event, PERF_EF_RELOAD);
3308 * combine freq adjustment with unthrottling to avoid two passes over the
3309 * events. At the same time, make sure, having freq events does not change
3310 * the rate of unthrottling as that would introduce bias.
3312 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3315 struct perf_event *event;
3316 struct hw_perf_event *hwc;
3317 u64 now, period = TICK_NSEC;
3321 * only need to iterate over all events iff:
3322 * - context have events in frequency mode (needs freq adjust)
3323 * - there are events to unthrottle on this cpu
3325 if (!(ctx->nr_freq || needs_unthr))
3328 raw_spin_lock(&ctx->lock);
3329 perf_pmu_disable(ctx->pmu);
3331 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3332 if (event->state != PERF_EVENT_STATE_ACTIVE)
3335 if (!event_filter_match(event))
3338 perf_pmu_disable(event->pmu);
3342 if (hwc->interrupts == MAX_INTERRUPTS) {
3343 hwc->interrupts = 0;
3344 perf_log_throttle(event, 1);
3345 event->pmu->start(event, 0);
3348 if (!event->attr.freq || !event->attr.sample_freq)
3352 * stop the event and update event->count
3354 event->pmu->stop(event, PERF_EF_UPDATE);
3356 now = local64_read(&event->count);
3357 delta = now - hwc->freq_count_stamp;
3358 hwc->freq_count_stamp = now;
3362 * reload only if value has changed
3363 * we have stopped the event so tell that
3364 * to perf_adjust_period() to avoid stopping it
3368 perf_adjust_period(event, period, delta, false);
3370 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3372 perf_pmu_enable(event->pmu);
3375 perf_pmu_enable(ctx->pmu);
3376 raw_spin_unlock(&ctx->lock);
3380 * Round-robin a context's events:
3382 static void rotate_ctx(struct perf_event_context *ctx)
3385 * Rotate the first entry last of non-pinned groups. Rotation might be
3386 * disabled by the inheritance code.
3388 if (!ctx->rotate_disable)
3389 list_rotate_left(&ctx->flexible_groups);
3392 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3394 struct perf_event_context *ctx = NULL;
3397 if (cpuctx->ctx.nr_events) {
3398 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3402 ctx = cpuctx->task_ctx;
3403 if (ctx && ctx->nr_events) {
3404 if (ctx->nr_events != ctx->nr_active)
3411 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3412 perf_pmu_disable(cpuctx->ctx.pmu);
3414 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3416 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3418 rotate_ctx(&cpuctx->ctx);
3422 perf_event_sched_in(cpuctx, ctx, current);
3424 perf_pmu_enable(cpuctx->ctx.pmu);
3425 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3431 void perf_event_task_tick(void)
3433 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3434 struct perf_event_context *ctx, *tmp;
3437 WARN_ON(!irqs_disabled());
3439 __this_cpu_inc(perf_throttled_seq);
3440 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3441 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3443 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3444 perf_adjust_freq_unthr_context(ctx, throttled);
3447 static int event_enable_on_exec(struct perf_event *event,
3448 struct perf_event_context *ctx)
3450 if (!event->attr.enable_on_exec)
3453 event->attr.enable_on_exec = 0;
3454 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3457 __perf_event_mark_enabled(event);
3463 * Enable all of a task's events that have been marked enable-on-exec.
3464 * This expects task == current.
3466 static void perf_event_enable_on_exec(int ctxn)
3468 struct perf_event_context *ctx, *clone_ctx = NULL;
3469 struct perf_cpu_context *cpuctx;
3470 struct perf_event *event;
3471 unsigned long flags;
3474 local_irq_save(flags);
3475 ctx = current->perf_event_ctxp[ctxn];
3476 if (!ctx || !ctx->nr_events)
3479 cpuctx = __get_cpu_context(ctx);
3480 perf_ctx_lock(cpuctx, ctx);
3481 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3482 list_for_each_entry(event, &ctx->event_list, event_entry)
3483 enabled |= event_enable_on_exec(event, ctx);
3486 * Unclone and reschedule this context if we enabled any event.
3489 clone_ctx = unclone_ctx(ctx);
3490 ctx_resched(cpuctx, ctx);
3492 perf_ctx_unlock(cpuctx, ctx);
3495 local_irq_restore(flags);
3501 struct perf_read_data {
3502 struct perf_event *event;
3507 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
3509 u16 local_pkg, event_pkg;
3511 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
3512 int local_cpu = smp_processor_id();
3514 event_pkg = topology_physical_package_id(event_cpu);
3515 local_pkg = topology_physical_package_id(local_cpu);
3517 if (event_pkg == local_pkg)
3525 * Cross CPU call to read the hardware event
3527 static void __perf_event_read(void *info)
3529 struct perf_read_data *data = info;
3530 struct perf_event *sub, *event = data->event;
3531 struct perf_event_context *ctx = event->ctx;
3532 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3533 struct pmu *pmu = event->pmu;
3536 * If this is a task context, we need to check whether it is
3537 * the current task context of this cpu. If not it has been
3538 * scheduled out before the smp call arrived. In that case
3539 * event->count would have been updated to a recent sample
3540 * when the event was scheduled out.
3542 if (ctx->task && cpuctx->task_ctx != ctx)
3545 raw_spin_lock(&ctx->lock);
3546 if (ctx->is_active) {
3547 update_context_time(ctx);
3548 update_cgrp_time_from_event(event);
3551 update_event_times(event);
3552 if (event->state != PERF_EVENT_STATE_ACTIVE)
3561 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3565 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3566 update_event_times(sub);
3567 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3569 * Use sibling's PMU rather than @event's since
3570 * sibling could be on different (eg: software) PMU.
3572 sub->pmu->read(sub);
3576 data->ret = pmu->commit_txn(pmu);
3579 raw_spin_unlock(&ctx->lock);
3582 static inline u64 perf_event_count(struct perf_event *event)
3584 if (event->pmu->count)
3585 return event->pmu->count(event);
3587 return __perf_event_count(event);
3591 * NMI-safe method to read a local event, that is an event that
3593 * - either for the current task, or for this CPU
3594 * - does not have inherit set, for inherited task events
3595 * will not be local and we cannot read them atomically
3596 * - must not have a pmu::count method
3598 u64 perf_event_read_local(struct perf_event *event)
3600 unsigned long flags;
3604 * Disabling interrupts avoids all counter scheduling (context
3605 * switches, timer based rotation and IPIs).
3607 local_irq_save(flags);
3609 /* If this is a per-task event, it must be for current */
3610 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3611 event->hw.target != current);
3613 /* If this is a per-CPU event, it must be for this CPU */
3614 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3615 event->cpu != smp_processor_id());
3618 * It must not be an event with inherit set, we cannot read
3619 * all child counters from atomic context.
3621 WARN_ON_ONCE(event->attr.inherit);
3624 * It must not have a pmu::count method, those are not
3627 WARN_ON_ONCE(event->pmu->count);
3630 * If the event is currently on this CPU, its either a per-task event,
3631 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3634 if (event->oncpu == smp_processor_id())
3635 event->pmu->read(event);
3637 val = local64_read(&event->count);
3638 local_irq_restore(flags);
3643 static int perf_event_read(struct perf_event *event, bool group)
3645 int event_cpu, ret = 0;
3648 * If event is enabled and currently active on a CPU, update the
3649 * value in the event structure:
3651 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3652 struct perf_read_data data = {
3658 event_cpu = READ_ONCE(event->oncpu);
3659 if ((unsigned)event_cpu >= nr_cpu_ids)
3663 event_cpu = __perf_event_read_cpu(event, event_cpu);
3666 * Purposely ignore the smp_call_function_single() return
3669 * If event_cpu isn't a valid CPU it means the event got
3670 * scheduled out and that will have updated the event count.
3672 * Therefore, either way, we'll have an up-to-date event count
3675 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
3678 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3679 struct perf_event_context *ctx = event->ctx;
3680 unsigned long flags;
3682 raw_spin_lock_irqsave(&ctx->lock, flags);
3684 * may read while context is not active
3685 * (e.g., thread is blocked), in that case
3686 * we cannot update context time
3688 if (ctx->is_active) {
3689 update_context_time(ctx);
3690 update_cgrp_time_from_event(event);
3693 update_group_times(event);
3695 update_event_times(event);
3696 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3703 * Initialize the perf_event context in a task_struct:
3705 static void __perf_event_init_context(struct perf_event_context *ctx)
3707 raw_spin_lock_init(&ctx->lock);
3708 mutex_init(&ctx->mutex);
3709 INIT_LIST_HEAD(&ctx->active_ctx_list);
3710 INIT_LIST_HEAD(&ctx->pinned_groups);
3711 INIT_LIST_HEAD(&ctx->flexible_groups);
3712 INIT_LIST_HEAD(&ctx->event_list);
3713 atomic_set(&ctx->refcount, 1);
3716 static struct perf_event_context *
3717 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3719 struct perf_event_context *ctx;
3721 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3725 __perf_event_init_context(ctx);
3728 get_task_struct(task);
3735 static struct task_struct *
3736 find_lively_task_by_vpid(pid_t vpid)
3738 struct task_struct *task;
3744 task = find_task_by_vpid(vpid);
3746 get_task_struct(task);
3750 return ERR_PTR(-ESRCH);
3756 * Returns a matching context with refcount and pincount.
3758 static struct perf_event_context *
3759 find_get_context(struct pmu *pmu, struct task_struct *task,
3760 struct perf_event *event)
3762 struct perf_event_context *ctx, *clone_ctx = NULL;
3763 struct perf_cpu_context *cpuctx;
3764 void *task_ctx_data = NULL;
3765 unsigned long flags;
3767 int cpu = event->cpu;
3770 /* Must be root to operate on a CPU event: */
3771 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3772 return ERR_PTR(-EACCES);
3775 * We could be clever and allow to attach a event to an
3776 * offline CPU and activate it when the CPU comes up, but
3779 if (!cpu_online(cpu))
3780 return ERR_PTR(-ENODEV);
3782 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3785 raw_spin_lock_irqsave(&ctx->lock, flags);
3787 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3793 ctxn = pmu->task_ctx_nr;
3797 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3798 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3799 if (!task_ctx_data) {
3806 ctx = perf_lock_task_context(task, ctxn, &flags);
3808 clone_ctx = unclone_ctx(ctx);
3811 if (task_ctx_data && !ctx->task_ctx_data) {
3812 ctx->task_ctx_data = task_ctx_data;
3813 task_ctx_data = NULL;
3815 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3820 ctx = alloc_perf_context(pmu, task);
3825 if (task_ctx_data) {
3826 ctx->task_ctx_data = task_ctx_data;
3827 task_ctx_data = NULL;
3831 mutex_lock(&task->perf_event_mutex);
3833 * If it has already passed perf_event_exit_task().
3834 * we must see PF_EXITING, it takes this mutex too.
3836 if (task->flags & PF_EXITING)
3838 else if (task->perf_event_ctxp[ctxn])
3843 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3845 mutex_unlock(&task->perf_event_mutex);
3847 if (unlikely(err)) {
3856 kfree(task_ctx_data);
3860 kfree(task_ctx_data);
3861 return ERR_PTR(err);
3864 static void perf_event_free_filter(struct perf_event *event);
3865 static void perf_event_free_bpf_prog(struct perf_event *event);
3867 static void free_event_rcu(struct rcu_head *head)
3869 struct perf_event *event;
3871 event = container_of(head, struct perf_event, rcu_head);
3873 put_pid_ns(event->ns);
3874 perf_event_free_filter(event);
3878 static void ring_buffer_attach(struct perf_event *event,
3879 struct ring_buffer *rb);
3881 static void detach_sb_event(struct perf_event *event)
3883 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
3885 raw_spin_lock(&pel->lock);
3886 list_del_rcu(&event->sb_list);
3887 raw_spin_unlock(&pel->lock);
3890 static bool is_sb_event(struct perf_event *event)
3892 struct perf_event_attr *attr = &event->attr;
3897 if (event->attach_state & PERF_ATTACH_TASK)
3900 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
3901 attr->comm || attr->comm_exec ||
3903 attr->context_switch)
3908 static void unaccount_pmu_sb_event(struct perf_event *event)
3910 if (is_sb_event(event))
3911 detach_sb_event(event);
3914 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3919 if (is_cgroup_event(event))
3920 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3923 #ifdef CONFIG_NO_HZ_FULL
3924 static DEFINE_SPINLOCK(nr_freq_lock);
3927 static void unaccount_freq_event_nohz(void)
3929 #ifdef CONFIG_NO_HZ_FULL
3930 spin_lock(&nr_freq_lock);
3931 if (atomic_dec_and_test(&nr_freq_events))
3932 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
3933 spin_unlock(&nr_freq_lock);
3937 static void unaccount_freq_event(void)
3939 if (tick_nohz_full_enabled())
3940 unaccount_freq_event_nohz();
3942 atomic_dec(&nr_freq_events);
3945 static void unaccount_event(struct perf_event *event)
3952 if (event->attach_state & PERF_ATTACH_TASK)
3954 if (event->attr.mmap || event->attr.mmap_data)
3955 atomic_dec(&nr_mmap_events);
3956 if (event->attr.comm)
3957 atomic_dec(&nr_comm_events);
3958 if (event->attr.task)
3959 atomic_dec(&nr_task_events);
3960 if (event->attr.freq)
3961 unaccount_freq_event();
3962 if (event->attr.context_switch) {
3964 atomic_dec(&nr_switch_events);
3966 if (is_cgroup_event(event))
3968 if (has_branch_stack(event))
3972 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3973 schedule_delayed_work(&perf_sched_work, HZ);
3976 unaccount_event_cpu(event, event->cpu);
3978 unaccount_pmu_sb_event(event);
3981 static void perf_sched_delayed(struct work_struct *work)
3983 mutex_lock(&perf_sched_mutex);
3984 if (atomic_dec_and_test(&perf_sched_count))
3985 static_branch_disable(&perf_sched_events);
3986 mutex_unlock(&perf_sched_mutex);
3990 * The following implement mutual exclusion of events on "exclusive" pmus
3991 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3992 * at a time, so we disallow creating events that might conflict, namely:
3994 * 1) cpu-wide events in the presence of per-task events,
3995 * 2) per-task events in the presence of cpu-wide events,
3996 * 3) two matching events on the same context.
3998 * The former two cases are handled in the allocation path (perf_event_alloc(),
3999 * _free_event()), the latter -- before the first perf_install_in_context().
4001 static int exclusive_event_init(struct perf_event *event)
4003 struct pmu *pmu = event->pmu;
4005 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4009 * Prevent co-existence of per-task and cpu-wide events on the
4010 * same exclusive pmu.
4012 * Negative pmu::exclusive_cnt means there are cpu-wide
4013 * events on this "exclusive" pmu, positive means there are
4016 * Since this is called in perf_event_alloc() path, event::ctx
4017 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4018 * to mean "per-task event", because unlike other attach states it
4019 * never gets cleared.
4021 if (event->attach_state & PERF_ATTACH_TASK) {
4022 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4025 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4032 static void exclusive_event_destroy(struct perf_event *event)
4034 struct pmu *pmu = event->pmu;
4036 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4039 /* see comment in exclusive_event_init() */
4040 if (event->attach_state & PERF_ATTACH_TASK)
4041 atomic_dec(&pmu->exclusive_cnt);
4043 atomic_inc(&pmu->exclusive_cnt);
4046 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4048 if ((e1->pmu == e2->pmu) &&
4049 (e1->cpu == e2->cpu ||
4056 /* Called under the same ctx::mutex as perf_install_in_context() */
4057 static bool exclusive_event_installable(struct perf_event *event,
4058 struct perf_event_context *ctx)
4060 struct perf_event *iter_event;
4061 struct pmu *pmu = event->pmu;
4063 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4066 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4067 if (exclusive_event_match(iter_event, event))
4074 static void perf_addr_filters_splice(struct perf_event *event,
4075 struct list_head *head);
4077 static void _free_event(struct perf_event *event)
4079 irq_work_sync(&event->pending);
4081 unaccount_event(event);
4085 * Can happen when we close an event with re-directed output.
4087 * Since we have a 0 refcount, perf_mmap_close() will skip
4088 * over us; possibly making our ring_buffer_put() the last.
4090 mutex_lock(&event->mmap_mutex);
4091 ring_buffer_attach(event, NULL);
4092 mutex_unlock(&event->mmap_mutex);
4095 if (is_cgroup_event(event))
4096 perf_detach_cgroup(event);
4098 if (!event->parent) {
4099 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4100 put_callchain_buffers();
4103 perf_event_free_bpf_prog(event);
4104 perf_addr_filters_splice(event, NULL);
4105 kfree(event->addr_filters_offs);
4108 event->destroy(event);
4111 put_ctx(event->ctx);
4113 if (event->hw.target)
4114 put_task_struct(event->hw.target);
4116 exclusive_event_destroy(event);
4117 module_put(event->pmu->module);
4119 call_rcu(&event->rcu_head, free_event_rcu);
4123 * Used to free events which have a known refcount of 1, such as in error paths
4124 * where the event isn't exposed yet and inherited events.
4126 static void free_event(struct perf_event *event)
4128 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4129 "unexpected event refcount: %ld; ptr=%p\n",
4130 atomic_long_read(&event->refcount), event)) {
4131 /* leak to avoid use-after-free */
4139 * Remove user event from the owner task.
4141 static void perf_remove_from_owner(struct perf_event *event)
4143 struct task_struct *owner;
4147 * Matches the smp_store_release() in perf_event_exit_task(). If we
4148 * observe !owner it means the list deletion is complete and we can
4149 * indeed free this event, otherwise we need to serialize on
4150 * owner->perf_event_mutex.
4152 owner = lockless_dereference(event->owner);
4155 * Since delayed_put_task_struct() also drops the last
4156 * task reference we can safely take a new reference
4157 * while holding the rcu_read_lock().
4159 get_task_struct(owner);
4165 * If we're here through perf_event_exit_task() we're already
4166 * holding ctx->mutex which would be an inversion wrt. the
4167 * normal lock order.
4169 * However we can safely take this lock because its the child
4172 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4175 * We have to re-check the event->owner field, if it is cleared
4176 * we raced with perf_event_exit_task(), acquiring the mutex
4177 * ensured they're done, and we can proceed with freeing the
4181 list_del_init(&event->owner_entry);
4182 smp_store_release(&event->owner, NULL);
4184 mutex_unlock(&owner->perf_event_mutex);
4185 put_task_struct(owner);
4189 static void put_event(struct perf_event *event)
4191 if (!atomic_long_dec_and_test(&event->refcount))
4198 * Kill an event dead; while event:refcount will preserve the event
4199 * object, it will not preserve its functionality. Once the last 'user'
4200 * gives up the object, we'll destroy the thing.
4202 int perf_event_release_kernel(struct perf_event *event)
4204 struct perf_event_context *ctx = event->ctx;
4205 struct perf_event *child, *tmp;
4208 * If we got here through err_file: fput(event_file); we will not have
4209 * attached to a context yet.
4212 WARN_ON_ONCE(event->attach_state &
4213 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4217 if (!is_kernel_event(event))
4218 perf_remove_from_owner(event);
4220 ctx = perf_event_ctx_lock(event);
4221 WARN_ON_ONCE(ctx->parent_ctx);
4222 perf_remove_from_context(event, DETACH_GROUP);
4224 raw_spin_lock_irq(&ctx->lock);
4226 * Mark this even as STATE_DEAD, there is no external reference to it
4229 * Anybody acquiring event->child_mutex after the below loop _must_
4230 * also see this, most importantly inherit_event() which will avoid
4231 * placing more children on the list.
4233 * Thus this guarantees that we will in fact observe and kill _ALL_
4236 event->state = PERF_EVENT_STATE_DEAD;
4237 raw_spin_unlock_irq(&ctx->lock);
4239 perf_event_ctx_unlock(event, ctx);
4242 mutex_lock(&event->child_mutex);
4243 list_for_each_entry(child, &event->child_list, child_list) {
4246 * Cannot change, child events are not migrated, see the
4247 * comment with perf_event_ctx_lock_nested().
4249 ctx = lockless_dereference(child->ctx);
4251 * Since child_mutex nests inside ctx::mutex, we must jump
4252 * through hoops. We start by grabbing a reference on the ctx.
4254 * Since the event cannot get freed while we hold the
4255 * child_mutex, the context must also exist and have a !0
4261 * Now that we have a ctx ref, we can drop child_mutex, and
4262 * acquire ctx::mutex without fear of it going away. Then we
4263 * can re-acquire child_mutex.
4265 mutex_unlock(&event->child_mutex);
4266 mutex_lock(&ctx->mutex);
4267 mutex_lock(&event->child_mutex);
4270 * Now that we hold ctx::mutex and child_mutex, revalidate our
4271 * state, if child is still the first entry, it didn't get freed
4272 * and we can continue doing so.
4274 tmp = list_first_entry_or_null(&event->child_list,
4275 struct perf_event, child_list);
4277 perf_remove_from_context(child, DETACH_GROUP);
4278 list_del(&child->child_list);
4281 * This matches the refcount bump in inherit_event();
4282 * this can't be the last reference.
4287 mutex_unlock(&event->child_mutex);
4288 mutex_unlock(&ctx->mutex);
4292 mutex_unlock(&event->child_mutex);
4295 put_event(event); /* Must be the 'last' reference */
4298 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4301 * Called when the last reference to the file is gone.
4303 static int perf_release(struct inode *inode, struct file *file)
4305 perf_event_release_kernel(file->private_data);
4309 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4311 struct perf_event *child;
4317 mutex_lock(&event->child_mutex);
4319 (void)perf_event_read(event, false);
4320 total += perf_event_count(event);
4322 *enabled += event->total_time_enabled +
4323 atomic64_read(&event->child_total_time_enabled);
4324 *running += event->total_time_running +
4325 atomic64_read(&event->child_total_time_running);
4327 list_for_each_entry(child, &event->child_list, child_list) {
4328 (void)perf_event_read(child, false);
4329 total += perf_event_count(child);
4330 *enabled += child->total_time_enabled;
4331 *running += child->total_time_running;
4333 mutex_unlock(&event->child_mutex);
4337 EXPORT_SYMBOL_GPL(perf_event_read_value);
4339 static int __perf_read_group_add(struct perf_event *leader,
4340 u64 read_format, u64 *values)
4342 struct perf_event_context *ctx = leader->ctx;
4343 struct perf_event *sub;
4344 unsigned long flags;
4345 int n = 1; /* skip @nr */
4348 ret = perf_event_read(leader, true);
4353 * Since we co-schedule groups, {enabled,running} times of siblings
4354 * will be identical to those of the leader, so we only publish one
4357 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4358 values[n++] += leader->total_time_enabled +
4359 atomic64_read(&leader->child_total_time_enabled);
4362 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4363 values[n++] += leader->total_time_running +
4364 atomic64_read(&leader->child_total_time_running);
4368 * Write {count,id} tuples for every sibling.
4370 values[n++] += perf_event_count(leader);
4371 if (read_format & PERF_FORMAT_ID)
4372 values[n++] = primary_event_id(leader);
4374 raw_spin_lock_irqsave(&ctx->lock, flags);
4376 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4377 values[n++] += perf_event_count(sub);
4378 if (read_format & PERF_FORMAT_ID)
4379 values[n++] = primary_event_id(sub);
4382 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4386 static int perf_read_group(struct perf_event *event,
4387 u64 read_format, char __user *buf)
4389 struct perf_event *leader = event->group_leader, *child;
4390 struct perf_event_context *ctx = leader->ctx;
4394 lockdep_assert_held(&ctx->mutex);
4396 values = kzalloc(event->read_size, GFP_KERNEL);
4400 values[0] = 1 + leader->nr_siblings;
4403 * By locking the child_mutex of the leader we effectively
4404 * lock the child list of all siblings.. XXX explain how.
4406 mutex_lock(&leader->child_mutex);
4408 ret = __perf_read_group_add(leader, read_format, values);
4412 list_for_each_entry(child, &leader->child_list, child_list) {
4413 ret = __perf_read_group_add(child, read_format, values);
4418 mutex_unlock(&leader->child_mutex);
4420 ret = event->read_size;
4421 if (copy_to_user(buf, values, event->read_size))
4426 mutex_unlock(&leader->child_mutex);
4432 static int perf_read_one(struct perf_event *event,
4433 u64 read_format, char __user *buf)
4435 u64 enabled, running;
4439 values[n++] = perf_event_read_value(event, &enabled, &running);
4440 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4441 values[n++] = enabled;
4442 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4443 values[n++] = running;
4444 if (read_format & PERF_FORMAT_ID)
4445 values[n++] = primary_event_id(event);
4447 if (copy_to_user(buf, values, n * sizeof(u64)))
4450 return n * sizeof(u64);
4453 static bool is_event_hup(struct perf_event *event)
4457 if (event->state > PERF_EVENT_STATE_EXIT)
4460 mutex_lock(&event->child_mutex);
4461 no_children = list_empty(&event->child_list);
4462 mutex_unlock(&event->child_mutex);
4467 * Read the performance event - simple non blocking version for now
4470 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4472 u64 read_format = event->attr.read_format;
4476 * Return end-of-file for a read on a event that is in
4477 * error state (i.e. because it was pinned but it couldn't be
4478 * scheduled on to the CPU at some point).
4480 if (event->state == PERF_EVENT_STATE_ERROR)
4483 if (count < event->read_size)
4486 WARN_ON_ONCE(event->ctx->parent_ctx);
4487 if (read_format & PERF_FORMAT_GROUP)
4488 ret = perf_read_group(event, read_format, buf);
4490 ret = perf_read_one(event, read_format, buf);
4496 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4498 struct perf_event *event = file->private_data;
4499 struct perf_event_context *ctx;
4502 ctx = perf_event_ctx_lock(event);
4503 ret = __perf_read(event, buf, count);
4504 perf_event_ctx_unlock(event, ctx);
4509 static unsigned int perf_poll(struct file *file, poll_table *wait)
4511 struct perf_event *event = file->private_data;
4512 struct ring_buffer *rb;
4513 unsigned int events = POLLHUP;
4515 poll_wait(file, &event->waitq, wait);
4517 if (is_event_hup(event))
4521 * Pin the event->rb by taking event->mmap_mutex; otherwise
4522 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4524 mutex_lock(&event->mmap_mutex);
4527 events = atomic_xchg(&rb->poll, 0);
4528 mutex_unlock(&event->mmap_mutex);
4532 static void _perf_event_reset(struct perf_event *event)
4534 (void)perf_event_read(event, false);
4535 local64_set(&event->count, 0);
4536 perf_event_update_userpage(event);
4540 * Holding the top-level event's child_mutex means that any
4541 * descendant process that has inherited this event will block
4542 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4543 * task existence requirements of perf_event_enable/disable.
4545 static void perf_event_for_each_child(struct perf_event *event,
4546 void (*func)(struct perf_event *))
4548 struct perf_event *child;
4550 WARN_ON_ONCE(event->ctx->parent_ctx);
4552 mutex_lock(&event->child_mutex);
4554 list_for_each_entry(child, &event->child_list, child_list)
4556 mutex_unlock(&event->child_mutex);
4559 static void perf_event_for_each(struct perf_event *event,
4560 void (*func)(struct perf_event *))
4562 struct perf_event_context *ctx = event->ctx;
4563 struct perf_event *sibling;
4565 lockdep_assert_held(&ctx->mutex);
4567 event = event->group_leader;
4569 perf_event_for_each_child(event, func);
4570 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4571 perf_event_for_each_child(sibling, func);
4574 static void __perf_event_period(struct perf_event *event,
4575 struct perf_cpu_context *cpuctx,
4576 struct perf_event_context *ctx,
4579 u64 value = *((u64 *)info);
4582 if (event->attr.freq) {
4583 event->attr.sample_freq = value;
4585 event->attr.sample_period = value;
4586 event->hw.sample_period = value;
4589 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4591 perf_pmu_disable(ctx->pmu);
4593 * We could be throttled; unthrottle now to avoid the tick
4594 * trying to unthrottle while we already re-started the event.
4596 if (event->hw.interrupts == MAX_INTERRUPTS) {
4597 event->hw.interrupts = 0;
4598 perf_log_throttle(event, 1);
4600 event->pmu->stop(event, PERF_EF_UPDATE);
4603 local64_set(&event->hw.period_left, 0);
4606 event->pmu->start(event, PERF_EF_RELOAD);
4607 perf_pmu_enable(ctx->pmu);
4611 static int perf_event_check_period(struct perf_event *event, u64 value)
4613 return event->pmu->check_period(event, value);
4616 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4620 if (!is_sampling_event(event))
4623 if (copy_from_user(&value, arg, sizeof(value)))
4629 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4632 if (perf_event_check_period(event, value))
4635 if (!event->attr.freq && (value & (1ULL << 63)))
4638 event_function_call(event, __perf_event_period, &value);
4643 static const struct file_operations perf_fops;
4645 static inline int perf_fget_light(int fd, struct fd *p)
4647 struct fd f = fdget(fd);
4651 if (f.file->f_op != &perf_fops) {
4659 static int perf_event_set_output(struct perf_event *event,
4660 struct perf_event *output_event);
4661 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4662 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4664 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4666 void (*func)(struct perf_event *);
4670 case PERF_EVENT_IOC_ENABLE:
4671 func = _perf_event_enable;
4673 case PERF_EVENT_IOC_DISABLE:
4674 func = _perf_event_disable;
4676 case PERF_EVENT_IOC_RESET:
4677 func = _perf_event_reset;
4680 case PERF_EVENT_IOC_REFRESH:
4681 return _perf_event_refresh(event, arg);
4683 case PERF_EVENT_IOC_PERIOD:
4684 return perf_event_period(event, (u64 __user *)arg);
4686 case PERF_EVENT_IOC_ID:
4688 u64 id = primary_event_id(event);
4690 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4695 case PERF_EVENT_IOC_SET_OUTPUT:
4699 struct perf_event *output_event;
4701 ret = perf_fget_light(arg, &output);
4704 output_event = output.file->private_data;
4705 ret = perf_event_set_output(event, output_event);
4708 ret = perf_event_set_output(event, NULL);
4713 case PERF_EVENT_IOC_SET_FILTER:
4714 return perf_event_set_filter(event, (void __user *)arg);
4716 case PERF_EVENT_IOC_SET_BPF:
4717 return perf_event_set_bpf_prog(event, arg);
4719 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
4720 struct ring_buffer *rb;
4723 rb = rcu_dereference(event->rb);
4724 if (!rb || !rb->nr_pages) {
4728 rb_toggle_paused(rb, !!arg);
4736 if (flags & PERF_IOC_FLAG_GROUP)
4737 perf_event_for_each(event, func);
4739 perf_event_for_each_child(event, func);
4744 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4746 struct perf_event *event = file->private_data;
4747 struct perf_event_context *ctx;
4750 ctx = perf_event_ctx_lock(event);
4751 ret = _perf_ioctl(event, cmd, arg);
4752 perf_event_ctx_unlock(event, ctx);
4757 #ifdef CONFIG_COMPAT
4758 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4761 switch (_IOC_NR(cmd)) {
4762 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4763 case _IOC_NR(PERF_EVENT_IOC_ID):
4764 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4765 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4766 cmd &= ~IOCSIZE_MASK;
4767 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4771 return perf_ioctl(file, cmd, arg);
4774 # define perf_compat_ioctl NULL
4777 int perf_event_task_enable(void)
4779 struct perf_event_context *ctx;
4780 struct perf_event *event;
4782 mutex_lock(¤t->perf_event_mutex);
4783 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4784 ctx = perf_event_ctx_lock(event);
4785 perf_event_for_each_child(event, _perf_event_enable);
4786 perf_event_ctx_unlock(event, ctx);
4788 mutex_unlock(¤t->perf_event_mutex);
4793 int perf_event_task_disable(void)
4795 struct perf_event_context *ctx;
4796 struct perf_event *event;
4798 mutex_lock(¤t->perf_event_mutex);
4799 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4800 ctx = perf_event_ctx_lock(event);
4801 perf_event_for_each_child(event, _perf_event_disable);
4802 perf_event_ctx_unlock(event, ctx);
4804 mutex_unlock(¤t->perf_event_mutex);
4809 static int perf_event_index(struct perf_event *event)
4811 if (event->hw.state & PERF_HES_STOPPED)
4814 if (event->state != PERF_EVENT_STATE_ACTIVE)
4817 return event->pmu->event_idx(event);
4820 static void calc_timer_values(struct perf_event *event,
4827 *now = perf_clock();
4828 ctx_time = event->shadow_ctx_time + *now;
4829 *enabled = ctx_time - event->tstamp_enabled;
4830 *running = ctx_time - event->tstamp_running;
4833 static void perf_event_init_userpage(struct perf_event *event)
4835 struct perf_event_mmap_page *userpg;
4836 struct ring_buffer *rb;
4839 rb = rcu_dereference(event->rb);
4843 userpg = rb->user_page;
4845 /* Allow new userspace to detect that bit 0 is deprecated */
4846 userpg->cap_bit0_is_deprecated = 1;
4847 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4848 userpg->data_offset = PAGE_SIZE;
4849 userpg->data_size = perf_data_size(rb);
4855 void __weak arch_perf_update_userpage(
4856 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4861 * Callers need to ensure there can be no nesting of this function, otherwise
4862 * the seqlock logic goes bad. We can not serialize this because the arch
4863 * code calls this from NMI context.
4865 void perf_event_update_userpage(struct perf_event *event)
4867 struct perf_event_mmap_page *userpg;
4868 struct ring_buffer *rb;
4869 u64 enabled, running, now;
4872 rb = rcu_dereference(event->rb);
4877 * compute total_time_enabled, total_time_running
4878 * based on snapshot values taken when the event
4879 * was last scheduled in.
4881 * we cannot simply called update_context_time()
4882 * because of locking issue as we can be called in
4885 calc_timer_values(event, &now, &enabled, &running);
4887 userpg = rb->user_page;
4889 * Disable preemption so as to not let the corresponding user-space
4890 * spin too long if we get preempted.
4895 userpg->index = perf_event_index(event);
4896 userpg->offset = perf_event_count(event);
4898 userpg->offset -= local64_read(&event->hw.prev_count);
4900 userpg->time_enabled = enabled +
4901 atomic64_read(&event->child_total_time_enabled);
4903 userpg->time_running = running +
4904 atomic64_read(&event->child_total_time_running);
4906 arch_perf_update_userpage(event, userpg, now);
4915 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4917 struct perf_event *event = vma->vm_file->private_data;
4918 struct ring_buffer *rb;
4919 int ret = VM_FAULT_SIGBUS;
4921 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4922 if (vmf->pgoff == 0)
4928 rb = rcu_dereference(event->rb);
4932 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4935 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4939 get_page(vmf->page);
4940 vmf->page->mapping = vma->vm_file->f_mapping;
4941 vmf->page->index = vmf->pgoff;
4950 static void ring_buffer_attach(struct perf_event *event,
4951 struct ring_buffer *rb)
4953 struct ring_buffer *old_rb = NULL;
4954 unsigned long flags;
4958 * Should be impossible, we set this when removing
4959 * event->rb_entry and wait/clear when adding event->rb_entry.
4961 WARN_ON_ONCE(event->rcu_pending);
4964 spin_lock_irqsave(&old_rb->event_lock, flags);
4965 list_del_rcu(&event->rb_entry);
4966 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4968 event->rcu_batches = get_state_synchronize_rcu();
4969 event->rcu_pending = 1;
4973 if (event->rcu_pending) {
4974 cond_synchronize_rcu(event->rcu_batches);
4975 event->rcu_pending = 0;
4978 spin_lock_irqsave(&rb->event_lock, flags);
4979 list_add_rcu(&event->rb_entry, &rb->event_list);
4980 spin_unlock_irqrestore(&rb->event_lock, flags);
4984 * Avoid racing with perf_mmap_close(AUX): stop the event
4985 * before swizzling the event::rb pointer; if it's getting
4986 * unmapped, its aux_mmap_count will be 0 and it won't
4987 * restart. See the comment in __perf_pmu_output_stop().
4989 * Data will inevitably be lost when set_output is done in
4990 * mid-air, but then again, whoever does it like this is
4991 * not in for the data anyway.
4994 perf_event_stop(event, 0);
4996 rcu_assign_pointer(event->rb, rb);
4999 ring_buffer_put(old_rb);
5001 * Since we detached before setting the new rb, so that we
5002 * could attach the new rb, we could have missed a wakeup.
5005 wake_up_all(&event->waitq);
5009 static void ring_buffer_wakeup(struct perf_event *event)
5011 struct ring_buffer *rb;
5014 rb = rcu_dereference(event->rb);
5016 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5017 wake_up_all(&event->waitq);
5022 struct ring_buffer *ring_buffer_get(struct perf_event *event)
5024 struct ring_buffer *rb;
5027 rb = rcu_dereference(event->rb);
5029 if (!atomic_inc_not_zero(&rb->refcount))
5037 void ring_buffer_put(struct ring_buffer *rb)
5039 if (!atomic_dec_and_test(&rb->refcount))
5042 WARN_ON_ONCE(!list_empty(&rb->event_list));
5044 call_rcu(&rb->rcu_head, rb_free_rcu);
5047 static void perf_mmap_open(struct vm_area_struct *vma)
5049 struct perf_event *event = vma->vm_file->private_data;
5051 atomic_inc(&event->mmap_count);
5052 atomic_inc(&event->rb->mmap_count);
5055 atomic_inc(&event->rb->aux_mmap_count);
5057 if (event->pmu->event_mapped)
5058 event->pmu->event_mapped(event);
5061 static void perf_pmu_output_stop(struct perf_event *event);
5064 * A buffer can be mmap()ed multiple times; either directly through the same
5065 * event, or through other events by use of perf_event_set_output().
5067 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5068 * the buffer here, where we still have a VM context. This means we need
5069 * to detach all events redirecting to us.
5071 static void perf_mmap_close(struct vm_area_struct *vma)
5073 struct perf_event *event = vma->vm_file->private_data;
5074 struct ring_buffer *rb = ring_buffer_get(event);
5075 struct user_struct *mmap_user = rb->mmap_user;
5076 int mmap_locked = rb->mmap_locked;
5077 unsigned long size = perf_data_size(rb);
5078 bool detach_rest = false;
5080 if (event->pmu->event_unmapped)
5081 event->pmu->event_unmapped(event);
5084 * rb->aux_mmap_count will always drop before rb->mmap_count and
5085 * event->mmap_count, so it is ok to use event->mmap_mutex to
5086 * serialize with perf_mmap here.
5088 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5089 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5091 * Stop all AUX events that are writing to this buffer,
5092 * so that we can free its AUX pages and corresponding PMU
5093 * data. Note that after rb::aux_mmap_count dropped to zero,
5094 * they won't start any more (see perf_aux_output_begin()).
5096 perf_pmu_output_stop(event);
5098 /* now it's safe to free the pages */
5099 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
5100 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
5102 /* this has to be the last one */
5104 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
5106 mutex_unlock(&event->mmap_mutex);
5109 if (atomic_dec_and_test(&rb->mmap_count))
5112 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5115 ring_buffer_attach(event, NULL);
5116 mutex_unlock(&event->mmap_mutex);
5118 /* If there's still other mmap()s of this buffer, we're done. */
5123 * No other mmap()s, detach from all other events that might redirect
5124 * into the now unreachable buffer. Somewhat complicated by the
5125 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5129 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5130 if (!atomic_long_inc_not_zero(&event->refcount)) {
5132 * This event is en-route to free_event() which will
5133 * detach it and remove it from the list.
5139 mutex_lock(&event->mmap_mutex);
5141 * Check we didn't race with perf_event_set_output() which can
5142 * swizzle the rb from under us while we were waiting to
5143 * acquire mmap_mutex.
5145 * If we find a different rb; ignore this event, a next
5146 * iteration will no longer find it on the list. We have to
5147 * still restart the iteration to make sure we're not now
5148 * iterating the wrong list.
5150 if (event->rb == rb)
5151 ring_buffer_attach(event, NULL);
5153 mutex_unlock(&event->mmap_mutex);
5157 * Restart the iteration; either we're on the wrong list or
5158 * destroyed its integrity by doing a deletion.
5165 * It could be there's still a few 0-ref events on the list; they'll
5166 * get cleaned up by free_event() -- they'll also still have their
5167 * ref on the rb and will free it whenever they are done with it.
5169 * Aside from that, this buffer is 'fully' detached and unmapped,
5170 * undo the VM accounting.
5173 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
5174 vma->vm_mm->pinned_vm -= mmap_locked;
5175 free_uid(mmap_user);
5178 ring_buffer_put(rb); /* could be last */
5181 static const struct vm_operations_struct perf_mmap_vmops = {
5182 .open = perf_mmap_open,
5183 .close = perf_mmap_close, /* non mergable */
5184 .fault = perf_mmap_fault,
5185 .page_mkwrite = perf_mmap_fault,
5188 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5190 struct perf_event *event = file->private_data;
5191 unsigned long user_locked, user_lock_limit;
5192 struct user_struct *user = current_user();
5193 unsigned long locked, lock_limit;
5194 struct ring_buffer *rb = NULL;
5195 unsigned long vma_size;
5196 unsigned long nr_pages;
5197 long user_extra = 0, extra = 0;
5198 int ret = 0, flags = 0;
5201 * Don't allow mmap() of inherited per-task counters. This would
5202 * create a performance issue due to all children writing to the
5205 if (event->cpu == -1 && event->attr.inherit)
5208 if (!(vma->vm_flags & VM_SHARED))
5211 vma_size = vma->vm_end - vma->vm_start;
5213 if (vma->vm_pgoff == 0) {
5214 nr_pages = (vma_size / PAGE_SIZE) - 1;
5217 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5218 * mapped, all subsequent mappings should have the same size
5219 * and offset. Must be above the normal perf buffer.
5221 u64 aux_offset, aux_size;
5226 nr_pages = vma_size / PAGE_SIZE;
5228 mutex_lock(&event->mmap_mutex);
5235 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
5236 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
5238 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5241 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5244 /* already mapped with a different offset */
5245 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5248 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5251 /* already mapped with a different size */
5252 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5255 if (!is_power_of_2(nr_pages))
5258 if (!atomic_inc_not_zero(&rb->mmap_count))
5261 if (rb_has_aux(rb)) {
5262 atomic_inc(&rb->aux_mmap_count);
5267 atomic_set(&rb->aux_mmap_count, 1);
5268 user_extra = nr_pages;
5274 * If we have rb pages ensure they're a power-of-two number, so we
5275 * can do bitmasks instead of modulo.
5277 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5280 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5283 WARN_ON_ONCE(event->ctx->parent_ctx);
5285 mutex_lock(&event->mmap_mutex);
5287 if (event->rb->nr_pages != nr_pages) {
5292 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5294 * Raced against perf_mmap_close(); remove the
5295 * event and try again.
5297 ring_buffer_attach(event, NULL);
5298 mutex_unlock(&event->mmap_mutex);
5305 user_extra = nr_pages + 1;
5308 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5311 * Increase the limit linearly with more CPUs:
5313 user_lock_limit *= num_online_cpus();
5315 user_locked = atomic_long_read(&user->locked_vm);
5318 * sysctl_perf_event_mlock may have changed, so that
5319 * user->locked_vm > user_lock_limit
5321 if (user_locked > user_lock_limit)
5322 user_locked = user_lock_limit;
5323 user_locked += user_extra;
5325 if (user_locked > user_lock_limit)
5326 extra = user_locked - user_lock_limit;
5328 lock_limit = rlimit(RLIMIT_MEMLOCK);
5329 lock_limit >>= PAGE_SHIFT;
5330 locked = vma->vm_mm->pinned_vm + extra;
5332 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5333 !capable(CAP_IPC_LOCK)) {
5338 WARN_ON(!rb && event->rb);
5340 if (vma->vm_flags & VM_WRITE)
5341 flags |= RING_BUFFER_WRITABLE;
5344 rb = rb_alloc(nr_pages,
5345 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5353 atomic_set(&rb->mmap_count, 1);
5354 rb->mmap_user = get_current_user();
5355 rb->mmap_locked = extra;
5357 ring_buffer_attach(event, rb);
5359 perf_event_init_userpage(event);
5360 perf_event_update_userpage(event);
5362 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5363 event->attr.aux_watermark, flags);
5365 rb->aux_mmap_locked = extra;
5370 atomic_long_add(user_extra, &user->locked_vm);
5371 vma->vm_mm->pinned_vm += extra;
5373 atomic_inc(&event->mmap_count);
5375 atomic_dec(&rb->mmap_count);
5378 mutex_unlock(&event->mmap_mutex);
5381 * Since pinned accounting is per vm we cannot allow fork() to copy our
5384 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5385 vma->vm_ops = &perf_mmap_vmops;
5387 if (event->pmu->event_mapped)
5388 event->pmu->event_mapped(event);
5393 static int perf_fasync(int fd, struct file *filp, int on)
5395 struct inode *inode = file_inode(filp);
5396 struct perf_event *event = filp->private_data;
5400 retval = fasync_helper(fd, filp, on, &event->fasync);
5401 inode_unlock(inode);
5409 static const struct file_operations perf_fops = {
5410 .llseek = no_llseek,
5411 .release = perf_release,
5414 .unlocked_ioctl = perf_ioctl,
5415 .compat_ioctl = perf_compat_ioctl,
5417 .fasync = perf_fasync,
5423 * If there's data, ensure we set the poll() state and publish everything
5424 * to user-space before waking everybody up.
5427 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5429 /* only the parent has fasync state */
5431 event = event->parent;
5432 return &event->fasync;
5435 void perf_event_wakeup(struct perf_event *event)
5437 ring_buffer_wakeup(event);
5439 if (event->pending_kill) {
5440 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5441 event->pending_kill = 0;
5445 static void perf_pending_event(struct irq_work *entry)
5447 struct perf_event *event = container_of(entry,
5448 struct perf_event, pending);
5451 rctx = perf_swevent_get_recursion_context();
5453 * If we 'fail' here, that's OK, it means recursion is already disabled
5454 * and we won't recurse 'further'.
5457 if (event->pending_disable) {
5458 event->pending_disable = 0;
5459 perf_event_disable_local(event);
5462 if (event->pending_wakeup) {
5463 event->pending_wakeup = 0;
5464 perf_event_wakeup(event);
5468 perf_swevent_put_recursion_context(rctx);
5472 * We assume there is only KVM supporting the callbacks.
5473 * Later on, we might change it to a list if there is
5474 * another virtualization implementation supporting the callbacks.
5476 struct perf_guest_info_callbacks *perf_guest_cbs;
5478 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5480 perf_guest_cbs = cbs;
5483 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5485 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5487 perf_guest_cbs = NULL;
5490 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5493 perf_output_sample_regs(struct perf_output_handle *handle,
5494 struct pt_regs *regs, u64 mask)
5497 DECLARE_BITMAP(_mask, 64);
5499 bitmap_from_u64(_mask, mask);
5500 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
5503 val = perf_reg_value(regs, bit);
5504 perf_output_put(handle, val);
5508 static void perf_sample_regs_user(struct perf_regs *regs_user,
5509 struct pt_regs *regs,
5510 struct pt_regs *regs_user_copy)
5512 if (user_mode(regs)) {
5513 regs_user->abi = perf_reg_abi(current);
5514 regs_user->regs = regs;
5515 } else if (!(current->flags & PF_KTHREAD)) {
5516 perf_get_regs_user(regs_user, regs, regs_user_copy);
5518 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5519 regs_user->regs = NULL;
5523 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5524 struct pt_regs *regs)
5526 regs_intr->regs = regs;
5527 regs_intr->abi = perf_reg_abi(current);
5532 * Get remaining task size from user stack pointer.
5534 * It'd be better to take stack vma map and limit this more
5535 * precisly, but there's no way to get it safely under interrupt,
5536 * so using TASK_SIZE as limit.
5538 static u64 perf_ustack_task_size(struct pt_regs *regs)
5540 unsigned long addr = perf_user_stack_pointer(regs);
5542 if (!addr || addr >= TASK_SIZE)
5545 return TASK_SIZE - addr;
5549 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5550 struct pt_regs *regs)
5554 /* No regs, no stack pointer, no dump. */
5559 * Check if we fit in with the requested stack size into the:
5561 * If we don't, we limit the size to the TASK_SIZE.
5563 * - remaining sample size
5564 * If we don't, we customize the stack size to
5565 * fit in to the remaining sample size.
5568 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5569 stack_size = min(stack_size, (u16) task_size);
5571 /* Current header size plus static size and dynamic size. */
5572 header_size += 2 * sizeof(u64);
5574 /* Do we fit in with the current stack dump size? */
5575 if ((u16) (header_size + stack_size) < header_size) {
5577 * If we overflow the maximum size for the sample,
5578 * we customize the stack dump size to fit in.
5580 stack_size = USHRT_MAX - header_size - sizeof(u64);
5581 stack_size = round_up(stack_size, sizeof(u64));
5588 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5589 struct pt_regs *regs)
5591 /* Case of a kernel thread, nothing to dump */
5594 perf_output_put(handle, size);
5604 * - the size requested by user or the best one we can fit
5605 * in to the sample max size
5607 * - user stack dump data
5609 * - the actual dumped size
5613 perf_output_put(handle, dump_size);
5616 sp = perf_user_stack_pointer(regs);
5619 rem = __output_copy_user(handle, (void *) sp, dump_size);
5621 dyn_size = dump_size - rem;
5623 perf_output_skip(handle, rem);
5626 perf_output_put(handle, dyn_size);
5630 static void __perf_event_header__init_id(struct perf_event_header *header,
5631 struct perf_sample_data *data,
5632 struct perf_event *event)
5634 u64 sample_type = event->attr.sample_type;
5636 data->type = sample_type;
5637 header->size += event->id_header_size;
5639 if (sample_type & PERF_SAMPLE_TID) {
5640 /* namespace issues */
5641 data->tid_entry.pid = perf_event_pid(event, current);
5642 data->tid_entry.tid = perf_event_tid(event, current);
5645 if (sample_type & PERF_SAMPLE_TIME)
5646 data->time = perf_event_clock(event);
5648 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5649 data->id = primary_event_id(event);
5651 if (sample_type & PERF_SAMPLE_STREAM_ID)
5652 data->stream_id = event->id;
5654 if (sample_type & PERF_SAMPLE_CPU) {
5655 data->cpu_entry.cpu = raw_smp_processor_id();
5656 data->cpu_entry.reserved = 0;
5660 void perf_event_header__init_id(struct perf_event_header *header,
5661 struct perf_sample_data *data,
5662 struct perf_event *event)
5664 if (event->attr.sample_id_all)
5665 __perf_event_header__init_id(header, data, event);
5668 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5669 struct perf_sample_data *data)
5671 u64 sample_type = data->type;
5673 if (sample_type & PERF_SAMPLE_TID)
5674 perf_output_put(handle, data->tid_entry);
5676 if (sample_type & PERF_SAMPLE_TIME)
5677 perf_output_put(handle, data->time);
5679 if (sample_type & PERF_SAMPLE_ID)
5680 perf_output_put(handle, data->id);
5682 if (sample_type & PERF_SAMPLE_STREAM_ID)
5683 perf_output_put(handle, data->stream_id);
5685 if (sample_type & PERF_SAMPLE_CPU)
5686 perf_output_put(handle, data->cpu_entry);
5688 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5689 perf_output_put(handle, data->id);
5692 void perf_event__output_id_sample(struct perf_event *event,
5693 struct perf_output_handle *handle,
5694 struct perf_sample_data *sample)
5696 if (event->attr.sample_id_all)
5697 __perf_event__output_id_sample(handle, sample);
5700 static void perf_output_read_one(struct perf_output_handle *handle,
5701 struct perf_event *event,
5702 u64 enabled, u64 running)
5704 u64 read_format = event->attr.read_format;
5708 values[n++] = perf_event_count(event);
5709 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5710 values[n++] = enabled +
5711 atomic64_read(&event->child_total_time_enabled);
5713 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5714 values[n++] = running +
5715 atomic64_read(&event->child_total_time_running);
5717 if (read_format & PERF_FORMAT_ID)
5718 values[n++] = primary_event_id(event);
5720 __output_copy(handle, values, n * sizeof(u64));
5723 static void perf_output_read_group(struct perf_output_handle *handle,
5724 struct perf_event *event,
5725 u64 enabled, u64 running)
5727 struct perf_event *leader = event->group_leader, *sub;
5728 u64 read_format = event->attr.read_format;
5732 values[n++] = 1 + leader->nr_siblings;
5734 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5735 values[n++] = enabled;
5737 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5738 values[n++] = running;
5740 if ((leader != event) &&
5741 (leader->state == PERF_EVENT_STATE_ACTIVE))
5742 leader->pmu->read(leader);
5744 values[n++] = perf_event_count(leader);
5745 if (read_format & PERF_FORMAT_ID)
5746 values[n++] = primary_event_id(leader);
5748 __output_copy(handle, values, n * sizeof(u64));
5750 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5753 if ((sub != event) &&
5754 (sub->state == PERF_EVENT_STATE_ACTIVE))
5755 sub->pmu->read(sub);
5757 values[n++] = perf_event_count(sub);
5758 if (read_format & PERF_FORMAT_ID)
5759 values[n++] = primary_event_id(sub);
5761 __output_copy(handle, values, n * sizeof(u64));
5765 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5766 PERF_FORMAT_TOTAL_TIME_RUNNING)
5769 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5771 * The problem is that its both hard and excessively expensive to iterate the
5772 * child list, not to mention that its impossible to IPI the children running
5773 * on another CPU, from interrupt/NMI context.
5775 static void perf_output_read(struct perf_output_handle *handle,
5776 struct perf_event *event)
5778 u64 enabled = 0, running = 0, now;
5779 u64 read_format = event->attr.read_format;
5782 * compute total_time_enabled, total_time_running
5783 * based on snapshot values taken when the event
5784 * was last scheduled in.
5786 * we cannot simply called update_context_time()
5787 * because of locking issue as we are called in
5790 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5791 calc_timer_values(event, &now, &enabled, &running);
5793 if (event->attr.read_format & PERF_FORMAT_GROUP)
5794 perf_output_read_group(handle, event, enabled, running);
5796 perf_output_read_one(handle, event, enabled, running);
5799 void perf_output_sample(struct perf_output_handle *handle,
5800 struct perf_event_header *header,
5801 struct perf_sample_data *data,
5802 struct perf_event *event)
5804 u64 sample_type = data->type;
5806 perf_output_put(handle, *header);
5808 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5809 perf_output_put(handle, data->id);
5811 if (sample_type & PERF_SAMPLE_IP)
5812 perf_output_put(handle, data->ip);
5814 if (sample_type & PERF_SAMPLE_TID)
5815 perf_output_put(handle, data->tid_entry);
5817 if (sample_type & PERF_SAMPLE_TIME)
5818 perf_output_put(handle, data->time);
5820 if (sample_type & PERF_SAMPLE_ADDR)
5821 perf_output_put(handle, data->addr);
5823 if (sample_type & PERF_SAMPLE_ID)
5824 perf_output_put(handle, data->id);
5826 if (sample_type & PERF_SAMPLE_STREAM_ID)
5827 perf_output_put(handle, data->stream_id);
5829 if (sample_type & PERF_SAMPLE_CPU)
5830 perf_output_put(handle, data->cpu_entry);
5832 if (sample_type & PERF_SAMPLE_PERIOD)
5833 perf_output_put(handle, data->period);
5835 if (sample_type & PERF_SAMPLE_READ)
5836 perf_output_read(handle, event);
5838 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5839 if (data->callchain) {
5842 if (data->callchain)
5843 size += data->callchain->nr;
5845 size *= sizeof(u64);
5847 __output_copy(handle, data->callchain, size);
5850 perf_output_put(handle, nr);
5854 if (sample_type & PERF_SAMPLE_RAW) {
5855 struct perf_raw_record *raw = data->raw;
5858 struct perf_raw_frag *frag = &raw->frag;
5860 perf_output_put(handle, raw->size);
5863 __output_custom(handle, frag->copy,
5864 frag->data, frag->size);
5866 __output_copy(handle, frag->data,
5869 if (perf_raw_frag_last(frag))
5874 __output_skip(handle, NULL, frag->pad);
5880 .size = sizeof(u32),
5883 perf_output_put(handle, raw);
5887 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5888 if (data->br_stack) {
5891 size = data->br_stack->nr
5892 * sizeof(struct perf_branch_entry);
5894 perf_output_put(handle, data->br_stack->nr);
5895 perf_output_copy(handle, data->br_stack->entries, size);
5898 * we always store at least the value of nr
5901 perf_output_put(handle, nr);
5905 if (sample_type & PERF_SAMPLE_REGS_USER) {
5906 u64 abi = data->regs_user.abi;
5909 * If there are no regs to dump, notice it through
5910 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5912 perf_output_put(handle, abi);
5915 u64 mask = event->attr.sample_regs_user;
5916 perf_output_sample_regs(handle,
5917 data->regs_user.regs,
5922 if (sample_type & PERF_SAMPLE_STACK_USER) {
5923 perf_output_sample_ustack(handle,
5924 data->stack_user_size,
5925 data->regs_user.regs);
5928 if (sample_type & PERF_SAMPLE_WEIGHT)
5929 perf_output_put(handle, data->weight);
5931 if (sample_type & PERF_SAMPLE_DATA_SRC)
5932 perf_output_put(handle, data->data_src.val);
5934 if (sample_type & PERF_SAMPLE_TRANSACTION)
5935 perf_output_put(handle, data->txn);
5937 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5938 u64 abi = data->regs_intr.abi;
5940 * If there are no regs to dump, notice it through
5941 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5943 perf_output_put(handle, abi);
5946 u64 mask = event->attr.sample_regs_intr;
5948 perf_output_sample_regs(handle,
5949 data->regs_intr.regs,
5954 if (!event->attr.watermark) {
5955 int wakeup_events = event->attr.wakeup_events;
5957 if (wakeup_events) {
5958 struct ring_buffer *rb = handle->rb;
5959 int events = local_inc_return(&rb->events);
5961 if (events >= wakeup_events) {
5962 local_sub(wakeup_events, &rb->events);
5963 local_inc(&rb->wakeup);
5969 void perf_prepare_sample(struct perf_event_header *header,
5970 struct perf_sample_data *data,
5971 struct perf_event *event,
5972 struct pt_regs *regs)
5974 u64 sample_type = event->attr.sample_type;
5976 header->type = PERF_RECORD_SAMPLE;
5977 header->size = sizeof(*header) + event->header_size;
5980 header->misc |= perf_misc_flags(regs);
5982 __perf_event_header__init_id(header, data, event);
5984 if (sample_type & PERF_SAMPLE_IP)
5985 data->ip = perf_instruction_pointer(regs);
5987 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5990 data->callchain = perf_callchain(event, regs);
5992 if (data->callchain)
5993 size += data->callchain->nr;
5995 header->size += size * sizeof(u64);
5998 if (sample_type & PERF_SAMPLE_RAW) {
5999 struct perf_raw_record *raw = data->raw;
6003 struct perf_raw_frag *frag = &raw->frag;
6008 if (perf_raw_frag_last(frag))
6013 size = round_up(sum + sizeof(u32), sizeof(u64));
6014 raw->size = size - sizeof(u32);
6015 frag->pad = raw->size - sum;
6020 header->size += size;
6023 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6024 int size = sizeof(u64); /* nr */
6025 if (data->br_stack) {
6026 size += data->br_stack->nr
6027 * sizeof(struct perf_branch_entry);
6029 header->size += size;
6032 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
6033 perf_sample_regs_user(&data->regs_user, regs,
6034 &data->regs_user_copy);
6036 if (sample_type & PERF_SAMPLE_REGS_USER) {
6037 /* regs dump ABI info */
6038 int size = sizeof(u64);
6040 if (data->regs_user.regs) {
6041 u64 mask = event->attr.sample_regs_user;
6042 size += hweight64(mask) * sizeof(u64);
6045 header->size += size;
6048 if (sample_type & PERF_SAMPLE_STACK_USER) {
6050 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
6051 * processed as the last one or have additional check added
6052 * in case new sample type is added, because we could eat
6053 * up the rest of the sample size.
6055 u16 stack_size = event->attr.sample_stack_user;
6056 u16 size = sizeof(u64);
6058 stack_size = perf_sample_ustack_size(stack_size, header->size,
6059 data->regs_user.regs);
6062 * If there is something to dump, add space for the dump
6063 * itself and for the field that tells the dynamic size,
6064 * which is how many have been actually dumped.
6067 size += sizeof(u64) + stack_size;
6069 data->stack_user_size = stack_size;
6070 header->size += size;
6073 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6074 /* regs dump ABI info */
6075 int size = sizeof(u64);
6077 perf_sample_regs_intr(&data->regs_intr, regs);
6079 if (data->regs_intr.regs) {
6080 u64 mask = event->attr.sample_regs_intr;
6082 size += hweight64(mask) * sizeof(u64);
6085 header->size += size;
6089 static void __always_inline
6090 __perf_event_output(struct perf_event *event,
6091 struct perf_sample_data *data,
6092 struct pt_regs *regs,
6093 int (*output_begin)(struct perf_output_handle *,
6094 struct perf_event *,
6097 struct perf_output_handle handle;
6098 struct perf_event_header header;
6100 /* protect the callchain buffers */
6103 perf_prepare_sample(&header, data, event, regs);
6105 if (output_begin(&handle, event, header.size))
6108 perf_output_sample(&handle, &header, data, event);
6110 perf_output_end(&handle);
6117 perf_event_output_forward(struct perf_event *event,
6118 struct perf_sample_data *data,
6119 struct pt_regs *regs)
6121 __perf_event_output(event, data, regs, perf_output_begin_forward);
6125 perf_event_output_backward(struct perf_event *event,
6126 struct perf_sample_data *data,
6127 struct pt_regs *regs)
6129 __perf_event_output(event, data, regs, perf_output_begin_backward);
6133 perf_event_output(struct perf_event *event,
6134 struct perf_sample_data *data,
6135 struct pt_regs *regs)
6137 __perf_event_output(event, data, regs, perf_output_begin);
6144 struct perf_read_event {
6145 struct perf_event_header header;
6152 perf_event_read_event(struct perf_event *event,
6153 struct task_struct *task)
6155 struct perf_output_handle handle;
6156 struct perf_sample_data sample;
6157 struct perf_read_event read_event = {
6159 .type = PERF_RECORD_READ,
6161 .size = sizeof(read_event) + event->read_size,
6163 .pid = perf_event_pid(event, task),
6164 .tid = perf_event_tid(event, task),
6168 perf_event_header__init_id(&read_event.header, &sample, event);
6169 ret = perf_output_begin(&handle, event, read_event.header.size);
6173 perf_output_put(&handle, read_event);
6174 perf_output_read(&handle, event);
6175 perf_event__output_id_sample(event, &handle, &sample);
6177 perf_output_end(&handle);
6180 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
6183 perf_iterate_ctx(struct perf_event_context *ctx,
6184 perf_iterate_f output,
6185 void *data, bool all)
6187 struct perf_event *event;
6189 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6191 if (event->state < PERF_EVENT_STATE_INACTIVE)
6193 if (!event_filter_match(event))
6197 output(event, data);
6201 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
6203 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
6204 struct perf_event *event;
6206 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6208 * Skip events that are not fully formed yet; ensure that
6209 * if we observe event->ctx, both event and ctx will be
6210 * complete enough. See perf_install_in_context().
6212 if (!smp_load_acquire(&event->ctx))
6215 if (event->state < PERF_EVENT_STATE_INACTIVE)
6217 if (!event_filter_match(event))
6219 output(event, data);
6224 * Iterate all events that need to receive side-band events.
6226 * For new callers; ensure that account_pmu_sb_event() includes
6227 * your event, otherwise it might not get delivered.
6230 perf_iterate_sb(perf_iterate_f output, void *data,
6231 struct perf_event_context *task_ctx)
6233 struct perf_event_context *ctx;
6240 * If we have task_ctx != NULL we only notify the task context itself.
6241 * The task_ctx is set only for EXIT events before releasing task
6245 perf_iterate_ctx(task_ctx, output, data, false);
6249 perf_iterate_sb_cpu(output, data);
6251 for_each_task_context_nr(ctxn) {
6252 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6254 perf_iterate_ctx(ctx, output, data, false);
6262 * Clear all file-based filters at exec, they'll have to be
6263 * re-instated when/if these objects are mmapped again.
6265 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6267 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6268 struct perf_addr_filter *filter;
6269 unsigned int restart = 0, count = 0;
6270 unsigned long flags;
6272 if (!has_addr_filter(event))
6275 raw_spin_lock_irqsave(&ifh->lock, flags);
6276 list_for_each_entry(filter, &ifh->list, entry) {
6277 if (filter->path.dentry) {
6278 event->addr_filters_offs[count] = 0;
6286 event->addr_filters_gen++;
6287 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6290 perf_event_stop(event, 1);
6293 void perf_event_exec(void)
6295 struct perf_event_context *ctx;
6299 for_each_task_context_nr(ctxn) {
6300 ctx = current->perf_event_ctxp[ctxn];
6304 perf_event_enable_on_exec(ctxn);
6306 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6312 struct remote_output {
6313 struct ring_buffer *rb;
6317 static void __perf_event_output_stop(struct perf_event *event, void *data)
6319 struct perf_event *parent = event->parent;
6320 struct remote_output *ro = data;
6321 struct ring_buffer *rb = ro->rb;
6322 struct stop_event_data sd = {
6326 if (!has_aux(event))
6333 * In case of inheritance, it will be the parent that links to the
6334 * ring-buffer, but it will be the child that's actually using it.
6336 * We are using event::rb to determine if the event should be stopped,
6337 * however this may race with ring_buffer_attach() (through set_output),
6338 * which will make us skip the event that actually needs to be stopped.
6339 * So ring_buffer_attach() has to stop an aux event before re-assigning
6342 if (rcu_dereference(parent->rb) == rb)
6343 ro->err = __perf_event_stop(&sd);
6346 static int __perf_pmu_output_stop(void *info)
6348 struct perf_event *event = info;
6349 struct pmu *pmu = event->pmu;
6350 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6351 struct remote_output ro = {
6356 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6357 if (cpuctx->task_ctx)
6358 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6365 static void perf_pmu_output_stop(struct perf_event *event)
6367 struct perf_event *iter;
6372 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6374 * For per-CPU events, we need to make sure that neither they
6375 * nor their children are running; for cpu==-1 events it's
6376 * sufficient to stop the event itself if it's active, since
6377 * it can't have children.
6381 cpu = READ_ONCE(iter->oncpu);
6386 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6387 if (err == -EAGAIN) {
6396 * task tracking -- fork/exit
6398 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6401 struct perf_task_event {
6402 struct task_struct *task;
6403 struct perf_event_context *task_ctx;
6406 struct perf_event_header header;
6416 static int perf_event_task_match(struct perf_event *event)
6418 return event->attr.comm || event->attr.mmap ||
6419 event->attr.mmap2 || event->attr.mmap_data ||
6423 static void perf_event_task_output(struct perf_event *event,
6426 struct perf_task_event *task_event = data;
6427 struct perf_output_handle handle;
6428 struct perf_sample_data sample;
6429 struct task_struct *task = task_event->task;
6430 int ret, size = task_event->event_id.header.size;
6432 if (!perf_event_task_match(event))
6435 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6437 ret = perf_output_begin(&handle, event,
6438 task_event->event_id.header.size);
6442 task_event->event_id.pid = perf_event_pid(event, task);
6443 task_event->event_id.tid = perf_event_tid(event, task);
6445 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
6446 task_event->event_id.ppid = perf_event_pid(event,
6448 task_event->event_id.ptid = perf_event_pid(event,
6450 } else { /* PERF_RECORD_FORK */
6451 task_event->event_id.ppid = perf_event_pid(event, current);
6452 task_event->event_id.ptid = perf_event_tid(event, current);
6455 task_event->event_id.time = perf_event_clock(event);
6457 perf_output_put(&handle, task_event->event_id);
6459 perf_event__output_id_sample(event, &handle, &sample);
6461 perf_output_end(&handle);
6463 task_event->event_id.header.size = size;
6466 static void perf_event_task(struct task_struct *task,
6467 struct perf_event_context *task_ctx,
6470 struct perf_task_event task_event;
6472 if (!atomic_read(&nr_comm_events) &&
6473 !atomic_read(&nr_mmap_events) &&
6474 !atomic_read(&nr_task_events))
6477 task_event = (struct perf_task_event){
6479 .task_ctx = task_ctx,
6482 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6484 .size = sizeof(task_event.event_id),
6494 perf_iterate_sb(perf_event_task_output,
6499 void perf_event_fork(struct task_struct *task)
6501 perf_event_task(task, NULL, 1);
6508 struct perf_comm_event {
6509 struct task_struct *task;
6514 struct perf_event_header header;
6521 static int perf_event_comm_match(struct perf_event *event)
6523 return event->attr.comm;
6526 static void perf_event_comm_output(struct perf_event *event,
6529 struct perf_comm_event *comm_event = data;
6530 struct perf_output_handle handle;
6531 struct perf_sample_data sample;
6532 int size = comm_event->event_id.header.size;
6535 if (!perf_event_comm_match(event))
6538 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6539 ret = perf_output_begin(&handle, event,
6540 comm_event->event_id.header.size);
6545 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6546 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6548 perf_output_put(&handle, comm_event->event_id);
6549 __output_copy(&handle, comm_event->comm,
6550 comm_event->comm_size);
6552 perf_event__output_id_sample(event, &handle, &sample);
6554 perf_output_end(&handle);
6556 comm_event->event_id.header.size = size;
6559 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6561 char comm[TASK_COMM_LEN];
6564 memset(comm, 0, sizeof(comm));
6565 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6566 size = ALIGN(strlen(comm)+1, sizeof(u64));
6568 comm_event->comm = comm;
6569 comm_event->comm_size = size;
6571 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6573 perf_iterate_sb(perf_event_comm_output,
6578 void perf_event_comm(struct task_struct *task, bool exec)
6580 struct perf_comm_event comm_event;
6582 if (!atomic_read(&nr_comm_events))
6585 comm_event = (struct perf_comm_event){
6591 .type = PERF_RECORD_COMM,
6592 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6600 perf_event_comm_event(&comm_event);
6607 struct perf_mmap_event {
6608 struct vm_area_struct *vma;
6610 const char *file_name;
6618 struct perf_event_header header;
6628 static int perf_event_mmap_match(struct perf_event *event,
6631 struct perf_mmap_event *mmap_event = data;
6632 struct vm_area_struct *vma = mmap_event->vma;
6633 int executable = vma->vm_flags & VM_EXEC;
6635 return (!executable && event->attr.mmap_data) ||
6636 (executable && (event->attr.mmap || event->attr.mmap2));
6639 static void perf_event_mmap_output(struct perf_event *event,
6642 struct perf_mmap_event *mmap_event = data;
6643 struct perf_output_handle handle;
6644 struct perf_sample_data sample;
6645 int size = mmap_event->event_id.header.size;
6646 u32 type = mmap_event->event_id.header.type;
6649 if (!perf_event_mmap_match(event, data))
6652 if (event->attr.mmap2) {
6653 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6654 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6655 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6656 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6657 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6658 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6659 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6662 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6663 ret = perf_output_begin(&handle, event,
6664 mmap_event->event_id.header.size);
6668 mmap_event->event_id.pid = perf_event_pid(event, current);
6669 mmap_event->event_id.tid = perf_event_tid(event, current);
6671 perf_output_put(&handle, mmap_event->event_id);
6673 if (event->attr.mmap2) {
6674 perf_output_put(&handle, mmap_event->maj);
6675 perf_output_put(&handle, mmap_event->min);
6676 perf_output_put(&handle, mmap_event->ino);
6677 perf_output_put(&handle, mmap_event->ino_generation);
6678 perf_output_put(&handle, mmap_event->prot);
6679 perf_output_put(&handle, mmap_event->flags);
6682 __output_copy(&handle, mmap_event->file_name,
6683 mmap_event->file_size);
6685 perf_event__output_id_sample(event, &handle, &sample);
6687 perf_output_end(&handle);
6689 mmap_event->event_id.header.size = size;
6690 mmap_event->event_id.header.type = type;
6693 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6695 struct vm_area_struct *vma = mmap_event->vma;
6696 struct file *file = vma->vm_file;
6697 int maj = 0, min = 0;
6698 u64 ino = 0, gen = 0;
6699 u32 prot = 0, flags = 0;
6705 if (vma->vm_flags & VM_READ)
6707 if (vma->vm_flags & VM_WRITE)
6709 if (vma->vm_flags & VM_EXEC)
6712 if (vma->vm_flags & VM_MAYSHARE)
6715 flags = MAP_PRIVATE;
6717 if (vma->vm_flags & VM_DENYWRITE)
6718 flags |= MAP_DENYWRITE;
6719 if (vma->vm_flags & VM_MAYEXEC)
6720 flags |= MAP_EXECUTABLE;
6721 if (vma->vm_flags & VM_LOCKED)
6722 flags |= MAP_LOCKED;
6723 if (vma->vm_flags & VM_HUGETLB)
6724 flags |= MAP_HUGETLB;
6727 struct inode *inode;
6730 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6736 * d_path() works from the end of the rb backwards, so we
6737 * need to add enough zero bytes after the string to handle
6738 * the 64bit alignment we do later.
6740 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6745 inode = file_inode(vma->vm_file);
6746 dev = inode->i_sb->s_dev;
6748 gen = inode->i_generation;
6754 if (vma->vm_ops && vma->vm_ops->name) {
6755 name = (char *) vma->vm_ops->name(vma);
6760 name = (char *)arch_vma_name(vma);
6764 if (vma->vm_start <= vma->vm_mm->start_brk &&
6765 vma->vm_end >= vma->vm_mm->brk) {
6769 if (vma->vm_start <= vma->vm_mm->start_stack &&
6770 vma->vm_end >= vma->vm_mm->start_stack) {
6780 strlcpy(tmp, name, sizeof(tmp));
6784 * Since our buffer works in 8 byte units we need to align our string
6785 * size to a multiple of 8. However, we must guarantee the tail end is
6786 * zero'd out to avoid leaking random bits to userspace.
6788 size = strlen(name)+1;
6789 while (!IS_ALIGNED(size, sizeof(u64)))
6790 name[size++] = '\0';
6792 mmap_event->file_name = name;
6793 mmap_event->file_size = size;
6794 mmap_event->maj = maj;
6795 mmap_event->min = min;
6796 mmap_event->ino = ino;
6797 mmap_event->ino_generation = gen;
6798 mmap_event->prot = prot;
6799 mmap_event->flags = flags;
6801 if (!(vma->vm_flags & VM_EXEC))
6802 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6804 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6806 perf_iterate_sb(perf_event_mmap_output,
6814 * Check whether inode and address range match filter criteria.
6816 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
6817 struct file *file, unsigned long offset,
6820 /* d_inode(NULL) won't be equal to any mapped user-space file */
6821 if (!filter->path.dentry)
6824 if (d_inode(filter->path.dentry) != file_inode(file))
6827 if (filter->offset > offset + size)
6830 if (filter->offset + filter->size < offset)
6836 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
6838 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6839 struct vm_area_struct *vma = data;
6840 unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
6841 struct file *file = vma->vm_file;
6842 struct perf_addr_filter *filter;
6843 unsigned int restart = 0, count = 0;
6845 if (!has_addr_filter(event))
6851 raw_spin_lock_irqsave(&ifh->lock, flags);
6852 list_for_each_entry(filter, &ifh->list, entry) {
6853 if (perf_addr_filter_match(filter, file, off,
6854 vma->vm_end - vma->vm_start)) {
6855 event->addr_filters_offs[count] = vma->vm_start;
6863 event->addr_filters_gen++;
6864 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6867 perf_event_stop(event, 1);
6871 * Adjust all task's events' filters to the new vma
6873 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
6875 struct perf_event_context *ctx;
6879 * Data tracing isn't supported yet and as such there is no need
6880 * to keep track of anything that isn't related to executable code:
6882 if (!(vma->vm_flags & VM_EXEC))
6886 for_each_task_context_nr(ctxn) {
6887 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6891 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
6896 void perf_event_mmap(struct vm_area_struct *vma)
6898 struct perf_mmap_event mmap_event;
6900 if (!atomic_read(&nr_mmap_events))
6903 mmap_event = (struct perf_mmap_event){
6909 .type = PERF_RECORD_MMAP,
6910 .misc = PERF_RECORD_MISC_USER,
6915 .start = vma->vm_start,
6916 .len = vma->vm_end - vma->vm_start,
6917 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6919 /* .maj (attr_mmap2 only) */
6920 /* .min (attr_mmap2 only) */
6921 /* .ino (attr_mmap2 only) */
6922 /* .ino_generation (attr_mmap2 only) */
6923 /* .prot (attr_mmap2 only) */
6924 /* .flags (attr_mmap2 only) */
6927 perf_addr_filters_adjust(vma);
6928 perf_event_mmap_event(&mmap_event);
6931 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6932 unsigned long size, u64 flags)
6934 struct perf_output_handle handle;
6935 struct perf_sample_data sample;
6936 struct perf_aux_event {
6937 struct perf_event_header header;
6943 .type = PERF_RECORD_AUX,
6945 .size = sizeof(rec),
6953 perf_event_header__init_id(&rec.header, &sample, event);
6954 ret = perf_output_begin(&handle, event, rec.header.size);
6959 perf_output_put(&handle, rec);
6960 perf_event__output_id_sample(event, &handle, &sample);
6962 perf_output_end(&handle);
6966 * Lost/dropped samples logging
6968 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6970 struct perf_output_handle handle;
6971 struct perf_sample_data sample;
6975 struct perf_event_header header;
6977 } lost_samples_event = {
6979 .type = PERF_RECORD_LOST_SAMPLES,
6981 .size = sizeof(lost_samples_event),
6986 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6988 ret = perf_output_begin(&handle, event,
6989 lost_samples_event.header.size);
6993 perf_output_put(&handle, lost_samples_event);
6994 perf_event__output_id_sample(event, &handle, &sample);
6995 perf_output_end(&handle);
6999 * context_switch tracking
7002 struct perf_switch_event {
7003 struct task_struct *task;
7004 struct task_struct *next_prev;
7007 struct perf_event_header header;
7013 static int perf_event_switch_match(struct perf_event *event)
7015 return event->attr.context_switch;
7018 static void perf_event_switch_output(struct perf_event *event, void *data)
7020 struct perf_switch_event *se = data;
7021 struct perf_output_handle handle;
7022 struct perf_sample_data sample;
7025 if (!perf_event_switch_match(event))
7028 /* Only CPU-wide events are allowed to see next/prev pid/tid */
7029 if (event->ctx->task) {
7030 se->event_id.header.type = PERF_RECORD_SWITCH;
7031 se->event_id.header.size = sizeof(se->event_id.header);
7033 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
7034 se->event_id.header.size = sizeof(se->event_id);
7035 se->event_id.next_prev_pid =
7036 perf_event_pid(event, se->next_prev);
7037 se->event_id.next_prev_tid =
7038 perf_event_tid(event, se->next_prev);
7041 perf_event_header__init_id(&se->event_id.header, &sample, event);
7043 ret = perf_output_begin(&handle, event, se->event_id.header.size);
7047 if (event->ctx->task)
7048 perf_output_put(&handle, se->event_id.header);
7050 perf_output_put(&handle, se->event_id);
7052 perf_event__output_id_sample(event, &handle, &sample);
7054 perf_output_end(&handle);
7057 static void perf_event_switch(struct task_struct *task,
7058 struct task_struct *next_prev, bool sched_in)
7060 struct perf_switch_event switch_event;
7062 /* N.B. caller checks nr_switch_events != 0 */
7064 switch_event = (struct perf_switch_event){
7066 .next_prev = next_prev,
7070 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
7073 /* .next_prev_pid */
7074 /* .next_prev_tid */
7078 perf_iterate_sb(perf_event_switch_output,
7084 * IRQ throttle logging
7087 static void perf_log_throttle(struct perf_event *event, int enable)
7089 struct perf_output_handle handle;
7090 struct perf_sample_data sample;
7094 struct perf_event_header header;
7098 } throttle_event = {
7100 .type = PERF_RECORD_THROTTLE,
7102 .size = sizeof(throttle_event),
7104 .time = perf_event_clock(event),
7105 .id = primary_event_id(event),
7106 .stream_id = event->id,
7110 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
7112 perf_event_header__init_id(&throttle_event.header, &sample, event);
7114 ret = perf_output_begin(&handle, event,
7115 throttle_event.header.size);
7119 perf_output_put(&handle, throttle_event);
7120 perf_event__output_id_sample(event, &handle, &sample);
7121 perf_output_end(&handle);
7124 static void perf_log_itrace_start(struct perf_event *event)
7126 struct perf_output_handle handle;
7127 struct perf_sample_data sample;
7128 struct perf_aux_event {
7129 struct perf_event_header header;
7136 event = event->parent;
7138 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
7139 event->hw.itrace_started)
7142 rec.header.type = PERF_RECORD_ITRACE_START;
7143 rec.header.misc = 0;
7144 rec.header.size = sizeof(rec);
7145 rec.pid = perf_event_pid(event, current);
7146 rec.tid = perf_event_tid(event, current);
7148 perf_event_header__init_id(&rec.header, &sample, event);
7149 ret = perf_output_begin(&handle, event, rec.header.size);
7154 perf_output_put(&handle, rec);
7155 perf_event__output_id_sample(event, &handle, &sample);
7157 perf_output_end(&handle);
7161 __perf_event_account_interrupt(struct perf_event *event, int throttle)
7163 struct hw_perf_event *hwc = &event->hw;
7167 seq = __this_cpu_read(perf_throttled_seq);
7168 if (seq != hwc->interrupts_seq) {
7169 hwc->interrupts_seq = seq;
7170 hwc->interrupts = 1;
7173 if (unlikely(throttle
7174 && hwc->interrupts >= max_samples_per_tick)) {
7175 __this_cpu_inc(perf_throttled_count);
7176 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
7177 hwc->interrupts = MAX_INTERRUPTS;
7178 perf_log_throttle(event, 0);
7183 if (event->attr.freq) {
7184 u64 now = perf_clock();
7185 s64 delta = now - hwc->freq_time_stamp;
7187 hwc->freq_time_stamp = now;
7189 if (delta > 0 && delta < 2*TICK_NSEC)
7190 perf_adjust_period(event, delta, hwc->last_period, true);
7196 int perf_event_account_interrupt(struct perf_event *event)
7198 return __perf_event_account_interrupt(event, 1);
7202 * Generic event overflow handling, sampling.
7205 static int __perf_event_overflow(struct perf_event *event,
7206 int throttle, struct perf_sample_data *data,
7207 struct pt_regs *regs)
7209 int events = atomic_read(&event->event_limit);
7213 * Non-sampling counters might still use the PMI to fold short
7214 * hardware counters, ignore those.
7216 if (unlikely(!is_sampling_event(event)))
7219 ret = __perf_event_account_interrupt(event, throttle);
7222 * XXX event_limit might not quite work as expected on inherited
7226 event->pending_kill = POLL_IN;
7227 if (events && atomic_dec_and_test(&event->event_limit)) {
7229 event->pending_kill = POLL_HUP;
7231 perf_event_disable_inatomic(event);
7234 READ_ONCE(event->overflow_handler)(event, data, regs);
7236 if (*perf_event_fasync(event) && event->pending_kill) {
7237 event->pending_wakeup = 1;
7238 irq_work_queue(&event->pending);
7244 int perf_event_overflow(struct perf_event *event,
7245 struct perf_sample_data *data,
7246 struct pt_regs *regs)
7248 return __perf_event_overflow(event, 1, data, regs);
7252 * Generic software event infrastructure
7255 struct swevent_htable {
7256 struct swevent_hlist *swevent_hlist;
7257 struct mutex hlist_mutex;
7260 /* Recursion avoidance in each contexts */
7261 int recursion[PERF_NR_CONTEXTS];
7264 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
7267 * We directly increment event->count and keep a second value in
7268 * event->hw.period_left to count intervals. This period event
7269 * is kept in the range [-sample_period, 0] so that we can use the
7273 u64 perf_swevent_set_period(struct perf_event *event)
7275 struct hw_perf_event *hwc = &event->hw;
7276 u64 period = hwc->last_period;
7280 hwc->last_period = hwc->sample_period;
7283 old = val = local64_read(&hwc->period_left);
7287 nr = div64_u64(period + val, period);
7288 offset = nr * period;
7290 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7296 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
7297 struct perf_sample_data *data,
7298 struct pt_regs *regs)
7300 struct hw_perf_event *hwc = &event->hw;
7304 overflow = perf_swevent_set_period(event);
7306 if (hwc->interrupts == MAX_INTERRUPTS)
7309 for (; overflow; overflow--) {
7310 if (__perf_event_overflow(event, throttle,
7313 * We inhibit the overflow from happening when
7314 * hwc->interrupts == MAX_INTERRUPTS.
7322 static void perf_swevent_event(struct perf_event *event, u64 nr,
7323 struct perf_sample_data *data,
7324 struct pt_regs *regs)
7326 struct hw_perf_event *hwc = &event->hw;
7328 local64_add(nr, &event->count);
7333 if (!is_sampling_event(event))
7336 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
7338 return perf_swevent_overflow(event, 1, data, regs);
7340 data->period = event->hw.last_period;
7342 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
7343 return perf_swevent_overflow(event, 1, data, regs);
7345 if (local64_add_negative(nr, &hwc->period_left))
7348 perf_swevent_overflow(event, 0, data, regs);
7351 static int perf_exclude_event(struct perf_event *event,
7352 struct pt_regs *regs)
7354 if (event->hw.state & PERF_HES_STOPPED)
7358 if (event->attr.exclude_user && user_mode(regs))
7361 if (event->attr.exclude_kernel && !user_mode(regs))
7368 static int perf_swevent_match(struct perf_event *event,
7369 enum perf_type_id type,
7371 struct perf_sample_data *data,
7372 struct pt_regs *regs)
7374 if (event->attr.type != type)
7377 if (event->attr.config != event_id)
7380 if (perf_exclude_event(event, regs))
7386 static inline u64 swevent_hash(u64 type, u32 event_id)
7388 u64 val = event_id | (type << 32);
7390 return hash_64(val, SWEVENT_HLIST_BITS);
7393 static inline struct hlist_head *
7394 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
7396 u64 hash = swevent_hash(type, event_id);
7398 return &hlist->heads[hash];
7401 /* For the read side: events when they trigger */
7402 static inline struct hlist_head *
7403 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
7405 struct swevent_hlist *hlist;
7407 hlist = rcu_dereference(swhash->swevent_hlist);
7411 return __find_swevent_head(hlist, type, event_id);
7414 /* For the event head insertion and removal in the hlist */
7415 static inline struct hlist_head *
7416 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
7418 struct swevent_hlist *hlist;
7419 u32 event_id = event->attr.config;
7420 u64 type = event->attr.type;
7423 * Event scheduling is always serialized against hlist allocation
7424 * and release. Which makes the protected version suitable here.
7425 * The context lock guarantees that.
7427 hlist = rcu_dereference_protected(swhash->swevent_hlist,
7428 lockdep_is_held(&event->ctx->lock));
7432 return __find_swevent_head(hlist, type, event_id);
7435 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
7437 struct perf_sample_data *data,
7438 struct pt_regs *regs)
7440 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7441 struct perf_event *event;
7442 struct hlist_head *head;
7445 head = find_swevent_head_rcu(swhash, type, event_id);
7449 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7450 if (perf_swevent_match(event, type, event_id, data, regs))
7451 perf_swevent_event(event, nr, data, regs);
7457 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
7459 int perf_swevent_get_recursion_context(void)
7461 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7463 return get_recursion_context(swhash->recursion);
7465 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
7467 void perf_swevent_put_recursion_context(int rctx)
7469 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7471 put_recursion_context(swhash->recursion, rctx);
7474 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7476 struct perf_sample_data data;
7478 if (WARN_ON_ONCE(!regs))
7481 perf_sample_data_init(&data, addr, 0);
7482 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
7485 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7489 preempt_disable_notrace();
7490 rctx = perf_swevent_get_recursion_context();
7491 if (unlikely(rctx < 0))
7494 ___perf_sw_event(event_id, nr, regs, addr);
7496 perf_swevent_put_recursion_context(rctx);
7498 preempt_enable_notrace();
7501 static void perf_swevent_read(struct perf_event *event)
7505 static int perf_swevent_add(struct perf_event *event, int flags)
7507 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7508 struct hw_perf_event *hwc = &event->hw;
7509 struct hlist_head *head;
7511 if (is_sampling_event(event)) {
7512 hwc->last_period = hwc->sample_period;
7513 perf_swevent_set_period(event);
7516 hwc->state = !(flags & PERF_EF_START);
7518 head = find_swevent_head(swhash, event);
7519 if (WARN_ON_ONCE(!head))
7522 hlist_add_head_rcu(&event->hlist_entry, head);
7523 perf_event_update_userpage(event);
7528 static void perf_swevent_del(struct perf_event *event, int flags)
7530 hlist_del_rcu(&event->hlist_entry);
7533 static void perf_swevent_start(struct perf_event *event, int flags)
7535 event->hw.state = 0;
7538 static void perf_swevent_stop(struct perf_event *event, int flags)
7540 event->hw.state = PERF_HES_STOPPED;
7543 /* Deref the hlist from the update side */
7544 static inline struct swevent_hlist *
7545 swevent_hlist_deref(struct swevent_htable *swhash)
7547 return rcu_dereference_protected(swhash->swevent_hlist,
7548 lockdep_is_held(&swhash->hlist_mutex));
7551 static void swevent_hlist_release(struct swevent_htable *swhash)
7553 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7558 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7559 kfree_rcu(hlist, rcu_head);
7562 static void swevent_hlist_put_cpu(int cpu)
7564 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7566 mutex_lock(&swhash->hlist_mutex);
7568 if (!--swhash->hlist_refcount)
7569 swevent_hlist_release(swhash);
7571 mutex_unlock(&swhash->hlist_mutex);
7574 static void swevent_hlist_put(void)
7578 for_each_possible_cpu(cpu)
7579 swevent_hlist_put_cpu(cpu);
7582 static int swevent_hlist_get_cpu(int cpu)
7584 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7587 mutex_lock(&swhash->hlist_mutex);
7588 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7589 struct swevent_hlist *hlist;
7591 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7596 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7598 swhash->hlist_refcount++;
7600 mutex_unlock(&swhash->hlist_mutex);
7605 static int swevent_hlist_get(void)
7607 int err, cpu, failed_cpu;
7610 for_each_possible_cpu(cpu) {
7611 err = swevent_hlist_get_cpu(cpu);
7621 for_each_possible_cpu(cpu) {
7622 if (cpu == failed_cpu)
7624 swevent_hlist_put_cpu(cpu);
7631 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7633 static void sw_perf_event_destroy(struct perf_event *event)
7635 u64 event_id = event->attr.config;
7637 WARN_ON(event->parent);
7639 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7640 swevent_hlist_put();
7643 static int perf_swevent_init(struct perf_event *event)
7645 u64 event_id = event->attr.config;
7647 if (event->attr.type != PERF_TYPE_SOFTWARE)
7651 * no branch sampling for software events
7653 if (has_branch_stack(event))
7657 case PERF_COUNT_SW_CPU_CLOCK:
7658 case PERF_COUNT_SW_TASK_CLOCK:
7665 if (event_id >= PERF_COUNT_SW_MAX)
7668 if (!event->parent) {
7671 err = swevent_hlist_get();
7675 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7676 event->destroy = sw_perf_event_destroy;
7682 static struct pmu perf_swevent = {
7683 .task_ctx_nr = perf_sw_context,
7685 .capabilities = PERF_PMU_CAP_NO_NMI,
7687 .event_init = perf_swevent_init,
7688 .add = perf_swevent_add,
7689 .del = perf_swevent_del,
7690 .start = perf_swevent_start,
7691 .stop = perf_swevent_stop,
7692 .read = perf_swevent_read,
7695 #ifdef CONFIG_EVENT_TRACING
7697 static int perf_tp_filter_match(struct perf_event *event,
7698 struct perf_sample_data *data)
7700 void *record = data->raw->frag.data;
7702 /* only top level events have filters set */
7704 event = event->parent;
7706 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7711 static int perf_tp_event_match(struct perf_event *event,
7712 struct perf_sample_data *data,
7713 struct pt_regs *regs)
7715 if (event->hw.state & PERF_HES_STOPPED)
7718 * All tracepoints are from kernel-space.
7720 if (event->attr.exclude_kernel)
7723 if (!perf_tp_filter_match(event, data))
7729 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
7730 struct trace_event_call *call, u64 count,
7731 struct pt_regs *regs, struct hlist_head *head,
7732 struct task_struct *task)
7734 struct bpf_prog *prog = call->prog;
7737 *(struct pt_regs **)raw_data = regs;
7738 if (!trace_call_bpf(prog, raw_data) || hlist_empty(head)) {
7739 perf_swevent_put_recursion_context(rctx);
7743 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
7746 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
7748 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
7749 struct pt_regs *regs, struct hlist_head *head, int rctx,
7750 struct task_struct *task)
7752 struct perf_sample_data data;
7753 struct perf_event *event;
7755 struct perf_raw_record raw = {
7762 perf_sample_data_init(&data, 0, 0);
7765 perf_trace_buf_update(record, event_type);
7767 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7768 if (perf_tp_event_match(event, &data, regs))
7769 perf_swevent_event(event, count, &data, regs);
7773 * If we got specified a target task, also iterate its context and
7774 * deliver this event there too.
7776 if (task && task != current) {
7777 struct perf_event_context *ctx;
7778 struct trace_entry *entry = record;
7781 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7785 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7786 if (event->cpu != smp_processor_id())
7788 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7790 if (event->attr.config != entry->type)
7792 if (perf_tp_event_match(event, &data, regs))
7793 perf_swevent_event(event, count, &data, regs);
7799 perf_swevent_put_recursion_context(rctx);
7801 EXPORT_SYMBOL_GPL(perf_tp_event);
7803 static void tp_perf_event_destroy(struct perf_event *event)
7805 perf_trace_destroy(event);
7808 static int perf_tp_event_init(struct perf_event *event)
7812 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7816 * no branch sampling for tracepoint events
7818 if (has_branch_stack(event))
7821 err = perf_trace_init(event);
7825 event->destroy = tp_perf_event_destroy;
7830 static struct pmu perf_tracepoint = {
7831 .task_ctx_nr = perf_sw_context,
7833 .event_init = perf_tp_event_init,
7834 .add = perf_trace_add,
7835 .del = perf_trace_del,
7836 .start = perf_swevent_start,
7837 .stop = perf_swevent_stop,
7838 .read = perf_swevent_read,
7841 static inline void perf_tp_register(void)
7843 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7846 static void perf_event_free_filter(struct perf_event *event)
7848 ftrace_profile_free_filter(event);
7851 #ifdef CONFIG_BPF_SYSCALL
7852 static void bpf_overflow_handler(struct perf_event *event,
7853 struct perf_sample_data *data,
7854 struct pt_regs *regs)
7856 struct bpf_perf_event_data_kern ctx = {
7863 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
7866 ret = BPF_PROG_RUN(event->prog, (void *)&ctx);
7869 __this_cpu_dec(bpf_prog_active);
7874 event->orig_overflow_handler(event, data, regs);
7877 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
7879 struct bpf_prog *prog;
7881 if (event->overflow_handler_context)
7882 /* hw breakpoint or kernel counter */
7888 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
7890 return PTR_ERR(prog);
7893 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
7894 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
7898 static void perf_event_free_bpf_handler(struct perf_event *event)
7900 struct bpf_prog *prog = event->prog;
7905 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
7910 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
7914 static void perf_event_free_bpf_handler(struct perf_event *event)
7919 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7921 bool is_kprobe, is_tracepoint;
7922 struct bpf_prog *prog;
7924 if (event->attr.type == PERF_TYPE_HARDWARE ||
7925 event->attr.type == PERF_TYPE_SOFTWARE)
7926 return perf_event_set_bpf_handler(event, prog_fd);
7928 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7931 if (event->tp_event->prog)
7934 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
7935 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
7936 if (!is_kprobe && !is_tracepoint)
7937 /* bpf programs can only be attached to u/kprobe or tracepoint */
7940 prog = bpf_prog_get(prog_fd);
7942 return PTR_ERR(prog);
7944 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
7945 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
7946 /* valid fd, but invalid bpf program type */
7951 if (is_tracepoint) {
7952 int off = trace_event_get_offsets(event->tp_event);
7954 if (prog->aux->max_ctx_offset > off) {
7959 event->tp_event->prog = prog;
7960 event->tp_event->bpf_prog_owner = event;
7965 static void perf_event_free_bpf_prog(struct perf_event *event)
7967 struct bpf_prog *prog;
7969 perf_event_free_bpf_handler(event);
7971 if (!event->tp_event)
7974 prog = event->tp_event->prog;
7975 if (prog && event->tp_event->bpf_prog_owner == event) {
7976 event->tp_event->prog = NULL;
7983 static inline void perf_tp_register(void)
7987 static void perf_event_free_filter(struct perf_event *event)
7991 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7996 static void perf_event_free_bpf_prog(struct perf_event *event)
7999 #endif /* CONFIG_EVENT_TRACING */
8001 #ifdef CONFIG_HAVE_HW_BREAKPOINT
8002 void perf_bp_event(struct perf_event *bp, void *data)
8004 struct perf_sample_data sample;
8005 struct pt_regs *regs = data;
8007 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
8009 if (!bp->hw.state && !perf_exclude_event(bp, regs))
8010 perf_swevent_event(bp, 1, &sample, regs);
8015 * Allocate a new address filter
8017 static struct perf_addr_filter *
8018 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
8020 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
8021 struct perf_addr_filter *filter;
8023 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
8027 INIT_LIST_HEAD(&filter->entry);
8028 list_add_tail(&filter->entry, filters);
8033 static void free_filters_list(struct list_head *filters)
8035 struct perf_addr_filter *filter, *iter;
8037 list_for_each_entry_safe(filter, iter, filters, entry) {
8038 path_put(&filter->path);
8039 list_del(&filter->entry);
8045 * Free existing address filters and optionally install new ones
8047 static void perf_addr_filters_splice(struct perf_event *event,
8048 struct list_head *head)
8050 unsigned long flags;
8053 if (!has_addr_filter(event))
8056 /* don't bother with children, they don't have their own filters */
8060 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
8062 list_splice_init(&event->addr_filters.list, &list);
8064 list_splice(head, &event->addr_filters.list);
8066 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
8068 free_filters_list(&list);
8072 * Scan through mm's vmas and see if one of them matches the
8073 * @filter; if so, adjust filter's address range.
8074 * Called with mm::mmap_sem down for reading.
8076 static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
8077 struct mm_struct *mm)
8079 struct vm_area_struct *vma;
8081 for (vma = mm->mmap; vma; vma = vma->vm_next) {
8082 struct file *file = vma->vm_file;
8083 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8084 unsigned long vma_size = vma->vm_end - vma->vm_start;
8089 if (!perf_addr_filter_match(filter, file, off, vma_size))
8092 return vma->vm_start;
8099 * Update event's address range filters based on the
8100 * task's existing mappings, if any.
8102 static void perf_event_addr_filters_apply(struct perf_event *event)
8104 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8105 struct task_struct *task = READ_ONCE(event->ctx->task);
8106 struct perf_addr_filter *filter;
8107 struct mm_struct *mm = NULL;
8108 unsigned int count = 0;
8109 unsigned long flags;
8112 * We may observe TASK_TOMBSTONE, which means that the event tear-down
8113 * will stop on the parent's child_mutex that our caller is also holding
8115 if (task == TASK_TOMBSTONE)
8118 mm = get_task_mm(task);
8122 down_read(&mm->mmap_sem);
8124 raw_spin_lock_irqsave(&ifh->lock, flags);
8125 list_for_each_entry(filter, &ifh->list, entry) {
8126 event->addr_filters_offs[count] = 0;
8129 * Adjust base offset if the filter is associated to a binary
8130 * that needs to be mapped:
8132 if (filter->path.dentry)
8133 event->addr_filters_offs[count] =
8134 perf_addr_filter_apply(filter, mm);
8139 event->addr_filters_gen++;
8140 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8142 up_read(&mm->mmap_sem);
8147 perf_event_stop(event, 1);
8151 * Address range filtering: limiting the data to certain
8152 * instruction address ranges. Filters are ioctl()ed to us from
8153 * userspace as ascii strings.
8155 * Filter string format:
8158 * where ACTION is one of the
8159 * * "filter": limit the trace to this region
8160 * * "start": start tracing from this address
8161 * * "stop": stop tracing at this address/region;
8163 * * for kernel addresses: <start address>[/<size>]
8164 * * for object files: <start address>[/<size>]@</path/to/object/file>
8166 * if <size> is not specified, the range is treated as a single address.
8180 IF_STATE_ACTION = 0,
8185 static const match_table_t if_tokens = {
8186 { IF_ACT_FILTER, "filter" },
8187 { IF_ACT_START, "start" },
8188 { IF_ACT_STOP, "stop" },
8189 { IF_SRC_FILE, "%u/%u@%s" },
8190 { IF_SRC_KERNEL, "%u/%u" },
8191 { IF_SRC_FILEADDR, "%u@%s" },
8192 { IF_SRC_KERNELADDR, "%u" },
8193 { IF_ACT_NONE, NULL },
8197 * Address filter string parser
8200 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
8201 struct list_head *filters)
8203 struct perf_addr_filter *filter = NULL;
8204 char *start, *orig, *filename = NULL;
8205 substring_t args[MAX_OPT_ARGS];
8206 int state = IF_STATE_ACTION, token;
8207 unsigned int kernel = 0;
8210 orig = fstr = kstrdup(fstr, GFP_KERNEL);
8214 while ((start = strsep(&fstr, " ,\n")) != NULL) {
8220 /* filter definition begins */
8221 if (state == IF_STATE_ACTION) {
8222 filter = perf_addr_filter_new(event, filters);
8227 token = match_token(start, if_tokens, args);
8234 if (state != IF_STATE_ACTION)
8237 state = IF_STATE_SOURCE;
8240 case IF_SRC_KERNELADDR:
8244 case IF_SRC_FILEADDR:
8246 if (state != IF_STATE_SOURCE)
8249 if (token == IF_SRC_FILE || token == IF_SRC_KERNEL)
8253 ret = kstrtoul(args[0].from, 0, &filter->offset);
8257 if (filter->range) {
8259 ret = kstrtoul(args[1].from, 0, &filter->size);
8264 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
8265 int fpos = filter->range ? 2 : 1;
8268 filename = match_strdup(&args[fpos]);
8275 state = IF_STATE_END;
8283 * Filter definition is fully parsed, validate and install it.
8284 * Make sure that it doesn't contradict itself or the event's
8287 if (state == IF_STATE_END) {
8288 if (kernel && event->attr.exclude_kernel)
8295 /* look up the path and grab its inode */
8296 ret = kern_path(filename, LOOKUP_FOLLOW,
8302 if (!filter->path.dentry ||
8303 !S_ISREG(d_inode(filter->path.dentry)
8308 /* ready to consume more filters */
8311 state = IF_STATE_ACTION;
8317 if (state != IF_STATE_ACTION)
8327 free_filters_list(filters);
8334 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
8340 * Since this is called in perf_ioctl() path, we're already holding
8343 lockdep_assert_held(&event->ctx->mutex);
8345 if (WARN_ON_ONCE(event->parent))
8349 * For now, we only support filtering in per-task events; doing so
8350 * for CPU-wide events requires additional context switching trickery,
8351 * since same object code will be mapped at different virtual
8352 * addresses in different processes.
8354 if (!event->ctx->task)
8357 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
8361 ret = event->pmu->addr_filters_validate(&filters);
8363 free_filters_list(&filters);
8367 /* remove existing filters, if any */
8368 perf_addr_filters_splice(event, &filters);
8370 /* install new filters */
8371 perf_event_for_each_child(event, perf_event_addr_filters_apply);
8376 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
8381 if ((event->attr.type != PERF_TYPE_TRACEPOINT ||
8382 !IS_ENABLED(CONFIG_EVENT_TRACING)) &&
8383 !has_addr_filter(event))
8386 filter_str = strndup_user(arg, PAGE_SIZE);
8387 if (IS_ERR(filter_str))
8388 return PTR_ERR(filter_str);
8390 if (IS_ENABLED(CONFIG_EVENT_TRACING) &&
8391 event->attr.type == PERF_TYPE_TRACEPOINT)
8392 ret = ftrace_profile_set_filter(event, event->attr.config,
8394 else if (has_addr_filter(event))
8395 ret = perf_event_set_addr_filter(event, filter_str);
8402 * hrtimer based swevent callback
8405 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
8407 enum hrtimer_restart ret = HRTIMER_RESTART;
8408 struct perf_sample_data data;
8409 struct pt_regs *regs;
8410 struct perf_event *event;
8413 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
8415 if (event->state != PERF_EVENT_STATE_ACTIVE)
8416 return HRTIMER_NORESTART;
8418 event->pmu->read(event);
8420 perf_sample_data_init(&data, 0, event->hw.last_period);
8421 regs = get_irq_regs();
8423 if (regs && !perf_exclude_event(event, regs)) {
8424 if (!(event->attr.exclude_idle && is_idle_task(current)))
8425 if (__perf_event_overflow(event, 1, &data, regs))
8426 ret = HRTIMER_NORESTART;
8429 period = max_t(u64, 10000, event->hw.sample_period);
8430 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
8435 static void perf_swevent_start_hrtimer(struct perf_event *event)
8437 struct hw_perf_event *hwc = &event->hw;
8440 if (!is_sampling_event(event))
8443 period = local64_read(&hwc->period_left);
8448 local64_set(&hwc->period_left, 0);
8450 period = max_t(u64, 10000, hwc->sample_period);
8452 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
8453 HRTIMER_MODE_REL_PINNED);
8456 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
8458 struct hw_perf_event *hwc = &event->hw;
8460 if (is_sampling_event(event)) {
8461 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
8462 local64_set(&hwc->period_left, ktime_to_ns(remaining));
8464 hrtimer_cancel(&hwc->hrtimer);
8468 static void perf_swevent_init_hrtimer(struct perf_event *event)
8470 struct hw_perf_event *hwc = &event->hw;
8472 if (!is_sampling_event(event))
8475 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
8476 hwc->hrtimer.function = perf_swevent_hrtimer;
8479 * Since hrtimers have a fixed rate, we can do a static freq->period
8480 * mapping and avoid the whole period adjust feedback stuff.
8482 if (event->attr.freq) {
8483 long freq = event->attr.sample_freq;
8485 event->attr.sample_period = NSEC_PER_SEC / freq;
8486 hwc->sample_period = event->attr.sample_period;
8487 local64_set(&hwc->period_left, hwc->sample_period);
8488 hwc->last_period = hwc->sample_period;
8489 event->attr.freq = 0;
8494 * Software event: cpu wall time clock
8497 static void cpu_clock_event_update(struct perf_event *event)
8502 now = local_clock();
8503 prev = local64_xchg(&event->hw.prev_count, now);
8504 local64_add(now - prev, &event->count);
8507 static void cpu_clock_event_start(struct perf_event *event, int flags)
8509 local64_set(&event->hw.prev_count, local_clock());
8510 perf_swevent_start_hrtimer(event);
8513 static void cpu_clock_event_stop(struct perf_event *event, int flags)
8515 perf_swevent_cancel_hrtimer(event);
8516 cpu_clock_event_update(event);
8519 static int cpu_clock_event_add(struct perf_event *event, int flags)
8521 if (flags & PERF_EF_START)
8522 cpu_clock_event_start(event, flags);
8523 perf_event_update_userpage(event);
8528 static void cpu_clock_event_del(struct perf_event *event, int flags)
8530 cpu_clock_event_stop(event, flags);
8533 static void cpu_clock_event_read(struct perf_event *event)
8535 cpu_clock_event_update(event);
8538 static int cpu_clock_event_init(struct perf_event *event)
8540 if (event->attr.type != PERF_TYPE_SOFTWARE)
8543 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
8547 * no branch sampling for software events
8549 if (has_branch_stack(event))
8552 perf_swevent_init_hrtimer(event);
8557 static struct pmu perf_cpu_clock = {
8558 .task_ctx_nr = perf_sw_context,
8560 .capabilities = PERF_PMU_CAP_NO_NMI,
8562 .event_init = cpu_clock_event_init,
8563 .add = cpu_clock_event_add,
8564 .del = cpu_clock_event_del,
8565 .start = cpu_clock_event_start,
8566 .stop = cpu_clock_event_stop,
8567 .read = cpu_clock_event_read,
8571 * Software event: task time clock
8574 static void task_clock_event_update(struct perf_event *event, u64 now)
8579 prev = local64_xchg(&event->hw.prev_count, now);
8581 local64_add(delta, &event->count);
8584 static void task_clock_event_start(struct perf_event *event, int flags)
8586 local64_set(&event->hw.prev_count, event->ctx->time);
8587 perf_swevent_start_hrtimer(event);
8590 static void task_clock_event_stop(struct perf_event *event, int flags)
8592 perf_swevent_cancel_hrtimer(event);
8593 task_clock_event_update(event, event->ctx->time);
8596 static int task_clock_event_add(struct perf_event *event, int flags)
8598 if (flags & PERF_EF_START)
8599 task_clock_event_start(event, flags);
8600 perf_event_update_userpage(event);
8605 static void task_clock_event_del(struct perf_event *event, int flags)
8607 task_clock_event_stop(event, PERF_EF_UPDATE);
8610 static void task_clock_event_read(struct perf_event *event)
8612 u64 now = perf_clock();
8613 u64 delta = now - event->ctx->timestamp;
8614 u64 time = event->ctx->time + delta;
8616 task_clock_event_update(event, time);
8619 static int task_clock_event_init(struct perf_event *event)
8621 if (event->attr.type != PERF_TYPE_SOFTWARE)
8624 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
8628 * no branch sampling for software events
8630 if (has_branch_stack(event))
8633 perf_swevent_init_hrtimer(event);
8638 static struct pmu perf_task_clock = {
8639 .task_ctx_nr = perf_sw_context,
8641 .capabilities = PERF_PMU_CAP_NO_NMI,
8643 .event_init = task_clock_event_init,
8644 .add = task_clock_event_add,
8645 .del = task_clock_event_del,
8646 .start = task_clock_event_start,
8647 .stop = task_clock_event_stop,
8648 .read = task_clock_event_read,
8651 static void perf_pmu_nop_void(struct pmu *pmu)
8655 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
8659 static int perf_pmu_nop_int(struct pmu *pmu)
8664 static int perf_event_nop_int(struct perf_event *event, u64 value)
8669 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
8671 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
8673 __this_cpu_write(nop_txn_flags, flags);
8675 if (flags & ~PERF_PMU_TXN_ADD)
8678 perf_pmu_disable(pmu);
8681 static int perf_pmu_commit_txn(struct pmu *pmu)
8683 unsigned int flags = __this_cpu_read(nop_txn_flags);
8685 __this_cpu_write(nop_txn_flags, 0);
8687 if (flags & ~PERF_PMU_TXN_ADD)
8690 perf_pmu_enable(pmu);
8694 static void perf_pmu_cancel_txn(struct pmu *pmu)
8696 unsigned int flags = __this_cpu_read(nop_txn_flags);
8698 __this_cpu_write(nop_txn_flags, 0);
8700 if (flags & ~PERF_PMU_TXN_ADD)
8703 perf_pmu_enable(pmu);
8706 static int perf_event_idx_default(struct perf_event *event)
8712 * Ensures all contexts with the same task_ctx_nr have the same
8713 * pmu_cpu_context too.
8715 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
8722 list_for_each_entry(pmu, &pmus, entry) {
8723 if (pmu->task_ctx_nr == ctxn)
8724 return pmu->pmu_cpu_context;
8730 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
8734 for_each_possible_cpu(cpu) {
8735 struct perf_cpu_context *cpuctx;
8737 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8739 if (cpuctx->unique_pmu == old_pmu)
8740 cpuctx->unique_pmu = pmu;
8744 static void free_pmu_context(struct pmu *pmu)
8748 mutex_lock(&pmus_lock);
8750 * Like a real lame refcount.
8752 list_for_each_entry(i, &pmus, entry) {
8753 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
8754 update_pmu_context(i, pmu);
8759 free_percpu(pmu->pmu_cpu_context);
8761 mutex_unlock(&pmus_lock);
8765 * Let userspace know that this PMU supports address range filtering:
8767 static ssize_t nr_addr_filters_show(struct device *dev,
8768 struct device_attribute *attr,
8771 struct pmu *pmu = dev_get_drvdata(dev);
8773 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
8775 DEVICE_ATTR_RO(nr_addr_filters);
8777 static struct idr pmu_idr;
8780 type_show(struct device *dev, struct device_attribute *attr, char *page)
8782 struct pmu *pmu = dev_get_drvdata(dev);
8784 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
8786 static DEVICE_ATTR_RO(type);
8789 perf_event_mux_interval_ms_show(struct device *dev,
8790 struct device_attribute *attr,
8793 struct pmu *pmu = dev_get_drvdata(dev);
8795 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
8798 static DEFINE_MUTEX(mux_interval_mutex);
8801 perf_event_mux_interval_ms_store(struct device *dev,
8802 struct device_attribute *attr,
8803 const char *buf, size_t count)
8805 struct pmu *pmu = dev_get_drvdata(dev);
8806 int timer, cpu, ret;
8808 ret = kstrtoint(buf, 0, &timer);
8815 /* same value, noting to do */
8816 if (timer == pmu->hrtimer_interval_ms)
8819 mutex_lock(&mux_interval_mutex);
8820 pmu->hrtimer_interval_ms = timer;
8822 /* update all cpuctx for this PMU */
8824 for_each_online_cpu(cpu) {
8825 struct perf_cpu_context *cpuctx;
8826 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8827 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
8829 cpu_function_call(cpu,
8830 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
8833 mutex_unlock(&mux_interval_mutex);
8837 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
8839 static struct attribute *pmu_dev_attrs[] = {
8840 &dev_attr_type.attr,
8841 &dev_attr_perf_event_mux_interval_ms.attr,
8844 ATTRIBUTE_GROUPS(pmu_dev);
8846 static int pmu_bus_running;
8847 static struct bus_type pmu_bus = {
8848 .name = "event_source",
8849 .dev_groups = pmu_dev_groups,
8852 static void pmu_dev_release(struct device *dev)
8857 static int pmu_dev_alloc(struct pmu *pmu)
8861 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
8865 pmu->dev->groups = pmu->attr_groups;
8866 device_initialize(pmu->dev);
8868 dev_set_drvdata(pmu->dev, pmu);
8869 pmu->dev->bus = &pmu_bus;
8870 pmu->dev->release = pmu_dev_release;
8872 ret = dev_set_name(pmu->dev, "%s", pmu->name);
8876 ret = device_add(pmu->dev);
8880 /* For PMUs with address filters, throw in an extra attribute: */
8881 if (pmu->nr_addr_filters)
8882 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
8891 device_del(pmu->dev);
8894 put_device(pmu->dev);
8898 static struct lock_class_key cpuctx_mutex;
8899 static struct lock_class_key cpuctx_lock;
8901 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
8905 mutex_lock(&pmus_lock);
8907 pmu->pmu_disable_count = alloc_percpu(int);
8908 if (!pmu->pmu_disable_count)
8917 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
8925 if (pmu_bus_running) {
8926 ret = pmu_dev_alloc(pmu);
8932 if (pmu->task_ctx_nr == perf_hw_context) {
8933 static int hw_context_taken = 0;
8936 * Other than systems with heterogeneous CPUs, it never makes
8937 * sense for two PMUs to share perf_hw_context. PMUs which are
8938 * uncore must use perf_invalid_context.
8940 if (WARN_ON_ONCE(hw_context_taken &&
8941 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
8942 pmu->task_ctx_nr = perf_invalid_context;
8944 hw_context_taken = 1;
8947 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
8948 if (pmu->pmu_cpu_context)
8949 goto got_cpu_context;
8952 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
8953 if (!pmu->pmu_cpu_context)
8956 for_each_possible_cpu(cpu) {
8957 struct perf_cpu_context *cpuctx;
8959 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8960 __perf_event_init_context(&cpuctx->ctx);
8961 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
8962 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
8963 cpuctx->ctx.pmu = pmu;
8965 __perf_mux_hrtimer_init(cpuctx, cpu);
8967 cpuctx->unique_pmu = pmu;
8971 if (!pmu->start_txn) {
8972 if (pmu->pmu_enable) {
8974 * If we have pmu_enable/pmu_disable calls, install
8975 * transaction stubs that use that to try and batch
8976 * hardware accesses.
8978 pmu->start_txn = perf_pmu_start_txn;
8979 pmu->commit_txn = perf_pmu_commit_txn;
8980 pmu->cancel_txn = perf_pmu_cancel_txn;
8982 pmu->start_txn = perf_pmu_nop_txn;
8983 pmu->commit_txn = perf_pmu_nop_int;
8984 pmu->cancel_txn = perf_pmu_nop_void;
8988 if (!pmu->pmu_enable) {
8989 pmu->pmu_enable = perf_pmu_nop_void;
8990 pmu->pmu_disable = perf_pmu_nop_void;
8993 if (!pmu->check_period)
8994 pmu->check_period = perf_event_nop_int;
8996 if (!pmu->event_idx)
8997 pmu->event_idx = perf_event_idx_default;
8999 list_add_rcu(&pmu->entry, &pmus);
9000 atomic_set(&pmu->exclusive_cnt, 0);
9003 mutex_unlock(&pmus_lock);
9008 device_del(pmu->dev);
9009 put_device(pmu->dev);
9012 if (pmu->type >= PERF_TYPE_MAX)
9013 idr_remove(&pmu_idr, pmu->type);
9016 free_percpu(pmu->pmu_disable_count);
9019 EXPORT_SYMBOL_GPL(perf_pmu_register);
9021 void perf_pmu_unregister(struct pmu *pmu)
9025 mutex_lock(&pmus_lock);
9026 remove_device = pmu_bus_running;
9027 list_del_rcu(&pmu->entry);
9028 mutex_unlock(&pmus_lock);
9031 * We dereference the pmu list under both SRCU and regular RCU, so
9032 * synchronize against both of those.
9034 synchronize_srcu(&pmus_srcu);
9037 free_percpu(pmu->pmu_disable_count);
9038 if (pmu->type >= PERF_TYPE_MAX)
9039 idr_remove(&pmu_idr, pmu->type);
9040 if (remove_device) {
9041 if (pmu->nr_addr_filters)
9042 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
9043 device_del(pmu->dev);
9044 put_device(pmu->dev);
9046 free_pmu_context(pmu);
9048 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
9050 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
9052 struct perf_event_context *ctx = NULL;
9055 if (!try_module_get(pmu->module))
9058 if (event->group_leader != event) {
9060 * This ctx->mutex can nest when we're called through
9061 * inheritance. See the perf_event_ctx_lock_nested() comment.
9063 ctx = perf_event_ctx_lock_nested(event->group_leader,
9064 SINGLE_DEPTH_NESTING);
9069 ret = pmu->event_init(event);
9072 perf_event_ctx_unlock(event->group_leader, ctx);
9075 module_put(pmu->module);
9080 static struct pmu *perf_init_event(struct perf_event *event)
9082 struct pmu *pmu = NULL;
9086 idx = srcu_read_lock(&pmus_srcu);
9089 pmu = idr_find(&pmu_idr, event->attr.type);
9092 ret = perf_try_init_event(pmu, event);
9098 list_for_each_entry_rcu(pmu, &pmus, entry) {
9099 ret = perf_try_init_event(pmu, event);
9103 if (ret != -ENOENT) {
9108 pmu = ERR_PTR(-ENOENT);
9110 srcu_read_unlock(&pmus_srcu, idx);
9115 static void attach_sb_event(struct perf_event *event)
9117 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
9119 raw_spin_lock(&pel->lock);
9120 list_add_rcu(&event->sb_list, &pel->list);
9121 raw_spin_unlock(&pel->lock);
9125 * We keep a list of all !task (and therefore per-cpu) events
9126 * that need to receive side-band records.
9128 * This avoids having to scan all the various PMU per-cpu contexts
9131 static void account_pmu_sb_event(struct perf_event *event)
9133 if (is_sb_event(event))
9134 attach_sb_event(event);
9137 static void account_event_cpu(struct perf_event *event, int cpu)
9142 if (is_cgroup_event(event))
9143 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
9146 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
9147 static void account_freq_event_nohz(void)
9149 #ifdef CONFIG_NO_HZ_FULL
9150 /* Lock so we don't race with concurrent unaccount */
9151 spin_lock(&nr_freq_lock);
9152 if (atomic_inc_return(&nr_freq_events) == 1)
9153 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
9154 spin_unlock(&nr_freq_lock);
9158 static void account_freq_event(void)
9160 if (tick_nohz_full_enabled())
9161 account_freq_event_nohz();
9163 atomic_inc(&nr_freq_events);
9167 static void account_event(struct perf_event *event)
9174 if (event->attach_state & PERF_ATTACH_TASK)
9176 if (event->attr.mmap || event->attr.mmap_data)
9177 atomic_inc(&nr_mmap_events);
9178 if (event->attr.comm)
9179 atomic_inc(&nr_comm_events);
9180 if (event->attr.task)
9181 atomic_inc(&nr_task_events);
9182 if (event->attr.freq)
9183 account_freq_event();
9184 if (event->attr.context_switch) {
9185 atomic_inc(&nr_switch_events);
9188 if (has_branch_stack(event))
9190 if (is_cgroup_event(event))
9194 if (atomic_inc_not_zero(&perf_sched_count))
9197 mutex_lock(&perf_sched_mutex);
9198 if (!atomic_read(&perf_sched_count)) {
9199 static_branch_enable(&perf_sched_events);
9201 * Guarantee that all CPUs observe they key change and
9202 * call the perf scheduling hooks before proceeding to
9203 * install events that need them.
9205 synchronize_sched();
9208 * Now that we have waited for the sync_sched(), allow further
9209 * increments to by-pass the mutex.
9211 atomic_inc(&perf_sched_count);
9212 mutex_unlock(&perf_sched_mutex);
9216 account_event_cpu(event, event->cpu);
9218 account_pmu_sb_event(event);
9222 * Allocate and initialize a event structure
9224 static struct perf_event *
9225 perf_event_alloc(struct perf_event_attr *attr, int cpu,
9226 struct task_struct *task,
9227 struct perf_event *group_leader,
9228 struct perf_event *parent_event,
9229 perf_overflow_handler_t overflow_handler,
9230 void *context, int cgroup_fd)
9233 struct perf_event *event;
9234 struct hw_perf_event *hwc;
9237 if ((unsigned)cpu >= nr_cpu_ids) {
9238 if (!task || cpu != -1)
9239 return ERR_PTR(-EINVAL);
9242 event = kzalloc(sizeof(*event), GFP_KERNEL);
9244 return ERR_PTR(-ENOMEM);
9247 * Single events are their own group leaders, with an
9248 * empty sibling list:
9251 group_leader = event;
9253 mutex_init(&event->child_mutex);
9254 INIT_LIST_HEAD(&event->child_list);
9256 INIT_LIST_HEAD(&event->group_entry);
9257 INIT_LIST_HEAD(&event->event_entry);
9258 INIT_LIST_HEAD(&event->sibling_list);
9259 INIT_LIST_HEAD(&event->rb_entry);
9260 INIT_LIST_HEAD(&event->active_entry);
9261 INIT_LIST_HEAD(&event->addr_filters.list);
9262 INIT_HLIST_NODE(&event->hlist_entry);
9265 init_waitqueue_head(&event->waitq);
9266 init_irq_work(&event->pending, perf_pending_event);
9268 mutex_init(&event->mmap_mutex);
9269 raw_spin_lock_init(&event->addr_filters.lock);
9271 atomic_long_set(&event->refcount, 1);
9273 event->attr = *attr;
9274 event->group_leader = group_leader;
9278 event->parent = parent_event;
9280 event->ns = get_pid_ns(task_active_pid_ns(current));
9281 event->id = atomic64_inc_return(&perf_event_id);
9283 event->state = PERF_EVENT_STATE_INACTIVE;
9286 event->attach_state = PERF_ATTACH_TASK;
9288 * XXX pmu::event_init needs to know what task to account to
9289 * and we cannot use the ctx information because we need the
9290 * pmu before we get a ctx.
9292 get_task_struct(task);
9293 event->hw.target = task;
9296 event->clock = &local_clock;
9298 event->clock = parent_event->clock;
9300 if (!overflow_handler && parent_event) {
9301 overflow_handler = parent_event->overflow_handler;
9302 context = parent_event->overflow_handler_context;
9303 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
9304 if (overflow_handler == bpf_overflow_handler) {
9305 struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
9308 err = PTR_ERR(prog);
9312 event->orig_overflow_handler =
9313 parent_event->orig_overflow_handler;
9318 if (overflow_handler) {
9319 event->overflow_handler = overflow_handler;
9320 event->overflow_handler_context = context;
9321 } else if (is_write_backward(event)){
9322 event->overflow_handler = perf_event_output_backward;
9323 event->overflow_handler_context = NULL;
9325 event->overflow_handler = perf_event_output_forward;
9326 event->overflow_handler_context = NULL;
9329 perf_event__state_init(event);
9334 hwc->sample_period = attr->sample_period;
9335 if (attr->freq && attr->sample_freq)
9336 hwc->sample_period = 1;
9337 hwc->last_period = hwc->sample_period;
9339 local64_set(&hwc->period_left, hwc->sample_period);
9342 * We currently do not support PERF_SAMPLE_READ on inherited events.
9343 * See perf_output_read().
9345 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
9348 if (!has_branch_stack(event))
9349 event->attr.branch_sample_type = 0;
9351 if (cgroup_fd != -1) {
9352 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
9357 pmu = perf_init_event(event);
9360 else if (IS_ERR(pmu)) {
9365 err = exclusive_event_init(event);
9369 if (has_addr_filter(event)) {
9370 event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
9371 sizeof(unsigned long),
9373 if (!event->addr_filters_offs) {
9378 /* force hw sync on the address filters */
9379 event->addr_filters_gen = 1;
9382 if (!event->parent) {
9383 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
9384 err = get_callchain_buffers(attr->sample_max_stack);
9386 goto err_addr_filters;
9390 /* symmetric to unaccount_event() in _free_event() */
9391 account_event(event);
9396 kfree(event->addr_filters_offs);
9399 exclusive_event_destroy(event);
9403 event->destroy(event);
9404 module_put(pmu->module);
9406 if (is_cgroup_event(event))
9407 perf_detach_cgroup(event);
9409 put_pid_ns(event->ns);
9410 if (event->hw.target)
9411 put_task_struct(event->hw.target);
9414 return ERR_PTR(err);
9417 static int perf_copy_attr(struct perf_event_attr __user *uattr,
9418 struct perf_event_attr *attr)
9423 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
9427 * zero the full structure, so that a short copy will be nice.
9429 memset(attr, 0, sizeof(*attr));
9431 ret = get_user(size, &uattr->size);
9435 if (size > PAGE_SIZE) /* silly large */
9438 if (!size) /* abi compat */
9439 size = PERF_ATTR_SIZE_VER0;
9441 if (size < PERF_ATTR_SIZE_VER0)
9445 * If we're handed a bigger struct than we know of,
9446 * ensure all the unknown bits are 0 - i.e. new
9447 * user-space does not rely on any kernel feature
9448 * extensions we dont know about yet.
9450 if (size > sizeof(*attr)) {
9451 unsigned char __user *addr;
9452 unsigned char __user *end;
9455 addr = (void __user *)uattr + sizeof(*attr);
9456 end = (void __user *)uattr + size;
9458 for (; addr < end; addr++) {
9459 ret = get_user(val, addr);
9465 size = sizeof(*attr);
9468 ret = copy_from_user(attr, uattr, size);
9472 if (attr->__reserved_1)
9475 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
9478 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
9481 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
9482 u64 mask = attr->branch_sample_type;
9484 /* only using defined bits */
9485 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
9488 /* at least one branch bit must be set */
9489 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
9492 /* propagate priv level, when not set for branch */
9493 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
9495 /* exclude_kernel checked on syscall entry */
9496 if (!attr->exclude_kernel)
9497 mask |= PERF_SAMPLE_BRANCH_KERNEL;
9499 if (!attr->exclude_user)
9500 mask |= PERF_SAMPLE_BRANCH_USER;
9502 if (!attr->exclude_hv)
9503 mask |= PERF_SAMPLE_BRANCH_HV;
9505 * adjust user setting (for HW filter setup)
9507 attr->branch_sample_type = mask;
9509 /* privileged levels capture (kernel, hv): check permissions */
9510 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
9511 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9515 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
9516 ret = perf_reg_validate(attr->sample_regs_user);
9521 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
9522 if (!arch_perf_have_user_stack_dump())
9526 * We have __u32 type for the size, but so far
9527 * we can only use __u16 as maximum due to the
9528 * __u16 sample size limit.
9530 if (attr->sample_stack_user >= USHRT_MAX)
9532 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
9536 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
9537 ret = perf_reg_validate(attr->sample_regs_intr);
9542 put_user(sizeof(*attr), &uattr->size);
9547 static void mutex_lock_double(struct mutex *a, struct mutex *b)
9553 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
9557 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
9559 struct ring_buffer *rb = NULL;
9562 if (!output_event) {
9563 mutex_lock(&event->mmap_mutex);
9567 /* don't allow circular references */
9568 if (event == output_event)
9572 * Don't allow cross-cpu buffers
9574 if (output_event->cpu != event->cpu)
9578 * If its not a per-cpu rb, it must be the same task.
9580 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
9584 * Mixing clocks in the same buffer is trouble you don't need.
9586 if (output_event->clock != event->clock)
9590 * Either writing ring buffer from beginning or from end.
9591 * Mixing is not allowed.
9593 if (is_write_backward(output_event) != is_write_backward(event))
9597 * If both events generate aux data, they must be on the same PMU
9599 if (has_aux(event) && has_aux(output_event) &&
9600 event->pmu != output_event->pmu)
9604 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
9605 * output_event is already on rb->event_list, and the list iteration
9606 * restarts after every removal, it is guaranteed this new event is
9607 * observed *OR* if output_event is already removed, it's guaranteed we
9608 * observe !rb->mmap_count.
9610 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
9612 /* Can't redirect output if we've got an active mmap() */
9613 if (atomic_read(&event->mmap_count))
9617 /* get the rb we want to redirect to */
9618 rb = ring_buffer_get(output_event);
9622 /* did we race against perf_mmap_close() */
9623 if (!atomic_read(&rb->mmap_count)) {
9624 ring_buffer_put(rb);
9629 ring_buffer_attach(event, rb);
9633 mutex_unlock(&event->mmap_mutex);
9635 mutex_unlock(&output_event->mmap_mutex);
9641 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
9643 bool nmi_safe = false;
9646 case CLOCK_MONOTONIC:
9647 event->clock = &ktime_get_mono_fast_ns;
9651 case CLOCK_MONOTONIC_RAW:
9652 event->clock = &ktime_get_raw_fast_ns;
9656 case CLOCK_REALTIME:
9657 event->clock = &ktime_get_real_ns;
9660 case CLOCK_BOOTTIME:
9661 event->clock = &ktime_get_boot_ns;
9665 event->clock = &ktime_get_tai_ns;
9672 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
9679 * Variation on perf_event_ctx_lock_nested(), except we take two context
9682 static struct perf_event_context *
9683 __perf_event_ctx_lock_double(struct perf_event *group_leader,
9684 struct perf_event_context *ctx)
9686 struct perf_event_context *gctx;
9690 gctx = READ_ONCE(group_leader->ctx);
9691 if (!atomic_inc_not_zero(&gctx->refcount)) {
9697 mutex_lock_double(&gctx->mutex, &ctx->mutex);
9699 if (group_leader->ctx != gctx) {
9700 mutex_unlock(&ctx->mutex);
9701 mutex_unlock(&gctx->mutex);
9710 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9712 * @attr_uptr: event_id type attributes for monitoring/sampling
9715 * @group_fd: group leader event fd
9717 SYSCALL_DEFINE5(perf_event_open,
9718 struct perf_event_attr __user *, attr_uptr,
9719 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
9721 struct perf_event *group_leader = NULL, *output_event = NULL;
9722 struct perf_event *event, *sibling;
9723 struct perf_event_attr attr;
9724 struct perf_event_context *ctx, *uninitialized_var(gctx);
9725 struct file *event_file = NULL;
9726 struct fd group = {NULL, 0};
9727 struct task_struct *task = NULL;
9732 int f_flags = O_RDWR;
9735 /* for future expandability... */
9736 if (flags & ~PERF_FLAG_ALL)
9739 err = perf_copy_attr(attr_uptr, &attr);
9743 if (!attr.exclude_kernel) {
9744 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9749 if (attr.sample_freq > sysctl_perf_event_sample_rate)
9752 if (attr.sample_period & (1ULL << 63))
9756 if (!attr.sample_max_stack)
9757 attr.sample_max_stack = sysctl_perf_event_max_stack;
9760 * In cgroup mode, the pid argument is used to pass the fd
9761 * opened to the cgroup directory in cgroupfs. The cpu argument
9762 * designates the cpu on which to monitor threads from that
9765 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
9768 if (flags & PERF_FLAG_FD_CLOEXEC)
9769 f_flags |= O_CLOEXEC;
9771 event_fd = get_unused_fd_flags(f_flags);
9775 if (group_fd != -1) {
9776 err = perf_fget_light(group_fd, &group);
9779 group_leader = group.file->private_data;
9780 if (flags & PERF_FLAG_FD_OUTPUT)
9781 output_event = group_leader;
9782 if (flags & PERF_FLAG_FD_NO_GROUP)
9783 group_leader = NULL;
9786 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
9787 task = find_lively_task_by_vpid(pid);
9789 err = PTR_ERR(task);
9794 if (task && group_leader &&
9795 group_leader->attr.inherit != attr.inherit) {
9803 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
9808 * Reuse ptrace permission checks for now.
9810 * We must hold cred_guard_mutex across this and any potential
9811 * perf_install_in_context() call for this new event to
9812 * serialize against exec() altering our credentials (and the
9813 * perf_event_exit_task() that could imply).
9816 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
9820 if (flags & PERF_FLAG_PID_CGROUP)
9823 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
9824 NULL, NULL, cgroup_fd);
9825 if (IS_ERR(event)) {
9826 err = PTR_ERR(event);
9830 if (is_sampling_event(event)) {
9831 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
9838 * Special case software events and allow them to be part of
9839 * any hardware group.
9843 if (attr.use_clockid) {
9844 err = perf_event_set_clock(event, attr.clockid);
9849 if (pmu->task_ctx_nr == perf_sw_context)
9850 event->event_caps |= PERF_EV_CAP_SOFTWARE;
9853 (is_software_event(event) != is_software_event(group_leader))) {
9854 if (is_software_event(event)) {
9856 * If event and group_leader are not both a software
9857 * event, and event is, then group leader is not.
9859 * Allow the addition of software events to !software
9860 * groups, this is safe because software events never
9863 pmu = group_leader->pmu;
9864 } else if (is_software_event(group_leader) &&
9865 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
9867 * In case the group is a pure software group, and we
9868 * try to add a hardware event, move the whole group to
9869 * the hardware context.
9876 * Get the target context (task or percpu):
9878 ctx = find_get_context(pmu, task, event);
9884 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
9890 * Look up the group leader (we will attach this event to it):
9896 * Do not allow a recursive hierarchy (this new sibling
9897 * becoming part of another group-sibling):
9899 if (group_leader->group_leader != group_leader)
9902 /* All events in a group should have the same clock */
9903 if (group_leader->clock != event->clock)
9907 * Make sure we're both events for the same CPU;
9908 * grouping events for different CPUs is broken; since
9909 * you can never concurrently schedule them anyhow.
9911 if (group_leader->cpu != event->cpu)
9915 * Make sure we're both on the same task, or both
9918 if (group_leader->ctx->task != ctx->task)
9922 * Do not allow to attach to a group in a different task
9923 * or CPU context. If we're moving SW events, we'll fix
9924 * this up later, so allow that.
9926 * Racy, not holding group_leader->ctx->mutex, see comment with
9927 * perf_event_ctx_lock().
9929 if (!move_group && group_leader->ctx != ctx)
9933 * Only a group leader can be exclusive or pinned
9935 if (attr.exclusive || attr.pinned)
9940 err = perf_event_set_output(event, output_event);
9945 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
9947 if (IS_ERR(event_file)) {
9948 err = PTR_ERR(event_file);
9954 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
9956 if (gctx->task == TASK_TOMBSTONE) {
9962 * Check if we raced against another sys_perf_event_open() call
9963 * moving the software group underneath us.
9965 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
9967 * If someone moved the group out from under us, check
9968 * if this new event wound up on the same ctx, if so
9969 * its the regular !move_group case, otherwise fail.
9975 perf_event_ctx_unlock(group_leader, gctx);
9977 goto not_move_group;
9981 mutex_lock(&ctx->mutex);
9984 * Now that we hold ctx->lock, (re)validate group_leader->ctx == ctx,
9985 * see the group_leader && !move_group test earlier.
9987 if (group_leader && group_leader->ctx != ctx) {
9994 if (ctx->task == TASK_TOMBSTONE) {
9999 if (!perf_event_validate_size(event)) {
10005 * Must be under the same ctx::mutex as perf_install_in_context(),
10006 * because we need to serialize with concurrent event creation.
10008 if (!exclusive_event_installable(event, ctx)) {
10009 /* exclusive and group stuff are assumed mutually exclusive */
10010 WARN_ON_ONCE(move_group);
10016 WARN_ON_ONCE(ctx->parent_ctx);
10019 * This is the point on no return; we cannot fail hereafter. This is
10020 * where we start modifying current state.
10025 * See perf_event_ctx_lock() for comments on the details
10026 * of swizzling perf_event::ctx.
10028 perf_remove_from_context(group_leader, 0);
10030 list_for_each_entry(sibling, &group_leader->sibling_list,
10032 perf_remove_from_context(sibling, 0);
10037 * Wait for everybody to stop referencing the events through
10038 * the old lists, before installing it on new lists.
10043 * Install the group siblings before the group leader.
10045 * Because a group leader will try and install the entire group
10046 * (through the sibling list, which is still in-tact), we can
10047 * end up with siblings installed in the wrong context.
10049 * By installing siblings first we NO-OP because they're not
10050 * reachable through the group lists.
10052 list_for_each_entry(sibling, &group_leader->sibling_list,
10054 perf_event__state_init(sibling);
10055 perf_install_in_context(ctx, sibling, sibling->cpu);
10060 * Removing from the context ends up with disabled
10061 * event. What we want here is event in the initial
10062 * startup state, ready to be add into new context.
10064 perf_event__state_init(group_leader);
10065 perf_install_in_context(ctx, group_leader, group_leader->cpu);
10069 * Now that all events are installed in @ctx, nothing
10070 * references @gctx anymore, so drop the last reference we have
10077 * Precalculate sample_data sizes; do while holding ctx::mutex such
10078 * that we're serialized against further additions and before
10079 * perf_install_in_context() which is the point the event is active and
10080 * can use these values.
10082 perf_event__header_size(event);
10083 perf_event__id_header_size(event);
10085 event->owner = current;
10087 perf_install_in_context(ctx, event, event->cpu);
10088 perf_unpin_context(ctx);
10091 perf_event_ctx_unlock(group_leader, gctx);
10092 mutex_unlock(&ctx->mutex);
10095 mutex_unlock(&task->signal->cred_guard_mutex);
10096 put_task_struct(task);
10101 mutex_lock(¤t->perf_event_mutex);
10102 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
10103 mutex_unlock(¤t->perf_event_mutex);
10106 * Drop the reference on the group_event after placing the
10107 * new event on the sibling_list. This ensures destruction
10108 * of the group leader will find the pointer to itself in
10109 * perf_group_detach().
10112 fd_install(event_fd, event_file);
10117 perf_event_ctx_unlock(group_leader, gctx);
10118 mutex_unlock(&ctx->mutex);
10122 perf_unpin_context(ctx);
10126 * If event_file is set, the fput() above will have called ->release()
10127 * and that will take care of freeing the event.
10133 mutex_unlock(&task->signal->cred_guard_mutex);
10138 put_task_struct(task);
10142 put_unused_fd(event_fd);
10147 * perf_event_create_kernel_counter
10149 * @attr: attributes of the counter to create
10150 * @cpu: cpu in which the counter is bound
10151 * @task: task to profile (NULL for percpu)
10153 struct perf_event *
10154 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
10155 struct task_struct *task,
10156 perf_overflow_handler_t overflow_handler,
10159 struct perf_event_context *ctx;
10160 struct perf_event *event;
10164 * Get the target context (task or percpu):
10167 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
10168 overflow_handler, context, -1);
10169 if (IS_ERR(event)) {
10170 err = PTR_ERR(event);
10174 /* Mark owner so we could distinguish it from user events. */
10175 event->owner = TASK_TOMBSTONE;
10177 ctx = find_get_context(event->pmu, task, event);
10179 err = PTR_ERR(ctx);
10183 WARN_ON_ONCE(ctx->parent_ctx);
10184 mutex_lock(&ctx->mutex);
10185 if (ctx->task == TASK_TOMBSTONE) {
10190 if (!exclusive_event_installable(event, ctx)) {
10195 perf_install_in_context(ctx, event, event->cpu);
10196 perf_unpin_context(ctx);
10197 mutex_unlock(&ctx->mutex);
10202 mutex_unlock(&ctx->mutex);
10203 perf_unpin_context(ctx);
10208 return ERR_PTR(err);
10210 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
10212 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
10214 struct perf_event_context *src_ctx;
10215 struct perf_event_context *dst_ctx;
10216 struct perf_event *event, *tmp;
10219 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
10220 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
10223 * See perf_event_ctx_lock() for comments on the details
10224 * of swizzling perf_event::ctx.
10226 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
10227 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
10229 perf_remove_from_context(event, 0);
10230 unaccount_event_cpu(event, src_cpu);
10232 list_add(&event->migrate_entry, &events);
10236 * Wait for the events to quiesce before re-instating them.
10241 * Re-instate events in 2 passes.
10243 * Skip over group leaders and only install siblings on this first
10244 * pass, siblings will not get enabled without a leader, however a
10245 * leader will enable its siblings, even if those are still on the old
10248 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10249 if (event->group_leader == event)
10252 list_del(&event->migrate_entry);
10253 if (event->state >= PERF_EVENT_STATE_OFF)
10254 event->state = PERF_EVENT_STATE_INACTIVE;
10255 account_event_cpu(event, dst_cpu);
10256 perf_install_in_context(dst_ctx, event, dst_cpu);
10261 * Once all the siblings are setup properly, install the group leaders
10264 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10265 list_del(&event->migrate_entry);
10266 if (event->state >= PERF_EVENT_STATE_OFF)
10267 event->state = PERF_EVENT_STATE_INACTIVE;
10268 account_event_cpu(event, dst_cpu);
10269 perf_install_in_context(dst_ctx, event, dst_cpu);
10272 mutex_unlock(&dst_ctx->mutex);
10273 mutex_unlock(&src_ctx->mutex);
10275 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
10277 static void sync_child_event(struct perf_event *child_event,
10278 struct task_struct *child)
10280 struct perf_event *parent_event = child_event->parent;
10283 if (child_event->attr.inherit_stat)
10284 perf_event_read_event(child_event, child);
10286 child_val = perf_event_count(child_event);
10289 * Add back the child's count to the parent's count:
10291 atomic64_add(child_val, &parent_event->child_count);
10292 atomic64_add(child_event->total_time_enabled,
10293 &parent_event->child_total_time_enabled);
10294 atomic64_add(child_event->total_time_running,
10295 &parent_event->child_total_time_running);
10299 perf_event_exit_event(struct perf_event *child_event,
10300 struct perf_event_context *child_ctx,
10301 struct task_struct *child)
10303 struct perf_event *parent_event = child_event->parent;
10306 * Do not destroy the 'original' grouping; because of the context
10307 * switch optimization the original events could've ended up in a
10308 * random child task.
10310 * If we were to destroy the original group, all group related
10311 * operations would cease to function properly after this random
10314 * Do destroy all inherited groups, we don't care about those
10315 * and being thorough is better.
10317 raw_spin_lock_irq(&child_ctx->lock);
10318 WARN_ON_ONCE(child_ctx->is_active);
10321 perf_group_detach(child_event);
10322 list_del_event(child_event, child_ctx);
10323 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
10324 raw_spin_unlock_irq(&child_ctx->lock);
10327 * Parent events are governed by their filedesc, retain them.
10329 if (!parent_event) {
10330 perf_event_wakeup(child_event);
10334 * Child events can be cleaned up.
10337 sync_child_event(child_event, child);
10340 * Remove this event from the parent's list
10342 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
10343 mutex_lock(&parent_event->child_mutex);
10344 list_del_init(&child_event->child_list);
10345 mutex_unlock(&parent_event->child_mutex);
10348 * Kick perf_poll() for is_event_hup().
10350 perf_event_wakeup(parent_event);
10351 free_event(child_event);
10352 put_event(parent_event);
10355 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
10357 struct perf_event_context *child_ctx, *clone_ctx = NULL;
10358 struct perf_event *child_event, *next;
10360 WARN_ON_ONCE(child != current);
10362 child_ctx = perf_pin_task_context(child, ctxn);
10367 * In order to reduce the amount of tricky in ctx tear-down, we hold
10368 * ctx::mutex over the entire thing. This serializes against almost
10369 * everything that wants to access the ctx.
10371 * The exception is sys_perf_event_open() /
10372 * perf_event_create_kernel_count() which does find_get_context()
10373 * without ctx::mutex (it cannot because of the move_group double mutex
10374 * lock thing). See the comments in perf_install_in_context().
10376 mutex_lock(&child_ctx->mutex);
10379 * In a single ctx::lock section, de-schedule the events and detach the
10380 * context from the task such that we cannot ever get it scheduled back
10383 raw_spin_lock_irq(&child_ctx->lock);
10384 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
10387 * Now that the context is inactive, destroy the task <-> ctx relation
10388 * and mark the context dead.
10390 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
10391 put_ctx(child_ctx); /* cannot be last */
10392 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
10393 put_task_struct(current); /* cannot be last */
10395 clone_ctx = unclone_ctx(child_ctx);
10396 raw_spin_unlock_irq(&child_ctx->lock);
10399 put_ctx(clone_ctx);
10402 * Report the task dead after unscheduling the events so that we
10403 * won't get any samples after PERF_RECORD_EXIT. We can however still
10404 * get a few PERF_RECORD_READ events.
10406 perf_event_task(child, child_ctx, 0);
10408 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
10409 perf_event_exit_event(child_event, child_ctx, child);
10411 mutex_unlock(&child_ctx->mutex);
10413 put_ctx(child_ctx);
10417 * When a child task exits, feed back event values to parent events.
10419 * Can be called with cred_guard_mutex held when called from
10420 * install_exec_creds().
10422 void perf_event_exit_task(struct task_struct *child)
10424 struct perf_event *event, *tmp;
10427 mutex_lock(&child->perf_event_mutex);
10428 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
10430 list_del_init(&event->owner_entry);
10433 * Ensure the list deletion is visible before we clear
10434 * the owner, closes a race against perf_release() where
10435 * we need to serialize on the owner->perf_event_mutex.
10437 smp_store_release(&event->owner, NULL);
10439 mutex_unlock(&child->perf_event_mutex);
10441 for_each_task_context_nr(ctxn)
10442 perf_event_exit_task_context(child, ctxn);
10445 * The perf_event_exit_task_context calls perf_event_task
10446 * with child's task_ctx, which generates EXIT events for
10447 * child contexts and sets child->perf_event_ctxp[] to NULL.
10448 * At this point we need to send EXIT events to cpu contexts.
10450 perf_event_task(child, NULL, 0);
10453 static void perf_free_event(struct perf_event *event,
10454 struct perf_event_context *ctx)
10456 struct perf_event *parent = event->parent;
10458 if (WARN_ON_ONCE(!parent))
10461 mutex_lock(&parent->child_mutex);
10462 list_del_init(&event->child_list);
10463 mutex_unlock(&parent->child_mutex);
10467 raw_spin_lock_irq(&ctx->lock);
10468 perf_group_detach(event);
10469 list_del_event(event, ctx);
10470 raw_spin_unlock_irq(&ctx->lock);
10475 * Free an unexposed, unused context as created by inheritance by
10476 * perf_event_init_task below, used by fork() in case of fail.
10478 * Not all locks are strictly required, but take them anyway to be nice and
10479 * help out with the lockdep assertions.
10481 void perf_event_free_task(struct task_struct *task)
10483 struct perf_event_context *ctx;
10484 struct perf_event *event, *tmp;
10487 for_each_task_context_nr(ctxn) {
10488 ctx = task->perf_event_ctxp[ctxn];
10492 mutex_lock(&ctx->mutex);
10493 raw_spin_lock_irq(&ctx->lock);
10495 * Destroy the task <-> ctx relation and mark the context dead.
10497 * This is important because even though the task hasn't been
10498 * exposed yet the context has been (through child_list).
10500 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
10501 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
10502 put_task_struct(task); /* cannot be last */
10503 raw_spin_unlock_irq(&ctx->lock);
10505 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
10507 perf_free_event(event, ctx);
10509 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
10511 perf_free_event(event, ctx);
10513 if (!list_empty(&ctx->pinned_groups) ||
10514 !list_empty(&ctx->flexible_groups))
10517 mutex_unlock(&ctx->mutex);
10523 void perf_event_delayed_put(struct task_struct *task)
10527 for_each_task_context_nr(ctxn)
10528 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
10531 struct file *perf_event_get(unsigned int fd)
10535 file = fget_raw(fd);
10537 return ERR_PTR(-EBADF);
10539 if (file->f_op != &perf_fops) {
10541 return ERR_PTR(-EBADF);
10547 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
10550 return ERR_PTR(-EINVAL);
10552 return &event->attr;
10556 * inherit a event from parent task to child task:
10558 static struct perf_event *
10559 inherit_event(struct perf_event *parent_event,
10560 struct task_struct *parent,
10561 struct perf_event_context *parent_ctx,
10562 struct task_struct *child,
10563 struct perf_event *group_leader,
10564 struct perf_event_context *child_ctx)
10566 enum perf_event_active_state parent_state = parent_event->state;
10567 struct perf_event *child_event;
10568 unsigned long flags;
10571 * Instead of creating recursive hierarchies of events,
10572 * we link inherited events back to the original parent,
10573 * which has a filp for sure, which we use as the reference
10576 if (parent_event->parent)
10577 parent_event = parent_event->parent;
10579 child_event = perf_event_alloc(&parent_event->attr,
10582 group_leader, parent_event,
10584 if (IS_ERR(child_event))
10585 return child_event;
10588 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
10589 * must be under the same lock in order to serialize against
10590 * perf_event_release_kernel(), such that either we must observe
10591 * is_orphaned_event() or they will observe us on the child_list.
10593 mutex_lock(&parent_event->child_mutex);
10594 if (is_orphaned_event(parent_event) ||
10595 !atomic_long_inc_not_zero(&parent_event->refcount)) {
10596 mutex_unlock(&parent_event->child_mutex);
10597 free_event(child_event);
10601 get_ctx(child_ctx);
10604 * Make the child state follow the state of the parent event,
10605 * not its attr.disabled bit. We hold the parent's mutex,
10606 * so we won't race with perf_event_{en, dis}able_family.
10608 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
10609 child_event->state = PERF_EVENT_STATE_INACTIVE;
10611 child_event->state = PERF_EVENT_STATE_OFF;
10613 if (parent_event->attr.freq) {
10614 u64 sample_period = parent_event->hw.sample_period;
10615 struct hw_perf_event *hwc = &child_event->hw;
10617 hwc->sample_period = sample_period;
10618 hwc->last_period = sample_period;
10620 local64_set(&hwc->period_left, sample_period);
10623 child_event->ctx = child_ctx;
10624 child_event->overflow_handler = parent_event->overflow_handler;
10625 child_event->overflow_handler_context
10626 = parent_event->overflow_handler_context;
10629 * Precalculate sample_data sizes
10631 perf_event__header_size(child_event);
10632 perf_event__id_header_size(child_event);
10635 * Link it up in the child's context:
10637 raw_spin_lock_irqsave(&child_ctx->lock, flags);
10638 add_event_to_ctx(child_event, child_ctx);
10639 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
10642 * Link this into the parent event's child list
10644 list_add_tail(&child_event->child_list, &parent_event->child_list);
10645 mutex_unlock(&parent_event->child_mutex);
10647 return child_event;
10650 static int inherit_group(struct perf_event *parent_event,
10651 struct task_struct *parent,
10652 struct perf_event_context *parent_ctx,
10653 struct task_struct *child,
10654 struct perf_event_context *child_ctx)
10656 struct perf_event *leader;
10657 struct perf_event *sub;
10658 struct perf_event *child_ctr;
10660 leader = inherit_event(parent_event, parent, parent_ctx,
10661 child, NULL, child_ctx);
10662 if (IS_ERR(leader))
10663 return PTR_ERR(leader);
10664 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
10665 child_ctr = inherit_event(sub, parent, parent_ctx,
10666 child, leader, child_ctx);
10667 if (IS_ERR(child_ctr))
10668 return PTR_ERR(child_ctr);
10674 inherit_task_group(struct perf_event *event, struct task_struct *parent,
10675 struct perf_event_context *parent_ctx,
10676 struct task_struct *child, int ctxn,
10677 int *inherited_all)
10680 struct perf_event_context *child_ctx;
10682 if (!event->attr.inherit) {
10683 *inherited_all = 0;
10687 child_ctx = child->perf_event_ctxp[ctxn];
10690 * This is executed from the parent task context, so
10691 * inherit events that have been marked for cloning.
10692 * First allocate and initialize a context for the
10696 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
10700 child->perf_event_ctxp[ctxn] = child_ctx;
10703 ret = inherit_group(event, parent, parent_ctx,
10707 *inherited_all = 0;
10713 * Initialize the perf_event context in task_struct
10715 static int perf_event_init_context(struct task_struct *child, int ctxn)
10717 struct perf_event_context *child_ctx, *parent_ctx;
10718 struct perf_event_context *cloned_ctx;
10719 struct perf_event *event;
10720 struct task_struct *parent = current;
10721 int inherited_all = 1;
10722 unsigned long flags;
10725 if (likely(!parent->perf_event_ctxp[ctxn]))
10729 * If the parent's context is a clone, pin it so it won't get
10730 * swapped under us.
10732 parent_ctx = perf_pin_task_context(parent, ctxn);
10737 * No need to check if parent_ctx != NULL here; since we saw
10738 * it non-NULL earlier, the only reason for it to become NULL
10739 * is if we exit, and since we're currently in the middle of
10740 * a fork we can't be exiting at the same time.
10744 * Lock the parent list. No need to lock the child - not PID
10745 * hashed yet and not running, so nobody can access it.
10747 mutex_lock(&parent_ctx->mutex);
10750 * We dont have to disable NMIs - we are only looking at
10751 * the list, not manipulating it:
10753 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
10754 ret = inherit_task_group(event, parent, parent_ctx,
10755 child, ctxn, &inherited_all);
10761 * We can't hold ctx->lock when iterating the ->flexible_group list due
10762 * to allocations, but we need to prevent rotation because
10763 * rotate_ctx() will change the list from interrupt context.
10765 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10766 parent_ctx->rotate_disable = 1;
10767 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10769 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
10770 ret = inherit_task_group(event, parent, parent_ctx,
10771 child, ctxn, &inherited_all);
10776 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10777 parent_ctx->rotate_disable = 0;
10779 child_ctx = child->perf_event_ctxp[ctxn];
10781 if (child_ctx && inherited_all) {
10783 * Mark the child context as a clone of the parent
10784 * context, or of whatever the parent is a clone of.
10786 * Note that if the parent is a clone, the holding of
10787 * parent_ctx->lock avoids it from being uncloned.
10789 cloned_ctx = parent_ctx->parent_ctx;
10791 child_ctx->parent_ctx = cloned_ctx;
10792 child_ctx->parent_gen = parent_ctx->parent_gen;
10794 child_ctx->parent_ctx = parent_ctx;
10795 child_ctx->parent_gen = parent_ctx->generation;
10797 get_ctx(child_ctx->parent_ctx);
10800 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10802 mutex_unlock(&parent_ctx->mutex);
10804 perf_unpin_context(parent_ctx);
10805 put_ctx(parent_ctx);
10811 * Initialize the perf_event context in task_struct
10813 int perf_event_init_task(struct task_struct *child)
10817 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
10818 mutex_init(&child->perf_event_mutex);
10819 INIT_LIST_HEAD(&child->perf_event_list);
10821 for_each_task_context_nr(ctxn) {
10822 ret = perf_event_init_context(child, ctxn);
10824 perf_event_free_task(child);
10832 static void __init perf_event_init_all_cpus(void)
10834 struct swevent_htable *swhash;
10837 for_each_possible_cpu(cpu) {
10838 swhash = &per_cpu(swevent_htable, cpu);
10839 mutex_init(&swhash->hlist_mutex);
10840 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
10842 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
10843 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
10845 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
10849 int perf_event_init_cpu(unsigned int cpu)
10851 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10853 mutex_lock(&swhash->hlist_mutex);
10854 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
10855 struct swevent_hlist *hlist;
10857 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
10859 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10861 mutex_unlock(&swhash->hlist_mutex);
10865 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
10866 static void __perf_event_exit_context(void *__info)
10868 struct perf_event_context *ctx = __info;
10869 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
10870 struct perf_event *event;
10872 raw_spin_lock(&ctx->lock);
10873 list_for_each_entry(event, &ctx->event_list, event_entry)
10874 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
10875 raw_spin_unlock(&ctx->lock);
10878 static void perf_event_exit_cpu_context(int cpu)
10880 struct perf_event_context *ctx;
10884 idx = srcu_read_lock(&pmus_srcu);
10885 list_for_each_entry_rcu(pmu, &pmus, entry) {
10886 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
10888 mutex_lock(&ctx->mutex);
10889 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
10890 mutex_unlock(&ctx->mutex);
10892 srcu_read_unlock(&pmus_srcu, idx);
10896 static void perf_event_exit_cpu_context(int cpu) { }
10900 int perf_event_exit_cpu(unsigned int cpu)
10902 perf_event_exit_cpu_context(cpu);
10907 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
10911 for_each_online_cpu(cpu)
10912 perf_event_exit_cpu(cpu);
10918 * Run the perf reboot notifier at the very last possible moment so that
10919 * the generic watchdog code runs as long as possible.
10921 static struct notifier_block perf_reboot_notifier = {
10922 .notifier_call = perf_reboot,
10923 .priority = INT_MIN,
10926 void __init perf_event_init(void)
10930 idr_init(&pmu_idr);
10932 perf_event_init_all_cpus();
10933 init_srcu_struct(&pmus_srcu);
10934 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
10935 perf_pmu_register(&perf_cpu_clock, NULL, -1);
10936 perf_pmu_register(&perf_task_clock, NULL, -1);
10937 perf_tp_register();
10938 perf_event_init_cpu(smp_processor_id());
10939 register_reboot_notifier(&perf_reboot_notifier);
10941 ret = init_hw_breakpoint();
10942 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
10945 * Build time assertion that we keep the data_head at the intended
10946 * location. IOW, validation we got the __reserved[] size right.
10948 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
10952 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
10955 struct perf_pmu_events_attr *pmu_attr =
10956 container_of(attr, struct perf_pmu_events_attr, attr);
10958 if (pmu_attr->event_str)
10959 return sprintf(page, "%s\n", pmu_attr->event_str);
10963 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
10965 static int __init perf_event_sysfs_init(void)
10970 mutex_lock(&pmus_lock);
10972 ret = bus_register(&pmu_bus);
10976 list_for_each_entry(pmu, &pmus, entry) {
10977 if (!pmu->name || pmu->type < 0)
10980 ret = pmu_dev_alloc(pmu);
10981 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
10983 pmu_bus_running = 1;
10987 mutex_unlock(&pmus_lock);
10991 device_initcall(perf_event_sysfs_init);
10993 #ifdef CONFIG_CGROUP_PERF
10994 static struct cgroup_subsys_state *
10995 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10997 struct perf_cgroup *jc;
10999 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
11001 return ERR_PTR(-ENOMEM);
11003 jc->info = alloc_percpu(struct perf_cgroup_info);
11006 return ERR_PTR(-ENOMEM);
11012 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
11014 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
11016 free_percpu(jc->info);
11020 static int __perf_cgroup_move(void *info)
11022 struct task_struct *task = info;
11024 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
11029 static void perf_cgroup_attach(struct cgroup_taskset *tset)
11031 struct task_struct *task;
11032 struct cgroup_subsys_state *css;
11034 cgroup_taskset_for_each(task, css, tset)
11035 task_function_call(task, __perf_cgroup_move, task);
11038 struct cgroup_subsys perf_event_cgrp_subsys = {
11039 .css_alloc = perf_cgroup_css_alloc,
11040 .css_free = perf_cgroup_css_free,
11041 .attach = perf_cgroup_attach,
11043 #endif /* CONFIG_CGROUP_PERF */