2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
52 #include <asm/irq_regs.h>
54 typedef int (*remote_function_f)(void *);
56 struct remote_function_call {
57 struct task_struct *p;
58 remote_function_f func;
63 static void remote_function(void *data)
65 struct remote_function_call *tfc = data;
66 struct task_struct *p = tfc->p;
70 if (task_cpu(p) != smp_processor_id())
74 * Now that we're on right CPU with IRQs disabled, we can test
75 * if we hit the right task without races.
78 tfc->ret = -ESRCH; /* No such (running) process */
83 tfc->ret = tfc->func(tfc->info);
87 * task_function_call - call a function on the cpu on which a task runs
88 * @p: the task to evaluate
89 * @func: the function to be called
90 * @info: the function call argument
92 * Calls the function @func when the task is currently running. This might
93 * be on the current CPU, which just calls the function directly
95 * returns: @func return value, or
96 * -ESRCH - when the process isn't running
97 * -EAGAIN - when the process moved away
100 task_function_call(struct task_struct *p, remote_function_f func, void *info)
102 struct remote_function_call data = {
111 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
114 } while (ret == -EAGAIN);
120 * cpu_function_call - call a function on the cpu
121 * @func: the function to be called
122 * @info: the function call argument
124 * Calls the function @func on the remote cpu.
126 * returns: @func return value or -ENXIO when the cpu is offline
128 static int cpu_function_call(int cpu, remote_function_f func, void *info)
130 struct remote_function_call data = {
134 .ret = -ENXIO, /* No such CPU */
137 smp_call_function_single(cpu, remote_function, &data, 1);
142 static inline struct perf_cpu_context *
143 __get_cpu_context(struct perf_event_context *ctx)
145 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
148 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
149 struct perf_event_context *ctx)
151 raw_spin_lock(&cpuctx->ctx.lock);
153 raw_spin_lock(&ctx->lock);
156 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
157 struct perf_event_context *ctx)
160 raw_spin_unlock(&ctx->lock);
161 raw_spin_unlock(&cpuctx->ctx.lock);
164 #define TASK_TOMBSTONE ((void *)-1L)
166 static bool is_kernel_event(struct perf_event *event)
168 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
172 * On task ctx scheduling...
174 * When !ctx->nr_events a task context will not be scheduled. This means
175 * we can disable the scheduler hooks (for performance) without leaving
176 * pending task ctx state.
178 * This however results in two special cases:
180 * - removing the last event from a task ctx; this is relatively straight
181 * forward and is done in __perf_remove_from_context.
183 * - adding the first event to a task ctx; this is tricky because we cannot
184 * rely on ctx->is_active and therefore cannot use event_function_call().
185 * See perf_install_in_context().
187 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
190 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
191 struct perf_event_context *, void *);
193 struct event_function_struct {
194 struct perf_event *event;
199 static int event_function(void *info)
201 struct event_function_struct *efs = info;
202 struct perf_event *event = efs->event;
203 struct perf_event_context *ctx = event->ctx;
204 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
205 struct perf_event_context *task_ctx = cpuctx->task_ctx;
208 WARN_ON_ONCE(!irqs_disabled());
210 perf_ctx_lock(cpuctx, task_ctx);
212 * Since we do the IPI call without holding ctx->lock things can have
213 * changed, double check we hit the task we set out to hit.
216 if (ctx->task != current) {
222 * We only use event_function_call() on established contexts,
223 * and event_function() is only ever called when active (or
224 * rather, we'll have bailed in task_function_call() or the
225 * above ctx->task != current test), therefore we must have
226 * ctx->is_active here.
228 WARN_ON_ONCE(!ctx->is_active);
230 * And since we have ctx->is_active, cpuctx->task_ctx must
233 WARN_ON_ONCE(task_ctx != ctx);
235 WARN_ON_ONCE(&cpuctx->ctx != ctx);
238 efs->func(event, cpuctx, ctx, efs->data);
240 perf_ctx_unlock(cpuctx, task_ctx);
245 static void event_function_local(struct perf_event *event, event_f func, void *data)
247 struct event_function_struct efs = {
253 int ret = event_function(&efs);
257 static void event_function_call(struct perf_event *event, event_f func, void *data)
259 struct perf_event_context *ctx = event->ctx;
260 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
261 struct event_function_struct efs = {
267 if (!event->parent) {
269 * If this is a !child event, we must hold ctx::mutex to
270 * stabilize the the event->ctx relation. See
271 * perf_event_ctx_lock().
273 lockdep_assert_held(&ctx->mutex);
277 cpu_function_call(event->cpu, event_function, &efs);
281 if (task == TASK_TOMBSTONE)
285 if (!task_function_call(task, event_function, &efs))
288 raw_spin_lock_irq(&ctx->lock);
290 * Reload the task pointer, it might have been changed by
291 * a concurrent perf_event_context_sched_out().
294 if (task == TASK_TOMBSTONE) {
295 raw_spin_unlock_irq(&ctx->lock);
298 if (ctx->is_active) {
299 raw_spin_unlock_irq(&ctx->lock);
302 func(event, NULL, ctx, data);
303 raw_spin_unlock_irq(&ctx->lock);
306 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
307 PERF_FLAG_FD_OUTPUT |\
308 PERF_FLAG_PID_CGROUP |\
309 PERF_FLAG_FD_CLOEXEC)
312 * branch priv levels that need permission checks
314 #define PERF_SAMPLE_BRANCH_PERM_PLM \
315 (PERF_SAMPLE_BRANCH_KERNEL |\
316 PERF_SAMPLE_BRANCH_HV)
319 EVENT_FLEXIBLE = 0x1,
322 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
326 * perf_sched_events : >0 events exist
327 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
330 static void perf_sched_delayed(struct work_struct *work);
331 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
332 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
333 static DEFINE_MUTEX(perf_sched_mutex);
334 static atomic_t perf_sched_count;
336 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
337 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
338 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
340 static atomic_t nr_mmap_events __read_mostly;
341 static atomic_t nr_comm_events __read_mostly;
342 static atomic_t nr_task_events __read_mostly;
343 static atomic_t nr_freq_events __read_mostly;
344 static atomic_t nr_switch_events __read_mostly;
346 static LIST_HEAD(pmus);
347 static DEFINE_MUTEX(pmus_lock);
348 static struct srcu_struct pmus_srcu;
351 * perf event paranoia level:
352 * -1 - not paranoid at all
353 * 0 - disallow raw tracepoint access for unpriv
354 * 1 - disallow cpu events for unpriv
355 * 2 - disallow kernel profiling for unpriv
357 int sysctl_perf_event_paranoid __read_mostly = 2;
359 /* Minimum for 512 kiB + 1 user control page */
360 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
363 * max perf event sample rate
365 #define DEFAULT_MAX_SAMPLE_RATE 100000
366 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
367 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
369 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
371 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
372 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
374 static int perf_sample_allowed_ns __read_mostly =
375 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
377 static void update_perf_cpu_limits(void)
379 u64 tmp = perf_sample_period_ns;
381 tmp *= sysctl_perf_cpu_time_max_percent;
382 tmp = div_u64(tmp, 100);
386 WRITE_ONCE(perf_sample_allowed_ns, tmp);
389 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
391 int perf_proc_update_handler(struct ctl_table *table, int write,
392 void __user *buffer, size_t *lenp,
395 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
401 * If throttling is disabled don't allow the write:
403 if (sysctl_perf_cpu_time_max_percent == 100 ||
404 sysctl_perf_cpu_time_max_percent == 0)
407 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
408 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
409 update_perf_cpu_limits();
414 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
416 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
417 void __user *buffer, size_t *lenp,
420 int ret = proc_dointvec(table, write, buffer, lenp, ppos);
425 if (sysctl_perf_cpu_time_max_percent == 100 ||
426 sysctl_perf_cpu_time_max_percent == 0) {
428 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
429 WRITE_ONCE(perf_sample_allowed_ns, 0);
431 update_perf_cpu_limits();
438 * perf samples are done in some very critical code paths (NMIs).
439 * If they take too much CPU time, the system can lock up and not
440 * get any real work done. This will drop the sample rate when
441 * we detect that events are taking too long.
443 #define NR_ACCUMULATED_SAMPLES 128
444 static DEFINE_PER_CPU(u64, running_sample_length);
446 static u64 __report_avg;
447 static u64 __report_allowed;
449 static void perf_duration_warn(struct irq_work *w)
451 printk_ratelimited(KERN_INFO
452 "perf: interrupt took too long (%lld > %lld), lowering "
453 "kernel.perf_event_max_sample_rate to %d\n",
454 __report_avg, __report_allowed,
455 sysctl_perf_event_sample_rate);
458 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
460 void perf_sample_event_took(u64 sample_len_ns)
462 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
470 /* Decay the counter by 1 average sample. */
471 running_len = __this_cpu_read(running_sample_length);
472 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
473 running_len += sample_len_ns;
474 __this_cpu_write(running_sample_length, running_len);
477 * Note: this will be biased artifically low until we have
478 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
479 * from having to maintain a count.
481 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
482 if (avg_len <= max_len)
485 __report_avg = avg_len;
486 __report_allowed = max_len;
489 * Compute a throttle threshold 25% below the current duration.
491 avg_len += avg_len / 4;
492 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
498 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
499 WRITE_ONCE(max_samples_per_tick, max);
501 sysctl_perf_event_sample_rate = max * HZ;
502 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
504 if (!irq_work_queue(&perf_duration_work)) {
505 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
506 "kernel.perf_event_max_sample_rate to %d\n",
507 __report_avg, __report_allowed,
508 sysctl_perf_event_sample_rate);
512 static atomic64_t perf_event_id;
514 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
515 enum event_type_t event_type);
517 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
518 enum event_type_t event_type,
519 struct task_struct *task);
521 static void update_context_time(struct perf_event_context *ctx);
522 static u64 perf_event_time(struct perf_event *event);
524 void __weak perf_event_print_debug(void) { }
526 extern __weak const char *perf_pmu_name(void)
531 static inline u64 perf_clock(void)
533 return local_clock();
536 static inline u64 perf_event_clock(struct perf_event *event)
538 return event->clock();
541 #ifdef CONFIG_CGROUP_PERF
544 perf_cgroup_match(struct perf_event *event)
546 struct perf_event_context *ctx = event->ctx;
547 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
549 /* @event doesn't care about cgroup */
553 /* wants specific cgroup scope but @cpuctx isn't associated with any */
558 * Cgroup scoping is recursive. An event enabled for a cgroup is
559 * also enabled for all its descendant cgroups. If @cpuctx's
560 * cgroup is a descendant of @event's (the test covers identity
561 * case), it's a match.
563 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
564 event->cgrp->css.cgroup);
567 static inline void perf_detach_cgroup(struct perf_event *event)
569 css_put(&event->cgrp->css);
573 static inline int is_cgroup_event(struct perf_event *event)
575 return event->cgrp != NULL;
578 static inline u64 perf_cgroup_event_time(struct perf_event *event)
580 struct perf_cgroup_info *t;
582 t = per_cpu_ptr(event->cgrp->info, event->cpu);
586 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
588 struct perf_cgroup_info *info;
593 info = this_cpu_ptr(cgrp->info);
595 info->time += now - info->timestamp;
596 info->timestamp = now;
599 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
601 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
603 __update_cgrp_time(cgrp_out);
606 static inline void update_cgrp_time_from_event(struct perf_event *event)
608 struct perf_cgroup *cgrp;
611 * ensure we access cgroup data only when needed and
612 * when we know the cgroup is pinned (css_get)
614 if (!is_cgroup_event(event))
617 cgrp = perf_cgroup_from_task(current, event->ctx);
619 * Do not update time when cgroup is not active
621 if (cgrp == event->cgrp)
622 __update_cgrp_time(event->cgrp);
626 perf_cgroup_set_timestamp(struct task_struct *task,
627 struct perf_event_context *ctx)
629 struct perf_cgroup *cgrp;
630 struct perf_cgroup_info *info;
633 * ctx->lock held by caller
634 * ensure we do not access cgroup data
635 * unless we have the cgroup pinned (css_get)
637 if (!task || !ctx->nr_cgroups)
640 cgrp = perf_cgroup_from_task(task, ctx);
641 info = this_cpu_ptr(cgrp->info);
642 info->timestamp = ctx->timestamp;
645 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
646 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
649 * reschedule events based on the cgroup constraint of task.
651 * mode SWOUT : schedule out everything
652 * mode SWIN : schedule in based on cgroup for next
654 static void perf_cgroup_switch(struct task_struct *task, int mode)
656 struct perf_cpu_context *cpuctx;
661 * disable interrupts to avoid geting nr_cgroup
662 * changes via __perf_event_disable(). Also
665 local_irq_save(flags);
668 * we reschedule only in the presence of cgroup
669 * constrained events.
672 list_for_each_entry_rcu(pmu, &pmus, entry) {
673 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
674 if (cpuctx->unique_pmu != pmu)
675 continue; /* ensure we process each cpuctx once */
678 * perf_cgroup_events says at least one
679 * context on this CPU has cgroup events.
681 * ctx->nr_cgroups reports the number of cgroup
682 * events for a context.
684 if (cpuctx->ctx.nr_cgroups > 0) {
685 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
686 perf_pmu_disable(cpuctx->ctx.pmu);
688 if (mode & PERF_CGROUP_SWOUT) {
689 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
691 * must not be done before ctxswout due
692 * to event_filter_match() in event_sched_out()
697 if (mode & PERF_CGROUP_SWIN) {
698 WARN_ON_ONCE(cpuctx->cgrp);
700 * set cgrp before ctxsw in to allow
701 * event_filter_match() to not have to pass
703 * we pass the cpuctx->ctx to perf_cgroup_from_task()
704 * because cgorup events are only per-cpu
706 cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
707 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
709 perf_pmu_enable(cpuctx->ctx.pmu);
710 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
714 local_irq_restore(flags);
717 static inline void perf_cgroup_sched_out(struct task_struct *task,
718 struct task_struct *next)
720 struct perf_cgroup *cgrp1;
721 struct perf_cgroup *cgrp2 = NULL;
725 * we come here when we know perf_cgroup_events > 0
726 * we do not need to pass the ctx here because we know
727 * we are holding the rcu lock
729 cgrp1 = perf_cgroup_from_task(task, NULL);
730 cgrp2 = perf_cgroup_from_task(next, NULL);
733 * only schedule out current cgroup events if we know
734 * that we are switching to a different cgroup. Otherwise,
735 * do no touch the cgroup events.
738 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
743 static inline void perf_cgroup_sched_in(struct task_struct *prev,
744 struct task_struct *task)
746 struct perf_cgroup *cgrp1;
747 struct perf_cgroup *cgrp2 = NULL;
751 * we come here when we know perf_cgroup_events > 0
752 * we do not need to pass the ctx here because we know
753 * we are holding the rcu lock
755 cgrp1 = perf_cgroup_from_task(task, NULL);
756 cgrp2 = perf_cgroup_from_task(prev, NULL);
759 * only need to schedule in cgroup events if we are changing
760 * cgroup during ctxsw. Cgroup events were not scheduled
761 * out of ctxsw out if that was not the case.
764 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
769 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
770 struct perf_event_attr *attr,
771 struct perf_event *group_leader)
773 struct perf_cgroup *cgrp;
774 struct cgroup_subsys_state *css;
775 struct fd f = fdget(fd);
781 css = css_tryget_online_from_dir(f.file->f_path.dentry,
782 &perf_event_cgrp_subsys);
788 cgrp = container_of(css, struct perf_cgroup, css);
792 * all events in a group must monitor
793 * the same cgroup because a task belongs
794 * to only one perf cgroup at a time
796 if (group_leader && group_leader->cgrp != cgrp) {
797 perf_detach_cgroup(event);
806 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
808 struct perf_cgroup_info *t;
809 t = per_cpu_ptr(event->cgrp->info, event->cpu);
810 event->shadow_ctx_time = now - t->timestamp;
814 perf_cgroup_defer_enabled(struct perf_event *event)
817 * when the current task's perf cgroup does not match
818 * the event's, we need to remember to call the
819 * perf_mark_enable() function the first time a task with
820 * a matching perf cgroup is scheduled in.
822 if (is_cgroup_event(event) && !perf_cgroup_match(event))
823 event->cgrp_defer_enabled = 1;
827 perf_cgroup_mark_enabled(struct perf_event *event,
828 struct perf_event_context *ctx)
830 struct perf_event *sub;
831 u64 tstamp = perf_event_time(event);
833 if (!event->cgrp_defer_enabled)
836 event->cgrp_defer_enabled = 0;
838 event->tstamp_enabled = tstamp - event->total_time_enabled;
839 list_for_each_entry(sub, &event->sibling_list, group_entry) {
840 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
841 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
842 sub->cgrp_defer_enabled = 0;
848 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
849 * cleared when last cgroup event is removed.
852 list_update_cgroup_event(struct perf_event *event,
853 struct perf_event_context *ctx, bool add)
855 struct perf_cpu_context *cpuctx;
857 if (!is_cgroup_event(event))
860 if (add && ctx->nr_cgroups++)
862 else if (!add && --ctx->nr_cgroups)
865 * Because cgroup events are always per-cpu events,
866 * this will always be called from the right CPU.
868 cpuctx = __get_cpu_context(ctx);
869 cpuctx->cgrp = add ? event->cgrp : NULL;
872 #else /* !CONFIG_CGROUP_PERF */
875 perf_cgroup_match(struct perf_event *event)
880 static inline void perf_detach_cgroup(struct perf_event *event)
883 static inline int is_cgroup_event(struct perf_event *event)
888 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
893 static inline void update_cgrp_time_from_event(struct perf_event *event)
897 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
901 static inline void perf_cgroup_sched_out(struct task_struct *task,
902 struct task_struct *next)
906 static inline void perf_cgroup_sched_in(struct task_struct *prev,
907 struct task_struct *task)
911 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
912 struct perf_event_attr *attr,
913 struct perf_event *group_leader)
919 perf_cgroup_set_timestamp(struct task_struct *task,
920 struct perf_event_context *ctx)
925 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
930 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
934 static inline u64 perf_cgroup_event_time(struct perf_event *event)
940 perf_cgroup_defer_enabled(struct perf_event *event)
945 perf_cgroup_mark_enabled(struct perf_event *event,
946 struct perf_event_context *ctx)
951 list_update_cgroup_event(struct perf_event *event,
952 struct perf_event_context *ctx, bool add)
959 * set default to be dependent on timer tick just
962 #define PERF_CPU_HRTIMER (1000 / HZ)
964 * function must be called with interrupts disbled
966 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
968 struct perf_cpu_context *cpuctx;
971 WARN_ON(!irqs_disabled());
973 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
974 rotations = perf_rotate_context(cpuctx);
976 raw_spin_lock(&cpuctx->hrtimer_lock);
978 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
980 cpuctx->hrtimer_active = 0;
981 raw_spin_unlock(&cpuctx->hrtimer_lock);
983 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
986 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
988 struct hrtimer *timer = &cpuctx->hrtimer;
989 struct pmu *pmu = cpuctx->ctx.pmu;
992 /* no multiplexing needed for SW PMU */
993 if (pmu->task_ctx_nr == perf_sw_context)
997 * check default is sane, if not set then force to
998 * default interval (1/tick)
1000 interval = pmu->hrtimer_interval_ms;
1002 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1004 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1006 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1007 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
1008 timer->function = perf_mux_hrtimer_handler;
1011 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1013 struct hrtimer *timer = &cpuctx->hrtimer;
1014 struct pmu *pmu = cpuctx->ctx.pmu;
1015 unsigned long flags;
1017 /* not for SW PMU */
1018 if (pmu->task_ctx_nr == perf_sw_context)
1021 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1022 if (!cpuctx->hrtimer_active) {
1023 cpuctx->hrtimer_active = 1;
1024 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1025 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
1027 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1032 void perf_pmu_disable(struct pmu *pmu)
1034 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1036 pmu->pmu_disable(pmu);
1039 void perf_pmu_enable(struct pmu *pmu)
1041 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1043 pmu->pmu_enable(pmu);
1046 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1049 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1050 * perf_event_task_tick() are fully serialized because they're strictly cpu
1051 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1052 * disabled, while perf_event_task_tick is called from IRQ context.
1054 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1056 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1058 WARN_ON(!irqs_disabled());
1060 WARN_ON(!list_empty(&ctx->active_ctx_list));
1062 list_add(&ctx->active_ctx_list, head);
1065 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1067 WARN_ON(!irqs_disabled());
1069 WARN_ON(list_empty(&ctx->active_ctx_list));
1071 list_del_init(&ctx->active_ctx_list);
1074 static void get_ctx(struct perf_event_context *ctx)
1076 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1079 static void free_ctx(struct rcu_head *head)
1081 struct perf_event_context *ctx;
1083 ctx = container_of(head, struct perf_event_context, rcu_head);
1084 kfree(ctx->task_ctx_data);
1088 static void put_ctx(struct perf_event_context *ctx)
1090 if (atomic_dec_and_test(&ctx->refcount)) {
1091 if (ctx->parent_ctx)
1092 put_ctx(ctx->parent_ctx);
1093 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1094 put_task_struct(ctx->task);
1095 call_rcu(&ctx->rcu_head, free_ctx);
1100 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1101 * perf_pmu_migrate_context() we need some magic.
1103 * Those places that change perf_event::ctx will hold both
1104 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1106 * Lock ordering is by mutex address. There are two other sites where
1107 * perf_event_context::mutex nests and those are:
1109 * - perf_event_exit_task_context() [ child , 0 ]
1110 * perf_event_exit_event()
1111 * put_event() [ parent, 1 ]
1113 * - perf_event_init_context() [ parent, 0 ]
1114 * inherit_task_group()
1117 * perf_event_alloc()
1119 * perf_try_init_event() [ child , 1 ]
1121 * While it appears there is an obvious deadlock here -- the parent and child
1122 * nesting levels are inverted between the two. This is in fact safe because
1123 * life-time rules separate them. That is an exiting task cannot fork, and a
1124 * spawning task cannot (yet) exit.
1126 * But remember that that these are parent<->child context relations, and
1127 * migration does not affect children, therefore these two orderings should not
1130 * The change in perf_event::ctx does not affect children (as claimed above)
1131 * because the sys_perf_event_open() case will install a new event and break
1132 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1133 * concerned with cpuctx and that doesn't have children.
1135 * The places that change perf_event::ctx will issue:
1137 * perf_remove_from_context();
1138 * synchronize_rcu();
1139 * perf_install_in_context();
1141 * to affect the change. The remove_from_context() + synchronize_rcu() should
1142 * quiesce the event, after which we can install it in the new location. This
1143 * means that only external vectors (perf_fops, prctl) can perturb the event
1144 * while in transit. Therefore all such accessors should also acquire
1145 * perf_event_context::mutex to serialize against this.
1147 * However; because event->ctx can change while we're waiting to acquire
1148 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1153 * task_struct::perf_event_mutex
1154 * perf_event_context::mutex
1155 * perf_event::child_mutex;
1156 * perf_event_context::lock
1157 * perf_event::mmap_mutex
1160 static struct perf_event_context *
1161 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1163 struct perf_event_context *ctx;
1167 ctx = ACCESS_ONCE(event->ctx);
1168 if (!atomic_inc_not_zero(&ctx->refcount)) {
1174 mutex_lock_nested(&ctx->mutex, nesting);
1175 if (event->ctx != ctx) {
1176 mutex_unlock(&ctx->mutex);
1184 static inline struct perf_event_context *
1185 perf_event_ctx_lock(struct perf_event *event)
1187 return perf_event_ctx_lock_nested(event, 0);
1190 static void perf_event_ctx_unlock(struct perf_event *event,
1191 struct perf_event_context *ctx)
1193 mutex_unlock(&ctx->mutex);
1198 * This must be done under the ctx->lock, such as to serialize against
1199 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1200 * calling scheduler related locks and ctx->lock nests inside those.
1202 static __must_check struct perf_event_context *
1203 unclone_ctx(struct perf_event_context *ctx)
1205 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1207 lockdep_assert_held(&ctx->lock);
1210 ctx->parent_ctx = NULL;
1216 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1219 * only top level events have the pid namespace they were created in
1222 event = event->parent;
1224 return task_tgid_nr_ns(p, event->ns);
1227 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1230 * only top level events have the pid namespace they were created in
1233 event = event->parent;
1235 return task_pid_nr_ns(p, event->ns);
1239 * If we inherit events we want to return the parent event id
1242 static u64 primary_event_id(struct perf_event *event)
1247 id = event->parent->id;
1253 * Get the perf_event_context for a task and lock it.
1255 * This has to cope with with the fact that until it is locked,
1256 * the context could get moved to another task.
1258 static struct perf_event_context *
1259 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1261 struct perf_event_context *ctx;
1265 * One of the few rules of preemptible RCU is that one cannot do
1266 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1267 * part of the read side critical section was irqs-enabled -- see
1268 * rcu_read_unlock_special().
1270 * Since ctx->lock nests under rq->lock we must ensure the entire read
1271 * side critical section has interrupts disabled.
1273 local_irq_save(*flags);
1275 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1278 * If this context is a clone of another, it might
1279 * get swapped for another underneath us by
1280 * perf_event_task_sched_out, though the
1281 * rcu_read_lock() protects us from any context
1282 * getting freed. Lock the context and check if it
1283 * got swapped before we could get the lock, and retry
1284 * if so. If we locked the right context, then it
1285 * can't get swapped on us any more.
1287 raw_spin_lock(&ctx->lock);
1288 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1289 raw_spin_unlock(&ctx->lock);
1291 local_irq_restore(*flags);
1295 if (ctx->task == TASK_TOMBSTONE ||
1296 !atomic_inc_not_zero(&ctx->refcount)) {
1297 raw_spin_unlock(&ctx->lock);
1300 WARN_ON_ONCE(ctx->task != task);
1305 local_irq_restore(*flags);
1310 * Get the context for a task and increment its pin_count so it
1311 * can't get swapped to another task. This also increments its
1312 * reference count so that the context can't get freed.
1314 static struct perf_event_context *
1315 perf_pin_task_context(struct task_struct *task, int ctxn)
1317 struct perf_event_context *ctx;
1318 unsigned long flags;
1320 ctx = perf_lock_task_context(task, ctxn, &flags);
1323 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1328 static void perf_unpin_context(struct perf_event_context *ctx)
1330 unsigned long flags;
1332 raw_spin_lock_irqsave(&ctx->lock, flags);
1334 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1338 * Update the record of the current time in a context.
1340 static void update_context_time(struct perf_event_context *ctx)
1342 u64 now = perf_clock();
1344 ctx->time += now - ctx->timestamp;
1345 ctx->timestamp = now;
1348 static u64 perf_event_time(struct perf_event *event)
1350 struct perf_event_context *ctx = event->ctx;
1352 if (is_cgroup_event(event))
1353 return perf_cgroup_event_time(event);
1355 return ctx ? ctx->time : 0;
1359 * Update the total_time_enabled and total_time_running fields for a event.
1361 static void update_event_times(struct perf_event *event)
1363 struct perf_event_context *ctx = event->ctx;
1366 lockdep_assert_held(&ctx->lock);
1368 if (event->state < PERF_EVENT_STATE_INACTIVE ||
1369 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1373 * in cgroup mode, time_enabled represents
1374 * the time the event was enabled AND active
1375 * tasks were in the monitored cgroup. This is
1376 * independent of the activity of the context as
1377 * there may be a mix of cgroup and non-cgroup events.
1379 * That is why we treat cgroup events differently
1382 if (is_cgroup_event(event))
1383 run_end = perf_cgroup_event_time(event);
1384 else if (ctx->is_active)
1385 run_end = ctx->time;
1387 run_end = event->tstamp_stopped;
1389 event->total_time_enabled = run_end - event->tstamp_enabled;
1391 if (event->state == PERF_EVENT_STATE_INACTIVE)
1392 run_end = event->tstamp_stopped;
1394 run_end = perf_event_time(event);
1396 event->total_time_running = run_end - event->tstamp_running;
1401 * Update total_time_enabled and total_time_running for all events in a group.
1403 static void update_group_times(struct perf_event *leader)
1405 struct perf_event *event;
1407 update_event_times(leader);
1408 list_for_each_entry(event, &leader->sibling_list, group_entry)
1409 update_event_times(event);
1412 static struct list_head *
1413 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1415 if (event->attr.pinned)
1416 return &ctx->pinned_groups;
1418 return &ctx->flexible_groups;
1422 * Add a event from the lists for its context.
1423 * Must be called with ctx->mutex and ctx->lock held.
1426 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1429 lockdep_assert_held(&ctx->lock);
1431 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1432 event->attach_state |= PERF_ATTACH_CONTEXT;
1435 * If we're a stand alone event or group leader, we go to the context
1436 * list, group events are kept attached to the group so that
1437 * perf_group_detach can, at all times, locate all siblings.
1439 if (event->group_leader == event) {
1440 struct list_head *list;
1442 if (is_software_event(event))
1443 event->group_flags |= PERF_GROUP_SOFTWARE;
1445 list = ctx_group_list(event, ctx);
1446 list_add_tail(&event->group_entry, list);
1449 list_update_cgroup_event(event, ctx, true);
1451 list_add_rcu(&event->event_entry, &ctx->event_list);
1453 if (event->attr.inherit_stat)
1460 * Initialize event state based on the perf_event_attr::disabled.
1462 static inline void perf_event__state_init(struct perf_event *event)
1464 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1465 PERF_EVENT_STATE_INACTIVE;
1468 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1470 int entry = sizeof(u64); /* value */
1474 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1475 size += sizeof(u64);
1477 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1478 size += sizeof(u64);
1480 if (event->attr.read_format & PERF_FORMAT_ID)
1481 entry += sizeof(u64);
1483 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1485 size += sizeof(u64);
1489 event->read_size = size;
1492 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1494 struct perf_sample_data *data;
1497 if (sample_type & PERF_SAMPLE_IP)
1498 size += sizeof(data->ip);
1500 if (sample_type & PERF_SAMPLE_ADDR)
1501 size += sizeof(data->addr);
1503 if (sample_type & PERF_SAMPLE_PERIOD)
1504 size += sizeof(data->period);
1506 if (sample_type & PERF_SAMPLE_WEIGHT)
1507 size += sizeof(data->weight);
1509 if (sample_type & PERF_SAMPLE_READ)
1510 size += event->read_size;
1512 if (sample_type & PERF_SAMPLE_DATA_SRC)
1513 size += sizeof(data->data_src.val);
1515 if (sample_type & PERF_SAMPLE_TRANSACTION)
1516 size += sizeof(data->txn);
1518 event->header_size = size;
1522 * Called at perf_event creation and when events are attached/detached from a
1525 static void perf_event__header_size(struct perf_event *event)
1527 __perf_event_read_size(event,
1528 event->group_leader->nr_siblings);
1529 __perf_event_header_size(event, event->attr.sample_type);
1532 static void perf_event__id_header_size(struct perf_event *event)
1534 struct perf_sample_data *data;
1535 u64 sample_type = event->attr.sample_type;
1538 if (sample_type & PERF_SAMPLE_TID)
1539 size += sizeof(data->tid_entry);
1541 if (sample_type & PERF_SAMPLE_TIME)
1542 size += sizeof(data->time);
1544 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1545 size += sizeof(data->id);
1547 if (sample_type & PERF_SAMPLE_ID)
1548 size += sizeof(data->id);
1550 if (sample_type & PERF_SAMPLE_STREAM_ID)
1551 size += sizeof(data->stream_id);
1553 if (sample_type & PERF_SAMPLE_CPU)
1554 size += sizeof(data->cpu_entry);
1556 event->id_header_size = size;
1559 static bool perf_event_validate_size(struct perf_event *event)
1562 * The values computed here will be over-written when we actually
1565 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1566 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1567 perf_event__id_header_size(event);
1570 * Sum the lot; should not exceed the 64k limit we have on records.
1571 * Conservative limit to allow for callchains and other variable fields.
1573 if (event->read_size + event->header_size +
1574 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1580 static void perf_group_attach(struct perf_event *event)
1582 struct perf_event *group_leader = event->group_leader, *pos;
1585 * We can have double attach due to group movement in perf_event_open.
1587 if (event->attach_state & PERF_ATTACH_GROUP)
1590 event->attach_state |= PERF_ATTACH_GROUP;
1592 if (group_leader == event)
1595 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1597 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1598 !is_software_event(event))
1599 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1601 list_add_tail(&event->group_entry, &group_leader->sibling_list);
1602 group_leader->nr_siblings++;
1604 perf_event__header_size(group_leader);
1606 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1607 perf_event__header_size(pos);
1611 * Remove a event from the lists for its context.
1612 * Must be called with ctx->mutex and ctx->lock held.
1615 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1617 WARN_ON_ONCE(event->ctx != ctx);
1618 lockdep_assert_held(&ctx->lock);
1621 * We can have double detach due to exit/hot-unplug + close.
1623 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1626 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1628 list_update_cgroup_event(event, ctx, false);
1631 if (event->attr.inherit_stat)
1634 list_del_rcu(&event->event_entry);
1636 if (event->group_leader == event)
1637 list_del_init(&event->group_entry);
1639 update_group_times(event);
1642 * If event was in error state, then keep it
1643 * that way, otherwise bogus counts will be
1644 * returned on read(). The only way to get out
1645 * of error state is by explicit re-enabling
1648 if (event->state > PERF_EVENT_STATE_OFF)
1649 event->state = PERF_EVENT_STATE_OFF;
1654 static void perf_group_detach(struct perf_event *event)
1656 struct perf_event *sibling, *tmp;
1657 struct list_head *list = NULL;
1660 * We can have double detach due to exit/hot-unplug + close.
1662 if (!(event->attach_state & PERF_ATTACH_GROUP))
1665 event->attach_state &= ~PERF_ATTACH_GROUP;
1668 * If this is a sibling, remove it from its group.
1670 if (event->group_leader != event) {
1671 list_del_init(&event->group_entry);
1672 event->group_leader->nr_siblings--;
1676 if (!list_empty(&event->group_entry))
1677 list = &event->group_entry;
1680 * If this was a group event with sibling events then
1681 * upgrade the siblings to singleton events by adding them
1682 * to whatever list we are on.
1684 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1686 list_move_tail(&sibling->group_entry, list);
1687 sibling->group_leader = sibling;
1689 /* Inherit group flags from the previous leader */
1690 sibling->group_flags = event->group_flags;
1692 WARN_ON_ONCE(sibling->ctx != event->ctx);
1696 perf_event__header_size(event->group_leader);
1698 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1699 perf_event__header_size(tmp);
1702 static bool is_orphaned_event(struct perf_event *event)
1704 return event->state == PERF_EVENT_STATE_DEAD;
1707 static inline int __pmu_filter_match(struct perf_event *event)
1709 struct pmu *pmu = event->pmu;
1710 return pmu->filter_match ? pmu->filter_match(event) : 1;
1714 * Check whether we should attempt to schedule an event group based on
1715 * PMU-specific filtering. An event group can consist of HW and SW events,
1716 * potentially with a SW leader, so we must check all the filters, to
1717 * determine whether a group is schedulable:
1719 static inline int pmu_filter_match(struct perf_event *event)
1721 struct perf_event *child;
1723 if (!__pmu_filter_match(event))
1726 list_for_each_entry(child, &event->sibling_list, group_entry) {
1727 if (!__pmu_filter_match(child))
1735 event_filter_match(struct perf_event *event)
1737 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
1738 perf_cgroup_match(event) && pmu_filter_match(event);
1742 event_sched_out(struct perf_event *event,
1743 struct perf_cpu_context *cpuctx,
1744 struct perf_event_context *ctx)
1746 u64 tstamp = perf_event_time(event);
1749 WARN_ON_ONCE(event->ctx != ctx);
1750 lockdep_assert_held(&ctx->lock);
1753 * An event which could not be activated because of
1754 * filter mismatch still needs to have its timings
1755 * maintained, otherwise bogus information is return
1756 * via read() for time_enabled, time_running:
1758 if (event->state == PERF_EVENT_STATE_INACTIVE &&
1759 !event_filter_match(event)) {
1760 delta = tstamp - event->tstamp_stopped;
1761 event->tstamp_running += delta;
1762 event->tstamp_stopped = tstamp;
1765 if (event->state != PERF_EVENT_STATE_ACTIVE)
1768 perf_pmu_disable(event->pmu);
1770 event->tstamp_stopped = tstamp;
1771 event->pmu->del(event, 0);
1773 event->state = PERF_EVENT_STATE_INACTIVE;
1774 if (event->pending_disable) {
1775 event->pending_disable = 0;
1776 event->state = PERF_EVENT_STATE_OFF;
1779 if (!is_software_event(event))
1780 cpuctx->active_oncpu--;
1781 if (!--ctx->nr_active)
1782 perf_event_ctx_deactivate(ctx);
1783 if (event->attr.freq && event->attr.sample_freq)
1785 if (event->attr.exclusive || !cpuctx->active_oncpu)
1786 cpuctx->exclusive = 0;
1788 perf_pmu_enable(event->pmu);
1792 group_sched_out(struct perf_event *group_event,
1793 struct perf_cpu_context *cpuctx,
1794 struct perf_event_context *ctx)
1796 struct perf_event *event;
1797 int state = group_event->state;
1799 perf_pmu_disable(ctx->pmu);
1801 event_sched_out(group_event, cpuctx, ctx);
1804 * Schedule out siblings (if any):
1806 list_for_each_entry(event, &group_event->sibling_list, group_entry)
1807 event_sched_out(event, cpuctx, ctx);
1809 perf_pmu_enable(ctx->pmu);
1811 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1812 cpuctx->exclusive = 0;
1815 #define DETACH_GROUP 0x01UL
1818 * Cross CPU call to remove a performance event
1820 * We disable the event on the hardware level first. After that we
1821 * remove it from the context list.
1824 __perf_remove_from_context(struct perf_event *event,
1825 struct perf_cpu_context *cpuctx,
1826 struct perf_event_context *ctx,
1829 unsigned long flags = (unsigned long)info;
1831 event_sched_out(event, cpuctx, ctx);
1832 if (flags & DETACH_GROUP)
1833 perf_group_detach(event);
1834 list_del_event(event, ctx);
1836 if (!ctx->nr_events && ctx->is_active) {
1839 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
1840 cpuctx->task_ctx = NULL;
1846 * Remove the event from a task's (or a CPU's) list of events.
1848 * If event->ctx is a cloned context, callers must make sure that
1849 * every task struct that event->ctx->task could possibly point to
1850 * remains valid. This is OK when called from perf_release since
1851 * that only calls us on the top-level context, which can't be a clone.
1852 * When called from perf_event_exit_task, it's OK because the
1853 * context has been detached from its task.
1855 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
1857 lockdep_assert_held(&event->ctx->mutex);
1859 event_function_call(event, __perf_remove_from_context, (void *)flags);
1863 * Cross CPU call to disable a performance event
1865 static void __perf_event_disable(struct perf_event *event,
1866 struct perf_cpu_context *cpuctx,
1867 struct perf_event_context *ctx,
1870 if (event->state < PERF_EVENT_STATE_INACTIVE)
1873 update_context_time(ctx);
1874 update_cgrp_time_from_event(event);
1875 update_group_times(event);
1876 if (event == event->group_leader)
1877 group_sched_out(event, cpuctx, ctx);
1879 event_sched_out(event, cpuctx, ctx);
1880 event->state = PERF_EVENT_STATE_OFF;
1886 * If event->ctx is a cloned context, callers must make sure that
1887 * every task struct that event->ctx->task could possibly point to
1888 * remains valid. This condition is satisifed when called through
1889 * perf_event_for_each_child or perf_event_for_each because they
1890 * hold the top-level event's child_mutex, so any descendant that
1891 * goes to exit will block in perf_event_exit_event().
1893 * When called from perf_pending_event it's OK because event->ctx
1894 * is the current context on this CPU and preemption is disabled,
1895 * hence we can't get into perf_event_task_sched_out for this context.
1897 static void _perf_event_disable(struct perf_event *event)
1899 struct perf_event_context *ctx = event->ctx;
1901 raw_spin_lock_irq(&ctx->lock);
1902 if (event->state <= PERF_EVENT_STATE_OFF) {
1903 raw_spin_unlock_irq(&ctx->lock);
1906 raw_spin_unlock_irq(&ctx->lock);
1908 event_function_call(event, __perf_event_disable, NULL);
1911 void perf_event_disable_local(struct perf_event *event)
1913 event_function_local(event, __perf_event_disable, NULL);
1917 * Strictly speaking kernel users cannot create groups and therefore this
1918 * interface does not need the perf_event_ctx_lock() magic.
1920 void perf_event_disable(struct perf_event *event)
1922 struct perf_event_context *ctx;
1924 ctx = perf_event_ctx_lock(event);
1925 _perf_event_disable(event);
1926 perf_event_ctx_unlock(event, ctx);
1928 EXPORT_SYMBOL_GPL(perf_event_disable);
1930 static void perf_set_shadow_time(struct perf_event *event,
1931 struct perf_event_context *ctx,
1935 * use the correct time source for the time snapshot
1937 * We could get by without this by leveraging the
1938 * fact that to get to this function, the caller
1939 * has most likely already called update_context_time()
1940 * and update_cgrp_time_xx() and thus both timestamp
1941 * are identical (or very close). Given that tstamp is,
1942 * already adjusted for cgroup, we could say that:
1943 * tstamp - ctx->timestamp
1945 * tstamp - cgrp->timestamp.
1947 * Then, in perf_output_read(), the calculation would
1948 * work with no changes because:
1949 * - event is guaranteed scheduled in
1950 * - no scheduled out in between
1951 * - thus the timestamp would be the same
1953 * But this is a bit hairy.
1955 * So instead, we have an explicit cgroup call to remain
1956 * within the time time source all along. We believe it
1957 * is cleaner and simpler to understand.
1959 if (is_cgroup_event(event))
1960 perf_cgroup_set_shadow_time(event, tstamp);
1962 event->shadow_ctx_time = tstamp - ctx->timestamp;
1965 #define MAX_INTERRUPTS (~0ULL)
1967 static void perf_log_throttle(struct perf_event *event, int enable);
1968 static void perf_log_itrace_start(struct perf_event *event);
1971 event_sched_in(struct perf_event *event,
1972 struct perf_cpu_context *cpuctx,
1973 struct perf_event_context *ctx)
1975 u64 tstamp = perf_event_time(event);
1978 lockdep_assert_held(&ctx->lock);
1980 if (event->state <= PERF_EVENT_STATE_OFF)
1983 WRITE_ONCE(event->oncpu, smp_processor_id());
1985 * Order event::oncpu write to happen before the ACTIVE state
1989 WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE);
1992 * Unthrottle events, since we scheduled we might have missed several
1993 * ticks already, also for a heavily scheduling task there is little
1994 * guarantee it'll get a tick in a timely manner.
1996 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1997 perf_log_throttle(event, 1);
1998 event->hw.interrupts = 0;
2002 * The new state must be visible before we turn it on in the hardware:
2006 perf_pmu_disable(event->pmu);
2008 perf_set_shadow_time(event, ctx, tstamp);
2010 perf_log_itrace_start(event);
2012 if (event->pmu->add(event, PERF_EF_START)) {
2013 event->state = PERF_EVENT_STATE_INACTIVE;
2019 event->tstamp_running += tstamp - event->tstamp_stopped;
2021 if (!is_software_event(event))
2022 cpuctx->active_oncpu++;
2023 if (!ctx->nr_active++)
2024 perf_event_ctx_activate(ctx);
2025 if (event->attr.freq && event->attr.sample_freq)
2028 if (event->attr.exclusive)
2029 cpuctx->exclusive = 1;
2032 perf_pmu_enable(event->pmu);
2038 group_sched_in(struct perf_event *group_event,
2039 struct perf_cpu_context *cpuctx,
2040 struct perf_event_context *ctx)
2042 struct perf_event *event, *partial_group = NULL;
2043 struct pmu *pmu = ctx->pmu;
2044 u64 now = ctx->time;
2045 bool simulate = false;
2047 if (group_event->state == PERF_EVENT_STATE_OFF)
2050 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2052 if (event_sched_in(group_event, cpuctx, ctx)) {
2053 pmu->cancel_txn(pmu);
2054 perf_mux_hrtimer_restart(cpuctx);
2059 * Schedule in siblings as one group (if any):
2061 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2062 if (event_sched_in(event, cpuctx, ctx)) {
2063 partial_group = event;
2068 if (!pmu->commit_txn(pmu))
2073 * Groups can be scheduled in as one unit only, so undo any
2074 * partial group before returning:
2075 * The events up to the failed event are scheduled out normally,
2076 * tstamp_stopped will be updated.
2078 * The failed events and the remaining siblings need to have
2079 * their timings updated as if they had gone thru event_sched_in()
2080 * and event_sched_out(). This is required to get consistent timings
2081 * across the group. This also takes care of the case where the group
2082 * could never be scheduled by ensuring tstamp_stopped is set to mark
2083 * the time the event was actually stopped, such that time delta
2084 * calculation in update_event_times() is correct.
2086 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
2087 if (event == partial_group)
2091 event->tstamp_running += now - event->tstamp_stopped;
2092 event->tstamp_stopped = now;
2094 event_sched_out(event, cpuctx, ctx);
2097 event_sched_out(group_event, cpuctx, ctx);
2099 pmu->cancel_txn(pmu);
2101 perf_mux_hrtimer_restart(cpuctx);
2107 * Work out whether we can put this event group on the CPU now.
2109 static int group_can_go_on(struct perf_event *event,
2110 struct perf_cpu_context *cpuctx,
2114 * Groups consisting entirely of software events can always go on.
2116 if (event->group_flags & PERF_GROUP_SOFTWARE)
2119 * If an exclusive group is already on, no other hardware
2122 if (cpuctx->exclusive)
2125 * If this group is exclusive and there are already
2126 * events on the CPU, it can't go on.
2128 if (event->attr.exclusive && cpuctx->active_oncpu)
2131 * Otherwise, try to add it if all previous groups were able
2137 static void add_event_to_ctx(struct perf_event *event,
2138 struct perf_event_context *ctx)
2140 u64 tstamp = perf_event_time(event);
2142 list_add_event(event, ctx);
2143 perf_group_attach(event);
2144 event->tstamp_enabled = tstamp;
2145 event->tstamp_running = tstamp;
2146 event->tstamp_stopped = tstamp;
2149 static void ctx_sched_out(struct perf_event_context *ctx,
2150 struct perf_cpu_context *cpuctx,
2151 enum event_type_t event_type);
2153 ctx_sched_in(struct perf_event_context *ctx,
2154 struct perf_cpu_context *cpuctx,
2155 enum event_type_t event_type,
2156 struct task_struct *task);
2158 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2159 struct perf_event_context *ctx)
2161 if (!cpuctx->task_ctx)
2164 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2167 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2170 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2171 struct perf_event_context *ctx,
2172 struct task_struct *task)
2174 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2176 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2177 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2179 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2182 static void ctx_resched(struct perf_cpu_context *cpuctx,
2183 struct perf_event_context *task_ctx)
2185 perf_pmu_disable(cpuctx->ctx.pmu);
2187 task_ctx_sched_out(cpuctx, task_ctx);
2188 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
2189 perf_event_sched_in(cpuctx, task_ctx, current);
2190 perf_pmu_enable(cpuctx->ctx.pmu);
2194 * Cross CPU call to install and enable a performance event
2196 * Very similar to remote_function() + event_function() but cannot assume that
2197 * things like ctx->is_active and cpuctx->task_ctx are set.
2199 static int __perf_install_in_context(void *info)
2201 struct perf_event *event = info;
2202 struct perf_event_context *ctx = event->ctx;
2203 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2204 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2205 bool activate = true;
2208 raw_spin_lock(&cpuctx->ctx.lock);
2210 raw_spin_lock(&ctx->lock);
2213 /* If we're on the wrong CPU, try again */
2214 if (task_cpu(ctx->task) != smp_processor_id()) {
2220 * If we're on the right CPU, see if the task we target is
2221 * current, if not we don't have to activate the ctx, a future
2222 * context switch will do that for us.
2224 if (ctx->task != current)
2227 WARN_ON_ONCE(cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2229 } else if (task_ctx) {
2230 raw_spin_lock(&task_ctx->lock);
2234 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2235 add_event_to_ctx(event, ctx);
2236 ctx_resched(cpuctx, task_ctx);
2238 add_event_to_ctx(event, ctx);
2242 perf_ctx_unlock(cpuctx, task_ctx);
2248 * Attach a performance event to a context.
2250 * Very similar to event_function_call, see comment there.
2253 perf_install_in_context(struct perf_event_context *ctx,
2254 struct perf_event *event,
2257 struct task_struct *task = READ_ONCE(ctx->task);
2259 lockdep_assert_held(&ctx->mutex);
2261 if (event->cpu != -1)
2265 * Ensures that if we can observe event->ctx, both the event and ctx
2266 * will be 'complete'. See perf_iterate_sb_cpu().
2268 smp_store_release(&event->ctx, ctx);
2271 cpu_function_call(cpu, __perf_install_in_context, event);
2276 * Should not happen, we validate the ctx is still alive before calling.
2278 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2282 * Installing events is tricky because we cannot rely on ctx->is_active
2283 * to be set in case this is the nr_events 0 -> 1 transition.
2287 * Cannot use task_function_call() because we need to run on the task's
2288 * CPU regardless of whether its current or not.
2290 if (!cpu_function_call(task_cpu(task), __perf_install_in_context, event))
2293 raw_spin_lock_irq(&ctx->lock);
2295 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2297 * Cannot happen because we already checked above (which also
2298 * cannot happen), and we hold ctx->mutex, which serializes us
2299 * against perf_event_exit_task_context().
2301 raw_spin_unlock_irq(&ctx->lock);
2304 raw_spin_unlock_irq(&ctx->lock);
2306 * Since !ctx->is_active doesn't mean anything, we must IPI
2313 * Put a event into inactive state and update time fields.
2314 * Enabling the leader of a group effectively enables all
2315 * the group members that aren't explicitly disabled, so we
2316 * have to update their ->tstamp_enabled also.
2317 * Note: this works for group members as well as group leaders
2318 * since the non-leader members' sibling_lists will be empty.
2320 static void __perf_event_mark_enabled(struct perf_event *event)
2322 struct perf_event *sub;
2323 u64 tstamp = perf_event_time(event);
2325 event->state = PERF_EVENT_STATE_INACTIVE;
2326 event->tstamp_enabled = tstamp - event->total_time_enabled;
2327 list_for_each_entry(sub, &event->sibling_list, group_entry) {
2328 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2329 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2334 * Cross CPU call to enable a performance event
2336 static void __perf_event_enable(struct perf_event *event,
2337 struct perf_cpu_context *cpuctx,
2338 struct perf_event_context *ctx,
2341 struct perf_event *leader = event->group_leader;
2342 struct perf_event_context *task_ctx;
2344 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2345 event->state <= PERF_EVENT_STATE_ERROR)
2349 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2351 __perf_event_mark_enabled(event);
2353 if (!ctx->is_active)
2356 if (!event_filter_match(event)) {
2357 if (is_cgroup_event(event))
2358 perf_cgroup_defer_enabled(event);
2359 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2364 * If the event is in a group and isn't the group leader,
2365 * then don't put it on unless the group is on.
2367 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2368 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2372 task_ctx = cpuctx->task_ctx;
2374 WARN_ON_ONCE(task_ctx != ctx);
2376 ctx_resched(cpuctx, task_ctx);
2382 * If event->ctx is a cloned context, callers must make sure that
2383 * every task struct that event->ctx->task could possibly point to
2384 * remains valid. This condition is satisfied when called through
2385 * perf_event_for_each_child or perf_event_for_each as described
2386 * for perf_event_disable.
2388 static void _perf_event_enable(struct perf_event *event)
2390 struct perf_event_context *ctx = event->ctx;
2392 raw_spin_lock_irq(&ctx->lock);
2393 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2394 event->state < PERF_EVENT_STATE_ERROR) {
2395 raw_spin_unlock_irq(&ctx->lock);
2400 * If the event is in error state, clear that first.
2402 * That way, if we see the event in error state below, we know that it
2403 * has gone back into error state, as distinct from the task having
2404 * been scheduled away before the cross-call arrived.
2406 if (event->state == PERF_EVENT_STATE_ERROR)
2407 event->state = PERF_EVENT_STATE_OFF;
2408 raw_spin_unlock_irq(&ctx->lock);
2410 event_function_call(event, __perf_event_enable, NULL);
2414 * See perf_event_disable();
2416 void perf_event_enable(struct perf_event *event)
2418 struct perf_event_context *ctx;
2420 ctx = perf_event_ctx_lock(event);
2421 _perf_event_enable(event);
2422 perf_event_ctx_unlock(event, ctx);
2424 EXPORT_SYMBOL_GPL(perf_event_enable);
2426 struct stop_event_data {
2427 struct perf_event *event;
2428 unsigned int restart;
2431 static int __perf_event_stop(void *info)
2433 struct stop_event_data *sd = info;
2434 struct perf_event *event = sd->event;
2436 /* if it's already INACTIVE, do nothing */
2437 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2440 /* matches smp_wmb() in event_sched_in() */
2444 * There is a window with interrupts enabled before we get here,
2445 * so we need to check again lest we try to stop another CPU's event.
2447 if (READ_ONCE(event->oncpu) != smp_processor_id())
2450 event->pmu->stop(event, PERF_EF_UPDATE);
2453 * May race with the actual stop (through perf_pmu_output_stop()),
2454 * but it is only used for events with AUX ring buffer, and such
2455 * events will refuse to restart because of rb::aux_mmap_count==0,
2456 * see comments in perf_aux_output_begin().
2458 * Since this is happening on a event-local CPU, no trace is lost
2462 event->pmu->start(event, PERF_EF_START);
2467 static int perf_event_restart(struct perf_event *event)
2469 struct stop_event_data sd = {
2476 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2479 /* matches smp_wmb() in event_sched_in() */
2483 * We only want to restart ACTIVE events, so if the event goes
2484 * inactive here (event->oncpu==-1), there's nothing more to do;
2485 * fall through with ret==-ENXIO.
2487 ret = cpu_function_call(READ_ONCE(event->oncpu),
2488 __perf_event_stop, &sd);
2489 } while (ret == -EAGAIN);
2495 * In order to contain the amount of racy and tricky in the address filter
2496 * configuration management, it is a two part process:
2498 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2499 * we update the addresses of corresponding vmas in
2500 * event::addr_filters_offs array and bump the event::addr_filters_gen;
2501 * (p2) when an event is scheduled in (pmu::add), it calls
2502 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2503 * if the generation has changed since the previous call.
2505 * If (p1) happens while the event is active, we restart it to force (p2).
2507 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2508 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2510 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2511 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2513 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2516 void perf_event_addr_filters_sync(struct perf_event *event)
2518 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2520 if (!has_addr_filter(event))
2523 raw_spin_lock(&ifh->lock);
2524 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2525 event->pmu->addr_filters_sync(event);
2526 event->hw.addr_filters_gen = event->addr_filters_gen;
2528 raw_spin_unlock(&ifh->lock);
2530 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2532 static int _perf_event_refresh(struct perf_event *event, int refresh)
2535 * not supported on inherited events
2537 if (event->attr.inherit || !is_sampling_event(event))
2540 atomic_add(refresh, &event->event_limit);
2541 _perf_event_enable(event);
2547 * See perf_event_disable()
2549 int perf_event_refresh(struct perf_event *event, int refresh)
2551 struct perf_event_context *ctx;
2554 ctx = perf_event_ctx_lock(event);
2555 ret = _perf_event_refresh(event, refresh);
2556 perf_event_ctx_unlock(event, ctx);
2560 EXPORT_SYMBOL_GPL(perf_event_refresh);
2562 static void ctx_sched_out(struct perf_event_context *ctx,
2563 struct perf_cpu_context *cpuctx,
2564 enum event_type_t event_type)
2566 int is_active = ctx->is_active;
2567 struct perf_event *event;
2569 lockdep_assert_held(&ctx->lock);
2571 if (likely(!ctx->nr_events)) {
2573 * See __perf_remove_from_context().
2575 WARN_ON_ONCE(ctx->is_active);
2577 WARN_ON_ONCE(cpuctx->task_ctx);
2581 ctx->is_active &= ~event_type;
2582 if (!(ctx->is_active & EVENT_ALL))
2586 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2587 if (!ctx->is_active)
2588 cpuctx->task_ctx = NULL;
2592 * Always update time if it was set; not only when it changes.
2593 * Otherwise we can 'forget' to update time for any but the last
2594 * context we sched out. For example:
2596 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2597 * ctx_sched_out(.event_type = EVENT_PINNED)
2599 * would only update time for the pinned events.
2601 if (is_active & EVENT_TIME) {
2602 /* update (and stop) ctx time */
2603 update_context_time(ctx);
2604 update_cgrp_time_from_cpuctx(cpuctx);
2607 is_active ^= ctx->is_active; /* changed bits */
2609 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2612 perf_pmu_disable(ctx->pmu);
2613 if (is_active & EVENT_PINNED) {
2614 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2615 group_sched_out(event, cpuctx, ctx);
2618 if (is_active & EVENT_FLEXIBLE) {
2619 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2620 group_sched_out(event, cpuctx, ctx);
2622 perf_pmu_enable(ctx->pmu);
2626 * Test whether two contexts are equivalent, i.e. whether they have both been
2627 * cloned from the same version of the same context.
2629 * Equivalence is measured using a generation number in the context that is
2630 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2631 * and list_del_event().
2633 static int context_equiv(struct perf_event_context *ctx1,
2634 struct perf_event_context *ctx2)
2636 lockdep_assert_held(&ctx1->lock);
2637 lockdep_assert_held(&ctx2->lock);
2639 /* Pinning disables the swap optimization */
2640 if (ctx1->pin_count || ctx2->pin_count)
2643 /* If ctx1 is the parent of ctx2 */
2644 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2647 /* If ctx2 is the parent of ctx1 */
2648 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2652 * If ctx1 and ctx2 have the same parent; we flatten the parent
2653 * hierarchy, see perf_event_init_context().
2655 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2656 ctx1->parent_gen == ctx2->parent_gen)
2663 static void __perf_event_sync_stat(struct perf_event *event,
2664 struct perf_event *next_event)
2668 if (!event->attr.inherit_stat)
2672 * Update the event value, we cannot use perf_event_read()
2673 * because we're in the middle of a context switch and have IRQs
2674 * disabled, which upsets smp_call_function_single(), however
2675 * we know the event must be on the current CPU, therefore we
2676 * don't need to use it.
2678 switch (event->state) {
2679 case PERF_EVENT_STATE_ACTIVE:
2680 event->pmu->read(event);
2683 case PERF_EVENT_STATE_INACTIVE:
2684 update_event_times(event);
2692 * In order to keep per-task stats reliable we need to flip the event
2693 * values when we flip the contexts.
2695 value = local64_read(&next_event->count);
2696 value = local64_xchg(&event->count, value);
2697 local64_set(&next_event->count, value);
2699 swap(event->total_time_enabled, next_event->total_time_enabled);
2700 swap(event->total_time_running, next_event->total_time_running);
2703 * Since we swizzled the values, update the user visible data too.
2705 perf_event_update_userpage(event);
2706 perf_event_update_userpage(next_event);
2709 static void perf_event_sync_stat(struct perf_event_context *ctx,
2710 struct perf_event_context *next_ctx)
2712 struct perf_event *event, *next_event;
2717 update_context_time(ctx);
2719 event = list_first_entry(&ctx->event_list,
2720 struct perf_event, event_entry);
2722 next_event = list_first_entry(&next_ctx->event_list,
2723 struct perf_event, event_entry);
2725 while (&event->event_entry != &ctx->event_list &&
2726 &next_event->event_entry != &next_ctx->event_list) {
2728 __perf_event_sync_stat(event, next_event);
2730 event = list_next_entry(event, event_entry);
2731 next_event = list_next_entry(next_event, event_entry);
2735 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2736 struct task_struct *next)
2738 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2739 struct perf_event_context *next_ctx;
2740 struct perf_event_context *parent, *next_parent;
2741 struct perf_cpu_context *cpuctx;
2747 cpuctx = __get_cpu_context(ctx);
2748 if (!cpuctx->task_ctx)
2752 next_ctx = next->perf_event_ctxp[ctxn];
2756 parent = rcu_dereference(ctx->parent_ctx);
2757 next_parent = rcu_dereference(next_ctx->parent_ctx);
2759 /* If neither context have a parent context; they cannot be clones. */
2760 if (!parent && !next_parent)
2763 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2765 * Looks like the two contexts are clones, so we might be
2766 * able to optimize the context switch. We lock both
2767 * contexts and check that they are clones under the
2768 * lock (including re-checking that neither has been
2769 * uncloned in the meantime). It doesn't matter which
2770 * order we take the locks because no other cpu could
2771 * be trying to lock both of these tasks.
2773 raw_spin_lock(&ctx->lock);
2774 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2775 if (context_equiv(ctx, next_ctx)) {
2776 WRITE_ONCE(ctx->task, next);
2777 WRITE_ONCE(next_ctx->task, task);
2779 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
2782 * RCU_INIT_POINTER here is safe because we've not
2783 * modified the ctx and the above modification of
2784 * ctx->task and ctx->task_ctx_data are immaterial
2785 * since those values are always verified under
2786 * ctx->lock which we're now holding.
2788 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
2789 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
2793 perf_event_sync_stat(ctx, next_ctx);
2795 raw_spin_unlock(&next_ctx->lock);
2796 raw_spin_unlock(&ctx->lock);
2802 raw_spin_lock(&ctx->lock);
2803 task_ctx_sched_out(cpuctx, ctx);
2804 raw_spin_unlock(&ctx->lock);
2808 void perf_sched_cb_dec(struct pmu *pmu)
2810 this_cpu_dec(perf_sched_cb_usages);
2813 void perf_sched_cb_inc(struct pmu *pmu)
2815 this_cpu_inc(perf_sched_cb_usages);
2819 * This function provides the context switch callback to the lower code
2820 * layer. It is invoked ONLY when the context switch callback is enabled.
2822 static void perf_pmu_sched_task(struct task_struct *prev,
2823 struct task_struct *next,
2826 struct perf_cpu_context *cpuctx;
2828 unsigned long flags;
2833 local_irq_save(flags);
2837 list_for_each_entry_rcu(pmu, &pmus, entry) {
2838 if (pmu->sched_task) {
2839 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2841 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2843 perf_pmu_disable(pmu);
2845 pmu->sched_task(cpuctx->task_ctx, sched_in);
2847 perf_pmu_enable(pmu);
2849 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2855 local_irq_restore(flags);
2858 static void perf_event_switch(struct task_struct *task,
2859 struct task_struct *next_prev, bool sched_in);
2861 #define for_each_task_context_nr(ctxn) \
2862 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2865 * Called from scheduler to remove the events of the current task,
2866 * with interrupts disabled.
2868 * We stop each event and update the event value in event->count.
2870 * This does not protect us against NMI, but disable()
2871 * sets the disabled bit in the control field of event _before_
2872 * accessing the event control register. If a NMI hits, then it will
2873 * not restart the event.
2875 void __perf_event_task_sched_out(struct task_struct *task,
2876 struct task_struct *next)
2880 if (__this_cpu_read(perf_sched_cb_usages))
2881 perf_pmu_sched_task(task, next, false);
2883 if (atomic_read(&nr_switch_events))
2884 perf_event_switch(task, next, false);
2886 for_each_task_context_nr(ctxn)
2887 perf_event_context_sched_out(task, ctxn, next);
2890 * if cgroup events exist on this CPU, then we need
2891 * to check if we have to switch out PMU state.
2892 * cgroup event are system-wide mode only
2894 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
2895 perf_cgroup_sched_out(task, next);
2899 * Called with IRQs disabled
2901 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2902 enum event_type_t event_type)
2904 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2908 ctx_pinned_sched_in(struct perf_event_context *ctx,
2909 struct perf_cpu_context *cpuctx)
2911 struct perf_event *event;
2913 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2914 if (event->state <= PERF_EVENT_STATE_OFF)
2916 if (!event_filter_match(event))
2919 /* may need to reset tstamp_enabled */
2920 if (is_cgroup_event(event))
2921 perf_cgroup_mark_enabled(event, ctx);
2923 if (group_can_go_on(event, cpuctx, 1))
2924 group_sched_in(event, cpuctx, ctx);
2927 * If this pinned group hasn't been scheduled,
2928 * put it in error state.
2930 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2931 update_group_times(event);
2932 event->state = PERF_EVENT_STATE_ERROR;
2938 ctx_flexible_sched_in(struct perf_event_context *ctx,
2939 struct perf_cpu_context *cpuctx)
2941 struct perf_event *event;
2944 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2945 /* Ignore events in OFF or ERROR state */
2946 if (event->state <= PERF_EVENT_STATE_OFF)
2949 * Listen to the 'cpu' scheduling filter constraint
2952 if (!event_filter_match(event))
2955 /* may need to reset tstamp_enabled */
2956 if (is_cgroup_event(event))
2957 perf_cgroup_mark_enabled(event, ctx);
2959 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2960 if (group_sched_in(event, cpuctx, ctx))
2967 ctx_sched_in(struct perf_event_context *ctx,
2968 struct perf_cpu_context *cpuctx,
2969 enum event_type_t event_type,
2970 struct task_struct *task)
2972 int is_active = ctx->is_active;
2975 lockdep_assert_held(&ctx->lock);
2977 if (likely(!ctx->nr_events))
2980 ctx->is_active |= (event_type | EVENT_TIME);
2983 cpuctx->task_ctx = ctx;
2985 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2988 is_active ^= ctx->is_active; /* changed bits */
2990 if (is_active & EVENT_TIME) {
2991 /* start ctx time */
2993 ctx->timestamp = now;
2994 perf_cgroup_set_timestamp(task, ctx);
2998 * First go through the list and put on any pinned groups
2999 * in order to give them the best chance of going on.
3001 if (is_active & EVENT_PINNED)
3002 ctx_pinned_sched_in(ctx, cpuctx);
3004 /* Then walk through the lower prio flexible groups */
3005 if (is_active & EVENT_FLEXIBLE)
3006 ctx_flexible_sched_in(ctx, cpuctx);
3009 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3010 enum event_type_t event_type,
3011 struct task_struct *task)
3013 struct perf_event_context *ctx = &cpuctx->ctx;
3015 ctx_sched_in(ctx, cpuctx, event_type, task);
3018 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3019 struct task_struct *task)
3021 struct perf_cpu_context *cpuctx;
3023 cpuctx = __get_cpu_context(ctx);
3024 if (cpuctx->task_ctx == ctx)
3027 perf_ctx_lock(cpuctx, ctx);
3028 perf_pmu_disable(ctx->pmu);
3030 * We want to keep the following priority order:
3031 * cpu pinned (that don't need to move), task pinned,
3032 * cpu flexible, task flexible.
3034 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3035 perf_event_sched_in(cpuctx, ctx, task);
3036 perf_pmu_enable(ctx->pmu);
3037 perf_ctx_unlock(cpuctx, ctx);
3041 * Called from scheduler to add the events of the current task
3042 * with interrupts disabled.
3044 * We restore the event value and then enable it.
3046 * This does not protect us against NMI, but enable()
3047 * sets the enabled bit in the control field of event _before_
3048 * accessing the event control register. If a NMI hits, then it will
3049 * keep the event running.
3051 void __perf_event_task_sched_in(struct task_struct *prev,
3052 struct task_struct *task)
3054 struct perf_event_context *ctx;
3058 * If cgroup events exist on this CPU, then we need to check if we have
3059 * to switch in PMU state; cgroup event are system-wide mode only.
3061 * Since cgroup events are CPU events, we must schedule these in before
3062 * we schedule in the task events.
3064 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3065 perf_cgroup_sched_in(prev, task);
3067 for_each_task_context_nr(ctxn) {
3068 ctx = task->perf_event_ctxp[ctxn];
3072 perf_event_context_sched_in(ctx, task);
3075 if (atomic_read(&nr_switch_events))
3076 perf_event_switch(task, prev, true);
3078 if (__this_cpu_read(perf_sched_cb_usages))
3079 perf_pmu_sched_task(prev, task, true);
3082 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3084 u64 frequency = event->attr.sample_freq;
3085 u64 sec = NSEC_PER_SEC;
3086 u64 divisor, dividend;
3088 int count_fls, nsec_fls, frequency_fls, sec_fls;
3090 count_fls = fls64(count);
3091 nsec_fls = fls64(nsec);
3092 frequency_fls = fls64(frequency);
3096 * We got @count in @nsec, with a target of sample_freq HZ
3097 * the target period becomes:
3100 * period = -------------------
3101 * @nsec * sample_freq
3106 * Reduce accuracy by one bit such that @a and @b converge
3107 * to a similar magnitude.
3109 #define REDUCE_FLS(a, b) \
3111 if (a##_fls > b##_fls) { \
3121 * Reduce accuracy until either term fits in a u64, then proceed with
3122 * the other, so that finally we can do a u64/u64 division.
3124 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3125 REDUCE_FLS(nsec, frequency);
3126 REDUCE_FLS(sec, count);
3129 if (count_fls + sec_fls > 64) {
3130 divisor = nsec * frequency;
3132 while (count_fls + sec_fls > 64) {
3133 REDUCE_FLS(count, sec);
3137 dividend = count * sec;
3139 dividend = count * sec;
3141 while (nsec_fls + frequency_fls > 64) {
3142 REDUCE_FLS(nsec, frequency);
3146 divisor = nsec * frequency;
3152 return div64_u64(dividend, divisor);
3155 static DEFINE_PER_CPU(int, perf_throttled_count);
3156 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3158 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3160 struct hw_perf_event *hwc = &event->hw;
3161 s64 period, sample_period;
3164 period = perf_calculate_period(event, nsec, count);
3166 delta = (s64)(period - hwc->sample_period);
3167 delta = (delta + 7) / 8; /* low pass filter */
3169 sample_period = hwc->sample_period + delta;
3174 hwc->sample_period = sample_period;
3176 if (local64_read(&hwc->period_left) > 8*sample_period) {
3178 event->pmu->stop(event, PERF_EF_UPDATE);
3180 local64_set(&hwc->period_left, 0);
3183 event->pmu->start(event, PERF_EF_RELOAD);
3188 * combine freq adjustment with unthrottling to avoid two passes over the
3189 * events. At the same time, make sure, having freq events does not change
3190 * the rate of unthrottling as that would introduce bias.
3192 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3195 struct perf_event *event;
3196 struct hw_perf_event *hwc;
3197 u64 now, period = TICK_NSEC;
3201 * only need to iterate over all events iff:
3202 * - context have events in frequency mode (needs freq adjust)
3203 * - there are events to unthrottle on this cpu
3205 if (!(ctx->nr_freq || needs_unthr))
3208 raw_spin_lock(&ctx->lock);
3209 perf_pmu_disable(ctx->pmu);
3211 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3212 if (event->state != PERF_EVENT_STATE_ACTIVE)
3215 if (!event_filter_match(event))
3218 perf_pmu_disable(event->pmu);
3222 if (hwc->interrupts == MAX_INTERRUPTS) {
3223 hwc->interrupts = 0;
3224 perf_log_throttle(event, 1);
3225 event->pmu->start(event, 0);
3228 if (!event->attr.freq || !event->attr.sample_freq)
3232 * stop the event and update event->count
3234 event->pmu->stop(event, PERF_EF_UPDATE);
3236 now = local64_read(&event->count);
3237 delta = now - hwc->freq_count_stamp;
3238 hwc->freq_count_stamp = now;
3242 * reload only if value has changed
3243 * we have stopped the event so tell that
3244 * to perf_adjust_period() to avoid stopping it
3248 perf_adjust_period(event, period, delta, false);
3250 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3252 perf_pmu_enable(event->pmu);
3255 perf_pmu_enable(ctx->pmu);
3256 raw_spin_unlock(&ctx->lock);
3260 * Round-robin a context's events:
3262 static void rotate_ctx(struct perf_event_context *ctx)
3265 * Rotate the first entry last of non-pinned groups. Rotation might be
3266 * disabled by the inheritance code.
3268 if (!ctx->rotate_disable)
3269 list_rotate_left(&ctx->flexible_groups);
3272 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
3274 struct perf_event_context *ctx = NULL;
3277 if (cpuctx->ctx.nr_events) {
3278 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3282 ctx = cpuctx->task_ctx;
3283 if (ctx && ctx->nr_events) {
3284 if (ctx->nr_events != ctx->nr_active)
3291 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3292 perf_pmu_disable(cpuctx->ctx.pmu);
3294 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3296 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3298 rotate_ctx(&cpuctx->ctx);
3302 perf_event_sched_in(cpuctx, ctx, current);
3304 perf_pmu_enable(cpuctx->ctx.pmu);
3305 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3311 void perf_event_task_tick(void)
3313 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3314 struct perf_event_context *ctx, *tmp;
3317 WARN_ON(!irqs_disabled());
3319 __this_cpu_inc(perf_throttled_seq);
3320 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3321 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3323 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3324 perf_adjust_freq_unthr_context(ctx, throttled);
3327 static int event_enable_on_exec(struct perf_event *event,
3328 struct perf_event_context *ctx)
3330 if (!event->attr.enable_on_exec)
3333 event->attr.enable_on_exec = 0;
3334 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3337 __perf_event_mark_enabled(event);
3343 * Enable all of a task's events that have been marked enable-on-exec.
3344 * This expects task == current.
3346 static void perf_event_enable_on_exec(int ctxn)
3348 struct perf_event_context *ctx, *clone_ctx = NULL;
3349 struct perf_cpu_context *cpuctx;
3350 struct perf_event *event;
3351 unsigned long flags;
3354 local_irq_save(flags);
3355 ctx = current->perf_event_ctxp[ctxn];
3356 if (!ctx || !ctx->nr_events)
3359 cpuctx = __get_cpu_context(ctx);
3360 perf_ctx_lock(cpuctx, ctx);
3361 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3362 list_for_each_entry(event, &ctx->event_list, event_entry)
3363 enabled |= event_enable_on_exec(event, ctx);
3366 * Unclone and reschedule this context if we enabled any event.
3369 clone_ctx = unclone_ctx(ctx);
3370 ctx_resched(cpuctx, ctx);
3372 perf_ctx_unlock(cpuctx, ctx);
3375 local_irq_restore(flags);
3381 struct perf_read_data {
3382 struct perf_event *event;
3388 * Cross CPU call to read the hardware event
3390 static void __perf_event_read(void *info)
3392 struct perf_read_data *data = info;
3393 struct perf_event *sub, *event = data->event;
3394 struct perf_event_context *ctx = event->ctx;
3395 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3396 struct pmu *pmu = event->pmu;
3399 * If this is a task context, we need to check whether it is
3400 * the current task context of this cpu. If not it has been
3401 * scheduled out before the smp call arrived. In that case
3402 * event->count would have been updated to a recent sample
3403 * when the event was scheduled out.
3405 if (ctx->task && cpuctx->task_ctx != ctx)
3408 raw_spin_lock(&ctx->lock);
3409 if (ctx->is_active) {
3410 update_context_time(ctx);
3411 update_cgrp_time_from_event(event);
3414 update_event_times(event);
3415 if (event->state != PERF_EVENT_STATE_ACTIVE)
3424 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3428 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3429 update_event_times(sub);
3430 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3432 * Use sibling's PMU rather than @event's since
3433 * sibling could be on different (eg: software) PMU.
3435 sub->pmu->read(sub);
3439 data->ret = pmu->commit_txn(pmu);
3442 raw_spin_unlock(&ctx->lock);
3445 static inline u64 perf_event_count(struct perf_event *event)
3447 if (event->pmu->count)
3448 return event->pmu->count(event);
3450 return __perf_event_count(event);
3454 * NMI-safe method to read a local event, that is an event that
3456 * - either for the current task, or for this CPU
3457 * - does not have inherit set, for inherited task events
3458 * will not be local and we cannot read them atomically
3459 * - must not have a pmu::count method
3461 u64 perf_event_read_local(struct perf_event *event)
3463 unsigned long flags;
3467 * Disabling interrupts avoids all counter scheduling (context
3468 * switches, timer based rotation and IPIs).
3470 local_irq_save(flags);
3472 /* If this is a per-task event, it must be for current */
3473 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3474 event->hw.target != current);
3476 /* If this is a per-CPU event, it must be for this CPU */
3477 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3478 event->cpu != smp_processor_id());
3481 * It must not be an event with inherit set, we cannot read
3482 * all child counters from atomic context.
3484 WARN_ON_ONCE(event->attr.inherit);
3487 * It must not have a pmu::count method, those are not
3490 WARN_ON_ONCE(event->pmu->count);
3493 * If the event is currently on this CPU, its either a per-task event,
3494 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3497 if (event->oncpu == smp_processor_id())
3498 event->pmu->read(event);
3500 val = local64_read(&event->count);
3501 local_irq_restore(flags);
3506 static int perf_event_read(struct perf_event *event, bool group)
3511 * If event is enabled and currently active on a CPU, update the
3512 * value in the event structure:
3514 if (event->state == PERF_EVENT_STATE_ACTIVE) {
3515 struct perf_read_data data = {
3520 smp_call_function_single(event->oncpu,
3521 __perf_event_read, &data, 1);
3523 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3524 struct perf_event_context *ctx = event->ctx;
3525 unsigned long flags;
3527 raw_spin_lock_irqsave(&ctx->lock, flags);
3529 * may read while context is not active
3530 * (e.g., thread is blocked), in that case
3531 * we cannot update context time
3533 if (ctx->is_active) {
3534 update_context_time(ctx);
3535 update_cgrp_time_from_event(event);
3538 update_group_times(event);
3540 update_event_times(event);
3541 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3548 * Initialize the perf_event context in a task_struct:
3550 static void __perf_event_init_context(struct perf_event_context *ctx)
3552 raw_spin_lock_init(&ctx->lock);
3553 mutex_init(&ctx->mutex);
3554 INIT_LIST_HEAD(&ctx->active_ctx_list);
3555 INIT_LIST_HEAD(&ctx->pinned_groups);
3556 INIT_LIST_HEAD(&ctx->flexible_groups);
3557 INIT_LIST_HEAD(&ctx->event_list);
3558 atomic_set(&ctx->refcount, 1);
3561 static struct perf_event_context *
3562 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3564 struct perf_event_context *ctx;
3566 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3570 __perf_event_init_context(ctx);
3573 get_task_struct(task);
3580 static struct task_struct *
3581 find_lively_task_by_vpid(pid_t vpid)
3583 struct task_struct *task;
3589 task = find_task_by_vpid(vpid);
3591 get_task_struct(task);
3595 return ERR_PTR(-ESRCH);
3601 * Returns a matching context with refcount and pincount.
3603 static struct perf_event_context *
3604 find_get_context(struct pmu *pmu, struct task_struct *task,
3605 struct perf_event *event)
3607 struct perf_event_context *ctx, *clone_ctx = NULL;
3608 struct perf_cpu_context *cpuctx;
3609 void *task_ctx_data = NULL;
3610 unsigned long flags;
3612 int cpu = event->cpu;
3615 /* Must be root to operate on a CPU event: */
3616 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3617 return ERR_PTR(-EACCES);
3620 * We could be clever and allow to attach a event to an
3621 * offline CPU and activate it when the CPU comes up, but
3624 if (!cpu_online(cpu))
3625 return ERR_PTR(-ENODEV);
3627 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3636 ctxn = pmu->task_ctx_nr;
3640 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3641 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3642 if (!task_ctx_data) {
3649 ctx = perf_lock_task_context(task, ctxn, &flags);
3651 clone_ctx = unclone_ctx(ctx);
3654 if (task_ctx_data && !ctx->task_ctx_data) {
3655 ctx->task_ctx_data = task_ctx_data;
3656 task_ctx_data = NULL;
3658 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3663 ctx = alloc_perf_context(pmu, task);
3668 if (task_ctx_data) {
3669 ctx->task_ctx_data = task_ctx_data;
3670 task_ctx_data = NULL;
3674 mutex_lock(&task->perf_event_mutex);
3676 * If it has already passed perf_event_exit_task().
3677 * we must see PF_EXITING, it takes this mutex too.
3679 if (task->flags & PF_EXITING)
3681 else if (task->perf_event_ctxp[ctxn])
3686 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3688 mutex_unlock(&task->perf_event_mutex);
3690 if (unlikely(err)) {
3699 kfree(task_ctx_data);
3703 kfree(task_ctx_data);
3704 return ERR_PTR(err);
3707 static void perf_event_free_filter(struct perf_event *event);
3708 static void perf_event_free_bpf_prog(struct perf_event *event);
3710 static void free_event_rcu(struct rcu_head *head)
3712 struct perf_event *event;
3714 event = container_of(head, struct perf_event, rcu_head);
3716 put_pid_ns(event->ns);
3717 perf_event_free_filter(event);
3721 static void ring_buffer_attach(struct perf_event *event,
3722 struct ring_buffer *rb);
3724 static void detach_sb_event(struct perf_event *event)
3726 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
3728 raw_spin_lock(&pel->lock);
3729 list_del_rcu(&event->sb_list);
3730 raw_spin_unlock(&pel->lock);
3733 static bool is_sb_event(struct perf_event *event)
3735 struct perf_event_attr *attr = &event->attr;
3740 if (event->attach_state & PERF_ATTACH_TASK)
3743 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
3744 attr->comm || attr->comm_exec ||
3746 attr->context_switch)
3751 static void unaccount_pmu_sb_event(struct perf_event *event)
3753 if (is_sb_event(event))
3754 detach_sb_event(event);
3757 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3762 if (is_cgroup_event(event))
3763 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3766 #ifdef CONFIG_NO_HZ_FULL
3767 static DEFINE_SPINLOCK(nr_freq_lock);
3770 static void unaccount_freq_event_nohz(void)
3772 #ifdef CONFIG_NO_HZ_FULL
3773 spin_lock(&nr_freq_lock);
3774 if (atomic_dec_and_test(&nr_freq_events))
3775 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
3776 spin_unlock(&nr_freq_lock);
3780 static void unaccount_freq_event(void)
3782 if (tick_nohz_full_enabled())
3783 unaccount_freq_event_nohz();
3785 atomic_dec(&nr_freq_events);
3788 static void unaccount_event(struct perf_event *event)
3795 if (event->attach_state & PERF_ATTACH_TASK)
3797 if (event->attr.mmap || event->attr.mmap_data)
3798 atomic_dec(&nr_mmap_events);
3799 if (event->attr.comm)
3800 atomic_dec(&nr_comm_events);
3801 if (event->attr.task)
3802 atomic_dec(&nr_task_events);
3803 if (event->attr.freq)
3804 unaccount_freq_event();
3805 if (event->attr.context_switch) {
3807 atomic_dec(&nr_switch_events);
3809 if (is_cgroup_event(event))
3811 if (has_branch_stack(event))
3815 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3816 schedule_delayed_work(&perf_sched_work, HZ);
3819 unaccount_event_cpu(event, event->cpu);
3821 unaccount_pmu_sb_event(event);
3824 static void perf_sched_delayed(struct work_struct *work)
3826 mutex_lock(&perf_sched_mutex);
3827 if (atomic_dec_and_test(&perf_sched_count))
3828 static_branch_disable(&perf_sched_events);
3829 mutex_unlock(&perf_sched_mutex);
3833 * The following implement mutual exclusion of events on "exclusive" pmus
3834 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3835 * at a time, so we disallow creating events that might conflict, namely:
3837 * 1) cpu-wide events in the presence of per-task events,
3838 * 2) per-task events in the presence of cpu-wide events,
3839 * 3) two matching events on the same context.
3841 * The former two cases are handled in the allocation path (perf_event_alloc(),
3842 * _free_event()), the latter -- before the first perf_install_in_context().
3844 static int exclusive_event_init(struct perf_event *event)
3846 struct pmu *pmu = event->pmu;
3848 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3852 * Prevent co-existence of per-task and cpu-wide events on the
3853 * same exclusive pmu.
3855 * Negative pmu::exclusive_cnt means there are cpu-wide
3856 * events on this "exclusive" pmu, positive means there are
3859 * Since this is called in perf_event_alloc() path, event::ctx
3860 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3861 * to mean "per-task event", because unlike other attach states it
3862 * never gets cleared.
3864 if (event->attach_state & PERF_ATTACH_TASK) {
3865 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3868 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3875 static void exclusive_event_destroy(struct perf_event *event)
3877 struct pmu *pmu = event->pmu;
3879 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3882 /* see comment in exclusive_event_init() */
3883 if (event->attach_state & PERF_ATTACH_TASK)
3884 atomic_dec(&pmu->exclusive_cnt);
3886 atomic_inc(&pmu->exclusive_cnt);
3889 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3891 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3892 (e1->cpu == e2->cpu ||
3899 /* Called under the same ctx::mutex as perf_install_in_context() */
3900 static bool exclusive_event_installable(struct perf_event *event,
3901 struct perf_event_context *ctx)
3903 struct perf_event *iter_event;
3904 struct pmu *pmu = event->pmu;
3906 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3909 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3910 if (exclusive_event_match(iter_event, event))
3917 static void perf_addr_filters_splice(struct perf_event *event,
3918 struct list_head *head);
3920 static void _free_event(struct perf_event *event)
3922 irq_work_sync(&event->pending);
3924 unaccount_event(event);
3928 * Can happen when we close an event with re-directed output.
3930 * Since we have a 0 refcount, perf_mmap_close() will skip
3931 * over us; possibly making our ring_buffer_put() the last.
3933 mutex_lock(&event->mmap_mutex);
3934 ring_buffer_attach(event, NULL);
3935 mutex_unlock(&event->mmap_mutex);
3938 if (is_cgroup_event(event))
3939 perf_detach_cgroup(event);
3941 if (!event->parent) {
3942 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3943 put_callchain_buffers();
3946 perf_event_free_bpf_prog(event);
3947 perf_addr_filters_splice(event, NULL);
3948 kfree(event->addr_filters_offs);
3951 event->destroy(event);
3954 put_ctx(event->ctx);
3956 exclusive_event_destroy(event);
3957 module_put(event->pmu->module);
3959 call_rcu(&event->rcu_head, free_event_rcu);
3963 * Used to free events which have a known refcount of 1, such as in error paths
3964 * where the event isn't exposed yet and inherited events.
3966 static void free_event(struct perf_event *event)
3968 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3969 "unexpected event refcount: %ld; ptr=%p\n",
3970 atomic_long_read(&event->refcount), event)) {
3971 /* leak to avoid use-after-free */
3979 * Remove user event from the owner task.
3981 static void perf_remove_from_owner(struct perf_event *event)
3983 struct task_struct *owner;
3987 * Matches the smp_store_release() in perf_event_exit_task(). If we
3988 * observe !owner it means the list deletion is complete and we can
3989 * indeed free this event, otherwise we need to serialize on
3990 * owner->perf_event_mutex.
3992 owner = lockless_dereference(event->owner);
3995 * Since delayed_put_task_struct() also drops the last
3996 * task reference we can safely take a new reference
3997 * while holding the rcu_read_lock().
3999 get_task_struct(owner);
4005 * If we're here through perf_event_exit_task() we're already
4006 * holding ctx->mutex which would be an inversion wrt. the
4007 * normal lock order.
4009 * However we can safely take this lock because its the child
4012 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4015 * We have to re-check the event->owner field, if it is cleared
4016 * we raced with perf_event_exit_task(), acquiring the mutex
4017 * ensured they're done, and we can proceed with freeing the
4021 list_del_init(&event->owner_entry);
4022 smp_store_release(&event->owner, NULL);
4024 mutex_unlock(&owner->perf_event_mutex);
4025 put_task_struct(owner);
4029 static void put_event(struct perf_event *event)
4031 if (!atomic_long_dec_and_test(&event->refcount))
4038 * Kill an event dead; while event:refcount will preserve the event
4039 * object, it will not preserve its functionality. Once the last 'user'
4040 * gives up the object, we'll destroy the thing.
4042 int perf_event_release_kernel(struct perf_event *event)
4044 struct perf_event_context *ctx = event->ctx;
4045 struct perf_event *child, *tmp;
4048 * If we got here through err_file: fput(event_file); we will not have
4049 * attached to a context yet.
4052 WARN_ON_ONCE(event->attach_state &
4053 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4057 if (!is_kernel_event(event))
4058 perf_remove_from_owner(event);
4060 ctx = perf_event_ctx_lock(event);
4061 WARN_ON_ONCE(ctx->parent_ctx);
4062 perf_remove_from_context(event, DETACH_GROUP);
4064 raw_spin_lock_irq(&ctx->lock);
4066 * Mark this even as STATE_DEAD, there is no external reference to it
4069 * Anybody acquiring event->child_mutex after the below loop _must_
4070 * also see this, most importantly inherit_event() which will avoid
4071 * placing more children on the list.
4073 * Thus this guarantees that we will in fact observe and kill _ALL_
4076 event->state = PERF_EVENT_STATE_DEAD;
4077 raw_spin_unlock_irq(&ctx->lock);
4079 perf_event_ctx_unlock(event, ctx);
4082 mutex_lock(&event->child_mutex);
4083 list_for_each_entry(child, &event->child_list, child_list) {
4086 * Cannot change, child events are not migrated, see the
4087 * comment with perf_event_ctx_lock_nested().
4089 ctx = lockless_dereference(child->ctx);
4091 * Since child_mutex nests inside ctx::mutex, we must jump
4092 * through hoops. We start by grabbing a reference on the ctx.
4094 * Since the event cannot get freed while we hold the
4095 * child_mutex, the context must also exist and have a !0
4101 * Now that we have a ctx ref, we can drop child_mutex, and
4102 * acquire ctx::mutex without fear of it going away. Then we
4103 * can re-acquire child_mutex.
4105 mutex_unlock(&event->child_mutex);
4106 mutex_lock(&ctx->mutex);
4107 mutex_lock(&event->child_mutex);
4110 * Now that we hold ctx::mutex and child_mutex, revalidate our
4111 * state, if child is still the first entry, it didn't get freed
4112 * and we can continue doing so.
4114 tmp = list_first_entry_or_null(&event->child_list,
4115 struct perf_event, child_list);
4117 perf_remove_from_context(child, DETACH_GROUP);
4118 list_del(&child->child_list);
4121 * This matches the refcount bump in inherit_event();
4122 * this can't be the last reference.
4127 mutex_unlock(&event->child_mutex);
4128 mutex_unlock(&ctx->mutex);
4132 mutex_unlock(&event->child_mutex);
4135 put_event(event); /* Must be the 'last' reference */
4138 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4141 * Called when the last reference to the file is gone.
4143 static int perf_release(struct inode *inode, struct file *file)
4145 perf_event_release_kernel(file->private_data);
4149 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4151 struct perf_event *child;
4157 mutex_lock(&event->child_mutex);
4159 (void)perf_event_read(event, false);
4160 total += perf_event_count(event);
4162 *enabled += event->total_time_enabled +
4163 atomic64_read(&event->child_total_time_enabled);
4164 *running += event->total_time_running +
4165 atomic64_read(&event->child_total_time_running);
4167 list_for_each_entry(child, &event->child_list, child_list) {
4168 (void)perf_event_read(child, false);
4169 total += perf_event_count(child);
4170 *enabled += child->total_time_enabled;
4171 *running += child->total_time_running;
4173 mutex_unlock(&event->child_mutex);
4177 EXPORT_SYMBOL_GPL(perf_event_read_value);
4179 static int __perf_read_group_add(struct perf_event *leader,
4180 u64 read_format, u64 *values)
4182 struct perf_event *sub;
4183 int n = 1; /* skip @nr */
4186 ret = perf_event_read(leader, true);
4191 * Since we co-schedule groups, {enabled,running} times of siblings
4192 * will be identical to those of the leader, so we only publish one
4195 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4196 values[n++] += leader->total_time_enabled +
4197 atomic64_read(&leader->child_total_time_enabled);
4200 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4201 values[n++] += leader->total_time_running +
4202 atomic64_read(&leader->child_total_time_running);
4206 * Write {count,id} tuples for every sibling.
4208 values[n++] += perf_event_count(leader);
4209 if (read_format & PERF_FORMAT_ID)
4210 values[n++] = primary_event_id(leader);
4212 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4213 values[n++] += perf_event_count(sub);
4214 if (read_format & PERF_FORMAT_ID)
4215 values[n++] = primary_event_id(sub);
4221 static int perf_read_group(struct perf_event *event,
4222 u64 read_format, char __user *buf)
4224 struct perf_event *leader = event->group_leader, *child;
4225 struct perf_event_context *ctx = leader->ctx;
4229 lockdep_assert_held(&ctx->mutex);
4231 values = kzalloc(event->read_size, GFP_KERNEL);
4235 values[0] = 1 + leader->nr_siblings;
4238 * By locking the child_mutex of the leader we effectively
4239 * lock the child list of all siblings.. XXX explain how.
4241 mutex_lock(&leader->child_mutex);
4243 ret = __perf_read_group_add(leader, read_format, values);
4247 list_for_each_entry(child, &leader->child_list, child_list) {
4248 ret = __perf_read_group_add(child, read_format, values);
4253 mutex_unlock(&leader->child_mutex);
4255 ret = event->read_size;
4256 if (copy_to_user(buf, values, event->read_size))
4261 mutex_unlock(&leader->child_mutex);
4267 static int perf_read_one(struct perf_event *event,
4268 u64 read_format, char __user *buf)
4270 u64 enabled, running;
4274 values[n++] = perf_event_read_value(event, &enabled, &running);
4275 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4276 values[n++] = enabled;
4277 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4278 values[n++] = running;
4279 if (read_format & PERF_FORMAT_ID)
4280 values[n++] = primary_event_id(event);
4282 if (copy_to_user(buf, values, n * sizeof(u64)))
4285 return n * sizeof(u64);
4288 static bool is_event_hup(struct perf_event *event)
4292 if (event->state > PERF_EVENT_STATE_EXIT)
4295 mutex_lock(&event->child_mutex);
4296 no_children = list_empty(&event->child_list);
4297 mutex_unlock(&event->child_mutex);
4302 * Read the performance event - simple non blocking version for now
4305 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4307 u64 read_format = event->attr.read_format;
4311 * Return end-of-file for a read on a event that is in
4312 * error state (i.e. because it was pinned but it couldn't be
4313 * scheduled on to the CPU at some point).
4315 if (event->state == PERF_EVENT_STATE_ERROR)
4318 if (count < event->read_size)
4321 WARN_ON_ONCE(event->ctx->parent_ctx);
4322 if (read_format & PERF_FORMAT_GROUP)
4323 ret = perf_read_group(event, read_format, buf);
4325 ret = perf_read_one(event, read_format, buf);
4331 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4333 struct perf_event *event = file->private_data;
4334 struct perf_event_context *ctx;
4337 ctx = perf_event_ctx_lock(event);
4338 ret = __perf_read(event, buf, count);
4339 perf_event_ctx_unlock(event, ctx);
4344 static unsigned int perf_poll(struct file *file, poll_table *wait)
4346 struct perf_event *event = file->private_data;
4347 struct ring_buffer *rb;
4348 unsigned int events = POLLHUP;
4350 poll_wait(file, &event->waitq, wait);
4352 if (is_event_hup(event))
4356 * Pin the event->rb by taking event->mmap_mutex; otherwise
4357 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4359 mutex_lock(&event->mmap_mutex);
4362 events = atomic_xchg(&rb->poll, 0);
4363 mutex_unlock(&event->mmap_mutex);
4367 static void _perf_event_reset(struct perf_event *event)
4369 (void)perf_event_read(event, false);
4370 local64_set(&event->count, 0);
4371 perf_event_update_userpage(event);
4375 * Holding the top-level event's child_mutex means that any
4376 * descendant process that has inherited this event will block
4377 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4378 * task existence requirements of perf_event_enable/disable.
4380 static void perf_event_for_each_child(struct perf_event *event,
4381 void (*func)(struct perf_event *))
4383 struct perf_event *child;
4385 WARN_ON_ONCE(event->ctx->parent_ctx);
4387 mutex_lock(&event->child_mutex);
4389 list_for_each_entry(child, &event->child_list, child_list)
4391 mutex_unlock(&event->child_mutex);
4394 static void perf_event_for_each(struct perf_event *event,
4395 void (*func)(struct perf_event *))
4397 struct perf_event_context *ctx = event->ctx;
4398 struct perf_event *sibling;
4400 lockdep_assert_held(&ctx->mutex);
4402 event = event->group_leader;
4404 perf_event_for_each_child(event, func);
4405 list_for_each_entry(sibling, &event->sibling_list, group_entry)
4406 perf_event_for_each_child(sibling, func);
4409 static void __perf_event_period(struct perf_event *event,
4410 struct perf_cpu_context *cpuctx,
4411 struct perf_event_context *ctx,
4414 u64 value = *((u64 *)info);
4417 if (event->attr.freq) {
4418 event->attr.sample_freq = value;
4420 event->attr.sample_period = value;
4421 event->hw.sample_period = value;
4424 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4426 perf_pmu_disable(ctx->pmu);
4428 * We could be throttled; unthrottle now to avoid the tick
4429 * trying to unthrottle while we already re-started the event.
4431 if (event->hw.interrupts == MAX_INTERRUPTS) {
4432 event->hw.interrupts = 0;
4433 perf_log_throttle(event, 1);
4435 event->pmu->stop(event, PERF_EF_UPDATE);
4438 local64_set(&event->hw.period_left, 0);
4441 event->pmu->start(event, PERF_EF_RELOAD);
4442 perf_pmu_enable(ctx->pmu);
4446 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4450 if (!is_sampling_event(event))
4453 if (copy_from_user(&value, arg, sizeof(value)))
4459 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4462 event_function_call(event, __perf_event_period, &value);
4467 static const struct file_operations perf_fops;
4469 static inline int perf_fget_light(int fd, struct fd *p)
4471 struct fd f = fdget(fd);
4475 if (f.file->f_op != &perf_fops) {
4483 static int perf_event_set_output(struct perf_event *event,
4484 struct perf_event *output_event);
4485 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4486 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4488 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4490 void (*func)(struct perf_event *);
4494 case PERF_EVENT_IOC_ENABLE:
4495 func = _perf_event_enable;
4497 case PERF_EVENT_IOC_DISABLE:
4498 func = _perf_event_disable;
4500 case PERF_EVENT_IOC_RESET:
4501 func = _perf_event_reset;
4504 case PERF_EVENT_IOC_REFRESH:
4505 return _perf_event_refresh(event, arg);
4507 case PERF_EVENT_IOC_PERIOD:
4508 return perf_event_period(event, (u64 __user *)arg);
4510 case PERF_EVENT_IOC_ID:
4512 u64 id = primary_event_id(event);
4514 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4519 case PERF_EVENT_IOC_SET_OUTPUT:
4523 struct perf_event *output_event;
4525 ret = perf_fget_light(arg, &output);
4528 output_event = output.file->private_data;
4529 ret = perf_event_set_output(event, output_event);
4532 ret = perf_event_set_output(event, NULL);
4537 case PERF_EVENT_IOC_SET_FILTER:
4538 return perf_event_set_filter(event, (void __user *)arg);
4540 case PERF_EVENT_IOC_SET_BPF:
4541 return perf_event_set_bpf_prog(event, arg);
4543 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
4544 struct ring_buffer *rb;
4547 rb = rcu_dereference(event->rb);
4548 if (!rb || !rb->nr_pages) {
4552 rb_toggle_paused(rb, !!arg);
4560 if (flags & PERF_IOC_FLAG_GROUP)
4561 perf_event_for_each(event, func);
4563 perf_event_for_each_child(event, func);
4568 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4570 struct perf_event *event = file->private_data;
4571 struct perf_event_context *ctx;
4574 ctx = perf_event_ctx_lock(event);
4575 ret = _perf_ioctl(event, cmd, arg);
4576 perf_event_ctx_unlock(event, ctx);
4581 #ifdef CONFIG_COMPAT
4582 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4585 switch (_IOC_NR(cmd)) {
4586 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4587 case _IOC_NR(PERF_EVENT_IOC_ID):
4588 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4589 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4590 cmd &= ~IOCSIZE_MASK;
4591 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4595 return perf_ioctl(file, cmd, arg);
4598 # define perf_compat_ioctl NULL
4601 int perf_event_task_enable(void)
4603 struct perf_event_context *ctx;
4604 struct perf_event *event;
4606 mutex_lock(¤t->perf_event_mutex);
4607 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4608 ctx = perf_event_ctx_lock(event);
4609 perf_event_for_each_child(event, _perf_event_enable);
4610 perf_event_ctx_unlock(event, ctx);
4612 mutex_unlock(¤t->perf_event_mutex);
4617 int perf_event_task_disable(void)
4619 struct perf_event_context *ctx;
4620 struct perf_event *event;
4622 mutex_lock(¤t->perf_event_mutex);
4623 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
4624 ctx = perf_event_ctx_lock(event);
4625 perf_event_for_each_child(event, _perf_event_disable);
4626 perf_event_ctx_unlock(event, ctx);
4628 mutex_unlock(¤t->perf_event_mutex);
4633 static int perf_event_index(struct perf_event *event)
4635 if (event->hw.state & PERF_HES_STOPPED)
4638 if (event->state != PERF_EVENT_STATE_ACTIVE)
4641 return event->pmu->event_idx(event);
4644 static void calc_timer_values(struct perf_event *event,
4651 *now = perf_clock();
4652 ctx_time = event->shadow_ctx_time + *now;
4653 *enabled = ctx_time - event->tstamp_enabled;
4654 *running = ctx_time - event->tstamp_running;
4657 static void perf_event_init_userpage(struct perf_event *event)
4659 struct perf_event_mmap_page *userpg;
4660 struct ring_buffer *rb;
4663 rb = rcu_dereference(event->rb);
4667 userpg = rb->user_page;
4669 /* Allow new userspace to detect that bit 0 is deprecated */
4670 userpg->cap_bit0_is_deprecated = 1;
4671 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4672 userpg->data_offset = PAGE_SIZE;
4673 userpg->data_size = perf_data_size(rb);
4679 void __weak arch_perf_update_userpage(
4680 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4685 * Callers need to ensure there can be no nesting of this function, otherwise
4686 * the seqlock logic goes bad. We can not serialize this because the arch
4687 * code calls this from NMI context.
4689 void perf_event_update_userpage(struct perf_event *event)
4691 struct perf_event_mmap_page *userpg;
4692 struct ring_buffer *rb;
4693 u64 enabled, running, now;
4696 rb = rcu_dereference(event->rb);
4701 * compute total_time_enabled, total_time_running
4702 * based on snapshot values taken when the event
4703 * was last scheduled in.
4705 * we cannot simply called update_context_time()
4706 * because of locking issue as we can be called in
4709 calc_timer_values(event, &now, &enabled, &running);
4711 userpg = rb->user_page;
4713 * Disable preemption so as to not let the corresponding user-space
4714 * spin too long if we get preempted.
4719 userpg->index = perf_event_index(event);
4720 userpg->offset = perf_event_count(event);
4722 userpg->offset -= local64_read(&event->hw.prev_count);
4724 userpg->time_enabled = enabled +
4725 atomic64_read(&event->child_total_time_enabled);
4727 userpg->time_running = running +
4728 atomic64_read(&event->child_total_time_running);
4730 arch_perf_update_userpage(event, userpg, now);
4739 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4741 struct perf_event *event = vma->vm_file->private_data;
4742 struct ring_buffer *rb;
4743 int ret = VM_FAULT_SIGBUS;
4745 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4746 if (vmf->pgoff == 0)
4752 rb = rcu_dereference(event->rb);
4756 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4759 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4763 get_page(vmf->page);
4764 vmf->page->mapping = vma->vm_file->f_mapping;
4765 vmf->page->index = vmf->pgoff;
4774 static void ring_buffer_attach(struct perf_event *event,
4775 struct ring_buffer *rb)
4777 struct ring_buffer *old_rb = NULL;
4778 unsigned long flags;
4782 * Should be impossible, we set this when removing
4783 * event->rb_entry and wait/clear when adding event->rb_entry.
4785 WARN_ON_ONCE(event->rcu_pending);
4788 spin_lock_irqsave(&old_rb->event_lock, flags);
4789 list_del_rcu(&event->rb_entry);
4790 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4792 event->rcu_batches = get_state_synchronize_rcu();
4793 event->rcu_pending = 1;
4797 if (event->rcu_pending) {
4798 cond_synchronize_rcu(event->rcu_batches);
4799 event->rcu_pending = 0;
4802 spin_lock_irqsave(&rb->event_lock, flags);
4803 list_add_rcu(&event->rb_entry, &rb->event_list);
4804 spin_unlock_irqrestore(&rb->event_lock, flags);
4807 rcu_assign_pointer(event->rb, rb);
4810 ring_buffer_put(old_rb);
4812 * Since we detached before setting the new rb, so that we
4813 * could attach the new rb, we could have missed a wakeup.
4816 wake_up_all(&event->waitq);
4820 static void ring_buffer_wakeup(struct perf_event *event)
4822 struct ring_buffer *rb;
4825 rb = rcu_dereference(event->rb);
4827 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4828 wake_up_all(&event->waitq);
4833 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4835 struct ring_buffer *rb;
4838 rb = rcu_dereference(event->rb);
4840 if (!atomic_inc_not_zero(&rb->refcount))
4848 void ring_buffer_put(struct ring_buffer *rb)
4850 if (!atomic_dec_and_test(&rb->refcount))
4853 WARN_ON_ONCE(!list_empty(&rb->event_list));
4855 call_rcu(&rb->rcu_head, rb_free_rcu);
4858 static void perf_mmap_open(struct vm_area_struct *vma)
4860 struct perf_event *event = vma->vm_file->private_data;
4862 atomic_inc(&event->mmap_count);
4863 atomic_inc(&event->rb->mmap_count);
4866 atomic_inc(&event->rb->aux_mmap_count);
4868 if (event->pmu->event_mapped)
4869 event->pmu->event_mapped(event);
4872 static void perf_pmu_output_stop(struct perf_event *event);
4875 * A buffer can be mmap()ed multiple times; either directly through the same
4876 * event, or through other events by use of perf_event_set_output().
4878 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4879 * the buffer here, where we still have a VM context. This means we need
4880 * to detach all events redirecting to us.
4882 static void perf_mmap_close(struct vm_area_struct *vma)
4884 struct perf_event *event = vma->vm_file->private_data;
4886 struct ring_buffer *rb = ring_buffer_get(event);
4887 struct user_struct *mmap_user = rb->mmap_user;
4888 int mmap_locked = rb->mmap_locked;
4889 unsigned long size = perf_data_size(rb);
4891 if (event->pmu->event_unmapped)
4892 event->pmu->event_unmapped(event);
4895 * rb->aux_mmap_count will always drop before rb->mmap_count and
4896 * event->mmap_count, so it is ok to use event->mmap_mutex to
4897 * serialize with perf_mmap here.
4899 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4900 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4902 * Stop all AUX events that are writing to this buffer,
4903 * so that we can free its AUX pages and corresponding PMU
4904 * data. Note that after rb::aux_mmap_count dropped to zero,
4905 * they won't start any more (see perf_aux_output_begin()).
4907 perf_pmu_output_stop(event);
4909 /* now it's safe to free the pages */
4910 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4911 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4913 /* this has to be the last one */
4915 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
4917 mutex_unlock(&event->mmap_mutex);
4920 atomic_dec(&rb->mmap_count);
4922 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4925 ring_buffer_attach(event, NULL);
4926 mutex_unlock(&event->mmap_mutex);
4928 /* If there's still other mmap()s of this buffer, we're done. */
4929 if (atomic_read(&rb->mmap_count))
4933 * No other mmap()s, detach from all other events that might redirect
4934 * into the now unreachable buffer. Somewhat complicated by the
4935 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4939 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4940 if (!atomic_long_inc_not_zero(&event->refcount)) {
4942 * This event is en-route to free_event() which will
4943 * detach it and remove it from the list.
4949 mutex_lock(&event->mmap_mutex);
4951 * Check we didn't race with perf_event_set_output() which can
4952 * swizzle the rb from under us while we were waiting to
4953 * acquire mmap_mutex.
4955 * If we find a different rb; ignore this event, a next
4956 * iteration will no longer find it on the list. We have to
4957 * still restart the iteration to make sure we're not now
4958 * iterating the wrong list.
4960 if (event->rb == rb)
4961 ring_buffer_attach(event, NULL);
4963 mutex_unlock(&event->mmap_mutex);
4967 * Restart the iteration; either we're on the wrong list or
4968 * destroyed its integrity by doing a deletion.
4975 * It could be there's still a few 0-ref events on the list; they'll
4976 * get cleaned up by free_event() -- they'll also still have their
4977 * ref on the rb and will free it whenever they are done with it.
4979 * Aside from that, this buffer is 'fully' detached and unmapped,
4980 * undo the VM accounting.
4983 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4984 vma->vm_mm->pinned_vm -= mmap_locked;
4985 free_uid(mmap_user);
4988 ring_buffer_put(rb); /* could be last */
4991 static const struct vm_operations_struct perf_mmap_vmops = {
4992 .open = perf_mmap_open,
4993 .close = perf_mmap_close, /* non mergable */
4994 .fault = perf_mmap_fault,
4995 .page_mkwrite = perf_mmap_fault,
4998 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5000 struct perf_event *event = file->private_data;
5001 unsigned long user_locked, user_lock_limit;
5002 struct user_struct *user = current_user();
5003 unsigned long locked, lock_limit;
5004 struct ring_buffer *rb = NULL;
5005 unsigned long vma_size;
5006 unsigned long nr_pages;
5007 long user_extra = 0, extra = 0;
5008 int ret = 0, flags = 0;
5011 * Don't allow mmap() of inherited per-task counters. This would
5012 * create a performance issue due to all children writing to the
5015 if (event->cpu == -1 && event->attr.inherit)
5018 if (!(vma->vm_flags & VM_SHARED))
5021 vma_size = vma->vm_end - vma->vm_start;
5023 if (vma->vm_pgoff == 0) {
5024 nr_pages = (vma_size / PAGE_SIZE) - 1;
5027 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5028 * mapped, all subsequent mappings should have the same size
5029 * and offset. Must be above the normal perf buffer.
5031 u64 aux_offset, aux_size;
5036 nr_pages = vma_size / PAGE_SIZE;
5038 mutex_lock(&event->mmap_mutex);
5045 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
5046 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
5048 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5051 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5054 /* already mapped with a different offset */
5055 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5058 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5061 /* already mapped with a different size */
5062 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5065 if (!is_power_of_2(nr_pages))
5068 if (!atomic_inc_not_zero(&rb->mmap_count))
5071 if (rb_has_aux(rb)) {
5072 atomic_inc(&rb->aux_mmap_count);
5077 atomic_set(&rb->aux_mmap_count, 1);
5078 user_extra = nr_pages;
5084 * If we have rb pages ensure they're a power-of-two number, so we
5085 * can do bitmasks instead of modulo.
5087 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5090 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5093 WARN_ON_ONCE(event->ctx->parent_ctx);
5095 mutex_lock(&event->mmap_mutex);
5097 if (event->rb->nr_pages != nr_pages) {
5102 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5104 * Raced against perf_mmap_close() through
5105 * perf_event_set_output(). Try again, hope for better
5108 mutex_unlock(&event->mmap_mutex);
5115 user_extra = nr_pages + 1;
5118 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5121 * Increase the limit linearly with more CPUs:
5123 user_lock_limit *= num_online_cpus();
5125 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5127 if (user_locked > user_lock_limit)
5128 extra = user_locked - user_lock_limit;
5130 lock_limit = rlimit(RLIMIT_MEMLOCK);
5131 lock_limit >>= PAGE_SHIFT;
5132 locked = vma->vm_mm->pinned_vm + extra;
5134 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5135 !capable(CAP_IPC_LOCK)) {
5140 WARN_ON(!rb && event->rb);
5142 if (vma->vm_flags & VM_WRITE)
5143 flags |= RING_BUFFER_WRITABLE;
5146 rb = rb_alloc(nr_pages,
5147 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5155 atomic_set(&rb->mmap_count, 1);
5156 rb->mmap_user = get_current_user();
5157 rb->mmap_locked = extra;
5159 ring_buffer_attach(event, rb);
5161 perf_event_init_userpage(event);
5162 perf_event_update_userpage(event);
5164 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5165 event->attr.aux_watermark, flags);
5167 rb->aux_mmap_locked = extra;
5172 atomic_long_add(user_extra, &user->locked_vm);
5173 vma->vm_mm->pinned_vm += extra;
5175 atomic_inc(&event->mmap_count);
5177 atomic_dec(&rb->mmap_count);
5180 mutex_unlock(&event->mmap_mutex);
5183 * Since pinned accounting is per vm we cannot allow fork() to copy our
5186 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5187 vma->vm_ops = &perf_mmap_vmops;
5189 if (event->pmu->event_mapped)
5190 event->pmu->event_mapped(event);
5195 static int perf_fasync(int fd, struct file *filp, int on)
5197 struct inode *inode = file_inode(filp);
5198 struct perf_event *event = filp->private_data;
5202 retval = fasync_helper(fd, filp, on, &event->fasync);
5203 inode_unlock(inode);
5211 static const struct file_operations perf_fops = {
5212 .llseek = no_llseek,
5213 .release = perf_release,
5216 .unlocked_ioctl = perf_ioctl,
5217 .compat_ioctl = perf_compat_ioctl,
5219 .fasync = perf_fasync,
5225 * If there's data, ensure we set the poll() state and publish everything
5226 * to user-space before waking everybody up.
5229 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5231 /* only the parent has fasync state */
5233 event = event->parent;
5234 return &event->fasync;
5237 void perf_event_wakeup(struct perf_event *event)
5239 ring_buffer_wakeup(event);
5241 if (event->pending_kill) {
5242 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5243 event->pending_kill = 0;
5247 static void perf_pending_event(struct irq_work *entry)
5249 struct perf_event *event = container_of(entry,
5250 struct perf_event, pending);
5253 rctx = perf_swevent_get_recursion_context();
5255 * If we 'fail' here, that's OK, it means recursion is already disabled
5256 * and we won't recurse 'further'.
5259 if (event->pending_disable) {
5260 event->pending_disable = 0;
5261 perf_event_disable_local(event);
5264 if (event->pending_wakeup) {
5265 event->pending_wakeup = 0;
5266 perf_event_wakeup(event);
5270 perf_swevent_put_recursion_context(rctx);
5274 * We assume there is only KVM supporting the callbacks.
5275 * Later on, we might change it to a list if there is
5276 * another virtualization implementation supporting the callbacks.
5278 struct perf_guest_info_callbacks *perf_guest_cbs;
5280 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5282 perf_guest_cbs = cbs;
5285 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5287 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5289 perf_guest_cbs = NULL;
5292 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5295 perf_output_sample_regs(struct perf_output_handle *handle,
5296 struct pt_regs *regs, u64 mask)
5300 for_each_set_bit(bit, (const unsigned long *) &mask,
5301 sizeof(mask) * BITS_PER_BYTE) {
5304 val = perf_reg_value(regs, bit);
5305 perf_output_put(handle, val);
5309 static void perf_sample_regs_user(struct perf_regs *regs_user,
5310 struct pt_regs *regs,
5311 struct pt_regs *regs_user_copy)
5313 if (user_mode(regs)) {
5314 regs_user->abi = perf_reg_abi(current);
5315 regs_user->regs = regs;
5316 } else if (current->mm) {
5317 perf_get_regs_user(regs_user, regs, regs_user_copy);
5319 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5320 regs_user->regs = NULL;
5324 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5325 struct pt_regs *regs)
5327 regs_intr->regs = regs;
5328 regs_intr->abi = perf_reg_abi(current);
5333 * Get remaining task size from user stack pointer.
5335 * It'd be better to take stack vma map and limit this more
5336 * precisly, but there's no way to get it safely under interrupt,
5337 * so using TASK_SIZE as limit.
5339 static u64 perf_ustack_task_size(struct pt_regs *regs)
5341 unsigned long addr = perf_user_stack_pointer(regs);
5343 if (!addr || addr >= TASK_SIZE)
5346 return TASK_SIZE - addr;
5350 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5351 struct pt_regs *regs)
5355 /* No regs, no stack pointer, no dump. */
5360 * Check if we fit in with the requested stack size into the:
5362 * If we don't, we limit the size to the TASK_SIZE.
5364 * - remaining sample size
5365 * If we don't, we customize the stack size to
5366 * fit in to the remaining sample size.
5369 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5370 stack_size = min(stack_size, (u16) task_size);
5372 /* Current header size plus static size and dynamic size. */
5373 header_size += 2 * sizeof(u64);
5375 /* Do we fit in with the current stack dump size? */
5376 if ((u16) (header_size + stack_size) < header_size) {
5378 * If we overflow the maximum size for the sample,
5379 * we customize the stack dump size to fit in.
5381 stack_size = USHRT_MAX - header_size - sizeof(u64);
5382 stack_size = round_up(stack_size, sizeof(u64));
5389 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5390 struct pt_regs *regs)
5392 /* Case of a kernel thread, nothing to dump */
5395 perf_output_put(handle, size);
5404 * - the size requested by user or the best one we can fit
5405 * in to the sample max size
5407 * - user stack dump data
5409 * - the actual dumped size
5413 perf_output_put(handle, dump_size);
5416 sp = perf_user_stack_pointer(regs);
5417 rem = __output_copy_user(handle, (void *) sp, dump_size);
5418 dyn_size = dump_size - rem;
5420 perf_output_skip(handle, rem);
5423 perf_output_put(handle, dyn_size);
5427 static void __perf_event_header__init_id(struct perf_event_header *header,
5428 struct perf_sample_data *data,
5429 struct perf_event *event)
5431 u64 sample_type = event->attr.sample_type;
5433 data->type = sample_type;
5434 header->size += event->id_header_size;
5436 if (sample_type & PERF_SAMPLE_TID) {
5437 /* namespace issues */
5438 data->tid_entry.pid = perf_event_pid(event, current);
5439 data->tid_entry.tid = perf_event_tid(event, current);
5442 if (sample_type & PERF_SAMPLE_TIME)
5443 data->time = perf_event_clock(event);
5445 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5446 data->id = primary_event_id(event);
5448 if (sample_type & PERF_SAMPLE_STREAM_ID)
5449 data->stream_id = event->id;
5451 if (sample_type & PERF_SAMPLE_CPU) {
5452 data->cpu_entry.cpu = raw_smp_processor_id();
5453 data->cpu_entry.reserved = 0;
5457 void perf_event_header__init_id(struct perf_event_header *header,
5458 struct perf_sample_data *data,
5459 struct perf_event *event)
5461 if (event->attr.sample_id_all)
5462 __perf_event_header__init_id(header, data, event);
5465 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5466 struct perf_sample_data *data)
5468 u64 sample_type = data->type;
5470 if (sample_type & PERF_SAMPLE_TID)
5471 perf_output_put(handle, data->tid_entry);
5473 if (sample_type & PERF_SAMPLE_TIME)
5474 perf_output_put(handle, data->time);
5476 if (sample_type & PERF_SAMPLE_ID)
5477 perf_output_put(handle, data->id);
5479 if (sample_type & PERF_SAMPLE_STREAM_ID)
5480 perf_output_put(handle, data->stream_id);
5482 if (sample_type & PERF_SAMPLE_CPU)
5483 perf_output_put(handle, data->cpu_entry);
5485 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5486 perf_output_put(handle, data->id);
5489 void perf_event__output_id_sample(struct perf_event *event,
5490 struct perf_output_handle *handle,
5491 struct perf_sample_data *sample)
5493 if (event->attr.sample_id_all)
5494 __perf_event__output_id_sample(handle, sample);
5497 static void perf_output_read_one(struct perf_output_handle *handle,
5498 struct perf_event *event,
5499 u64 enabled, u64 running)
5501 u64 read_format = event->attr.read_format;
5505 values[n++] = perf_event_count(event);
5506 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5507 values[n++] = enabled +
5508 atomic64_read(&event->child_total_time_enabled);
5510 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5511 values[n++] = running +
5512 atomic64_read(&event->child_total_time_running);
5514 if (read_format & PERF_FORMAT_ID)
5515 values[n++] = primary_event_id(event);
5517 __output_copy(handle, values, n * sizeof(u64));
5521 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
5523 static void perf_output_read_group(struct perf_output_handle *handle,
5524 struct perf_event *event,
5525 u64 enabled, u64 running)
5527 struct perf_event *leader = event->group_leader, *sub;
5528 u64 read_format = event->attr.read_format;
5532 values[n++] = 1 + leader->nr_siblings;
5534 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5535 values[n++] = enabled;
5537 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5538 values[n++] = running;
5540 if (leader != event)
5541 leader->pmu->read(leader);
5543 values[n++] = perf_event_count(leader);
5544 if (read_format & PERF_FORMAT_ID)
5545 values[n++] = primary_event_id(leader);
5547 __output_copy(handle, values, n * sizeof(u64));
5549 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5552 if ((sub != event) &&
5553 (sub->state == PERF_EVENT_STATE_ACTIVE))
5554 sub->pmu->read(sub);
5556 values[n++] = perf_event_count(sub);
5557 if (read_format & PERF_FORMAT_ID)
5558 values[n++] = primary_event_id(sub);
5560 __output_copy(handle, values, n * sizeof(u64));
5564 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5565 PERF_FORMAT_TOTAL_TIME_RUNNING)
5567 static void perf_output_read(struct perf_output_handle *handle,
5568 struct perf_event *event)
5570 u64 enabled = 0, running = 0, now;
5571 u64 read_format = event->attr.read_format;
5574 * compute total_time_enabled, total_time_running
5575 * based on snapshot values taken when the event
5576 * was last scheduled in.
5578 * we cannot simply called update_context_time()
5579 * because of locking issue as we are called in
5582 if (read_format & PERF_FORMAT_TOTAL_TIMES)
5583 calc_timer_values(event, &now, &enabled, &running);
5585 if (event->attr.read_format & PERF_FORMAT_GROUP)
5586 perf_output_read_group(handle, event, enabled, running);
5588 perf_output_read_one(handle, event, enabled, running);
5591 void perf_output_sample(struct perf_output_handle *handle,
5592 struct perf_event_header *header,
5593 struct perf_sample_data *data,
5594 struct perf_event *event)
5596 u64 sample_type = data->type;
5598 perf_output_put(handle, *header);
5600 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5601 perf_output_put(handle, data->id);
5603 if (sample_type & PERF_SAMPLE_IP)
5604 perf_output_put(handle, data->ip);
5606 if (sample_type & PERF_SAMPLE_TID)
5607 perf_output_put(handle, data->tid_entry);
5609 if (sample_type & PERF_SAMPLE_TIME)
5610 perf_output_put(handle, data->time);
5612 if (sample_type & PERF_SAMPLE_ADDR)
5613 perf_output_put(handle, data->addr);
5615 if (sample_type & PERF_SAMPLE_ID)
5616 perf_output_put(handle, data->id);
5618 if (sample_type & PERF_SAMPLE_STREAM_ID)
5619 perf_output_put(handle, data->stream_id);
5621 if (sample_type & PERF_SAMPLE_CPU)
5622 perf_output_put(handle, data->cpu_entry);
5624 if (sample_type & PERF_SAMPLE_PERIOD)
5625 perf_output_put(handle, data->period);
5627 if (sample_type & PERF_SAMPLE_READ)
5628 perf_output_read(handle, event);
5630 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5631 if (data->callchain) {
5634 if (data->callchain)
5635 size += data->callchain->nr;
5637 size *= sizeof(u64);
5639 __output_copy(handle, data->callchain, size);
5642 perf_output_put(handle, nr);
5646 if (sample_type & PERF_SAMPLE_RAW) {
5647 struct perf_raw_record *raw = data->raw;
5650 struct perf_raw_frag *frag = &raw->frag;
5652 perf_output_put(handle, raw->size);
5655 __output_custom(handle, frag->copy,
5656 frag->data, frag->size);
5658 __output_copy(handle, frag->data,
5661 if (perf_raw_frag_last(frag))
5666 __output_skip(handle, NULL, frag->pad);
5672 .size = sizeof(u32),
5675 perf_output_put(handle, raw);
5679 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5680 if (data->br_stack) {
5683 size = data->br_stack->nr
5684 * sizeof(struct perf_branch_entry);
5686 perf_output_put(handle, data->br_stack->nr);
5687 perf_output_copy(handle, data->br_stack->entries, size);
5690 * we always store at least the value of nr
5693 perf_output_put(handle, nr);
5697 if (sample_type & PERF_SAMPLE_REGS_USER) {
5698 u64 abi = data->regs_user.abi;
5701 * If there are no regs to dump, notice it through
5702 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5704 perf_output_put(handle, abi);
5707 u64 mask = event->attr.sample_regs_user;
5708 perf_output_sample_regs(handle,
5709 data->regs_user.regs,
5714 if (sample_type & PERF_SAMPLE_STACK_USER) {
5715 perf_output_sample_ustack(handle,
5716 data->stack_user_size,
5717 data->regs_user.regs);
5720 if (sample_type & PERF_SAMPLE_WEIGHT)
5721 perf_output_put(handle, data->weight);
5723 if (sample_type & PERF_SAMPLE_DATA_SRC)
5724 perf_output_put(handle, data->data_src.val);
5726 if (sample_type & PERF_SAMPLE_TRANSACTION)
5727 perf_output_put(handle, data->txn);
5729 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5730 u64 abi = data->regs_intr.abi;
5732 * If there are no regs to dump, notice it through
5733 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5735 perf_output_put(handle, abi);
5738 u64 mask = event->attr.sample_regs_intr;
5740 perf_output_sample_regs(handle,
5741 data->regs_intr.regs,
5746 if (!event->attr.watermark) {
5747 int wakeup_events = event->attr.wakeup_events;
5749 if (wakeup_events) {
5750 struct ring_buffer *rb = handle->rb;
5751 int events = local_inc_return(&rb->events);
5753 if (events >= wakeup_events) {
5754 local_sub(wakeup_events, &rb->events);
5755 local_inc(&rb->wakeup);
5761 void perf_prepare_sample(struct perf_event_header *header,
5762 struct perf_sample_data *data,
5763 struct perf_event *event,
5764 struct pt_regs *regs)
5766 u64 sample_type = event->attr.sample_type;
5768 header->type = PERF_RECORD_SAMPLE;
5769 header->size = sizeof(*header) + event->header_size;
5772 header->misc |= perf_misc_flags(regs);
5774 __perf_event_header__init_id(header, data, event);
5776 if (sample_type & PERF_SAMPLE_IP)
5777 data->ip = perf_instruction_pointer(regs);
5779 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5782 data->callchain = perf_callchain(event, regs);
5784 if (data->callchain)
5785 size += data->callchain->nr;
5787 header->size += size * sizeof(u64);
5790 if (sample_type & PERF_SAMPLE_RAW) {
5791 struct perf_raw_record *raw = data->raw;
5795 struct perf_raw_frag *frag = &raw->frag;
5800 if (perf_raw_frag_last(frag))
5805 size = round_up(sum + sizeof(u32), sizeof(u64));
5806 raw->size = size - sizeof(u32);
5807 frag->pad = raw->size - sum;
5812 header->size += size;
5815 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5816 int size = sizeof(u64); /* nr */
5817 if (data->br_stack) {
5818 size += data->br_stack->nr
5819 * sizeof(struct perf_branch_entry);
5821 header->size += size;
5824 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5825 perf_sample_regs_user(&data->regs_user, regs,
5826 &data->regs_user_copy);
5828 if (sample_type & PERF_SAMPLE_REGS_USER) {
5829 /* regs dump ABI info */
5830 int size = sizeof(u64);
5832 if (data->regs_user.regs) {
5833 u64 mask = event->attr.sample_regs_user;
5834 size += hweight64(mask) * sizeof(u64);
5837 header->size += size;
5840 if (sample_type & PERF_SAMPLE_STACK_USER) {
5842 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5843 * processed as the last one or have additional check added
5844 * in case new sample type is added, because we could eat
5845 * up the rest of the sample size.
5847 u16 stack_size = event->attr.sample_stack_user;
5848 u16 size = sizeof(u64);
5850 stack_size = perf_sample_ustack_size(stack_size, header->size,
5851 data->regs_user.regs);
5854 * If there is something to dump, add space for the dump
5855 * itself and for the field that tells the dynamic size,
5856 * which is how many have been actually dumped.
5859 size += sizeof(u64) + stack_size;
5861 data->stack_user_size = stack_size;
5862 header->size += size;
5865 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5866 /* regs dump ABI info */
5867 int size = sizeof(u64);
5869 perf_sample_regs_intr(&data->regs_intr, regs);
5871 if (data->regs_intr.regs) {
5872 u64 mask = event->attr.sample_regs_intr;
5874 size += hweight64(mask) * sizeof(u64);
5877 header->size += size;
5881 static void __always_inline
5882 __perf_event_output(struct perf_event *event,
5883 struct perf_sample_data *data,
5884 struct pt_regs *regs,
5885 int (*output_begin)(struct perf_output_handle *,
5886 struct perf_event *,
5889 struct perf_output_handle handle;
5890 struct perf_event_header header;
5892 /* protect the callchain buffers */
5895 perf_prepare_sample(&header, data, event, regs);
5897 if (output_begin(&handle, event, header.size))
5900 perf_output_sample(&handle, &header, data, event);
5902 perf_output_end(&handle);
5909 perf_event_output_forward(struct perf_event *event,
5910 struct perf_sample_data *data,
5911 struct pt_regs *regs)
5913 __perf_event_output(event, data, regs, perf_output_begin_forward);
5917 perf_event_output_backward(struct perf_event *event,
5918 struct perf_sample_data *data,
5919 struct pt_regs *regs)
5921 __perf_event_output(event, data, regs, perf_output_begin_backward);
5925 perf_event_output(struct perf_event *event,
5926 struct perf_sample_data *data,
5927 struct pt_regs *regs)
5929 __perf_event_output(event, data, regs, perf_output_begin);
5936 struct perf_read_event {
5937 struct perf_event_header header;
5944 perf_event_read_event(struct perf_event *event,
5945 struct task_struct *task)
5947 struct perf_output_handle handle;
5948 struct perf_sample_data sample;
5949 struct perf_read_event read_event = {
5951 .type = PERF_RECORD_READ,
5953 .size = sizeof(read_event) + event->read_size,
5955 .pid = perf_event_pid(event, task),
5956 .tid = perf_event_tid(event, task),
5960 perf_event_header__init_id(&read_event.header, &sample, event);
5961 ret = perf_output_begin(&handle, event, read_event.header.size);
5965 perf_output_put(&handle, read_event);
5966 perf_output_read(&handle, event);
5967 perf_event__output_id_sample(event, &handle, &sample);
5969 perf_output_end(&handle);
5972 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
5975 perf_iterate_ctx(struct perf_event_context *ctx,
5976 perf_iterate_f output,
5977 void *data, bool all)
5979 struct perf_event *event;
5981 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5983 if (event->state < PERF_EVENT_STATE_INACTIVE)
5985 if (!event_filter_match(event))
5989 output(event, data);
5993 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
5995 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
5996 struct perf_event *event;
5998 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6000 * Skip events that are not fully formed yet; ensure that
6001 * if we observe event->ctx, both event and ctx will be
6002 * complete enough. See perf_install_in_context().
6004 if (!smp_load_acquire(&event->ctx))
6007 if (event->state < PERF_EVENT_STATE_INACTIVE)
6009 if (!event_filter_match(event))
6011 output(event, data);
6016 * Iterate all events that need to receive side-band events.
6018 * For new callers; ensure that account_pmu_sb_event() includes
6019 * your event, otherwise it might not get delivered.
6022 perf_iterate_sb(perf_iterate_f output, void *data,
6023 struct perf_event_context *task_ctx)
6025 struct perf_event_context *ctx;
6032 * If we have task_ctx != NULL we only notify the task context itself.
6033 * The task_ctx is set only for EXIT events before releasing task
6037 perf_iterate_ctx(task_ctx, output, data, false);
6041 perf_iterate_sb_cpu(output, data);
6043 for_each_task_context_nr(ctxn) {
6044 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6046 perf_iterate_ctx(ctx, output, data, false);
6054 * Clear all file-based filters at exec, they'll have to be
6055 * re-instated when/if these objects are mmapped again.
6057 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6059 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6060 struct perf_addr_filter *filter;
6061 unsigned int restart = 0, count = 0;
6062 unsigned long flags;
6064 if (!has_addr_filter(event))
6067 raw_spin_lock_irqsave(&ifh->lock, flags);
6068 list_for_each_entry(filter, &ifh->list, entry) {
6069 if (filter->inode) {
6070 event->addr_filters_offs[count] = 0;
6078 event->addr_filters_gen++;
6079 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6082 perf_event_restart(event);
6085 void perf_event_exec(void)
6087 struct perf_event_context *ctx;
6091 for_each_task_context_nr(ctxn) {
6092 ctx = current->perf_event_ctxp[ctxn];
6096 perf_event_enable_on_exec(ctxn);
6098 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6104 struct remote_output {
6105 struct ring_buffer *rb;
6109 static void __perf_event_output_stop(struct perf_event *event, void *data)
6111 struct perf_event *parent = event->parent;
6112 struct remote_output *ro = data;
6113 struct ring_buffer *rb = ro->rb;
6114 struct stop_event_data sd = {
6118 if (!has_aux(event))
6125 * In case of inheritance, it will be the parent that links to the
6126 * ring-buffer, but it will be the child that's actually using it:
6128 if (rcu_dereference(parent->rb) == rb)
6129 ro->err = __perf_event_stop(&sd);
6132 static int __perf_pmu_output_stop(void *info)
6134 struct perf_event *event = info;
6135 struct pmu *pmu = event->pmu;
6136 struct perf_cpu_context *cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
6137 struct remote_output ro = {
6142 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6143 if (cpuctx->task_ctx)
6144 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6151 static void perf_pmu_output_stop(struct perf_event *event)
6153 struct perf_event *iter;
6158 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6160 * For per-CPU events, we need to make sure that neither they
6161 * nor their children are running; for cpu==-1 events it's
6162 * sufficient to stop the event itself if it's active, since
6163 * it can't have children.
6167 cpu = READ_ONCE(iter->oncpu);
6172 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6173 if (err == -EAGAIN) {
6182 * task tracking -- fork/exit
6184 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6187 struct perf_task_event {
6188 struct task_struct *task;
6189 struct perf_event_context *task_ctx;
6192 struct perf_event_header header;
6202 static int perf_event_task_match(struct perf_event *event)
6204 return event->attr.comm || event->attr.mmap ||
6205 event->attr.mmap2 || event->attr.mmap_data ||
6209 static void perf_event_task_output(struct perf_event *event,
6212 struct perf_task_event *task_event = data;
6213 struct perf_output_handle handle;
6214 struct perf_sample_data sample;
6215 struct task_struct *task = task_event->task;
6216 int ret, size = task_event->event_id.header.size;
6218 if (!perf_event_task_match(event))
6221 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6223 ret = perf_output_begin(&handle, event,
6224 task_event->event_id.header.size);
6228 task_event->event_id.pid = perf_event_pid(event, task);
6229 task_event->event_id.ppid = perf_event_pid(event, current);
6231 task_event->event_id.tid = perf_event_tid(event, task);
6232 task_event->event_id.ptid = perf_event_tid(event, current);
6234 task_event->event_id.time = perf_event_clock(event);
6236 perf_output_put(&handle, task_event->event_id);
6238 perf_event__output_id_sample(event, &handle, &sample);
6240 perf_output_end(&handle);
6242 task_event->event_id.header.size = size;
6245 static void perf_event_task(struct task_struct *task,
6246 struct perf_event_context *task_ctx,
6249 struct perf_task_event task_event;
6251 if (!atomic_read(&nr_comm_events) &&
6252 !atomic_read(&nr_mmap_events) &&
6253 !atomic_read(&nr_task_events))
6256 task_event = (struct perf_task_event){
6258 .task_ctx = task_ctx,
6261 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6263 .size = sizeof(task_event.event_id),
6273 perf_iterate_sb(perf_event_task_output,
6278 void perf_event_fork(struct task_struct *task)
6280 perf_event_task(task, NULL, 1);
6287 struct perf_comm_event {
6288 struct task_struct *task;
6293 struct perf_event_header header;
6300 static int perf_event_comm_match(struct perf_event *event)
6302 return event->attr.comm;
6305 static void perf_event_comm_output(struct perf_event *event,
6308 struct perf_comm_event *comm_event = data;
6309 struct perf_output_handle handle;
6310 struct perf_sample_data sample;
6311 int size = comm_event->event_id.header.size;
6314 if (!perf_event_comm_match(event))
6317 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6318 ret = perf_output_begin(&handle, event,
6319 comm_event->event_id.header.size);
6324 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6325 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6327 perf_output_put(&handle, comm_event->event_id);
6328 __output_copy(&handle, comm_event->comm,
6329 comm_event->comm_size);
6331 perf_event__output_id_sample(event, &handle, &sample);
6333 perf_output_end(&handle);
6335 comm_event->event_id.header.size = size;
6338 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6340 char comm[TASK_COMM_LEN];
6343 memset(comm, 0, sizeof(comm));
6344 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6345 size = ALIGN(strlen(comm)+1, sizeof(u64));
6347 comm_event->comm = comm;
6348 comm_event->comm_size = size;
6350 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6352 perf_iterate_sb(perf_event_comm_output,
6357 void perf_event_comm(struct task_struct *task, bool exec)
6359 struct perf_comm_event comm_event;
6361 if (!atomic_read(&nr_comm_events))
6364 comm_event = (struct perf_comm_event){
6370 .type = PERF_RECORD_COMM,
6371 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6379 perf_event_comm_event(&comm_event);
6386 struct perf_mmap_event {
6387 struct vm_area_struct *vma;
6389 const char *file_name;
6397 struct perf_event_header header;
6407 static int perf_event_mmap_match(struct perf_event *event,
6410 struct perf_mmap_event *mmap_event = data;
6411 struct vm_area_struct *vma = mmap_event->vma;
6412 int executable = vma->vm_flags & VM_EXEC;
6414 return (!executable && event->attr.mmap_data) ||
6415 (executable && (event->attr.mmap || event->attr.mmap2));
6418 static void perf_event_mmap_output(struct perf_event *event,
6421 struct perf_mmap_event *mmap_event = data;
6422 struct perf_output_handle handle;
6423 struct perf_sample_data sample;
6424 int size = mmap_event->event_id.header.size;
6427 if (!perf_event_mmap_match(event, data))
6430 if (event->attr.mmap2) {
6431 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6432 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6433 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6434 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6435 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6436 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6437 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6440 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6441 ret = perf_output_begin(&handle, event,
6442 mmap_event->event_id.header.size);
6446 mmap_event->event_id.pid = perf_event_pid(event, current);
6447 mmap_event->event_id.tid = perf_event_tid(event, current);
6449 perf_output_put(&handle, mmap_event->event_id);
6451 if (event->attr.mmap2) {
6452 perf_output_put(&handle, mmap_event->maj);
6453 perf_output_put(&handle, mmap_event->min);
6454 perf_output_put(&handle, mmap_event->ino);
6455 perf_output_put(&handle, mmap_event->ino_generation);
6456 perf_output_put(&handle, mmap_event->prot);
6457 perf_output_put(&handle, mmap_event->flags);
6460 __output_copy(&handle, mmap_event->file_name,
6461 mmap_event->file_size);
6463 perf_event__output_id_sample(event, &handle, &sample);
6465 perf_output_end(&handle);
6467 mmap_event->event_id.header.size = size;
6470 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6472 struct vm_area_struct *vma = mmap_event->vma;
6473 struct file *file = vma->vm_file;
6474 int maj = 0, min = 0;
6475 u64 ino = 0, gen = 0;
6476 u32 prot = 0, flags = 0;
6483 struct inode *inode;
6486 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6492 * d_path() works from the end of the rb backwards, so we
6493 * need to add enough zero bytes after the string to handle
6494 * the 64bit alignment we do later.
6496 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6501 inode = file_inode(vma->vm_file);
6502 dev = inode->i_sb->s_dev;
6504 gen = inode->i_generation;
6508 if (vma->vm_flags & VM_READ)
6510 if (vma->vm_flags & VM_WRITE)
6512 if (vma->vm_flags & VM_EXEC)
6515 if (vma->vm_flags & VM_MAYSHARE)
6518 flags = MAP_PRIVATE;
6520 if (vma->vm_flags & VM_DENYWRITE)
6521 flags |= MAP_DENYWRITE;
6522 if (vma->vm_flags & VM_MAYEXEC)
6523 flags |= MAP_EXECUTABLE;
6524 if (vma->vm_flags & VM_LOCKED)
6525 flags |= MAP_LOCKED;
6526 if (vma->vm_flags & VM_HUGETLB)
6527 flags |= MAP_HUGETLB;
6531 if (vma->vm_ops && vma->vm_ops->name) {
6532 name = (char *) vma->vm_ops->name(vma);
6537 name = (char *)arch_vma_name(vma);
6541 if (vma->vm_start <= vma->vm_mm->start_brk &&
6542 vma->vm_end >= vma->vm_mm->brk) {
6546 if (vma->vm_start <= vma->vm_mm->start_stack &&
6547 vma->vm_end >= vma->vm_mm->start_stack) {
6557 strlcpy(tmp, name, sizeof(tmp));
6561 * Since our buffer works in 8 byte units we need to align our string
6562 * size to a multiple of 8. However, we must guarantee the tail end is
6563 * zero'd out to avoid leaking random bits to userspace.
6565 size = strlen(name)+1;
6566 while (!IS_ALIGNED(size, sizeof(u64)))
6567 name[size++] = '\0';
6569 mmap_event->file_name = name;
6570 mmap_event->file_size = size;
6571 mmap_event->maj = maj;
6572 mmap_event->min = min;
6573 mmap_event->ino = ino;
6574 mmap_event->ino_generation = gen;
6575 mmap_event->prot = prot;
6576 mmap_event->flags = flags;
6578 if (!(vma->vm_flags & VM_EXEC))
6579 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6581 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6583 perf_iterate_sb(perf_event_mmap_output,
6591 * Whether this @filter depends on a dynamic object which is not loaded
6592 * yet or its load addresses are not known.
6594 static bool perf_addr_filter_needs_mmap(struct perf_addr_filter *filter)
6596 return filter->filter && filter->inode;
6600 * Check whether inode and address range match filter criteria.
6602 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
6603 struct file *file, unsigned long offset,
6606 if (filter->inode != file->f_inode)
6609 if (filter->offset > offset + size)
6612 if (filter->offset + filter->size < offset)
6618 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
6620 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6621 struct vm_area_struct *vma = data;
6622 unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
6623 struct file *file = vma->vm_file;
6624 struct perf_addr_filter *filter;
6625 unsigned int restart = 0, count = 0;
6627 if (!has_addr_filter(event))
6633 raw_spin_lock_irqsave(&ifh->lock, flags);
6634 list_for_each_entry(filter, &ifh->list, entry) {
6635 if (perf_addr_filter_match(filter, file, off,
6636 vma->vm_end - vma->vm_start)) {
6637 event->addr_filters_offs[count] = vma->vm_start;
6645 event->addr_filters_gen++;
6646 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6649 perf_event_restart(event);
6653 * Adjust all task's events' filters to the new vma
6655 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
6657 struct perf_event_context *ctx;
6661 for_each_task_context_nr(ctxn) {
6662 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6666 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
6671 void perf_event_mmap(struct vm_area_struct *vma)
6673 struct perf_mmap_event mmap_event;
6675 if (!atomic_read(&nr_mmap_events))
6678 mmap_event = (struct perf_mmap_event){
6684 .type = PERF_RECORD_MMAP,
6685 .misc = PERF_RECORD_MISC_USER,
6690 .start = vma->vm_start,
6691 .len = vma->vm_end - vma->vm_start,
6692 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
6694 /* .maj (attr_mmap2 only) */
6695 /* .min (attr_mmap2 only) */
6696 /* .ino (attr_mmap2 only) */
6697 /* .ino_generation (attr_mmap2 only) */
6698 /* .prot (attr_mmap2 only) */
6699 /* .flags (attr_mmap2 only) */
6702 perf_addr_filters_adjust(vma);
6703 perf_event_mmap_event(&mmap_event);
6706 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6707 unsigned long size, u64 flags)
6709 struct perf_output_handle handle;
6710 struct perf_sample_data sample;
6711 struct perf_aux_event {
6712 struct perf_event_header header;
6718 .type = PERF_RECORD_AUX,
6720 .size = sizeof(rec),
6728 perf_event_header__init_id(&rec.header, &sample, event);
6729 ret = perf_output_begin(&handle, event, rec.header.size);
6734 perf_output_put(&handle, rec);
6735 perf_event__output_id_sample(event, &handle, &sample);
6737 perf_output_end(&handle);
6741 * Lost/dropped samples logging
6743 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6745 struct perf_output_handle handle;
6746 struct perf_sample_data sample;
6750 struct perf_event_header header;
6752 } lost_samples_event = {
6754 .type = PERF_RECORD_LOST_SAMPLES,
6756 .size = sizeof(lost_samples_event),
6761 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6763 ret = perf_output_begin(&handle, event,
6764 lost_samples_event.header.size);
6768 perf_output_put(&handle, lost_samples_event);
6769 perf_event__output_id_sample(event, &handle, &sample);
6770 perf_output_end(&handle);
6774 * context_switch tracking
6777 struct perf_switch_event {
6778 struct task_struct *task;
6779 struct task_struct *next_prev;
6782 struct perf_event_header header;
6788 static int perf_event_switch_match(struct perf_event *event)
6790 return event->attr.context_switch;
6793 static void perf_event_switch_output(struct perf_event *event, void *data)
6795 struct perf_switch_event *se = data;
6796 struct perf_output_handle handle;
6797 struct perf_sample_data sample;
6800 if (!perf_event_switch_match(event))
6803 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6804 if (event->ctx->task) {
6805 se->event_id.header.type = PERF_RECORD_SWITCH;
6806 se->event_id.header.size = sizeof(se->event_id.header);
6808 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6809 se->event_id.header.size = sizeof(se->event_id);
6810 se->event_id.next_prev_pid =
6811 perf_event_pid(event, se->next_prev);
6812 se->event_id.next_prev_tid =
6813 perf_event_tid(event, se->next_prev);
6816 perf_event_header__init_id(&se->event_id.header, &sample, event);
6818 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6822 if (event->ctx->task)
6823 perf_output_put(&handle, se->event_id.header);
6825 perf_output_put(&handle, se->event_id);
6827 perf_event__output_id_sample(event, &handle, &sample);
6829 perf_output_end(&handle);
6832 static void perf_event_switch(struct task_struct *task,
6833 struct task_struct *next_prev, bool sched_in)
6835 struct perf_switch_event switch_event;
6837 /* N.B. caller checks nr_switch_events != 0 */
6839 switch_event = (struct perf_switch_event){
6841 .next_prev = next_prev,
6845 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6848 /* .next_prev_pid */
6849 /* .next_prev_tid */
6853 perf_iterate_sb(perf_event_switch_output,
6859 * IRQ throttle logging
6862 static void perf_log_throttle(struct perf_event *event, int enable)
6864 struct perf_output_handle handle;
6865 struct perf_sample_data sample;
6869 struct perf_event_header header;
6873 } throttle_event = {
6875 .type = PERF_RECORD_THROTTLE,
6877 .size = sizeof(throttle_event),
6879 .time = perf_event_clock(event),
6880 .id = primary_event_id(event),
6881 .stream_id = event->id,
6885 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6887 perf_event_header__init_id(&throttle_event.header, &sample, event);
6889 ret = perf_output_begin(&handle, event,
6890 throttle_event.header.size);
6894 perf_output_put(&handle, throttle_event);
6895 perf_event__output_id_sample(event, &handle, &sample);
6896 perf_output_end(&handle);
6899 static void perf_log_itrace_start(struct perf_event *event)
6901 struct perf_output_handle handle;
6902 struct perf_sample_data sample;
6903 struct perf_aux_event {
6904 struct perf_event_header header;
6911 event = event->parent;
6913 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6914 event->hw.itrace_started)
6917 rec.header.type = PERF_RECORD_ITRACE_START;
6918 rec.header.misc = 0;
6919 rec.header.size = sizeof(rec);
6920 rec.pid = perf_event_pid(event, current);
6921 rec.tid = perf_event_tid(event, current);
6923 perf_event_header__init_id(&rec.header, &sample, event);
6924 ret = perf_output_begin(&handle, event, rec.header.size);
6929 perf_output_put(&handle, rec);
6930 perf_event__output_id_sample(event, &handle, &sample);
6932 perf_output_end(&handle);
6936 * Generic event overflow handling, sampling.
6939 static int __perf_event_overflow(struct perf_event *event,
6940 int throttle, struct perf_sample_data *data,
6941 struct pt_regs *regs)
6943 int events = atomic_read(&event->event_limit);
6944 struct hw_perf_event *hwc = &event->hw;
6949 * Non-sampling counters might still use the PMI to fold short
6950 * hardware counters, ignore those.
6952 if (unlikely(!is_sampling_event(event)))
6955 seq = __this_cpu_read(perf_throttled_seq);
6956 if (seq != hwc->interrupts_seq) {
6957 hwc->interrupts_seq = seq;
6958 hwc->interrupts = 1;
6961 if (unlikely(throttle
6962 && hwc->interrupts >= max_samples_per_tick)) {
6963 __this_cpu_inc(perf_throttled_count);
6964 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
6965 hwc->interrupts = MAX_INTERRUPTS;
6966 perf_log_throttle(event, 0);
6971 if (event->attr.freq) {
6972 u64 now = perf_clock();
6973 s64 delta = now - hwc->freq_time_stamp;
6975 hwc->freq_time_stamp = now;
6977 if (delta > 0 && delta < 2*TICK_NSEC)
6978 perf_adjust_period(event, delta, hwc->last_period, true);
6982 * XXX event_limit might not quite work as expected on inherited
6986 event->pending_kill = POLL_IN;
6987 if (events && atomic_dec_and_test(&event->event_limit)) {
6989 event->pending_kill = POLL_HUP;
6990 event->pending_disable = 1;
6991 irq_work_queue(&event->pending);
6994 event->overflow_handler(event, data, regs);
6996 if (*perf_event_fasync(event) && event->pending_kill) {
6997 event->pending_wakeup = 1;
6998 irq_work_queue(&event->pending);
7004 int perf_event_overflow(struct perf_event *event,
7005 struct perf_sample_data *data,
7006 struct pt_regs *regs)
7008 return __perf_event_overflow(event, 1, data, regs);
7012 * Generic software event infrastructure
7015 struct swevent_htable {
7016 struct swevent_hlist *swevent_hlist;
7017 struct mutex hlist_mutex;
7020 /* Recursion avoidance in each contexts */
7021 int recursion[PERF_NR_CONTEXTS];
7024 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
7027 * We directly increment event->count and keep a second value in
7028 * event->hw.period_left to count intervals. This period event
7029 * is kept in the range [-sample_period, 0] so that we can use the
7033 u64 perf_swevent_set_period(struct perf_event *event)
7035 struct hw_perf_event *hwc = &event->hw;
7036 u64 period = hwc->last_period;
7040 hwc->last_period = hwc->sample_period;
7043 old = val = local64_read(&hwc->period_left);
7047 nr = div64_u64(period + val, period);
7048 offset = nr * period;
7050 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7056 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
7057 struct perf_sample_data *data,
7058 struct pt_regs *regs)
7060 struct hw_perf_event *hwc = &event->hw;
7064 overflow = perf_swevent_set_period(event);
7066 if (hwc->interrupts == MAX_INTERRUPTS)
7069 for (; overflow; overflow--) {
7070 if (__perf_event_overflow(event, throttle,
7073 * We inhibit the overflow from happening when
7074 * hwc->interrupts == MAX_INTERRUPTS.
7082 static void perf_swevent_event(struct perf_event *event, u64 nr,
7083 struct perf_sample_data *data,
7084 struct pt_regs *regs)
7086 struct hw_perf_event *hwc = &event->hw;
7088 local64_add(nr, &event->count);
7093 if (!is_sampling_event(event))
7096 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
7098 return perf_swevent_overflow(event, 1, data, regs);
7100 data->period = event->hw.last_period;
7102 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
7103 return perf_swevent_overflow(event, 1, data, regs);
7105 if (local64_add_negative(nr, &hwc->period_left))
7108 perf_swevent_overflow(event, 0, data, regs);
7111 static int perf_exclude_event(struct perf_event *event,
7112 struct pt_regs *regs)
7114 if (event->hw.state & PERF_HES_STOPPED)
7118 if (event->attr.exclude_user && user_mode(regs))
7121 if (event->attr.exclude_kernel && !user_mode(regs))
7128 static int perf_swevent_match(struct perf_event *event,
7129 enum perf_type_id type,
7131 struct perf_sample_data *data,
7132 struct pt_regs *regs)
7134 if (event->attr.type != type)
7137 if (event->attr.config != event_id)
7140 if (perf_exclude_event(event, regs))
7146 static inline u64 swevent_hash(u64 type, u32 event_id)
7148 u64 val = event_id | (type << 32);
7150 return hash_64(val, SWEVENT_HLIST_BITS);
7153 static inline struct hlist_head *
7154 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
7156 u64 hash = swevent_hash(type, event_id);
7158 return &hlist->heads[hash];
7161 /* For the read side: events when they trigger */
7162 static inline struct hlist_head *
7163 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
7165 struct swevent_hlist *hlist;
7167 hlist = rcu_dereference(swhash->swevent_hlist);
7171 return __find_swevent_head(hlist, type, event_id);
7174 /* For the event head insertion and removal in the hlist */
7175 static inline struct hlist_head *
7176 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
7178 struct swevent_hlist *hlist;
7179 u32 event_id = event->attr.config;
7180 u64 type = event->attr.type;
7183 * Event scheduling is always serialized against hlist allocation
7184 * and release. Which makes the protected version suitable here.
7185 * The context lock guarantees that.
7187 hlist = rcu_dereference_protected(swhash->swevent_hlist,
7188 lockdep_is_held(&event->ctx->lock));
7192 return __find_swevent_head(hlist, type, event_id);
7195 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
7197 struct perf_sample_data *data,
7198 struct pt_regs *regs)
7200 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7201 struct perf_event *event;
7202 struct hlist_head *head;
7205 head = find_swevent_head_rcu(swhash, type, event_id);
7209 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7210 if (perf_swevent_match(event, type, event_id, data, regs))
7211 perf_swevent_event(event, nr, data, regs);
7217 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
7219 int perf_swevent_get_recursion_context(void)
7221 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7223 return get_recursion_context(swhash->recursion);
7225 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
7227 void perf_swevent_put_recursion_context(int rctx)
7229 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7231 put_recursion_context(swhash->recursion, rctx);
7234 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7236 struct perf_sample_data data;
7238 if (WARN_ON_ONCE(!regs))
7241 perf_sample_data_init(&data, addr, 0);
7242 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
7245 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7249 preempt_disable_notrace();
7250 rctx = perf_swevent_get_recursion_context();
7251 if (unlikely(rctx < 0))
7254 ___perf_sw_event(event_id, nr, regs, addr);
7256 perf_swevent_put_recursion_context(rctx);
7258 preempt_enable_notrace();
7261 static void perf_swevent_read(struct perf_event *event)
7265 static int perf_swevent_add(struct perf_event *event, int flags)
7267 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7268 struct hw_perf_event *hwc = &event->hw;
7269 struct hlist_head *head;
7271 if (is_sampling_event(event)) {
7272 hwc->last_period = hwc->sample_period;
7273 perf_swevent_set_period(event);
7276 hwc->state = !(flags & PERF_EF_START);
7278 head = find_swevent_head(swhash, event);
7279 if (WARN_ON_ONCE(!head))
7282 hlist_add_head_rcu(&event->hlist_entry, head);
7283 perf_event_update_userpage(event);
7288 static void perf_swevent_del(struct perf_event *event, int flags)
7290 hlist_del_rcu(&event->hlist_entry);
7293 static void perf_swevent_start(struct perf_event *event, int flags)
7295 event->hw.state = 0;
7298 static void perf_swevent_stop(struct perf_event *event, int flags)
7300 event->hw.state = PERF_HES_STOPPED;
7303 /* Deref the hlist from the update side */
7304 static inline struct swevent_hlist *
7305 swevent_hlist_deref(struct swevent_htable *swhash)
7307 return rcu_dereference_protected(swhash->swevent_hlist,
7308 lockdep_is_held(&swhash->hlist_mutex));
7311 static void swevent_hlist_release(struct swevent_htable *swhash)
7313 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7318 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7319 kfree_rcu(hlist, rcu_head);
7322 static void swevent_hlist_put_cpu(int cpu)
7324 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7326 mutex_lock(&swhash->hlist_mutex);
7328 if (!--swhash->hlist_refcount)
7329 swevent_hlist_release(swhash);
7331 mutex_unlock(&swhash->hlist_mutex);
7334 static void swevent_hlist_put(void)
7338 for_each_possible_cpu(cpu)
7339 swevent_hlist_put_cpu(cpu);
7342 static int swevent_hlist_get_cpu(int cpu)
7344 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7347 mutex_lock(&swhash->hlist_mutex);
7348 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7349 struct swevent_hlist *hlist;
7351 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7356 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7358 swhash->hlist_refcount++;
7360 mutex_unlock(&swhash->hlist_mutex);
7365 static int swevent_hlist_get(void)
7367 int err, cpu, failed_cpu;
7370 for_each_possible_cpu(cpu) {
7371 err = swevent_hlist_get_cpu(cpu);
7381 for_each_possible_cpu(cpu) {
7382 if (cpu == failed_cpu)
7384 swevent_hlist_put_cpu(cpu);
7391 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7393 static void sw_perf_event_destroy(struct perf_event *event)
7395 u64 event_id = event->attr.config;
7397 WARN_ON(event->parent);
7399 static_key_slow_dec(&perf_swevent_enabled[event_id]);
7400 swevent_hlist_put();
7403 static int perf_swevent_init(struct perf_event *event)
7405 u64 event_id = event->attr.config;
7407 if (event->attr.type != PERF_TYPE_SOFTWARE)
7411 * no branch sampling for software events
7413 if (has_branch_stack(event))
7417 case PERF_COUNT_SW_CPU_CLOCK:
7418 case PERF_COUNT_SW_TASK_CLOCK:
7425 if (event_id >= PERF_COUNT_SW_MAX)
7428 if (!event->parent) {
7431 err = swevent_hlist_get();
7435 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7436 event->destroy = sw_perf_event_destroy;
7442 static struct pmu perf_swevent = {
7443 .task_ctx_nr = perf_sw_context,
7445 .capabilities = PERF_PMU_CAP_NO_NMI,
7447 .event_init = perf_swevent_init,
7448 .add = perf_swevent_add,
7449 .del = perf_swevent_del,
7450 .start = perf_swevent_start,
7451 .stop = perf_swevent_stop,
7452 .read = perf_swevent_read,
7455 #ifdef CONFIG_EVENT_TRACING
7457 static int perf_tp_filter_match(struct perf_event *event,
7458 struct perf_sample_data *data)
7460 void *record = data->raw->frag.data;
7462 /* only top level events have filters set */
7464 event = event->parent;
7466 if (likely(!event->filter) || filter_match_preds(event->filter, record))
7471 static int perf_tp_event_match(struct perf_event *event,
7472 struct perf_sample_data *data,
7473 struct pt_regs *regs)
7475 if (event->hw.state & PERF_HES_STOPPED)
7478 * All tracepoints are from kernel-space.
7480 if (event->attr.exclude_kernel)
7483 if (!perf_tp_filter_match(event, data))
7489 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
7490 struct trace_event_call *call, u64 count,
7491 struct pt_regs *regs, struct hlist_head *head,
7492 struct task_struct *task)
7494 struct bpf_prog *prog = call->prog;
7497 *(struct pt_regs **)raw_data = regs;
7498 if (!trace_call_bpf(prog, raw_data) || hlist_empty(head)) {
7499 perf_swevent_put_recursion_context(rctx);
7503 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
7506 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
7508 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
7509 struct pt_regs *regs, struct hlist_head *head, int rctx,
7510 struct task_struct *task)
7512 struct perf_sample_data data;
7513 struct perf_event *event;
7515 struct perf_raw_record raw = {
7522 perf_sample_data_init(&data, 0, 0);
7525 perf_trace_buf_update(record, event_type);
7527 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7528 if (perf_tp_event_match(event, &data, regs))
7529 perf_swevent_event(event, count, &data, regs);
7533 * If we got specified a target task, also iterate its context and
7534 * deliver this event there too.
7536 if (task && task != current) {
7537 struct perf_event_context *ctx;
7538 struct trace_entry *entry = record;
7541 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7545 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7546 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7548 if (event->attr.config != entry->type)
7550 if (perf_tp_event_match(event, &data, regs))
7551 perf_swevent_event(event, count, &data, regs);
7557 perf_swevent_put_recursion_context(rctx);
7559 EXPORT_SYMBOL_GPL(perf_tp_event);
7561 static void tp_perf_event_destroy(struct perf_event *event)
7563 perf_trace_destroy(event);
7566 static int perf_tp_event_init(struct perf_event *event)
7570 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7574 * no branch sampling for tracepoint events
7576 if (has_branch_stack(event))
7579 err = perf_trace_init(event);
7583 event->destroy = tp_perf_event_destroy;
7588 static struct pmu perf_tracepoint = {
7589 .task_ctx_nr = perf_sw_context,
7591 .event_init = perf_tp_event_init,
7592 .add = perf_trace_add,
7593 .del = perf_trace_del,
7594 .start = perf_swevent_start,
7595 .stop = perf_swevent_stop,
7596 .read = perf_swevent_read,
7599 static inline void perf_tp_register(void)
7601 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7604 static void perf_event_free_filter(struct perf_event *event)
7606 ftrace_profile_free_filter(event);
7609 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7611 bool is_kprobe, is_tracepoint;
7612 struct bpf_prog *prog;
7614 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7617 if (event->tp_event->prog)
7620 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
7621 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
7622 if (!is_kprobe && !is_tracepoint)
7623 /* bpf programs can only be attached to u/kprobe or tracepoint */
7626 prog = bpf_prog_get(prog_fd);
7628 return PTR_ERR(prog);
7630 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
7631 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
7632 /* valid fd, but invalid bpf program type */
7637 if (is_tracepoint) {
7638 int off = trace_event_get_offsets(event->tp_event);
7640 if (prog->aux->max_ctx_offset > off) {
7645 event->tp_event->prog = prog;
7650 static void perf_event_free_bpf_prog(struct perf_event *event)
7652 struct bpf_prog *prog;
7654 if (!event->tp_event)
7657 prog = event->tp_event->prog;
7659 event->tp_event->prog = NULL;
7666 static inline void perf_tp_register(void)
7670 static void perf_event_free_filter(struct perf_event *event)
7674 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7679 static void perf_event_free_bpf_prog(struct perf_event *event)
7682 #endif /* CONFIG_EVENT_TRACING */
7684 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7685 void perf_bp_event(struct perf_event *bp, void *data)
7687 struct perf_sample_data sample;
7688 struct pt_regs *regs = data;
7690 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7692 if (!bp->hw.state && !perf_exclude_event(bp, regs))
7693 perf_swevent_event(bp, 1, &sample, regs);
7698 * Allocate a new address filter
7700 static struct perf_addr_filter *
7701 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
7703 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
7704 struct perf_addr_filter *filter;
7706 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
7710 INIT_LIST_HEAD(&filter->entry);
7711 list_add_tail(&filter->entry, filters);
7716 static void free_filters_list(struct list_head *filters)
7718 struct perf_addr_filter *filter, *iter;
7720 list_for_each_entry_safe(filter, iter, filters, entry) {
7722 iput(filter->inode);
7723 list_del(&filter->entry);
7729 * Free existing address filters and optionally install new ones
7731 static void perf_addr_filters_splice(struct perf_event *event,
7732 struct list_head *head)
7734 unsigned long flags;
7737 if (!has_addr_filter(event))
7740 /* don't bother with children, they don't have their own filters */
7744 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
7746 list_splice_init(&event->addr_filters.list, &list);
7748 list_splice(head, &event->addr_filters.list);
7750 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
7752 free_filters_list(&list);
7756 * Scan through mm's vmas and see if one of them matches the
7757 * @filter; if so, adjust filter's address range.
7758 * Called with mm::mmap_sem down for reading.
7760 static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
7761 struct mm_struct *mm)
7763 struct vm_area_struct *vma;
7765 for (vma = mm->mmap; vma; vma = vma->vm_next) {
7766 struct file *file = vma->vm_file;
7767 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
7768 unsigned long vma_size = vma->vm_end - vma->vm_start;
7773 if (!perf_addr_filter_match(filter, file, off, vma_size))
7776 return vma->vm_start;
7783 * Update event's address range filters based on the
7784 * task's existing mappings, if any.
7786 static void perf_event_addr_filters_apply(struct perf_event *event)
7788 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7789 struct task_struct *task = READ_ONCE(event->ctx->task);
7790 struct perf_addr_filter *filter;
7791 struct mm_struct *mm = NULL;
7792 unsigned int count = 0;
7793 unsigned long flags;
7796 * We may observe TASK_TOMBSTONE, which means that the event tear-down
7797 * will stop on the parent's child_mutex that our caller is also holding
7799 if (task == TASK_TOMBSTONE)
7802 mm = get_task_mm(event->ctx->task);
7806 down_read(&mm->mmap_sem);
7808 raw_spin_lock_irqsave(&ifh->lock, flags);
7809 list_for_each_entry(filter, &ifh->list, entry) {
7810 event->addr_filters_offs[count] = 0;
7812 if (perf_addr_filter_needs_mmap(filter))
7813 event->addr_filters_offs[count] =
7814 perf_addr_filter_apply(filter, mm);
7819 event->addr_filters_gen++;
7820 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7822 up_read(&mm->mmap_sem);
7827 perf_event_restart(event);
7831 * Address range filtering: limiting the data to certain
7832 * instruction address ranges. Filters are ioctl()ed to us from
7833 * userspace as ascii strings.
7835 * Filter string format:
7838 * where ACTION is one of the
7839 * * "filter": limit the trace to this region
7840 * * "start": start tracing from this address
7841 * * "stop": stop tracing at this address/region;
7843 * * for kernel addresses: <start address>[/<size>]
7844 * * for object files: <start address>[/<size>]@</path/to/object/file>
7846 * if <size> is not specified, the range is treated as a single address.
7859 IF_STATE_ACTION = 0,
7864 static const match_table_t if_tokens = {
7865 { IF_ACT_FILTER, "filter" },
7866 { IF_ACT_START, "start" },
7867 { IF_ACT_STOP, "stop" },
7868 { IF_SRC_FILE, "%u/%u@%s" },
7869 { IF_SRC_KERNEL, "%u/%u" },
7870 { IF_SRC_FILEADDR, "%u@%s" },
7871 { IF_SRC_KERNELADDR, "%u" },
7875 * Address filter string parser
7878 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
7879 struct list_head *filters)
7881 struct perf_addr_filter *filter = NULL;
7882 char *start, *orig, *filename = NULL;
7884 substring_t args[MAX_OPT_ARGS];
7885 int state = IF_STATE_ACTION, token;
7886 unsigned int kernel = 0;
7889 orig = fstr = kstrdup(fstr, GFP_KERNEL);
7893 while ((start = strsep(&fstr, " ,\n")) != NULL) {
7899 /* filter definition begins */
7900 if (state == IF_STATE_ACTION) {
7901 filter = perf_addr_filter_new(event, filters);
7906 token = match_token(start, if_tokens, args);
7913 if (state != IF_STATE_ACTION)
7916 state = IF_STATE_SOURCE;
7919 case IF_SRC_KERNELADDR:
7923 case IF_SRC_FILEADDR:
7925 if (state != IF_STATE_SOURCE)
7928 if (token == IF_SRC_FILE || token == IF_SRC_KERNEL)
7932 ret = kstrtoul(args[0].from, 0, &filter->offset);
7936 if (filter->range) {
7938 ret = kstrtoul(args[1].from, 0, &filter->size);
7943 if (token == IF_SRC_FILE) {
7944 filename = match_strdup(&args[2]);
7951 state = IF_STATE_END;
7959 * Filter definition is fully parsed, validate and install it.
7960 * Make sure that it doesn't contradict itself or the event's
7963 if (state == IF_STATE_END) {
7964 if (kernel && event->attr.exclude_kernel)
7971 /* look up the path and grab its inode */
7972 ret = kern_path(filename, LOOKUP_FOLLOW, &path);
7974 goto fail_free_name;
7976 filter->inode = igrab(d_inode(path.dentry));
7982 if (!filter->inode ||
7983 !S_ISREG(filter->inode->i_mode))
7984 /* free_filters_list() will iput() */
7988 /* ready to consume more filters */
7989 state = IF_STATE_ACTION;
7994 if (state != IF_STATE_ACTION)
8004 free_filters_list(filters);
8011 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
8017 * Since this is called in perf_ioctl() path, we're already holding
8020 lockdep_assert_held(&event->ctx->mutex);
8022 if (WARN_ON_ONCE(event->parent))
8026 * For now, we only support filtering in per-task events; doing so
8027 * for CPU-wide events requires additional context switching trickery,
8028 * since same object code will be mapped at different virtual
8029 * addresses in different processes.
8031 if (!event->ctx->task)
8034 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
8038 ret = event->pmu->addr_filters_validate(&filters);
8040 free_filters_list(&filters);
8044 /* remove existing filters, if any */
8045 perf_addr_filters_splice(event, &filters);
8047 /* install new filters */
8048 perf_event_for_each_child(event, perf_event_addr_filters_apply);
8053 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
8058 if ((event->attr.type != PERF_TYPE_TRACEPOINT ||
8059 !IS_ENABLED(CONFIG_EVENT_TRACING)) &&
8060 !has_addr_filter(event))
8063 filter_str = strndup_user(arg, PAGE_SIZE);
8064 if (IS_ERR(filter_str))
8065 return PTR_ERR(filter_str);
8067 if (IS_ENABLED(CONFIG_EVENT_TRACING) &&
8068 event->attr.type == PERF_TYPE_TRACEPOINT)
8069 ret = ftrace_profile_set_filter(event, event->attr.config,
8071 else if (has_addr_filter(event))
8072 ret = perf_event_set_addr_filter(event, filter_str);
8079 * hrtimer based swevent callback
8082 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
8084 enum hrtimer_restart ret = HRTIMER_RESTART;
8085 struct perf_sample_data data;
8086 struct pt_regs *regs;
8087 struct perf_event *event;
8090 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
8092 if (event->state != PERF_EVENT_STATE_ACTIVE)
8093 return HRTIMER_NORESTART;
8095 event->pmu->read(event);
8097 perf_sample_data_init(&data, 0, event->hw.last_period);
8098 regs = get_irq_regs();
8100 if (regs && !perf_exclude_event(event, regs)) {
8101 if (!(event->attr.exclude_idle && is_idle_task(current)))
8102 if (__perf_event_overflow(event, 1, &data, regs))
8103 ret = HRTIMER_NORESTART;
8106 period = max_t(u64, 10000, event->hw.sample_period);
8107 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
8112 static void perf_swevent_start_hrtimer(struct perf_event *event)
8114 struct hw_perf_event *hwc = &event->hw;
8117 if (!is_sampling_event(event))
8120 period = local64_read(&hwc->period_left);
8125 local64_set(&hwc->period_left, 0);
8127 period = max_t(u64, 10000, hwc->sample_period);
8129 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
8130 HRTIMER_MODE_REL_PINNED);
8133 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
8135 struct hw_perf_event *hwc = &event->hw;
8137 if (is_sampling_event(event)) {
8138 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
8139 local64_set(&hwc->period_left, ktime_to_ns(remaining));
8141 hrtimer_cancel(&hwc->hrtimer);
8145 static void perf_swevent_init_hrtimer(struct perf_event *event)
8147 struct hw_perf_event *hwc = &event->hw;
8149 if (!is_sampling_event(event))
8152 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
8153 hwc->hrtimer.function = perf_swevent_hrtimer;
8156 * Since hrtimers have a fixed rate, we can do a static freq->period
8157 * mapping and avoid the whole period adjust feedback stuff.
8159 if (event->attr.freq) {
8160 long freq = event->attr.sample_freq;
8162 event->attr.sample_period = NSEC_PER_SEC / freq;
8163 hwc->sample_period = event->attr.sample_period;
8164 local64_set(&hwc->period_left, hwc->sample_period);
8165 hwc->last_period = hwc->sample_period;
8166 event->attr.freq = 0;
8171 * Software event: cpu wall time clock
8174 static void cpu_clock_event_update(struct perf_event *event)
8179 now = local_clock();
8180 prev = local64_xchg(&event->hw.prev_count, now);
8181 local64_add(now - prev, &event->count);
8184 static void cpu_clock_event_start(struct perf_event *event, int flags)
8186 local64_set(&event->hw.prev_count, local_clock());
8187 perf_swevent_start_hrtimer(event);
8190 static void cpu_clock_event_stop(struct perf_event *event, int flags)
8192 perf_swevent_cancel_hrtimer(event);
8193 cpu_clock_event_update(event);
8196 static int cpu_clock_event_add(struct perf_event *event, int flags)
8198 if (flags & PERF_EF_START)
8199 cpu_clock_event_start(event, flags);
8200 perf_event_update_userpage(event);
8205 static void cpu_clock_event_del(struct perf_event *event, int flags)
8207 cpu_clock_event_stop(event, flags);
8210 static void cpu_clock_event_read(struct perf_event *event)
8212 cpu_clock_event_update(event);
8215 static int cpu_clock_event_init(struct perf_event *event)
8217 if (event->attr.type != PERF_TYPE_SOFTWARE)
8220 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
8224 * no branch sampling for software events
8226 if (has_branch_stack(event))
8229 perf_swevent_init_hrtimer(event);
8234 static struct pmu perf_cpu_clock = {
8235 .task_ctx_nr = perf_sw_context,
8237 .capabilities = PERF_PMU_CAP_NO_NMI,
8239 .event_init = cpu_clock_event_init,
8240 .add = cpu_clock_event_add,
8241 .del = cpu_clock_event_del,
8242 .start = cpu_clock_event_start,
8243 .stop = cpu_clock_event_stop,
8244 .read = cpu_clock_event_read,
8248 * Software event: task time clock
8251 static void task_clock_event_update(struct perf_event *event, u64 now)
8256 prev = local64_xchg(&event->hw.prev_count, now);
8258 local64_add(delta, &event->count);
8261 static void task_clock_event_start(struct perf_event *event, int flags)
8263 local64_set(&event->hw.prev_count, event->ctx->time);
8264 perf_swevent_start_hrtimer(event);
8267 static void task_clock_event_stop(struct perf_event *event, int flags)
8269 perf_swevent_cancel_hrtimer(event);
8270 task_clock_event_update(event, event->ctx->time);
8273 static int task_clock_event_add(struct perf_event *event, int flags)
8275 if (flags & PERF_EF_START)
8276 task_clock_event_start(event, flags);
8277 perf_event_update_userpage(event);
8282 static void task_clock_event_del(struct perf_event *event, int flags)
8284 task_clock_event_stop(event, PERF_EF_UPDATE);
8287 static void task_clock_event_read(struct perf_event *event)
8289 u64 now = perf_clock();
8290 u64 delta = now - event->ctx->timestamp;
8291 u64 time = event->ctx->time + delta;
8293 task_clock_event_update(event, time);
8296 static int task_clock_event_init(struct perf_event *event)
8298 if (event->attr.type != PERF_TYPE_SOFTWARE)
8301 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
8305 * no branch sampling for software events
8307 if (has_branch_stack(event))
8310 perf_swevent_init_hrtimer(event);
8315 static struct pmu perf_task_clock = {
8316 .task_ctx_nr = perf_sw_context,
8318 .capabilities = PERF_PMU_CAP_NO_NMI,
8320 .event_init = task_clock_event_init,
8321 .add = task_clock_event_add,
8322 .del = task_clock_event_del,
8323 .start = task_clock_event_start,
8324 .stop = task_clock_event_stop,
8325 .read = task_clock_event_read,
8328 static void perf_pmu_nop_void(struct pmu *pmu)
8332 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
8336 static int perf_pmu_nop_int(struct pmu *pmu)
8341 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
8343 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
8345 __this_cpu_write(nop_txn_flags, flags);
8347 if (flags & ~PERF_PMU_TXN_ADD)
8350 perf_pmu_disable(pmu);
8353 static int perf_pmu_commit_txn(struct pmu *pmu)
8355 unsigned int flags = __this_cpu_read(nop_txn_flags);
8357 __this_cpu_write(nop_txn_flags, 0);
8359 if (flags & ~PERF_PMU_TXN_ADD)
8362 perf_pmu_enable(pmu);
8366 static void perf_pmu_cancel_txn(struct pmu *pmu)
8368 unsigned int flags = __this_cpu_read(nop_txn_flags);
8370 __this_cpu_write(nop_txn_flags, 0);
8372 if (flags & ~PERF_PMU_TXN_ADD)
8375 perf_pmu_enable(pmu);
8378 static int perf_event_idx_default(struct perf_event *event)
8384 * Ensures all contexts with the same task_ctx_nr have the same
8385 * pmu_cpu_context too.
8387 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
8394 list_for_each_entry(pmu, &pmus, entry) {
8395 if (pmu->task_ctx_nr == ctxn)
8396 return pmu->pmu_cpu_context;
8402 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
8406 for_each_possible_cpu(cpu) {
8407 struct perf_cpu_context *cpuctx;
8409 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8411 if (cpuctx->unique_pmu == old_pmu)
8412 cpuctx->unique_pmu = pmu;
8416 static void free_pmu_context(struct pmu *pmu)
8420 mutex_lock(&pmus_lock);
8422 * Like a real lame refcount.
8424 list_for_each_entry(i, &pmus, entry) {
8425 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
8426 update_pmu_context(i, pmu);
8431 free_percpu(pmu->pmu_cpu_context);
8433 mutex_unlock(&pmus_lock);
8437 * Let userspace know that this PMU supports address range filtering:
8439 static ssize_t nr_addr_filters_show(struct device *dev,
8440 struct device_attribute *attr,
8443 struct pmu *pmu = dev_get_drvdata(dev);
8445 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
8447 DEVICE_ATTR_RO(nr_addr_filters);
8449 static struct idr pmu_idr;
8452 type_show(struct device *dev, struct device_attribute *attr, char *page)
8454 struct pmu *pmu = dev_get_drvdata(dev);
8456 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
8458 static DEVICE_ATTR_RO(type);
8461 perf_event_mux_interval_ms_show(struct device *dev,
8462 struct device_attribute *attr,
8465 struct pmu *pmu = dev_get_drvdata(dev);
8467 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
8470 static DEFINE_MUTEX(mux_interval_mutex);
8473 perf_event_mux_interval_ms_store(struct device *dev,
8474 struct device_attribute *attr,
8475 const char *buf, size_t count)
8477 struct pmu *pmu = dev_get_drvdata(dev);
8478 int timer, cpu, ret;
8480 ret = kstrtoint(buf, 0, &timer);
8487 /* same value, noting to do */
8488 if (timer == pmu->hrtimer_interval_ms)
8491 mutex_lock(&mux_interval_mutex);
8492 pmu->hrtimer_interval_ms = timer;
8494 /* update all cpuctx for this PMU */
8496 for_each_online_cpu(cpu) {
8497 struct perf_cpu_context *cpuctx;
8498 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8499 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
8501 cpu_function_call(cpu,
8502 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
8505 mutex_unlock(&mux_interval_mutex);
8509 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
8511 static struct attribute *pmu_dev_attrs[] = {
8512 &dev_attr_type.attr,
8513 &dev_attr_perf_event_mux_interval_ms.attr,
8516 ATTRIBUTE_GROUPS(pmu_dev);
8518 static int pmu_bus_running;
8519 static struct bus_type pmu_bus = {
8520 .name = "event_source",
8521 .dev_groups = pmu_dev_groups,
8524 static void pmu_dev_release(struct device *dev)
8529 static int pmu_dev_alloc(struct pmu *pmu)
8533 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
8537 pmu->dev->groups = pmu->attr_groups;
8538 device_initialize(pmu->dev);
8539 ret = dev_set_name(pmu->dev, "%s", pmu->name);
8543 dev_set_drvdata(pmu->dev, pmu);
8544 pmu->dev->bus = &pmu_bus;
8545 pmu->dev->release = pmu_dev_release;
8546 ret = device_add(pmu->dev);
8550 /* For PMUs with address filters, throw in an extra attribute: */
8551 if (pmu->nr_addr_filters)
8552 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
8561 device_del(pmu->dev);
8564 put_device(pmu->dev);
8568 static struct lock_class_key cpuctx_mutex;
8569 static struct lock_class_key cpuctx_lock;
8571 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
8575 mutex_lock(&pmus_lock);
8577 pmu->pmu_disable_count = alloc_percpu(int);
8578 if (!pmu->pmu_disable_count)
8587 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
8595 if (pmu_bus_running) {
8596 ret = pmu_dev_alloc(pmu);
8602 if (pmu->task_ctx_nr == perf_hw_context) {
8603 static int hw_context_taken = 0;
8606 * Other than systems with heterogeneous CPUs, it never makes
8607 * sense for two PMUs to share perf_hw_context. PMUs which are
8608 * uncore must use perf_invalid_context.
8610 if (WARN_ON_ONCE(hw_context_taken &&
8611 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
8612 pmu->task_ctx_nr = perf_invalid_context;
8614 hw_context_taken = 1;
8617 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
8618 if (pmu->pmu_cpu_context)
8619 goto got_cpu_context;
8622 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
8623 if (!pmu->pmu_cpu_context)
8626 for_each_possible_cpu(cpu) {
8627 struct perf_cpu_context *cpuctx;
8629 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
8630 __perf_event_init_context(&cpuctx->ctx);
8631 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
8632 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
8633 cpuctx->ctx.pmu = pmu;
8635 __perf_mux_hrtimer_init(cpuctx, cpu);
8637 cpuctx->unique_pmu = pmu;
8641 if (!pmu->start_txn) {
8642 if (pmu->pmu_enable) {
8644 * If we have pmu_enable/pmu_disable calls, install
8645 * transaction stubs that use that to try and batch
8646 * hardware accesses.
8648 pmu->start_txn = perf_pmu_start_txn;
8649 pmu->commit_txn = perf_pmu_commit_txn;
8650 pmu->cancel_txn = perf_pmu_cancel_txn;
8652 pmu->start_txn = perf_pmu_nop_txn;
8653 pmu->commit_txn = perf_pmu_nop_int;
8654 pmu->cancel_txn = perf_pmu_nop_void;
8658 if (!pmu->pmu_enable) {
8659 pmu->pmu_enable = perf_pmu_nop_void;
8660 pmu->pmu_disable = perf_pmu_nop_void;
8663 if (!pmu->event_idx)
8664 pmu->event_idx = perf_event_idx_default;
8666 list_add_rcu(&pmu->entry, &pmus);
8667 atomic_set(&pmu->exclusive_cnt, 0);
8670 mutex_unlock(&pmus_lock);
8675 device_del(pmu->dev);
8676 put_device(pmu->dev);
8679 if (pmu->type >= PERF_TYPE_MAX)
8680 idr_remove(&pmu_idr, pmu->type);
8683 free_percpu(pmu->pmu_disable_count);
8686 EXPORT_SYMBOL_GPL(perf_pmu_register);
8688 void perf_pmu_unregister(struct pmu *pmu)
8690 mutex_lock(&pmus_lock);
8691 list_del_rcu(&pmu->entry);
8692 mutex_unlock(&pmus_lock);
8695 * We dereference the pmu list under both SRCU and regular RCU, so
8696 * synchronize against both of those.
8698 synchronize_srcu(&pmus_srcu);
8701 free_percpu(pmu->pmu_disable_count);
8702 if (pmu->type >= PERF_TYPE_MAX)
8703 idr_remove(&pmu_idr, pmu->type);
8704 if (pmu->nr_addr_filters)
8705 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
8706 device_del(pmu->dev);
8707 put_device(pmu->dev);
8708 free_pmu_context(pmu);
8710 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
8712 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
8714 struct perf_event_context *ctx = NULL;
8717 if (!try_module_get(pmu->module))
8720 if (event->group_leader != event) {
8722 * This ctx->mutex can nest when we're called through
8723 * inheritance. See the perf_event_ctx_lock_nested() comment.
8725 ctx = perf_event_ctx_lock_nested(event->group_leader,
8726 SINGLE_DEPTH_NESTING);
8731 ret = pmu->event_init(event);
8734 perf_event_ctx_unlock(event->group_leader, ctx);
8737 module_put(pmu->module);
8742 static struct pmu *perf_init_event(struct perf_event *event)
8744 struct pmu *pmu = NULL;
8748 idx = srcu_read_lock(&pmus_srcu);
8751 pmu = idr_find(&pmu_idr, event->attr.type);
8754 ret = perf_try_init_event(pmu, event);
8760 list_for_each_entry_rcu(pmu, &pmus, entry) {
8761 ret = perf_try_init_event(pmu, event);
8765 if (ret != -ENOENT) {
8770 pmu = ERR_PTR(-ENOENT);
8772 srcu_read_unlock(&pmus_srcu, idx);
8777 static void attach_sb_event(struct perf_event *event)
8779 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
8781 raw_spin_lock(&pel->lock);
8782 list_add_rcu(&event->sb_list, &pel->list);
8783 raw_spin_unlock(&pel->lock);
8787 * We keep a list of all !task (and therefore per-cpu) events
8788 * that need to receive side-band records.
8790 * This avoids having to scan all the various PMU per-cpu contexts
8793 static void account_pmu_sb_event(struct perf_event *event)
8795 if (is_sb_event(event))
8796 attach_sb_event(event);
8799 static void account_event_cpu(struct perf_event *event, int cpu)
8804 if (is_cgroup_event(event))
8805 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
8808 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
8809 static void account_freq_event_nohz(void)
8811 #ifdef CONFIG_NO_HZ_FULL
8812 /* Lock so we don't race with concurrent unaccount */
8813 spin_lock(&nr_freq_lock);
8814 if (atomic_inc_return(&nr_freq_events) == 1)
8815 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
8816 spin_unlock(&nr_freq_lock);
8820 static void account_freq_event(void)
8822 if (tick_nohz_full_enabled())
8823 account_freq_event_nohz();
8825 atomic_inc(&nr_freq_events);
8829 static void account_event(struct perf_event *event)
8836 if (event->attach_state & PERF_ATTACH_TASK)
8838 if (event->attr.mmap || event->attr.mmap_data)
8839 atomic_inc(&nr_mmap_events);
8840 if (event->attr.comm)
8841 atomic_inc(&nr_comm_events);
8842 if (event->attr.task)
8843 atomic_inc(&nr_task_events);
8844 if (event->attr.freq)
8845 account_freq_event();
8846 if (event->attr.context_switch) {
8847 atomic_inc(&nr_switch_events);
8850 if (has_branch_stack(event))
8852 if (is_cgroup_event(event))
8856 if (atomic_inc_not_zero(&perf_sched_count))
8859 mutex_lock(&perf_sched_mutex);
8860 if (!atomic_read(&perf_sched_count)) {
8861 static_branch_enable(&perf_sched_events);
8863 * Guarantee that all CPUs observe they key change and
8864 * call the perf scheduling hooks before proceeding to
8865 * install events that need them.
8867 synchronize_sched();
8870 * Now that we have waited for the sync_sched(), allow further
8871 * increments to by-pass the mutex.
8873 atomic_inc(&perf_sched_count);
8874 mutex_unlock(&perf_sched_mutex);
8878 account_event_cpu(event, event->cpu);
8880 account_pmu_sb_event(event);
8884 * Allocate and initialize a event structure
8886 static struct perf_event *
8887 perf_event_alloc(struct perf_event_attr *attr, int cpu,
8888 struct task_struct *task,
8889 struct perf_event *group_leader,
8890 struct perf_event *parent_event,
8891 perf_overflow_handler_t overflow_handler,
8892 void *context, int cgroup_fd)
8895 struct perf_event *event;
8896 struct hw_perf_event *hwc;
8899 if ((unsigned)cpu >= nr_cpu_ids) {
8900 if (!task || cpu != -1)
8901 return ERR_PTR(-EINVAL);
8904 event = kzalloc(sizeof(*event), GFP_KERNEL);
8906 return ERR_PTR(-ENOMEM);
8909 * Single events are their own group leaders, with an
8910 * empty sibling list:
8913 group_leader = event;
8915 mutex_init(&event->child_mutex);
8916 INIT_LIST_HEAD(&event->child_list);
8918 INIT_LIST_HEAD(&event->group_entry);
8919 INIT_LIST_HEAD(&event->event_entry);
8920 INIT_LIST_HEAD(&event->sibling_list);
8921 INIT_LIST_HEAD(&event->rb_entry);
8922 INIT_LIST_HEAD(&event->active_entry);
8923 INIT_LIST_HEAD(&event->addr_filters.list);
8924 INIT_HLIST_NODE(&event->hlist_entry);
8927 init_waitqueue_head(&event->waitq);
8928 init_irq_work(&event->pending, perf_pending_event);
8930 mutex_init(&event->mmap_mutex);
8931 raw_spin_lock_init(&event->addr_filters.lock);
8933 atomic_long_set(&event->refcount, 1);
8935 event->attr = *attr;
8936 event->group_leader = group_leader;
8940 event->parent = parent_event;
8942 event->ns = get_pid_ns(task_active_pid_ns(current));
8943 event->id = atomic64_inc_return(&perf_event_id);
8945 event->state = PERF_EVENT_STATE_INACTIVE;
8948 event->attach_state = PERF_ATTACH_TASK;
8950 * XXX pmu::event_init needs to know what task to account to
8951 * and we cannot use the ctx information because we need the
8952 * pmu before we get a ctx.
8954 event->hw.target = task;
8957 event->clock = &local_clock;
8959 event->clock = parent_event->clock;
8961 if (!overflow_handler && parent_event) {
8962 overflow_handler = parent_event->overflow_handler;
8963 context = parent_event->overflow_handler_context;
8966 if (overflow_handler) {
8967 event->overflow_handler = overflow_handler;
8968 event->overflow_handler_context = context;
8969 } else if (is_write_backward(event)){
8970 event->overflow_handler = perf_event_output_backward;
8971 event->overflow_handler_context = NULL;
8973 event->overflow_handler = perf_event_output_forward;
8974 event->overflow_handler_context = NULL;
8977 perf_event__state_init(event);
8982 hwc->sample_period = attr->sample_period;
8983 if (attr->freq && attr->sample_freq)
8984 hwc->sample_period = 1;
8985 hwc->last_period = hwc->sample_period;
8987 local64_set(&hwc->period_left, hwc->sample_period);
8990 * we currently do not support PERF_FORMAT_GROUP on inherited events
8992 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
8995 if (!has_branch_stack(event))
8996 event->attr.branch_sample_type = 0;
8998 if (cgroup_fd != -1) {
8999 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
9004 pmu = perf_init_event(event);
9007 else if (IS_ERR(pmu)) {
9012 err = exclusive_event_init(event);
9016 if (has_addr_filter(event)) {
9017 event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
9018 sizeof(unsigned long),
9020 if (!event->addr_filters_offs)
9023 /* force hw sync on the address filters */
9024 event->addr_filters_gen = 1;
9027 if (!event->parent) {
9028 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
9029 err = get_callchain_buffers(attr->sample_max_stack);
9031 goto err_addr_filters;
9035 /* symmetric to unaccount_event() in _free_event() */
9036 account_event(event);
9041 kfree(event->addr_filters_offs);
9044 exclusive_event_destroy(event);
9048 event->destroy(event);
9049 module_put(pmu->module);
9051 if (is_cgroup_event(event))
9052 perf_detach_cgroup(event);
9054 put_pid_ns(event->ns);
9057 return ERR_PTR(err);
9060 static int perf_copy_attr(struct perf_event_attr __user *uattr,
9061 struct perf_event_attr *attr)
9066 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
9070 * zero the full structure, so that a short copy will be nice.
9072 memset(attr, 0, sizeof(*attr));
9074 ret = get_user(size, &uattr->size);
9078 if (size > PAGE_SIZE) /* silly large */
9081 if (!size) /* abi compat */
9082 size = PERF_ATTR_SIZE_VER0;
9084 if (size < PERF_ATTR_SIZE_VER0)
9088 * If we're handed a bigger struct than we know of,
9089 * ensure all the unknown bits are 0 - i.e. new
9090 * user-space does not rely on any kernel feature
9091 * extensions we dont know about yet.
9093 if (size > sizeof(*attr)) {
9094 unsigned char __user *addr;
9095 unsigned char __user *end;
9098 addr = (void __user *)uattr + sizeof(*attr);
9099 end = (void __user *)uattr + size;
9101 for (; addr < end; addr++) {
9102 ret = get_user(val, addr);
9108 size = sizeof(*attr);
9111 ret = copy_from_user(attr, uattr, size);
9115 if (attr->__reserved_1)
9118 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
9121 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
9124 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
9125 u64 mask = attr->branch_sample_type;
9127 /* only using defined bits */
9128 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
9131 /* at least one branch bit must be set */
9132 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
9135 /* propagate priv level, when not set for branch */
9136 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
9138 /* exclude_kernel checked on syscall entry */
9139 if (!attr->exclude_kernel)
9140 mask |= PERF_SAMPLE_BRANCH_KERNEL;
9142 if (!attr->exclude_user)
9143 mask |= PERF_SAMPLE_BRANCH_USER;
9145 if (!attr->exclude_hv)
9146 mask |= PERF_SAMPLE_BRANCH_HV;
9148 * adjust user setting (for HW filter setup)
9150 attr->branch_sample_type = mask;
9152 /* privileged levels capture (kernel, hv): check permissions */
9153 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
9154 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9158 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
9159 ret = perf_reg_validate(attr->sample_regs_user);
9164 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
9165 if (!arch_perf_have_user_stack_dump())
9169 * We have __u32 type for the size, but so far
9170 * we can only use __u16 as maximum due to the
9171 * __u16 sample size limit.
9173 if (attr->sample_stack_user >= USHRT_MAX)
9175 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
9179 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
9180 ret = perf_reg_validate(attr->sample_regs_intr);
9185 put_user(sizeof(*attr), &uattr->size);
9191 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
9193 struct ring_buffer *rb = NULL;
9199 /* don't allow circular references */
9200 if (event == output_event)
9204 * Don't allow cross-cpu buffers
9206 if (output_event->cpu != event->cpu)
9210 * If its not a per-cpu rb, it must be the same task.
9212 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
9216 * Mixing clocks in the same buffer is trouble you don't need.
9218 if (output_event->clock != event->clock)
9222 * Either writing ring buffer from beginning or from end.
9223 * Mixing is not allowed.
9225 if (is_write_backward(output_event) != is_write_backward(event))
9229 * If both events generate aux data, they must be on the same PMU
9231 if (has_aux(event) && has_aux(output_event) &&
9232 event->pmu != output_event->pmu)
9236 mutex_lock(&event->mmap_mutex);
9237 /* Can't redirect output if we've got an active mmap() */
9238 if (atomic_read(&event->mmap_count))
9242 /* get the rb we want to redirect to */
9243 rb = ring_buffer_get(output_event);
9248 ring_buffer_attach(event, rb);
9252 mutex_unlock(&event->mmap_mutex);
9258 static void mutex_lock_double(struct mutex *a, struct mutex *b)
9264 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
9267 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
9269 bool nmi_safe = false;
9272 case CLOCK_MONOTONIC:
9273 event->clock = &ktime_get_mono_fast_ns;
9277 case CLOCK_MONOTONIC_RAW:
9278 event->clock = &ktime_get_raw_fast_ns;
9282 case CLOCK_REALTIME:
9283 event->clock = &ktime_get_real_ns;
9286 case CLOCK_BOOTTIME:
9287 event->clock = &ktime_get_boot_ns;
9291 event->clock = &ktime_get_tai_ns;
9298 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
9305 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9307 * @attr_uptr: event_id type attributes for monitoring/sampling
9310 * @group_fd: group leader event fd
9312 SYSCALL_DEFINE5(perf_event_open,
9313 struct perf_event_attr __user *, attr_uptr,
9314 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
9316 struct perf_event *group_leader = NULL, *output_event = NULL;
9317 struct perf_event *event, *sibling;
9318 struct perf_event_attr attr;
9319 struct perf_event_context *ctx, *uninitialized_var(gctx);
9320 struct file *event_file = NULL;
9321 struct fd group = {NULL, 0};
9322 struct task_struct *task = NULL;
9327 int f_flags = O_RDWR;
9330 /* for future expandability... */
9331 if (flags & ~PERF_FLAG_ALL)
9334 err = perf_copy_attr(attr_uptr, &attr);
9338 if (!attr.exclude_kernel) {
9339 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
9344 if (attr.sample_freq > sysctl_perf_event_sample_rate)
9347 if (attr.sample_period & (1ULL << 63))
9351 if (!attr.sample_max_stack)
9352 attr.sample_max_stack = sysctl_perf_event_max_stack;
9355 * In cgroup mode, the pid argument is used to pass the fd
9356 * opened to the cgroup directory in cgroupfs. The cpu argument
9357 * designates the cpu on which to monitor threads from that
9360 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
9363 if (flags & PERF_FLAG_FD_CLOEXEC)
9364 f_flags |= O_CLOEXEC;
9366 event_fd = get_unused_fd_flags(f_flags);
9370 if (group_fd != -1) {
9371 err = perf_fget_light(group_fd, &group);
9374 group_leader = group.file->private_data;
9375 if (flags & PERF_FLAG_FD_OUTPUT)
9376 output_event = group_leader;
9377 if (flags & PERF_FLAG_FD_NO_GROUP)
9378 group_leader = NULL;
9381 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
9382 task = find_lively_task_by_vpid(pid);
9384 err = PTR_ERR(task);
9389 if (task && group_leader &&
9390 group_leader->attr.inherit != attr.inherit) {
9398 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
9403 * Reuse ptrace permission checks for now.
9405 * We must hold cred_guard_mutex across this and any potential
9406 * perf_install_in_context() call for this new event to
9407 * serialize against exec() altering our credentials (and the
9408 * perf_event_exit_task() that could imply).
9411 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
9415 if (flags & PERF_FLAG_PID_CGROUP)
9418 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
9419 NULL, NULL, cgroup_fd);
9420 if (IS_ERR(event)) {
9421 err = PTR_ERR(event);
9425 if (is_sampling_event(event)) {
9426 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
9433 * Special case software events and allow them to be part of
9434 * any hardware group.
9438 if (attr.use_clockid) {
9439 err = perf_event_set_clock(event, attr.clockid);
9445 (is_software_event(event) != is_software_event(group_leader))) {
9446 if (is_software_event(event)) {
9448 * If event and group_leader are not both a software
9449 * event, and event is, then group leader is not.
9451 * Allow the addition of software events to !software
9452 * groups, this is safe because software events never
9455 pmu = group_leader->pmu;
9456 } else if (is_software_event(group_leader) &&
9457 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
9459 * In case the group is a pure software group, and we
9460 * try to add a hardware event, move the whole group to
9461 * the hardware context.
9468 * Get the target context (task or percpu):
9470 ctx = find_get_context(pmu, task, event);
9476 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
9482 * Look up the group leader (we will attach this event to it):
9488 * Do not allow a recursive hierarchy (this new sibling
9489 * becoming part of another group-sibling):
9491 if (group_leader->group_leader != group_leader)
9494 /* All events in a group should have the same clock */
9495 if (group_leader->clock != event->clock)
9499 * Do not allow to attach to a group in a different
9500 * task or CPU context:
9504 * Make sure we're both on the same task, or both
9507 if (group_leader->ctx->task != ctx->task)
9511 * Make sure we're both events for the same CPU;
9512 * grouping events for different CPUs is broken; since
9513 * you can never concurrently schedule them anyhow.
9515 if (group_leader->cpu != event->cpu)
9518 if (group_leader->ctx != ctx)
9523 * Only a group leader can be exclusive or pinned
9525 if (attr.exclusive || attr.pinned)
9530 err = perf_event_set_output(event, output_event);
9535 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
9537 if (IS_ERR(event_file)) {
9538 err = PTR_ERR(event_file);
9544 gctx = group_leader->ctx;
9545 mutex_lock_double(&gctx->mutex, &ctx->mutex);
9546 if (gctx->task == TASK_TOMBSTONE) {
9551 mutex_lock(&ctx->mutex);
9554 if (ctx->task == TASK_TOMBSTONE) {
9559 if (!perf_event_validate_size(event)) {
9565 * Must be under the same ctx::mutex as perf_install_in_context(),
9566 * because we need to serialize with concurrent event creation.
9568 if (!exclusive_event_installable(event, ctx)) {
9569 /* exclusive and group stuff are assumed mutually exclusive */
9570 WARN_ON_ONCE(move_group);
9576 WARN_ON_ONCE(ctx->parent_ctx);
9579 * This is the point on no return; we cannot fail hereafter. This is
9580 * where we start modifying current state.
9585 * See perf_event_ctx_lock() for comments on the details
9586 * of swizzling perf_event::ctx.
9588 perf_remove_from_context(group_leader, 0);
9590 list_for_each_entry(sibling, &group_leader->sibling_list,
9592 perf_remove_from_context(sibling, 0);
9597 * Wait for everybody to stop referencing the events through
9598 * the old lists, before installing it on new lists.
9603 * Install the group siblings before the group leader.
9605 * Because a group leader will try and install the entire group
9606 * (through the sibling list, which is still in-tact), we can
9607 * end up with siblings installed in the wrong context.
9609 * By installing siblings first we NO-OP because they're not
9610 * reachable through the group lists.
9612 list_for_each_entry(sibling, &group_leader->sibling_list,
9614 perf_event__state_init(sibling);
9615 perf_install_in_context(ctx, sibling, sibling->cpu);
9620 * Removing from the context ends up with disabled
9621 * event. What we want here is event in the initial
9622 * startup state, ready to be add into new context.
9624 perf_event__state_init(group_leader);
9625 perf_install_in_context(ctx, group_leader, group_leader->cpu);
9629 * Now that all events are installed in @ctx, nothing
9630 * references @gctx anymore, so drop the last reference we have
9637 * Precalculate sample_data sizes; do while holding ctx::mutex such
9638 * that we're serialized against further additions and before
9639 * perf_install_in_context() which is the point the event is active and
9640 * can use these values.
9642 perf_event__header_size(event);
9643 perf_event__id_header_size(event);
9645 event->owner = current;
9647 perf_install_in_context(ctx, event, event->cpu);
9648 perf_unpin_context(ctx);
9651 mutex_unlock(&gctx->mutex);
9652 mutex_unlock(&ctx->mutex);
9655 mutex_unlock(&task->signal->cred_guard_mutex);
9656 put_task_struct(task);
9661 mutex_lock(¤t->perf_event_mutex);
9662 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
9663 mutex_unlock(¤t->perf_event_mutex);
9666 * Drop the reference on the group_event after placing the
9667 * new event on the sibling_list. This ensures destruction
9668 * of the group leader will find the pointer to itself in
9669 * perf_group_detach().
9672 fd_install(event_fd, event_file);
9677 mutex_unlock(&gctx->mutex);
9678 mutex_unlock(&ctx->mutex);
9682 perf_unpin_context(ctx);
9686 * If event_file is set, the fput() above will have called ->release()
9687 * and that will take care of freeing the event.
9693 mutex_unlock(&task->signal->cred_guard_mutex);
9698 put_task_struct(task);
9702 put_unused_fd(event_fd);
9707 * perf_event_create_kernel_counter
9709 * @attr: attributes of the counter to create
9710 * @cpu: cpu in which the counter is bound
9711 * @task: task to profile (NULL for percpu)
9714 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
9715 struct task_struct *task,
9716 perf_overflow_handler_t overflow_handler,
9719 struct perf_event_context *ctx;
9720 struct perf_event *event;
9724 * Get the target context (task or percpu):
9727 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
9728 overflow_handler, context, -1);
9729 if (IS_ERR(event)) {
9730 err = PTR_ERR(event);
9734 /* Mark owner so we could distinguish it from user events. */
9735 event->owner = TASK_TOMBSTONE;
9737 ctx = find_get_context(event->pmu, task, event);
9743 WARN_ON_ONCE(ctx->parent_ctx);
9744 mutex_lock(&ctx->mutex);
9745 if (ctx->task == TASK_TOMBSTONE) {
9750 if (!exclusive_event_installable(event, ctx)) {
9755 perf_install_in_context(ctx, event, cpu);
9756 perf_unpin_context(ctx);
9757 mutex_unlock(&ctx->mutex);
9762 mutex_unlock(&ctx->mutex);
9763 perf_unpin_context(ctx);
9768 return ERR_PTR(err);
9770 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9772 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
9774 struct perf_event_context *src_ctx;
9775 struct perf_event_context *dst_ctx;
9776 struct perf_event *event, *tmp;
9779 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
9780 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
9783 * See perf_event_ctx_lock() for comments on the details
9784 * of swizzling perf_event::ctx.
9786 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
9787 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
9789 perf_remove_from_context(event, 0);
9790 unaccount_event_cpu(event, src_cpu);
9792 list_add(&event->migrate_entry, &events);
9796 * Wait for the events to quiesce before re-instating them.
9801 * Re-instate events in 2 passes.
9803 * Skip over group leaders and only install siblings on this first
9804 * pass, siblings will not get enabled without a leader, however a
9805 * leader will enable its siblings, even if those are still on the old
9808 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9809 if (event->group_leader == event)
9812 list_del(&event->migrate_entry);
9813 if (event->state >= PERF_EVENT_STATE_OFF)
9814 event->state = PERF_EVENT_STATE_INACTIVE;
9815 account_event_cpu(event, dst_cpu);
9816 perf_install_in_context(dst_ctx, event, dst_cpu);
9821 * Once all the siblings are setup properly, install the group leaders
9824 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9825 list_del(&event->migrate_entry);
9826 if (event->state >= PERF_EVENT_STATE_OFF)
9827 event->state = PERF_EVENT_STATE_INACTIVE;
9828 account_event_cpu(event, dst_cpu);
9829 perf_install_in_context(dst_ctx, event, dst_cpu);
9832 mutex_unlock(&dst_ctx->mutex);
9833 mutex_unlock(&src_ctx->mutex);
9835 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
9837 static void sync_child_event(struct perf_event *child_event,
9838 struct task_struct *child)
9840 struct perf_event *parent_event = child_event->parent;
9843 if (child_event->attr.inherit_stat)
9844 perf_event_read_event(child_event, child);
9846 child_val = perf_event_count(child_event);
9849 * Add back the child's count to the parent's count:
9851 atomic64_add(child_val, &parent_event->child_count);
9852 atomic64_add(child_event->total_time_enabled,
9853 &parent_event->child_total_time_enabled);
9854 atomic64_add(child_event->total_time_running,
9855 &parent_event->child_total_time_running);
9859 perf_event_exit_event(struct perf_event *child_event,
9860 struct perf_event_context *child_ctx,
9861 struct task_struct *child)
9863 struct perf_event *parent_event = child_event->parent;
9866 * Do not destroy the 'original' grouping; because of the context
9867 * switch optimization the original events could've ended up in a
9868 * random child task.
9870 * If we were to destroy the original group, all group related
9871 * operations would cease to function properly after this random
9874 * Do destroy all inherited groups, we don't care about those
9875 * and being thorough is better.
9877 raw_spin_lock_irq(&child_ctx->lock);
9878 WARN_ON_ONCE(child_ctx->is_active);
9881 perf_group_detach(child_event);
9882 list_del_event(child_event, child_ctx);
9883 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
9884 raw_spin_unlock_irq(&child_ctx->lock);
9887 * Parent events are governed by their filedesc, retain them.
9889 if (!parent_event) {
9890 perf_event_wakeup(child_event);
9894 * Child events can be cleaned up.
9897 sync_child_event(child_event, child);
9900 * Remove this event from the parent's list
9902 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9903 mutex_lock(&parent_event->child_mutex);
9904 list_del_init(&child_event->child_list);
9905 mutex_unlock(&parent_event->child_mutex);
9908 * Kick perf_poll() for is_event_hup().
9910 perf_event_wakeup(parent_event);
9911 free_event(child_event);
9912 put_event(parent_event);
9915 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9917 struct perf_event_context *child_ctx, *clone_ctx = NULL;
9918 struct perf_event *child_event, *next;
9920 WARN_ON_ONCE(child != current);
9922 child_ctx = perf_pin_task_context(child, ctxn);
9927 * In order to reduce the amount of tricky in ctx tear-down, we hold
9928 * ctx::mutex over the entire thing. This serializes against almost
9929 * everything that wants to access the ctx.
9931 * The exception is sys_perf_event_open() /
9932 * perf_event_create_kernel_count() which does find_get_context()
9933 * without ctx::mutex (it cannot because of the move_group double mutex
9934 * lock thing). See the comments in perf_install_in_context().
9936 mutex_lock(&child_ctx->mutex);
9939 * In a single ctx::lock section, de-schedule the events and detach the
9940 * context from the task such that we cannot ever get it scheduled back
9943 raw_spin_lock_irq(&child_ctx->lock);
9944 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
9947 * Now that the context is inactive, destroy the task <-> ctx relation
9948 * and mark the context dead.
9950 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
9951 put_ctx(child_ctx); /* cannot be last */
9952 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
9953 put_task_struct(current); /* cannot be last */
9955 clone_ctx = unclone_ctx(child_ctx);
9956 raw_spin_unlock_irq(&child_ctx->lock);
9962 * Report the task dead after unscheduling the events so that we
9963 * won't get any samples after PERF_RECORD_EXIT. We can however still
9964 * get a few PERF_RECORD_READ events.
9966 perf_event_task(child, child_ctx, 0);
9968 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9969 perf_event_exit_event(child_event, child_ctx, child);
9971 mutex_unlock(&child_ctx->mutex);
9977 * When a child task exits, feed back event values to parent events.
9979 * Can be called with cred_guard_mutex held when called from
9980 * install_exec_creds().
9982 void perf_event_exit_task(struct task_struct *child)
9984 struct perf_event *event, *tmp;
9987 mutex_lock(&child->perf_event_mutex);
9988 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9990 list_del_init(&event->owner_entry);
9993 * Ensure the list deletion is visible before we clear
9994 * the owner, closes a race against perf_release() where
9995 * we need to serialize on the owner->perf_event_mutex.
9997 smp_store_release(&event->owner, NULL);
9999 mutex_unlock(&child->perf_event_mutex);
10001 for_each_task_context_nr(ctxn)
10002 perf_event_exit_task_context(child, ctxn);
10005 * The perf_event_exit_task_context calls perf_event_task
10006 * with child's task_ctx, which generates EXIT events for
10007 * child contexts and sets child->perf_event_ctxp[] to NULL.
10008 * At this point we need to send EXIT events to cpu contexts.
10010 perf_event_task(child, NULL, 0);
10013 static void perf_free_event(struct perf_event *event,
10014 struct perf_event_context *ctx)
10016 struct perf_event *parent = event->parent;
10018 if (WARN_ON_ONCE(!parent))
10021 mutex_lock(&parent->child_mutex);
10022 list_del_init(&event->child_list);
10023 mutex_unlock(&parent->child_mutex);
10027 raw_spin_lock_irq(&ctx->lock);
10028 perf_group_detach(event);
10029 list_del_event(event, ctx);
10030 raw_spin_unlock_irq(&ctx->lock);
10035 * Free an unexposed, unused context as created by inheritance by
10036 * perf_event_init_task below, used by fork() in case of fail.
10038 * Not all locks are strictly required, but take them anyway to be nice and
10039 * help out with the lockdep assertions.
10041 void perf_event_free_task(struct task_struct *task)
10043 struct perf_event_context *ctx;
10044 struct perf_event *event, *tmp;
10047 for_each_task_context_nr(ctxn) {
10048 ctx = task->perf_event_ctxp[ctxn];
10052 mutex_lock(&ctx->mutex);
10054 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
10056 perf_free_event(event, ctx);
10058 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
10060 perf_free_event(event, ctx);
10062 if (!list_empty(&ctx->pinned_groups) ||
10063 !list_empty(&ctx->flexible_groups))
10066 mutex_unlock(&ctx->mutex);
10072 void perf_event_delayed_put(struct task_struct *task)
10076 for_each_task_context_nr(ctxn)
10077 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
10080 struct file *perf_event_get(unsigned int fd)
10084 file = fget_raw(fd);
10086 return ERR_PTR(-EBADF);
10088 if (file->f_op != &perf_fops) {
10090 return ERR_PTR(-EBADF);
10096 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
10099 return ERR_PTR(-EINVAL);
10101 return &event->attr;
10105 * inherit a event from parent task to child task:
10107 static struct perf_event *
10108 inherit_event(struct perf_event *parent_event,
10109 struct task_struct *parent,
10110 struct perf_event_context *parent_ctx,
10111 struct task_struct *child,
10112 struct perf_event *group_leader,
10113 struct perf_event_context *child_ctx)
10115 enum perf_event_active_state parent_state = parent_event->state;
10116 struct perf_event *child_event;
10117 unsigned long flags;
10120 * Instead of creating recursive hierarchies of events,
10121 * we link inherited events back to the original parent,
10122 * which has a filp for sure, which we use as the reference
10125 if (parent_event->parent)
10126 parent_event = parent_event->parent;
10128 child_event = perf_event_alloc(&parent_event->attr,
10131 group_leader, parent_event,
10133 if (IS_ERR(child_event))
10134 return child_event;
10137 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
10138 * must be under the same lock in order to serialize against
10139 * perf_event_release_kernel(), such that either we must observe
10140 * is_orphaned_event() or they will observe us on the child_list.
10142 mutex_lock(&parent_event->child_mutex);
10143 if (is_orphaned_event(parent_event) ||
10144 !atomic_long_inc_not_zero(&parent_event->refcount)) {
10145 mutex_unlock(&parent_event->child_mutex);
10146 free_event(child_event);
10150 get_ctx(child_ctx);
10153 * Make the child state follow the state of the parent event,
10154 * not its attr.disabled bit. We hold the parent's mutex,
10155 * so we won't race with perf_event_{en, dis}able_family.
10157 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
10158 child_event->state = PERF_EVENT_STATE_INACTIVE;
10160 child_event->state = PERF_EVENT_STATE_OFF;
10162 if (parent_event->attr.freq) {
10163 u64 sample_period = parent_event->hw.sample_period;
10164 struct hw_perf_event *hwc = &child_event->hw;
10166 hwc->sample_period = sample_period;
10167 hwc->last_period = sample_period;
10169 local64_set(&hwc->period_left, sample_period);
10172 child_event->ctx = child_ctx;
10173 child_event->overflow_handler = parent_event->overflow_handler;
10174 child_event->overflow_handler_context
10175 = parent_event->overflow_handler_context;
10178 * Precalculate sample_data sizes
10180 perf_event__header_size(child_event);
10181 perf_event__id_header_size(child_event);
10184 * Link it up in the child's context:
10186 raw_spin_lock_irqsave(&child_ctx->lock, flags);
10187 add_event_to_ctx(child_event, child_ctx);
10188 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
10191 * Link this into the parent event's child list
10193 list_add_tail(&child_event->child_list, &parent_event->child_list);
10194 mutex_unlock(&parent_event->child_mutex);
10196 return child_event;
10199 static int inherit_group(struct perf_event *parent_event,
10200 struct task_struct *parent,
10201 struct perf_event_context *parent_ctx,
10202 struct task_struct *child,
10203 struct perf_event_context *child_ctx)
10205 struct perf_event *leader;
10206 struct perf_event *sub;
10207 struct perf_event *child_ctr;
10209 leader = inherit_event(parent_event, parent, parent_ctx,
10210 child, NULL, child_ctx);
10211 if (IS_ERR(leader))
10212 return PTR_ERR(leader);
10213 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
10214 child_ctr = inherit_event(sub, parent, parent_ctx,
10215 child, leader, child_ctx);
10216 if (IS_ERR(child_ctr))
10217 return PTR_ERR(child_ctr);
10223 inherit_task_group(struct perf_event *event, struct task_struct *parent,
10224 struct perf_event_context *parent_ctx,
10225 struct task_struct *child, int ctxn,
10226 int *inherited_all)
10229 struct perf_event_context *child_ctx;
10231 if (!event->attr.inherit) {
10232 *inherited_all = 0;
10236 child_ctx = child->perf_event_ctxp[ctxn];
10239 * This is executed from the parent task context, so
10240 * inherit events that have been marked for cloning.
10241 * First allocate and initialize a context for the
10245 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
10249 child->perf_event_ctxp[ctxn] = child_ctx;
10252 ret = inherit_group(event, parent, parent_ctx,
10256 *inherited_all = 0;
10262 * Initialize the perf_event context in task_struct
10264 static int perf_event_init_context(struct task_struct *child, int ctxn)
10266 struct perf_event_context *child_ctx, *parent_ctx;
10267 struct perf_event_context *cloned_ctx;
10268 struct perf_event *event;
10269 struct task_struct *parent = current;
10270 int inherited_all = 1;
10271 unsigned long flags;
10274 if (likely(!parent->perf_event_ctxp[ctxn]))
10278 * If the parent's context is a clone, pin it so it won't get
10279 * swapped under us.
10281 parent_ctx = perf_pin_task_context(parent, ctxn);
10286 * No need to check if parent_ctx != NULL here; since we saw
10287 * it non-NULL earlier, the only reason for it to become NULL
10288 * is if we exit, and since we're currently in the middle of
10289 * a fork we can't be exiting at the same time.
10293 * Lock the parent list. No need to lock the child - not PID
10294 * hashed yet and not running, so nobody can access it.
10296 mutex_lock(&parent_ctx->mutex);
10299 * We dont have to disable NMIs - we are only looking at
10300 * the list, not manipulating it:
10302 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
10303 ret = inherit_task_group(event, parent, parent_ctx,
10304 child, ctxn, &inherited_all);
10310 * We can't hold ctx->lock when iterating the ->flexible_group list due
10311 * to allocations, but we need to prevent rotation because
10312 * rotate_ctx() will change the list from interrupt context.
10314 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10315 parent_ctx->rotate_disable = 1;
10316 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10318 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
10319 ret = inherit_task_group(event, parent, parent_ctx,
10320 child, ctxn, &inherited_all);
10325 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
10326 parent_ctx->rotate_disable = 0;
10328 child_ctx = child->perf_event_ctxp[ctxn];
10330 if (child_ctx && inherited_all) {
10332 * Mark the child context as a clone of the parent
10333 * context, or of whatever the parent is a clone of.
10335 * Note that if the parent is a clone, the holding of
10336 * parent_ctx->lock avoids it from being uncloned.
10338 cloned_ctx = parent_ctx->parent_ctx;
10340 child_ctx->parent_ctx = cloned_ctx;
10341 child_ctx->parent_gen = parent_ctx->parent_gen;
10343 child_ctx->parent_ctx = parent_ctx;
10344 child_ctx->parent_gen = parent_ctx->generation;
10346 get_ctx(child_ctx->parent_ctx);
10349 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
10350 mutex_unlock(&parent_ctx->mutex);
10352 perf_unpin_context(parent_ctx);
10353 put_ctx(parent_ctx);
10359 * Initialize the perf_event context in task_struct
10361 int perf_event_init_task(struct task_struct *child)
10365 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
10366 mutex_init(&child->perf_event_mutex);
10367 INIT_LIST_HEAD(&child->perf_event_list);
10369 for_each_task_context_nr(ctxn) {
10370 ret = perf_event_init_context(child, ctxn);
10372 perf_event_free_task(child);
10380 static void __init perf_event_init_all_cpus(void)
10382 struct swevent_htable *swhash;
10385 for_each_possible_cpu(cpu) {
10386 swhash = &per_cpu(swevent_htable, cpu);
10387 mutex_init(&swhash->hlist_mutex);
10388 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
10390 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
10391 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
10395 int perf_event_init_cpu(unsigned int cpu)
10397 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10399 mutex_lock(&swhash->hlist_mutex);
10400 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
10401 struct swevent_hlist *hlist;
10403 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
10405 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10407 mutex_unlock(&swhash->hlist_mutex);
10411 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
10412 static void __perf_event_exit_context(void *__info)
10414 struct perf_event_context *ctx = __info;
10415 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
10416 struct perf_event *event;
10418 raw_spin_lock(&ctx->lock);
10419 list_for_each_entry(event, &ctx->event_list, event_entry)
10420 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
10421 raw_spin_unlock(&ctx->lock);
10424 static void perf_event_exit_cpu_context(int cpu)
10426 struct perf_event_context *ctx;
10430 idx = srcu_read_lock(&pmus_srcu);
10431 list_for_each_entry_rcu(pmu, &pmus, entry) {
10432 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
10434 mutex_lock(&ctx->mutex);
10435 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
10436 mutex_unlock(&ctx->mutex);
10438 srcu_read_unlock(&pmus_srcu, idx);
10442 static void perf_event_exit_cpu_context(int cpu) { }
10446 int perf_event_exit_cpu(unsigned int cpu)
10448 perf_event_exit_cpu_context(cpu);
10453 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
10457 for_each_online_cpu(cpu)
10458 perf_event_exit_cpu(cpu);
10464 * Run the perf reboot notifier at the very last possible moment so that
10465 * the generic watchdog code runs as long as possible.
10467 static struct notifier_block perf_reboot_notifier = {
10468 .notifier_call = perf_reboot,
10469 .priority = INT_MIN,
10472 void __init perf_event_init(void)
10476 idr_init(&pmu_idr);
10478 perf_event_init_all_cpus();
10479 init_srcu_struct(&pmus_srcu);
10480 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
10481 perf_pmu_register(&perf_cpu_clock, NULL, -1);
10482 perf_pmu_register(&perf_task_clock, NULL, -1);
10483 perf_tp_register();
10484 perf_event_init_cpu(smp_processor_id());
10485 register_reboot_notifier(&perf_reboot_notifier);
10487 ret = init_hw_breakpoint();
10488 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
10491 * Build time assertion that we keep the data_head at the intended
10492 * location. IOW, validation we got the __reserved[] size right.
10494 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
10498 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
10501 struct perf_pmu_events_attr *pmu_attr =
10502 container_of(attr, struct perf_pmu_events_attr, attr);
10504 if (pmu_attr->event_str)
10505 return sprintf(page, "%s\n", pmu_attr->event_str);
10509 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
10511 static int __init perf_event_sysfs_init(void)
10516 mutex_lock(&pmus_lock);
10518 ret = bus_register(&pmu_bus);
10522 list_for_each_entry(pmu, &pmus, entry) {
10523 if (!pmu->name || pmu->type < 0)
10526 ret = pmu_dev_alloc(pmu);
10527 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
10529 pmu_bus_running = 1;
10533 mutex_unlock(&pmus_lock);
10537 device_initcall(perf_event_sysfs_init);
10539 #ifdef CONFIG_CGROUP_PERF
10540 static struct cgroup_subsys_state *
10541 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
10543 struct perf_cgroup *jc;
10545 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
10547 return ERR_PTR(-ENOMEM);
10549 jc->info = alloc_percpu(struct perf_cgroup_info);
10552 return ERR_PTR(-ENOMEM);
10558 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
10560 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
10562 free_percpu(jc->info);
10566 static int __perf_cgroup_move(void *info)
10568 struct task_struct *task = info;
10570 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
10575 static void perf_cgroup_attach(struct cgroup_taskset *tset)
10577 struct task_struct *task;
10578 struct cgroup_subsys_state *css;
10580 cgroup_taskset_for_each(task, css, tset)
10581 task_function_call(task, __perf_cgroup_move, task);
10584 struct cgroup_subsys perf_event_cgrp_subsys = {
10585 .css_alloc = perf_cgroup_css_alloc,
10586 .css_free = perf_cgroup_css_free,
10587 .attach = perf_cgroup_attach,
10589 #endif /* CONFIG_CGROUP_PERF */