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>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
56 #include <asm/irq_regs.h>
58 typedef int (*remote_function_f)(void *);
60 struct remote_function_call {
61 struct task_struct *p;
62 remote_function_f func;
67 static void remote_function(void *data)
69 struct remote_function_call *tfc = data;
70 struct task_struct *p = tfc->p;
74 if (task_cpu(p) != smp_processor_id())
78 * Now that we're on right CPU with IRQs disabled, we can test
79 * if we hit the right task without races.
82 tfc->ret = -ESRCH; /* No such (running) process */
87 tfc->ret = tfc->func(tfc->info);
91 * task_function_call - call a function on the cpu on which a task runs
92 * @p: the task to evaluate
93 * @func: the function to be called
94 * @info: the function call argument
96 * Calls the function @func when the task is currently running. This might
97 * be on the current CPU, which just calls the function directly
99 * returns: @func return value, or
100 * -ESRCH - when the process isn't running
101 * -EAGAIN - when the process moved away
104 task_function_call(struct task_struct *p, remote_function_f func, void *info)
106 struct remote_function_call data = {
115 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
118 } while (ret == -EAGAIN);
124 * cpu_function_call - call a function on the cpu
125 * @func: the function to be called
126 * @info: the function call argument
128 * Calls the function @func on the remote cpu.
130 * returns: @func return value or -ENXIO when the cpu is offline
132 static int cpu_function_call(int cpu, remote_function_f func, void *info)
134 struct remote_function_call data = {
138 .ret = -ENXIO, /* No such CPU */
141 smp_call_function_single(cpu, remote_function, &data, 1);
146 static inline struct perf_cpu_context *
147 __get_cpu_context(struct perf_event_context *ctx)
149 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
152 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
153 struct perf_event_context *ctx)
155 raw_spin_lock(&cpuctx->ctx.lock);
157 raw_spin_lock(&ctx->lock);
160 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
161 struct perf_event_context *ctx)
164 raw_spin_unlock(&ctx->lock);
165 raw_spin_unlock(&cpuctx->ctx.lock);
168 #define TASK_TOMBSTONE ((void *)-1L)
170 static bool is_kernel_event(struct perf_event *event)
172 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
176 * On task ctx scheduling...
178 * When !ctx->nr_events a task context will not be scheduled. This means
179 * we can disable the scheduler hooks (for performance) without leaving
180 * pending task ctx state.
182 * This however results in two special cases:
184 * - removing the last event from a task ctx; this is relatively straight
185 * forward and is done in __perf_remove_from_context.
187 * - adding the first event to a task ctx; this is tricky because we cannot
188 * rely on ctx->is_active and therefore cannot use event_function_call().
189 * See perf_install_in_context().
191 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
194 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
195 struct perf_event_context *, void *);
197 struct event_function_struct {
198 struct perf_event *event;
203 static int event_function(void *info)
205 struct event_function_struct *efs = info;
206 struct perf_event *event = efs->event;
207 struct perf_event_context *ctx = event->ctx;
208 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
209 struct perf_event_context *task_ctx = cpuctx->task_ctx;
212 lockdep_assert_irqs_disabled();
214 perf_ctx_lock(cpuctx, task_ctx);
216 * Since we do the IPI call without holding ctx->lock things can have
217 * changed, double check we hit the task we set out to hit.
220 if (ctx->task != current) {
226 * We only use event_function_call() on established contexts,
227 * and event_function() is only ever called when active (or
228 * rather, we'll have bailed in task_function_call() or the
229 * above ctx->task != current test), therefore we must have
230 * ctx->is_active here.
232 WARN_ON_ONCE(!ctx->is_active);
234 * And since we have ctx->is_active, cpuctx->task_ctx must
237 WARN_ON_ONCE(task_ctx != ctx);
239 WARN_ON_ONCE(&cpuctx->ctx != ctx);
242 efs->func(event, cpuctx, ctx, efs->data);
244 perf_ctx_unlock(cpuctx, task_ctx);
249 static void event_function_call(struct perf_event *event, event_f func, void *data)
251 struct perf_event_context *ctx = event->ctx;
252 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
253 struct event_function_struct efs = {
259 if (!event->parent) {
261 * If this is a !child event, we must hold ctx::mutex to
262 * stabilize the the event->ctx relation. See
263 * perf_event_ctx_lock().
265 lockdep_assert_held(&ctx->mutex);
269 cpu_function_call(event->cpu, event_function, &efs);
273 if (task == TASK_TOMBSTONE)
277 if (!task_function_call(task, event_function, &efs))
280 raw_spin_lock_irq(&ctx->lock);
282 * Reload the task pointer, it might have been changed by
283 * a concurrent perf_event_context_sched_out().
286 if (task == TASK_TOMBSTONE) {
287 raw_spin_unlock_irq(&ctx->lock);
290 if (ctx->is_active) {
291 raw_spin_unlock_irq(&ctx->lock);
294 func(event, NULL, ctx, data);
295 raw_spin_unlock_irq(&ctx->lock);
299 * Similar to event_function_call() + event_function(), but hard assumes IRQs
300 * are already disabled and we're on the right CPU.
302 static void event_function_local(struct perf_event *event, event_f func, void *data)
304 struct perf_event_context *ctx = event->ctx;
305 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
306 struct task_struct *task = READ_ONCE(ctx->task);
307 struct perf_event_context *task_ctx = NULL;
309 lockdep_assert_irqs_disabled();
312 if (task == TASK_TOMBSTONE)
318 perf_ctx_lock(cpuctx, task_ctx);
321 if (task == TASK_TOMBSTONE)
326 * We must be either inactive or active and the right task,
327 * otherwise we're screwed, since we cannot IPI to somewhere
330 if (ctx->is_active) {
331 if (WARN_ON_ONCE(task != current))
334 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
338 WARN_ON_ONCE(&cpuctx->ctx != ctx);
341 func(event, cpuctx, ctx, data);
343 perf_ctx_unlock(cpuctx, task_ctx);
346 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
347 PERF_FLAG_FD_OUTPUT |\
348 PERF_FLAG_PID_CGROUP |\
349 PERF_FLAG_FD_CLOEXEC)
352 * branch priv levels that need permission checks
354 #define PERF_SAMPLE_BRANCH_PERM_PLM \
355 (PERF_SAMPLE_BRANCH_KERNEL |\
356 PERF_SAMPLE_BRANCH_HV)
359 EVENT_FLEXIBLE = 0x1,
362 /* see ctx_resched() for details */
364 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
368 * perf_sched_events : >0 events exist
369 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
372 static void perf_sched_delayed(struct work_struct *work);
373 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
374 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
375 static DEFINE_MUTEX(perf_sched_mutex);
376 static atomic_t perf_sched_count;
378 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
379 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
380 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
382 static atomic_t nr_mmap_events __read_mostly;
383 static atomic_t nr_comm_events __read_mostly;
384 static atomic_t nr_namespaces_events __read_mostly;
385 static atomic_t nr_task_events __read_mostly;
386 static atomic_t nr_freq_events __read_mostly;
387 static atomic_t nr_switch_events __read_mostly;
389 static LIST_HEAD(pmus);
390 static DEFINE_MUTEX(pmus_lock);
391 static struct srcu_struct pmus_srcu;
392 static cpumask_var_t perf_online_mask;
395 * perf event paranoia level:
396 * -1 - not paranoid at all
397 * 0 - disallow raw tracepoint access for unpriv
398 * 1 - disallow cpu events for unpriv
399 * 2 - disallow kernel profiling for unpriv
401 int sysctl_perf_event_paranoid __read_mostly = 2;
403 /* Minimum for 512 kiB + 1 user control page */
404 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
407 * max perf event sample rate
409 #define DEFAULT_MAX_SAMPLE_RATE 100000
410 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
411 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
413 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
415 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
416 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
418 static int perf_sample_allowed_ns __read_mostly =
419 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
421 static void update_perf_cpu_limits(void)
423 u64 tmp = perf_sample_period_ns;
425 tmp *= sysctl_perf_cpu_time_max_percent;
426 tmp = div_u64(tmp, 100);
430 WRITE_ONCE(perf_sample_allowed_ns, tmp);
433 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
435 int perf_proc_update_handler(struct ctl_table *table, int write,
436 void __user *buffer, size_t *lenp,
439 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
445 * If throttling is disabled don't allow the write:
447 if (sysctl_perf_cpu_time_max_percent == 100 ||
448 sysctl_perf_cpu_time_max_percent == 0)
451 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
452 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
453 update_perf_cpu_limits();
458 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
460 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
461 void __user *buffer, size_t *lenp,
464 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
469 if (sysctl_perf_cpu_time_max_percent == 100 ||
470 sysctl_perf_cpu_time_max_percent == 0) {
472 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
473 WRITE_ONCE(perf_sample_allowed_ns, 0);
475 update_perf_cpu_limits();
482 * perf samples are done in some very critical code paths (NMIs).
483 * If they take too much CPU time, the system can lock up and not
484 * get any real work done. This will drop the sample rate when
485 * we detect that events are taking too long.
487 #define NR_ACCUMULATED_SAMPLES 128
488 static DEFINE_PER_CPU(u64, running_sample_length);
490 static u64 __report_avg;
491 static u64 __report_allowed;
493 static void perf_duration_warn(struct irq_work *w)
495 printk_ratelimited(KERN_INFO
496 "perf: interrupt took too long (%lld > %lld), lowering "
497 "kernel.perf_event_max_sample_rate to %d\n",
498 __report_avg, __report_allowed,
499 sysctl_perf_event_sample_rate);
502 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
504 void perf_sample_event_took(u64 sample_len_ns)
506 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
514 /* Decay the counter by 1 average sample. */
515 running_len = __this_cpu_read(running_sample_length);
516 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
517 running_len += sample_len_ns;
518 __this_cpu_write(running_sample_length, running_len);
521 * Note: this will be biased artifically low until we have
522 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
523 * from having to maintain a count.
525 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
526 if (avg_len <= max_len)
529 __report_avg = avg_len;
530 __report_allowed = max_len;
533 * Compute a throttle threshold 25% below the current duration.
535 avg_len += avg_len / 4;
536 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
542 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
543 WRITE_ONCE(max_samples_per_tick, max);
545 sysctl_perf_event_sample_rate = max * HZ;
546 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
548 if (!irq_work_queue(&perf_duration_work)) {
549 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
550 "kernel.perf_event_max_sample_rate to %d\n",
551 __report_avg, __report_allowed,
552 sysctl_perf_event_sample_rate);
556 static atomic64_t perf_event_id;
558 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
559 enum event_type_t event_type);
561 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
562 enum event_type_t event_type,
563 struct task_struct *task);
565 static void update_context_time(struct perf_event_context *ctx);
566 static u64 perf_event_time(struct perf_event *event);
568 void __weak perf_event_print_debug(void) { }
570 extern __weak const char *perf_pmu_name(void)
575 static inline u64 perf_clock(void)
577 return local_clock();
580 static inline u64 perf_event_clock(struct perf_event *event)
582 return event->clock();
586 * State based event timekeeping...
588 * The basic idea is to use event->state to determine which (if any) time
589 * fields to increment with the current delta. This means we only need to
590 * update timestamps when we change state or when they are explicitly requested
593 * Event groups make things a little more complicated, but not terribly so. The
594 * rules for a group are that if the group leader is OFF the entire group is
595 * OFF, irrespecive of what the group member states are. This results in
596 * __perf_effective_state().
598 * A futher ramification is that when a group leader flips between OFF and
599 * !OFF, we need to update all group member times.
602 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
603 * need to make sure the relevant context time is updated before we try and
604 * update our timestamps.
607 static __always_inline enum perf_event_state
608 __perf_effective_state(struct perf_event *event)
610 struct perf_event *leader = event->group_leader;
612 if (leader->state <= PERF_EVENT_STATE_OFF)
613 return leader->state;
618 static __always_inline void
619 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
621 enum perf_event_state state = __perf_effective_state(event);
622 u64 delta = now - event->tstamp;
624 *enabled = event->total_time_enabled;
625 if (state >= PERF_EVENT_STATE_INACTIVE)
628 *running = event->total_time_running;
629 if (state >= PERF_EVENT_STATE_ACTIVE)
633 static void perf_event_update_time(struct perf_event *event)
635 u64 now = perf_event_time(event);
637 __perf_update_times(event, now, &event->total_time_enabled,
638 &event->total_time_running);
642 static void perf_event_update_sibling_time(struct perf_event *leader)
644 struct perf_event *sibling;
646 for_each_sibling_event(sibling, leader)
647 perf_event_update_time(sibling);
651 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
653 if (event->state == state)
656 perf_event_update_time(event);
658 * If a group leader gets enabled/disabled all its siblings
661 if ((event->state < 0) ^ (state < 0))
662 perf_event_update_sibling_time(event);
664 WRITE_ONCE(event->state, state);
667 #ifdef CONFIG_CGROUP_PERF
670 perf_cgroup_match(struct perf_event *event)
672 struct perf_event_context *ctx = event->ctx;
673 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
675 /* @event doesn't care about cgroup */
679 /* wants specific cgroup scope but @cpuctx isn't associated with any */
684 * Cgroup scoping is recursive. An event enabled for a cgroup is
685 * also enabled for all its descendant cgroups. If @cpuctx's
686 * cgroup is a descendant of @event's (the test covers identity
687 * case), it's a match.
689 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
690 event->cgrp->css.cgroup);
693 static inline void perf_detach_cgroup(struct perf_event *event)
695 css_put(&event->cgrp->css);
699 static inline int is_cgroup_event(struct perf_event *event)
701 return event->cgrp != NULL;
704 static inline u64 perf_cgroup_event_time(struct perf_event *event)
706 struct perf_cgroup_info *t;
708 t = per_cpu_ptr(event->cgrp->info, event->cpu);
712 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
714 struct perf_cgroup_info *info;
719 info = this_cpu_ptr(cgrp->info);
721 info->time += now - info->timestamp;
722 info->timestamp = now;
725 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
727 struct perf_cgroup *cgrp_out = cpuctx->cgrp;
729 __update_cgrp_time(cgrp_out);
732 static inline void update_cgrp_time_from_event(struct perf_event *event)
734 struct perf_cgroup *cgrp;
737 * ensure we access cgroup data only when needed and
738 * when we know the cgroup is pinned (css_get)
740 if (!is_cgroup_event(event))
743 cgrp = perf_cgroup_from_task(current, event->ctx);
745 * Do not update time when cgroup is not active
747 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
748 __update_cgrp_time(event->cgrp);
752 perf_cgroup_set_timestamp(struct task_struct *task,
753 struct perf_event_context *ctx)
755 struct perf_cgroup *cgrp;
756 struct perf_cgroup_info *info;
759 * ctx->lock held by caller
760 * ensure we do not access cgroup data
761 * unless we have the cgroup pinned (css_get)
763 if (!task || !ctx->nr_cgroups)
766 cgrp = perf_cgroup_from_task(task, ctx);
767 info = this_cpu_ptr(cgrp->info);
768 info->timestamp = ctx->timestamp;
771 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
773 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
774 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
777 * reschedule events based on the cgroup constraint of task.
779 * mode SWOUT : schedule out everything
780 * mode SWIN : schedule in based on cgroup for next
782 static void perf_cgroup_switch(struct task_struct *task, int mode)
784 struct perf_cpu_context *cpuctx;
785 struct list_head *list;
789 * Disable interrupts and preemption to avoid this CPU's
790 * cgrp_cpuctx_entry to change under us.
792 local_irq_save(flags);
794 list = this_cpu_ptr(&cgrp_cpuctx_list);
795 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
796 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
798 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
799 perf_pmu_disable(cpuctx->ctx.pmu);
801 if (mode & PERF_CGROUP_SWOUT) {
802 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
804 * must not be done before ctxswout due
805 * to event_filter_match() in event_sched_out()
810 if (mode & PERF_CGROUP_SWIN) {
811 WARN_ON_ONCE(cpuctx->cgrp);
813 * set cgrp before ctxsw in to allow
814 * event_filter_match() to not have to pass
816 * we pass the cpuctx->ctx to perf_cgroup_from_task()
817 * because cgorup events are only per-cpu
819 cpuctx->cgrp = perf_cgroup_from_task(task,
821 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
823 perf_pmu_enable(cpuctx->ctx.pmu);
824 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
827 local_irq_restore(flags);
830 static inline void perf_cgroup_sched_out(struct task_struct *task,
831 struct task_struct *next)
833 struct perf_cgroup *cgrp1;
834 struct perf_cgroup *cgrp2 = NULL;
838 * we come here when we know perf_cgroup_events > 0
839 * we do not need to pass the ctx here because we know
840 * we are holding the rcu lock
842 cgrp1 = perf_cgroup_from_task(task, NULL);
843 cgrp2 = perf_cgroup_from_task(next, NULL);
846 * only schedule out current cgroup events if we know
847 * that we are switching to a different cgroup. Otherwise,
848 * do no touch the cgroup events.
851 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
856 static inline void perf_cgroup_sched_in(struct task_struct *prev,
857 struct task_struct *task)
859 struct perf_cgroup *cgrp1;
860 struct perf_cgroup *cgrp2 = NULL;
864 * we come here when we know perf_cgroup_events > 0
865 * we do not need to pass the ctx here because we know
866 * we are holding the rcu lock
868 cgrp1 = perf_cgroup_from_task(task, NULL);
869 cgrp2 = perf_cgroup_from_task(prev, NULL);
872 * only need to schedule in cgroup events if we are changing
873 * cgroup during ctxsw. Cgroup events were not scheduled
874 * out of ctxsw out if that was not the case.
877 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
882 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
883 struct perf_event_attr *attr,
884 struct perf_event *group_leader)
886 struct perf_cgroup *cgrp;
887 struct cgroup_subsys_state *css;
888 struct fd f = fdget(fd);
894 css = css_tryget_online_from_dir(f.file->f_path.dentry,
895 &perf_event_cgrp_subsys);
901 cgrp = container_of(css, struct perf_cgroup, css);
905 * all events in a group must monitor
906 * the same cgroup because a task belongs
907 * to only one perf cgroup at a time
909 if (group_leader && group_leader->cgrp != cgrp) {
910 perf_detach_cgroup(event);
919 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
921 struct perf_cgroup_info *t;
922 t = per_cpu_ptr(event->cgrp->info, event->cpu);
923 event->shadow_ctx_time = now - t->timestamp;
927 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
928 * cleared when last cgroup event is removed.
931 list_update_cgroup_event(struct perf_event *event,
932 struct perf_event_context *ctx, bool add)
934 struct perf_cpu_context *cpuctx;
935 struct list_head *cpuctx_entry;
937 if (!is_cgroup_event(event))
941 * Because cgroup events are always per-cpu events,
942 * this will always be called from the right CPU.
944 cpuctx = __get_cpu_context(ctx);
947 * Since setting cpuctx->cgrp is conditional on the current @cgrp
948 * matching the event's cgroup, we must do this for every new event,
949 * because if the first would mismatch, the second would not try again
950 * and we would leave cpuctx->cgrp unset.
952 if (add && !cpuctx->cgrp) {
953 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
955 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
959 if (add && ctx->nr_cgroups++)
961 else if (!add && --ctx->nr_cgroups)
964 /* no cgroup running */
968 cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
970 list_add(cpuctx_entry, this_cpu_ptr(&cgrp_cpuctx_list));
972 list_del(cpuctx_entry);
975 #else /* !CONFIG_CGROUP_PERF */
978 perf_cgroup_match(struct perf_event *event)
983 static inline void perf_detach_cgroup(struct perf_event *event)
986 static inline int is_cgroup_event(struct perf_event *event)
991 static inline void update_cgrp_time_from_event(struct perf_event *event)
995 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
999 static inline void perf_cgroup_sched_out(struct task_struct *task,
1000 struct task_struct *next)
1004 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1005 struct task_struct *task)
1009 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1010 struct perf_event_attr *attr,
1011 struct perf_event *group_leader)
1017 perf_cgroup_set_timestamp(struct task_struct *task,
1018 struct perf_event_context *ctx)
1023 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1028 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1032 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1038 list_update_cgroup_event(struct perf_event *event,
1039 struct perf_event_context *ctx, bool add)
1046 * set default to be dependent on timer tick just
1047 * like original code
1049 #define PERF_CPU_HRTIMER (1000 / HZ)
1051 * function must be called with interrupts disabled
1053 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1055 struct perf_cpu_context *cpuctx;
1058 lockdep_assert_irqs_disabled();
1060 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1061 rotations = perf_rotate_context(cpuctx);
1063 raw_spin_lock(&cpuctx->hrtimer_lock);
1065 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1067 cpuctx->hrtimer_active = 0;
1068 raw_spin_unlock(&cpuctx->hrtimer_lock);
1070 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1073 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1075 struct hrtimer *timer = &cpuctx->hrtimer;
1076 struct pmu *pmu = cpuctx->ctx.pmu;
1079 /* no multiplexing needed for SW PMU */
1080 if (pmu->task_ctx_nr == perf_sw_context)
1084 * check default is sane, if not set then force to
1085 * default interval (1/tick)
1087 interval = pmu->hrtimer_interval_ms;
1089 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1091 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1093 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1094 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
1095 timer->function = perf_mux_hrtimer_handler;
1098 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1100 struct hrtimer *timer = &cpuctx->hrtimer;
1101 struct pmu *pmu = cpuctx->ctx.pmu;
1102 unsigned long flags;
1104 /* not for SW PMU */
1105 if (pmu->task_ctx_nr == perf_sw_context)
1108 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1109 if (!cpuctx->hrtimer_active) {
1110 cpuctx->hrtimer_active = 1;
1111 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1112 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
1114 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1119 void perf_pmu_disable(struct pmu *pmu)
1121 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1123 pmu->pmu_disable(pmu);
1126 void perf_pmu_enable(struct pmu *pmu)
1128 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1130 pmu->pmu_enable(pmu);
1133 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1136 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1137 * perf_event_task_tick() are fully serialized because they're strictly cpu
1138 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1139 * disabled, while perf_event_task_tick is called from IRQ context.
1141 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1143 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1145 lockdep_assert_irqs_disabled();
1147 WARN_ON(!list_empty(&ctx->active_ctx_list));
1149 list_add(&ctx->active_ctx_list, head);
1152 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1154 lockdep_assert_irqs_disabled();
1156 WARN_ON(list_empty(&ctx->active_ctx_list));
1158 list_del_init(&ctx->active_ctx_list);
1161 static void get_ctx(struct perf_event_context *ctx)
1163 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
1166 static void free_ctx(struct rcu_head *head)
1168 struct perf_event_context *ctx;
1170 ctx = container_of(head, struct perf_event_context, rcu_head);
1171 kfree(ctx->task_ctx_data);
1175 static void put_ctx(struct perf_event_context *ctx)
1177 if (atomic_dec_and_test(&ctx->refcount)) {
1178 if (ctx->parent_ctx)
1179 put_ctx(ctx->parent_ctx);
1180 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1181 put_task_struct(ctx->task);
1182 call_rcu(&ctx->rcu_head, free_ctx);
1187 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1188 * perf_pmu_migrate_context() we need some magic.
1190 * Those places that change perf_event::ctx will hold both
1191 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1193 * Lock ordering is by mutex address. There are two other sites where
1194 * perf_event_context::mutex nests and those are:
1196 * - perf_event_exit_task_context() [ child , 0 ]
1197 * perf_event_exit_event()
1198 * put_event() [ parent, 1 ]
1200 * - perf_event_init_context() [ parent, 0 ]
1201 * inherit_task_group()
1204 * perf_event_alloc()
1206 * perf_try_init_event() [ child , 1 ]
1208 * While it appears there is an obvious deadlock here -- the parent and child
1209 * nesting levels are inverted between the two. This is in fact safe because
1210 * life-time rules separate them. That is an exiting task cannot fork, and a
1211 * spawning task cannot (yet) exit.
1213 * But remember that that these are parent<->child context relations, and
1214 * migration does not affect children, therefore these two orderings should not
1217 * The change in perf_event::ctx does not affect children (as claimed above)
1218 * because the sys_perf_event_open() case will install a new event and break
1219 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1220 * concerned with cpuctx and that doesn't have children.
1222 * The places that change perf_event::ctx will issue:
1224 * perf_remove_from_context();
1225 * synchronize_rcu();
1226 * perf_install_in_context();
1228 * to affect the change. The remove_from_context() + synchronize_rcu() should
1229 * quiesce the event, after which we can install it in the new location. This
1230 * means that only external vectors (perf_fops, prctl) can perturb the event
1231 * while in transit. Therefore all such accessors should also acquire
1232 * perf_event_context::mutex to serialize against this.
1234 * However; because event->ctx can change while we're waiting to acquire
1235 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1240 * task_struct::perf_event_mutex
1241 * perf_event_context::mutex
1242 * perf_event::child_mutex;
1243 * perf_event_context::lock
1244 * perf_event::mmap_mutex
1249 * cpuctx->mutex / perf_event_context::mutex
1251 static struct perf_event_context *
1252 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1254 struct perf_event_context *ctx;
1258 ctx = READ_ONCE(event->ctx);
1259 if (!atomic_inc_not_zero(&ctx->refcount)) {
1265 mutex_lock_nested(&ctx->mutex, nesting);
1266 if (event->ctx != ctx) {
1267 mutex_unlock(&ctx->mutex);
1275 static inline struct perf_event_context *
1276 perf_event_ctx_lock(struct perf_event *event)
1278 return perf_event_ctx_lock_nested(event, 0);
1281 static void perf_event_ctx_unlock(struct perf_event *event,
1282 struct perf_event_context *ctx)
1284 mutex_unlock(&ctx->mutex);
1289 * This must be done under the ctx->lock, such as to serialize against
1290 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1291 * calling scheduler related locks and ctx->lock nests inside those.
1293 static __must_check struct perf_event_context *
1294 unclone_ctx(struct perf_event_context *ctx)
1296 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1298 lockdep_assert_held(&ctx->lock);
1301 ctx->parent_ctx = NULL;
1307 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1312 * only top level events have the pid namespace they were created in
1315 event = event->parent;
1317 nr = __task_pid_nr_ns(p, type, event->ns);
1318 /* avoid -1 if it is idle thread or runs in another ns */
1319 if (!nr && !pid_alive(p))
1324 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1326 return perf_event_pid_type(event, p, __PIDTYPE_TGID);
1329 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1331 return perf_event_pid_type(event, p, PIDTYPE_PID);
1335 * If we inherit events we want to return the parent event id
1338 static u64 primary_event_id(struct perf_event *event)
1343 id = event->parent->id;
1349 * Get the perf_event_context for a task and lock it.
1351 * This has to cope with with the fact that until it is locked,
1352 * the context could get moved to another task.
1354 static struct perf_event_context *
1355 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1357 struct perf_event_context *ctx;
1361 * One of the few rules of preemptible RCU is that one cannot do
1362 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1363 * part of the read side critical section was irqs-enabled -- see
1364 * rcu_read_unlock_special().
1366 * Since ctx->lock nests under rq->lock we must ensure the entire read
1367 * side critical section has interrupts disabled.
1369 local_irq_save(*flags);
1371 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1374 * If this context is a clone of another, it might
1375 * get swapped for another underneath us by
1376 * perf_event_task_sched_out, though the
1377 * rcu_read_lock() protects us from any context
1378 * getting freed. Lock the context and check if it
1379 * got swapped before we could get the lock, and retry
1380 * if so. If we locked the right context, then it
1381 * can't get swapped on us any more.
1383 raw_spin_lock(&ctx->lock);
1384 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1385 raw_spin_unlock(&ctx->lock);
1387 local_irq_restore(*flags);
1391 if (ctx->task == TASK_TOMBSTONE ||
1392 !atomic_inc_not_zero(&ctx->refcount)) {
1393 raw_spin_unlock(&ctx->lock);
1396 WARN_ON_ONCE(ctx->task != task);
1401 local_irq_restore(*flags);
1406 * Get the context for a task and increment its pin_count so it
1407 * can't get swapped to another task. This also increments its
1408 * reference count so that the context can't get freed.
1410 static struct perf_event_context *
1411 perf_pin_task_context(struct task_struct *task, int ctxn)
1413 struct perf_event_context *ctx;
1414 unsigned long flags;
1416 ctx = perf_lock_task_context(task, ctxn, &flags);
1419 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1424 static void perf_unpin_context(struct perf_event_context *ctx)
1426 unsigned long flags;
1428 raw_spin_lock_irqsave(&ctx->lock, flags);
1430 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1434 * Update the record of the current time in a context.
1436 static void update_context_time(struct perf_event_context *ctx)
1438 u64 now = perf_clock();
1440 ctx->time += now - ctx->timestamp;
1441 ctx->timestamp = now;
1444 static u64 perf_event_time(struct perf_event *event)
1446 struct perf_event_context *ctx = event->ctx;
1448 if (is_cgroup_event(event))
1449 return perf_cgroup_event_time(event);
1451 return ctx ? ctx->time : 0;
1454 static enum event_type_t get_event_type(struct perf_event *event)
1456 struct perf_event_context *ctx = event->ctx;
1457 enum event_type_t event_type;
1459 lockdep_assert_held(&ctx->lock);
1462 * It's 'group type', really, because if our group leader is
1463 * pinned, so are we.
1465 if (event->group_leader != event)
1466 event = event->group_leader;
1468 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1470 event_type |= EVENT_CPU;
1476 * Helper function to initialize event group nodes.
1478 static void init_event_group(struct perf_event *event)
1480 RB_CLEAR_NODE(&event->group_node);
1481 event->group_index = 0;
1485 * Extract pinned or flexible groups from the context
1486 * based on event attrs bits.
1488 static struct perf_event_groups *
1489 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1491 if (event->attr.pinned)
1492 return &ctx->pinned_groups;
1494 return &ctx->flexible_groups;
1498 * Helper function to initializes perf_event_group trees.
1500 static void perf_event_groups_init(struct perf_event_groups *groups)
1502 groups->tree = RB_ROOT;
1507 * Compare function for event groups;
1509 * Implements complex key that first sorts by CPU and then by virtual index
1510 * which provides ordering when rotating groups for the same CPU.
1513 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1515 if (left->cpu < right->cpu)
1517 if (left->cpu > right->cpu)
1520 if (left->group_index < right->group_index)
1522 if (left->group_index > right->group_index)
1529 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1530 * key (see perf_event_groups_less). This places it last inside the CPU
1534 perf_event_groups_insert(struct perf_event_groups *groups,
1535 struct perf_event *event)
1537 struct perf_event *node_event;
1538 struct rb_node *parent;
1539 struct rb_node **node;
1541 event->group_index = ++groups->index;
1543 node = &groups->tree.rb_node;
1548 node_event = container_of(*node, struct perf_event, group_node);
1550 if (perf_event_groups_less(event, node_event))
1551 node = &parent->rb_left;
1553 node = &parent->rb_right;
1556 rb_link_node(&event->group_node, parent, node);
1557 rb_insert_color(&event->group_node, &groups->tree);
1561 * Helper function to insert event into the pinned or flexible groups.
1564 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1566 struct perf_event_groups *groups;
1568 groups = get_event_groups(event, ctx);
1569 perf_event_groups_insert(groups, event);
1573 * Delete a group from a tree.
1576 perf_event_groups_delete(struct perf_event_groups *groups,
1577 struct perf_event *event)
1579 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1580 RB_EMPTY_ROOT(&groups->tree));
1582 rb_erase(&event->group_node, &groups->tree);
1583 init_event_group(event);
1587 * Helper function to delete event from its groups.
1590 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1592 struct perf_event_groups *groups;
1594 groups = get_event_groups(event, ctx);
1595 perf_event_groups_delete(groups, event);
1599 * Get the leftmost event in the @cpu subtree.
1601 static struct perf_event *
1602 perf_event_groups_first(struct perf_event_groups *groups, int cpu)
1604 struct perf_event *node_event = NULL, *match = NULL;
1605 struct rb_node *node = groups->tree.rb_node;
1608 node_event = container_of(node, struct perf_event, group_node);
1610 if (cpu < node_event->cpu) {
1611 node = node->rb_left;
1612 } else if (cpu > node_event->cpu) {
1613 node = node->rb_right;
1616 node = node->rb_left;
1624 * Like rb_entry_next_safe() for the @cpu subtree.
1626 static struct perf_event *
1627 perf_event_groups_next(struct perf_event *event)
1629 struct perf_event *next;
1631 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1632 if (next && next->cpu == event->cpu)
1639 * Iterate through the whole groups tree.
1641 #define perf_event_groups_for_each(event, groups) \
1642 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1643 typeof(*event), group_node); event; \
1644 event = rb_entry_safe(rb_next(&event->group_node), \
1645 typeof(*event), group_node))
1648 * Add a event from the lists for its context.
1649 * Must be called with ctx->mutex and ctx->lock held.
1652 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1654 lockdep_assert_held(&ctx->lock);
1656 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1657 event->attach_state |= PERF_ATTACH_CONTEXT;
1659 event->tstamp = perf_event_time(event);
1662 * If we're a stand alone event or group leader, we go to the context
1663 * list, group events are kept attached to the group so that
1664 * perf_group_detach can, at all times, locate all siblings.
1666 if (event->group_leader == event) {
1667 event->group_caps = event->event_caps;
1668 add_event_to_groups(event, ctx);
1671 list_update_cgroup_event(event, ctx, true);
1673 list_add_rcu(&event->event_entry, &ctx->event_list);
1675 if (event->attr.inherit_stat)
1682 * Initialize event state based on the perf_event_attr::disabled.
1684 static inline void perf_event__state_init(struct perf_event *event)
1686 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1687 PERF_EVENT_STATE_INACTIVE;
1690 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1692 int entry = sizeof(u64); /* value */
1696 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1697 size += sizeof(u64);
1699 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1700 size += sizeof(u64);
1702 if (event->attr.read_format & PERF_FORMAT_ID)
1703 entry += sizeof(u64);
1705 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1707 size += sizeof(u64);
1711 event->read_size = size;
1714 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1716 struct perf_sample_data *data;
1719 if (sample_type & PERF_SAMPLE_IP)
1720 size += sizeof(data->ip);
1722 if (sample_type & PERF_SAMPLE_ADDR)
1723 size += sizeof(data->addr);
1725 if (sample_type & PERF_SAMPLE_PERIOD)
1726 size += sizeof(data->period);
1728 if (sample_type & PERF_SAMPLE_WEIGHT)
1729 size += sizeof(data->weight);
1731 if (sample_type & PERF_SAMPLE_READ)
1732 size += event->read_size;
1734 if (sample_type & PERF_SAMPLE_DATA_SRC)
1735 size += sizeof(data->data_src.val);
1737 if (sample_type & PERF_SAMPLE_TRANSACTION)
1738 size += sizeof(data->txn);
1740 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1741 size += sizeof(data->phys_addr);
1743 event->header_size = size;
1747 * Called at perf_event creation and when events are attached/detached from a
1750 static void perf_event__header_size(struct perf_event *event)
1752 __perf_event_read_size(event,
1753 event->group_leader->nr_siblings);
1754 __perf_event_header_size(event, event->attr.sample_type);
1757 static void perf_event__id_header_size(struct perf_event *event)
1759 struct perf_sample_data *data;
1760 u64 sample_type = event->attr.sample_type;
1763 if (sample_type & PERF_SAMPLE_TID)
1764 size += sizeof(data->tid_entry);
1766 if (sample_type & PERF_SAMPLE_TIME)
1767 size += sizeof(data->time);
1769 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1770 size += sizeof(data->id);
1772 if (sample_type & PERF_SAMPLE_ID)
1773 size += sizeof(data->id);
1775 if (sample_type & PERF_SAMPLE_STREAM_ID)
1776 size += sizeof(data->stream_id);
1778 if (sample_type & PERF_SAMPLE_CPU)
1779 size += sizeof(data->cpu_entry);
1781 event->id_header_size = size;
1784 static bool perf_event_validate_size(struct perf_event *event)
1787 * The values computed here will be over-written when we actually
1790 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1791 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1792 perf_event__id_header_size(event);
1795 * Sum the lot; should not exceed the 64k limit we have on records.
1796 * Conservative limit to allow for callchains and other variable fields.
1798 if (event->read_size + event->header_size +
1799 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1805 static void perf_group_attach(struct perf_event *event)
1807 struct perf_event *group_leader = event->group_leader, *pos;
1809 lockdep_assert_held(&event->ctx->lock);
1812 * We can have double attach due to group movement in perf_event_open.
1814 if (event->attach_state & PERF_ATTACH_GROUP)
1817 event->attach_state |= PERF_ATTACH_GROUP;
1819 if (group_leader == event)
1822 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1824 group_leader->group_caps &= event->event_caps;
1826 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1827 group_leader->nr_siblings++;
1829 perf_event__header_size(group_leader);
1831 for_each_sibling_event(pos, group_leader)
1832 perf_event__header_size(pos);
1836 * Remove a event from the lists for its context.
1837 * Must be called with ctx->mutex and ctx->lock held.
1840 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1842 WARN_ON_ONCE(event->ctx != ctx);
1843 lockdep_assert_held(&ctx->lock);
1846 * We can have double detach due to exit/hot-unplug + close.
1848 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1851 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1853 list_update_cgroup_event(event, ctx, false);
1856 if (event->attr.inherit_stat)
1859 list_del_rcu(&event->event_entry);
1861 if (event->group_leader == event)
1862 del_event_from_groups(event, ctx);
1865 * If event was in error state, then keep it
1866 * that way, otherwise bogus counts will be
1867 * returned on read(). The only way to get out
1868 * of error state is by explicit re-enabling
1871 if (event->state > PERF_EVENT_STATE_OFF)
1872 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
1877 static void perf_group_detach(struct perf_event *event)
1879 struct perf_event *sibling, *tmp;
1880 struct perf_event_context *ctx = event->ctx;
1882 lockdep_assert_held(&ctx->lock);
1885 * We can have double detach due to exit/hot-unplug + close.
1887 if (!(event->attach_state & PERF_ATTACH_GROUP))
1890 event->attach_state &= ~PERF_ATTACH_GROUP;
1893 * If this is a sibling, remove it from its group.
1895 if (event->group_leader != event) {
1896 list_del_init(&event->sibling_list);
1897 event->group_leader->nr_siblings--;
1902 * If this was a group event with sibling events then
1903 * upgrade the siblings to singleton events by adding them
1904 * to whatever list we are on.
1906 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
1908 sibling->group_leader = sibling;
1909 list_del_init(&sibling->sibling_list);
1911 /* Inherit group flags from the previous leader */
1912 sibling->group_caps = event->group_caps;
1914 if (!RB_EMPTY_NODE(&event->group_node)) {
1915 add_event_to_groups(sibling, event->ctx);
1917 if (sibling->state == PERF_EVENT_STATE_ACTIVE) {
1918 struct list_head *list = sibling->attr.pinned ?
1919 &ctx->pinned_active : &ctx->flexible_active;
1921 list_add_tail(&sibling->active_list, list);
1925 WARN_ON_ONCE(sibling->ctx != event->ctx);
1929 perf_event__header_size(event->group_leader);
1931 for_each_sibling_event(tmp, event->group_leader)
1932 perf_event__header_size(tmp);
1935 static bool is_orphaned_event(struct perf_event *event)
1937 return event->state == PERF_EVENT_STATE_DEAD;
1940 static inline int __pmu_filter_match(struct perf_event *event)
1942 struct pmu *pmu = event->pmu;
1943 return pmu->filter_match ? pmu->filter_match(event) : 1;
1947 * Check whether we should attempt to schedule an event group based on
1948 * PMU-specific filtering. An event group can consist of HW and SW events,
1949 * potentially with a SW leader, so we must check all the filters, to
1950 * determine whether a group is schedulable:
1952 static inline int pmu_filter_match(struct perf_event *event)
1954 struct perf_event *sibling;
1956 if (!__pmu_filter_match(event))
1959 for_each_sibling_event(sibling, event) {
1960 if (!__pmu_filter_match(sibling))
1968 event_filter_match(struct perf_event *event)
1970 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
1971 perf_cgroup_match(event) && pmu_filter_match(event);
1975 event_sched_out(struct perf_event *event,
1976 struct perf_cpu_context *cpuctx,
1977 struct perf_event_context *ctx)
1979 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
1981 WARN_ON_ONCE(event->ctx != ctx);
1982 lockdep_assert_held(&ctx->lock);
1984 if (event->state != PERF_EVENT_STATE_ACTIVE)
1988 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
1989 * we can schedule events _OUT_ individually through things like
1990 * __perf_remove_from_context().
1992 list_del_init(&event->active_list);
1994 perf_pmu_disable(event->pmu);
1996 event->pmu->del(event, 0);
1999 if (event->pending_disable) {
2000 event->pending_disable = 0;
2001 state = PERF_EVENT_STATE_OFF;
2003 perf_event_set_state(event, state);
2005 if (!is_software_event(event))
2006 cpuctx->active_oncpu--;
2007 if (!--ctx->nr_active)
2008 perf_event_ctx_deactivate(ctx);
2009 if (event->attr.freq && event->attr.sample_freq)
2011 if (event->attr.exclusive || !cpuctx->active_oncpu)
2012 cpuctx->exclusive = 0;
2014 perf_pmu_enable(event->pmu);
2018 group_sched_out(struct perf_event *group_event,
2019 struct perf_cpu_context *cpuctx,
2020 struct perf_event_context *ctx)
2022 struct perf_event *event;
2024 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2027 perf_pmu_disable(ctx->pmu);
2029 event_sched_out(group_event, cpuctx, ctx);
2032 * Schedule out siblings (if any):
2034 for_each_sibling_event(event, group_event)
2035 event_sched_out(event, cpuctx, ctx);
2037 perf_pmu_enable(ctx->pmu);
2039 if (group_event->attr.exclusive)
2040 cpuctx->exclusive = 0;
2043 #define DETACH_GROUP 0x01UL
2046 * Cross CPU call to remove a performance event
2048 * We disable the event on the hardware level first. After that we
2049 * remove it from the context list.
2052 __perf_remove_from_context(struct perf_event *event,
2053 struct perf_cpu_context *cpuctx,
2054 struct perf_event_context *ctx,
2057 unsigned long flags = (unsigned long)info;
2059 if (ctx->is_active & EVENT_TIME) {
2060 update_context_time(ctx);
2061 update_cgrp_time_from_cpuctx(cpuctx);
2064 event_sched_out(event, cpuctx, ctx);
2065 if (flags & DETACH_GROUP)
2066 perf_group_detach(event);
2067 list_del_event(event, ctx);
2069 if (!ctx->nr_events && ctx->is_active) {
2072 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2073 cpuctx->task_ctx = NULL;
2079 * Remove the event from a task's (or a CPU's) list of events.
2081 * If event->ctx is a cloned context, callers must make sure that
2082 * every task struct that event->ctx->task could possibly point to
2083 * remains valid. This is OK when called from perf_release since
2084 * that only calls us on the top-level context, which can't be a clone.
2085 * When called from perf_event_exit_task, it's OK because the
2086 * context has been detached from its task.
2088 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2090 struct perf_event_context *ctx = event->ctx;
2092 lockdep_assert_held(&ctx->mutex);
2094 event_function_call(event, __perf_remove_from_context, (void *)flags);
2097 * The above event_function_call() can NO-OP when it hits
2098 * TASK_TOMBSTONE. In that case we must already have been detached
2099 * from the context (by perf_event_exit_event()) but the grouping
2100 * might still be in-tact.
2102 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2103 if ((flags & DETACH_GROUP) &&
2104 (event->attach_state & PERF_ATTACH_GROUP)) {
2106 * Since in that case we cannot possibly be scheduled, simply
2109 raw_spin_lock_irq(&ctx->lock);
2110 perf_group_detach(event);
2111 raw_spin_unlock_irq(&ctx->lock);
2116 * Cross CPU call to disable a performance event
2118 static void __perf_event_disable(struct perf_event *event,
2119 struct perf_cpu_context *cpuctx,
2120 struct perf_event_context *ctx,
2123 if (event->state < PERF_EVENT_STATE_INACTIVE)
2126 if (ctx->is_active & EVENT_TIME) {
2127 update_context_time(ctx);
2128 update_cgrp_time_from_event(event);
2131 if (event == event->group_leader)
2132 group_sched_out(event, cpuctx, ctx);
2134 event_sched_out(event, cpuctx, ctx);
2136 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2142 * If event->ctx is a cloned context, callers must make sure that
2143 * every task struct that event->ctx->task could possibly point to
2144 * remains valid. This condition is satisifed when called through
2145 * perf_event_for_each_child or perf_event_for_each because they
2146 * hold the top-level event's child_mutex, so any descendant that
2147 * goes to exit will block in perf_event_exit_event().
2149 * When called from perf_pending_event it's OK because event->ctx
2150 * is the current context on this CPU and preemption is disabled,
2151 * hence we can't get into perf_event_task_sched_out for this context.
2153 static void _perf_event_disable(struct perf_event *event)
2155 struct perf_event_context *ctx = event->ctx;
2157 raw_spin_lock_irq(&ctx->lock);
2158 if (event->state <= PERF_EVENT_STATE_OFF) {
2159 raw_spin_unlock_irq(&ctx->lock);
2162 raw_spin_unlock_irq(&ctx->lock);
2164 event_function_call(event, __perf_event_disable, NULL);
2167 void perf_event_disable_local(struct perf_event *event)
2169 event_function_local(event, __perf_event_disable, NULL);
2173 * Strictly speaking kernel users cannot create groups and therefore this
2174 * interface does not need the perf_event_ctx_lock() magic.
2176 void perf_event_disable(struct perf_event *event)
2178 struct perf_event_context *ctx;
2180 ctx = perf_event_ctx_lock(event);
2181 _perf_event_disable(event);
2182 perf_event_ctx_unlock(event, ctx);
2184 EXPORT_SYMBOL_GPL(perf_event_disable);
2186 void perf_event_disable_inatomic(struct perf_event *event)
2188 event->pending_disable = 1;
2189 irq_work_queue(&event->pending);
2192 static void perf_set_shadow_time(struct perf_event *event,
2193 struct perf_event_context *ctx)
2196 * use the correct time source for the time snapshot
2198 * We could get by without this by leveraging the
2199 * fact that to get to this function, the caller
2200 * has most likely already called update_context_time()
2201 * and update_cgrp_time_xx() and thus both timestamp
2202 * are identical (or very close). Given that tstamp is,
2203 * already adjusted for cgroup, we could say that:
2204 * tstamp - ctx->timestamp
2206 * tstamp - cgrp->timestamp.
2208 * Then, in perf_output_read(), the calculation would
2209 * work with no changes because:
2210 * - event is guaranteed scheduled in
2211 * - no scheduled out in between
2212 * - thus the timestamp would be the same
2214 * But this is a bit hairy.
2216 * So instead, we have an explicit cgroup call to remain
2217 * within the time time source all along. We believe it
2218 * is cleaner and simpler to understand.
2220 if (is_cgroup_event(event))
2221 perf_cgroup_set_shadow_time(event, event->tstamp);
2223 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2226 #define MAX_INTERRUPTS (~0ULL)
2228 static void perf_log_throttle(struct perf_event *event, int enable);
2229 static void perf_log_itrace_start(struct perf_event *event);
2232 event_sched_in(struct perf_event *event,
2233 struct perf_cpu_context *cpuctx,
2234 struct perf_event_context *ctx)
2238 lockdep_assert_held(&ctx->lock);
2240 if (event->state <= PERF_EVENT_STATE_OFF)
2243 WRITE_ONCE(event->oncpu, smp_processor_id());
2245 * Order event::oncpu write to happen before the ACTIVE state is
2246 * visible. This allows perf_event_{stop,read}() to observe the correct
2247 * ->oncpu if it sees ACTIVE.
2250 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2253 * Unthrottle events, since we scheduled we might have missed several
2254 * ticks already, also for a heavily scheduling task there is little
2255 * guarantee it'll get a tick in a timely manner.
2257 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2258 perf_log_throttle(event, 1);
2259 event->hw.interrupts = 0;
2262 perf_pmu_disable(event->pmu);
2264 perf_set_shadow_time(event, ctx);
2266 perf_log_itrace_start(event);
2268 if (event->pmu->add(event, PERF_EF_START)) {
2269 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2275 if (!is_software_event(event))
2276 cpuctx->active_oncpu++;
2277 if (!ctx->nr_active++)
2278 perf_event_ctx_activate(ctx);
2279 if (event->attr.freq && event->attr.sample_freq)
2282 if (event->attr.exclusive)
2283 cpuctx->exclusive = 1;
2286 perf_pmu_enable(event->pmu);
2292 group_sched_in(struct perf_event *group_event,
2293 struct perf_cpu_context *cpuctx,
2294 struct perf_event_context *ctx)
2296 struct perf_event *event, *partial_group = NULL;
2297 struct pmu *pmu = ctx->pmu;
2299 if (group_event->state == PERF_EVENT_STATE_OFF)
2302 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2304 if (event_sched_in(group_event, cpuctx, ctx)) {
2305 pmu->cancel_txn(pmu);
2306 perf_mux_hrtimer_restart(cpuctx);
2311 * Schedule in siblings as one group (if any):
2313 for_each_sibling_event(event, group_event) {
2314 if (event_sched_in(event, cpuctx, ctx)) {
2315 partial_group = event;
2320 if (!pmu->commit_txn(pmu))
2325 * Groups can be scheduled in as one unit only, so undo any
2326 * partial group before returning:
2327 * The events up to the failed event are scheduled out normally.
2329 for_each_sibling_event(event, group_event) {
2330 if (event == partial_group)
2333 event_sched_out(event, cpuctx, ctx);
2335 event_sched_out(group_event, cpuctx, ctx);
2337 pmu->cancel_txn(pmu);
2339 perf_mux_hrtimer_restart(cpuctx);
2345 * Work out whether we can put this event group on the CPU now.
2347 static int group_can_go_on(struct perf_event *event,
2348 struct perf_cpu_context *cpuctx,
2352 * Groups consisting entirely of software events can always go on.
2354 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2357 * If an exclusive group is already on, no other hardware
2360 if (cpuctx->exclusive)
2363 * If this group is exclusive and there are already
2364 * events on the CPU, it can't go on.
2366 if (event->attr.exclusive && cpuctx->active_oncpu)
2369 * Otherwise, try to add it if all previous groups were able
2375 static void add_event_to_ctx(struct perf_event *event,
2376 struct perf_event_context *ctx)
2378 list_add_event(event, ctx);
2379 perf_group_attach(event);
2382 static void ctx_sched_out(struct perf_event_context *ctx,
2383 struct perf_cpu_context *cpuctx,
2384 enum event_type_t event_type);
2386 ctx_sched_in(struct perf_event_context *ctx,
2387 struct perf_cpu_context *cpuctx,
2388 enum event_type_t event_type,
2389 struct task_struct *task);
2391 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2392 struct perf_event_context *ctx,
2393 enum event_type_t event_type)
2395 if (!cpuctx->task_ctx)
2398 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2401 ctx_sched_out(ctx, cpuctx, event_type);
2404 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2405 struct perf_event_context *ctx,
2406 struct task_struct *task)
2408 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2410 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2411 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2413 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2417 * We want to maintain the following priority of scheduling:
2418 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2419 * - task pinned (EVENT_PINNED)
2420 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2421 * - task flexible (EVENT_FLEXIBLE).
2423 * In order to avoid unscheduling and scheduling back in everything every
2424 * time an event is added, only do it for the groups of equal priority and
2427 * This can be called after a batch operation on task events, in which case
2428 * event_type is a bit mask of the types of events involved. For CPU events,
2429 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2431 static void ctx_resched(struct perf_cpu_context *cpuctx,
2432 struct perf_event_context *task_ctx,
2433 enum event_type_t event_type)
2435 enum event_type_t ctx_event_type;
2436 bool cpu_event = !!(event_type & EVENT_CPU);
2439 * If pinned groups are involved, flexible groups also need to be
2442 if (event_type & EVENT_PINNED)
2443 event_type |= EVENT_FLEXIBLE;
2445 ctx_event_type = event_type & EVENT_ALL;
2447 perf_pmu_disable(cpuctx->ctx.pmu);
2449 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2452 * Decide which cpu ctx groups to schedule out based on the types
2453 * of events that caused rescheduling:
2454 * - EVENT_CPU: schedule out corresponding groups;
2455 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2456 * - otherwise, do nothing more.
2459 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2460 else if (ctx_event_type & EVENT_PINNED)
2461 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2463 perf_event_sched_in(cpuctx, task_ctx, current);
2464 perf_pmu_enable(cpuctx->ctx.pmu);
2468 * Cross CPU call to install and enable a performance event
2470 * Very similar to remote_function() + event_function() but cannot assume that
2471 * things like ctx->is_active and cpuctx->task_ctx are set.
2473 static int __perf_install_in_context(void *info)
2475 struct perf_event *event = info;
2476 struct perf_event_context *ctx = event->ctx;
2477 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2478 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2479 bool reprogram = true;
2482 raw_spin_lock(&cpuctx->ctx.lock);
2484 raw_spin_lock(&ctx->lock);
2487 reprogram = (ctx->task == current);
2490 * If the task is running, it must be running on this CPU,
2491 * otherwise we cannot reprogram things.
2493 * If its not running, we don't care, ctx->lock will
2494 * serialize against it becoming runnable.
2496 if (task_curr(ctx->task) && !reprogram) {
2501 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2502 } else if (task_ctx) {
2503 raw_spin_lock(&task_ctx->lock);
2506 #ifdef CONFIG_CGROUP_PERF
2507 if (is_cgroup_event(event)) {
2509 * If the current cgroup doesn't match the event's
2510 * cgroup, we should not try to schedule it.
2512 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2513 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2514 event->cgrp->css.cgroup);
2519 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2520 add_event_to_ctx(event, ctx);
2521 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2523 add_event_to_ctx(event, ctx);
2527 perf_ctx_unlock(cpuctx, task_ctx);
2533 * Attach a performance event to a context.
2535 * Very similar to event_function_call, see comment there.
2538 perf_install_in_context(struct perf_event_context *ctx,
2539 struct perf_event *event,
2542 struct task_struct *task = READ_ONCE(ctx->task);
2544 lockdep_assert_held(&ctx->mutex);
2546 if (event->cpu != -1)
2550 * Ensures that if we can observe event->ctx, both the event and ctx
2551 * will be 'complete'. See perf_iterate_sb_cpu().
2553 smp_store_release(&event->ctx, ctx);
2556 cpu_function_call(cpu, __perf_install_in_context, event);
2561 * Should not happen, we validate the ctx is still alive before calling.
2563 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2567 * Installing events is tricky because we cannot rely on ctx->is_active
2568 * to be set in case this is the nr_events 0 -> 1 transition.
2570 * Instead we use task_curr(), which tells us if the task is running.
2571 * However, since we use task_curr() outside of rq::lock, we can race
2572 * against the actual state. This means the result can be wrong.
2574 * If we get a false positive, we retry, this is harmless.
2576 * If we get a false negative, things are complicated. If we are after
2577 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2578 * value must be correct. If we're before, it doesn't matter since
2579 * perf_event_context_sched_in() will program the counter.
2581 * However, this hinges on the remote context switch having observed
2582 * our task->perf_event_ctxp[] store, such that it will in fact take
2583 * ctx::lock in perf_event_context_sched_in().
2585 * We do this by task_function_call(), if the IPI fails to hit the task
2586 * we know any future context switch of task must see the
2587 * perf_event_ctpx[] store.
2591 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2592 * task_cpu() load, such that if the IPI then does not find the task
2593 * running, a future context switch of that task must observe the
2598 if (!task_function_call(task, __perf_install_in_context, event))
2601 raw_spin_lock_irq(&ctx->lock);
2603 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2605 * Cannot happen because we already checked above (which also
2606 * cannot happen), and we hold ctx->mutex, which serializes us
2607 * against perf_event_exit_task_context().
2609 raw_spin_unlock_irq(&ctx->lock);
2613 * If the task is not running, ctx->lock will avoid it becoming so,
2614 * thus we can safely install the event.
2616 if (task_curr(task)) {
2617 raw_spin_unlock_irq(&ctx->lock);
2620 add_event_to_ctx(event, ctx);
2621 raw_spin_unlock_irq(&ctx->lock);
2625 * Cross CPU call to enable a performance event
2627 static void __perf_event_enable(struct perf_event *event,
2628 struct perf_cpu_context *cpuctx,
2629 struct perf_event_context *ctx,
2632 struct perf_event *leader = event->group_leader;
2633 struct perf_event_context *task_ctx;
2635 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2636 event->state <= PERF_EVENT_STATE_ERROR)
2640 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2642 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2644 if (!ctx->is_active)
2647 if (!event_filter_match(event)) {
2648 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2653 * If the event is in a group and isn't the group leader,
2654 * then don't put it on unless the group is on.
2656 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2657 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2661 task_ctx = cpuctx->task_ctx;
2663 WARN_ON_ONCE(task_ctx != ctx);
2665 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2671 * If event->ctx is a cloned context, callers must make sure that
2672 * every task struct that event->ctx->task could possibly point to
2673 * remains valid. This condition is satisfied when called through
2674 * perf_event_for_each_child or perf_event_for_each as described
2675 * for perf_event_disable.
2677 static void _perf_event_enable(struct perf_event *event)
2679 struct perf_event_context *ctx = event->ctx;
2681 raw_spin_lock_irq(&ctx->lock);
2682 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2683 event->state < PERF_EVENT_STATE_ERROR) {
2684 raw_spin_unlock_irq(&ctx->lock);
2689 * If the event is in error state, clear that first.
2691 * That way, if we see the event in error state below, we know that it
2692 * has gone back into error state, as distinct from the task having
2693 * been scheduled away before the cross-call arrived.
2695 if (event->state == PERF_EVENT_STATE_ERROR)
2696 event->state = PERF_EVENT_STATE_OFF;
2697 raw_spin_unlock_irq(&ctx->lock);
2699 event_function_call(event, __perf_event_enable, NULL);
2703 * See perf_event_disable();
2705 void perf_event_enable(struct perf_event *event)
2707 struct perf_event_context *ctx;
2709 ctx = perf_event_ctx_lock(event);
2710 _perf_event_enable(event);
2711 perf_event_ctx_unlock(event, ctx);
2713 EXPORT_SYMBOL_GPL(perf_event_enable);
2715 struct stop_event_data {
2716 struct perf_event *event;
2717 unsigned int restart;
2720 static int __perf_event_stop(void *info)
2722 struct stop_event_data *sd = info;
2723 struct perf_event *event = sd->event;
2725 /* if it's already INACTIVE, do nothing */
2726 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2729 /* matches smp_wmb() in event_sched_in() */
2733 * There is a window with interrupts enabled before we get here,
2734 * so we need to check again lest we try to stop another CPU's event.
2736 if (READ_ONCE(event->oncpu) != smp_processor_id())
2739 event->pmu->stop(event, PERF_EF_UPDATE);
2742 * May race with the actual stop (through perf_pmu_output_stop()),
2743 * but it is only used for events with AUX ring buffer, and such
2744 * events will refuse to restart because of rb::aux_mmap_count==0,
2745 * see comments in perf_aux_output_begin().
2747 * Since this is happening on a event-local CPU, no trace is lost
2751 event->pmu->start(event, 0);
2756 static int perf_event_stop(struct perf_event *event, int restart)
2758 struct stop_event_data sd = {
2765 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2768 /* matches smp_wmb() in event_sched_in() */
2772 * We only want to restart ACTIVE events, so if the event goes
2773 * inactive here (event->oncpu==-1), there's nothing more to do;
2774 * fall through with ret==-ENXIO.
2776 ret = cpu_function_call(READ_ONCE(event->oncpu),
2777 __perf_event_stop, &sd);
2778 } while (ret == -EAGAIN);
2784 * In order to contain the amount of racy and tricky in the address filter
2785 * configuration management, it is a two part process:
2787 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2788 * we update the addresses of corresponding vmas in
2789 * event::addr_filters_offs array and bump the event::addr_filters_gen;
2790 * (p2) when an event is scheduled in (pmu::add), it calls
2791 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2792 * if the generation has changed since the previous call.
2794 * If (p1) happens while the event is active, we restart it to force (p2).
2796 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2797 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2799 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2800 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2802 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2805 void perf_event_addr_filters_sync(struct perf_event *event)
2807 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2809 if (!has_addr_filter(event))
2812 raw_spin_lock(&ifh->lock);
2813 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2814 event->pmu->addr_filters_sync(event);
2815 event->hw.addr_filters_gen = event->addr_filters_gen;
2817 raw_spin_unlock(&ifh->lock);
2819 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2821 static int _perf_event_refresh(struct perf_event *event, int refresh)
2824 * not supported on inherited events
2826 if (event->attr.inherit || !is_sampling_event(event))
2829 atomic_add(refresh, &event->event_limit);
2830 _perf_event_enable(event);
2836 * See perf_event_disable()
2838 int perf_event_refresh(struct perf_event *event, int refresh)
2840 struct perf_event_context *ctx;
2843 ctx = perf_event_ctx_lock(event);
2844 ret = _perf_event_refresh(event, refresh);
2845 perf_event_ctx_unlock(event, ctx);
2849 EXPORT_SYMBOL_GPL(perf_event_refresh);
2851 static int perf_event_modify_breakpoint(struct perf_event *bp,
2852 struct perf_event_attr *attr)
2856 _perf_event_disable(bp);
2858 err = modify_user_hw_breakpoint_check(bp, attr, true);
2860 if (!bp->attr.disabled)
2861 _perf_event_enable(bp);
2866 if (!attr->disabled)
2867 _perf_event_enable(bp);
2871 static int perf_event_modify_attr(struct perf_event *event,
2872 struct perf_event_attr *attr)
2874 if (event->attr.type != attr->type)
2877 switch (event->attr.type) {
2878 case PERF_TYPE_BREAKPOINT:
2879 return perf_event_modify_breakpoint(event, attr);
2881 /* Place holder for future additions. */
2886 static void ctx_sched_out(struct perf_event_context *ctx,
2887 struct perf_cpu_context *cpuctx,
2888 enum event_type_t event_type)
2890 struct perf_event *event, *tmp;
2891 int is_active = ctx->is_active;
2893 lockdep_assert_held(&ctx->lock);
2895 if (likely(!ctx->nr_events)) {
2897 * See __perf_remove_from_context().
2899 WARN_ON_ONCE(ctx->is_active);
2901 WARN_ON_ONCE(cpuctx->task_ctx);
2905 ctx->is_active &= ~event_type;
2906 if (!(ctx->is_active & EVENT_ALL))
2910 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2911 if (!ctx->is_active)
2912 cpuctx->task_ctx = NULL;
2916 * Always update time if it was set; not only when it changes.
2917 * Otherwise we can 'forget' to update time for any but the last
2918 * context we sched out. For example:
2920 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2921 * ctx_sched_out(.event_type = EVENT_PINNED)
2923 * would only update time for the pinned events.
2925 if (is_active & EVENT_TIME) {
2926 /* update (and stop) ctx time */
2927 update_context_time(ctx);
2928 update_cgrp_time_from_cpuctx(cpuctx);
2931 is_active ^= ctx->is_active; /* changed bits */
2933 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2936 perf_pmu_disable(ctx->pmu);
2937 if (is_active & EVENT_PINNED) {
2938 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
2939 group_sched_out(event, cpuctx, ctx);
2942 if (is_active & EVENT_FLEXIBLE) {
2943 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
2944 group_sched_out(event, cpuctx, ctx);
2946 perf_pmu_enable(ctx->pmu);
2950 * Test whether two contexts are equivalent, i.e. whether they have both been
2951 * cloned from the same version of the same context.
2953 * Equivalence is measured using a generation number in the context that is
2954 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2955 * and list_del_event().
2957 static int context_equiv(struct perf_event_context *ctx1,
2958 struct perf_event_context *ctx2)
2960 lockdep_assert_held(&ctx1->lock);
2961 lockdep_assert_held(&ctx2->lock);
2963 /* Pinning disables the swap optimization */
2964 if (ctx1->pin_count || ctx2->pin_count)
2967 /* If ctx1 is the parent of ctx2 */
2968 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2971 /* If ctx2 is the parent of ctx1 */
2972 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2976 * If ctx1 and ctx2 have the same parent; we flatten the parent
2977 * hierarchy, see perf_event_init_context().
2979 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2980 ctx1->parent_gen == ctx2->parent_gen)
2987 static void __perf_event_sync_stat(struct perf_event *event,
2988 struct perf_event *next_event)
2992 if (!event->attr.inherit_stat)
2996 * Update the event value, we cannot use perf_event_read()
2997 * because we're in the middle of a context switch and have IRQs
2998 * disabled, which upsets smp_call_function_single(), however
2999 * we know the event must be on the current CPU, therefore we
3000 * don't need to use it.
3002 if (event->state == PERF_EVENT_STATE_ACTIVE)
3003 event->pmu->read(event);
3005 perf_event_update_time(event);
3008 * In order to keep per-task stats reliable we need to flip the event
3009 * values when we flip the contexts.
3011 value = local64_read(&next_event->count);
3012 value = local64_xchg(&event->count, value);
3013 local64_set(&next_event->count, value);
3015 swap(event->total_time_enabled, next_event->total_time_enabled);
3016 swap(event->total_time_running, next_event->total_time_running);
3019 * Since we swizzled the values, update the user visible data too.
3021 perf_event_update_userpage(event);
3022 perf_event_update_userpage(next_event);
3025 static void perf_event_sync_stat(struct perf_event_context *ctx,
3026 struct perf_event_context *next_ctx)
3028 struct perf_event *event, *next_event;
3033 update_context_time(ctx);
3035 event = list_first_entry(&ctx->event_list,
3036 struct perf_event, event_entry);
3038 next_event = list_first_entry(&next_ctx->event_list,
3039 struct perf_event, event_entry);
3041 while (&event->event_entry != &ctx->event_list &&
3042 &next_event->event_entry != &next_ctx->event_list) {
3044 __perf_event_sync_stat(event, next_event);
3046 event = list_next_entry(event, event_entry);
3047 next_event = list_next_entry(next_event, event_entry);
3051 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3052 struct task_struct *next)
3054 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3055 struct perf_event_context *next_ctx;
3056 struct perf_event_context *parent, *next_parent;
3057 struct perf_cpu_context *cpuctx;
3063 cpuctx = __get_cpu_context(ctx);
3064 if (!cpuctx->task_ctx)
3068 next_ctx = next->perf_event_ctxp[ctxn];
3072 parent = rcu_dereference(ctx->parent_ctx);
3073 next_parent = rcu_dereference(next_ctx->parent_ctx);
3075 /* If neither context have a parent context; they cannot be clones. */
3076 if (!parent && !next_parent)
3079 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3081 * Looks like the two contexts are clones, so we might be
3082 * able to optimize the context switch. We lock both
3083 * contexts and check that they are clones under the
3084 * lock (including re-checking that neither has been
3085 * uncloned in the meantime). It doesn't matter which
3086 * order we take the locks because no other cpu could
3087 * be trying to lock both of these tasks.
3089 raw_spin_lock(&ctx->lock);
3090 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3091 if (context_equiv(ctx, next_ctx)) {
3092 WRITE_ONCE(ctx->task, next);
3093 WRITE_ONCE(next_ctx->task, task);
3095 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3098 * RCU_INIT_POINTER here is safe because we've not
3099 * modified the ctx and the above modification of
3100 * ctx->task and ctx->task_ctx_data are immaterial
3101 * since those values are always verified under
3102 * ctx->lock which we're now holding.
3104 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3105 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3109 perf_event_sync_stat(ctx, next_ctx);
3111 raw_spin_unlock(&next_ctx->lock);
3112 raw_spin_unlock(&ctx->lock);
3118 raw_spin_lock(&ctx->lock);
3119 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3120 raw_spin_unlock(&ctx->lock);
3124 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3126 void perf_sched_cb_dec(struct pmu *pmu)
3128 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3130 this_cpu_dec(perf_sched_cb_usages);
3132 if (!--cpuctx->sched_cb_usage)
3133 list_del(&cpuctx->sched_cb_entry);
3137 void perf_sched_cb_inc(struct pmu *pmu)
3139 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3141 if (!cpuctx->sched_cb_usage++)
3142 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3144 this_cpu_inc(perf_sched_cb_usages);
3148 * This function provides the context switch callback to the lower code
3149 * layer. It is invoked ONLY when the context switch callback is enabled.
3151 * This callback is relevant even to per-cpu events; for example multi event
3152 * PEBS requires this to provide PID/TID information. This requires we flush
3153 * all queued PEBS records before we context switch to a new task.
3155 static void perf_pmu_sched_task(struct task_struct *prev,
3156 struct task_struct *next,
3159 struct perf_cpu_context *cpuctx;
3165 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3166 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3168 if (WARN_ON_ONCE(!pmu->sched_task))
3171 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3172 perf_pmu_disable(pmu);
3174 pmu->sched_task(cpuctx->task_ctx, sched_in);
3176 perf_pmu_enable(pmu);
3177 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3181 static void perf_event_switch(struct task_struct *task,
3182 struct task_struct *next_prev, bool sched_in);
3184 #define for_each_task_context_nr(ctxn) \
3185 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3188 * Called from scheduler to remove the events of the current task,
3189 * with interrupts disabled.
3191 * We stop each event and update the event value in event->count.
3193 * This does not protect us against NMI, but disable()
3194 * sets the disabled bit in the control field of event _before_
3195 * accessing the event control register. If a NMI hits, then it will
3196 * not restart the event.
3198 void __perf_event_task_sched_out(struct task_struct *task,
3199 struct task_struct *next)
3203 if (__this_cpu_read(perf_sched_cb_usages))
3204 perf_pmu_sched_task(task, next, false);
3206 if (atomic_read(&nr_switch_events))
3207 perf_event_switch(task, next, false);
3209 for_each_task_context_nr(ctxn)
3210 perf_event_context_sched_out(task, ctxn, next);
3213 * if cgroup events exist on this CPU, then we need
3214 * to check if we have to switch out PMU state.
3215 * cgroup event are system-wide mode only
3217 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3218 perf_cgroup_sched_out(task, next);
3222 * Called with IRQs disabled
3224 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3225 enum event_type_t event_type)
3227 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3230 static int visit_groups_merge(struct perf_event_groups *groups, int cpu,
3231 int (*func)(struct perf_event *, void *), void *data)
3233 struct perf_event **evt, *evt1, *evt2;
3236 evt1 = perf_event_groups_first(groups, -1);
3237 evt2 = perf_event_groups_first(groups, cpu);
3239 while (evt1 || evt2) {
3241 if (evt1->group_index < evt2->group_index)
3251 ret = func(*evt, data);
3255 *evt = perf_event_groups_next(*evt);
3261 struct sched_in_data {
3262 struct perf_event_context *ctx;
3263 struct perf_cpu_context *cpuctx;
3267 static int pinned_sched_in(struct perf_event *event, void *data)
3269 struct sched_in_data *sid = data;
3271 if (event->state <= PERF_EVENT_STATE_OFF)
3274 if (!event_filter_match(event))
3277 if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
3278 if (!group_sched_in(event, sid->cpuctx, sid->ctx))
3279 list_add_tail(&event->active_list, &sid->ctx->pinned_active);
3283 * If this pinned group hasn't been scheduled,
3284 * put it in error state.
3286 if (event->state == PERF_EVENT_STATE_INACTIVE)
3287 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3292 static int flexible_sched_in(struct perf_event *event, void *data)
3294 struct sched_in_data *sid = data;
3296 if (event->state <= PERF_EVENT_STATE_OFF)
3299 if (!event_filter_match(event))
3302 if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
3303 if (!group_sched_in(event, sid->cpuctx, sid->ctx))
3304 list_add_tail(&event->active_list, &sid->ctx->flexible_active);
3306 sid->can_add_hw = 0;
3313 ctx_pinned_sched_in(struct perf_event_context *ctx,
3314 struct perf_cpu_context *cpuctx)
3316 struct sched_in_data sid = {
3322 visit_groups_merge(&ctx->pinned_groups,
3324 pinned_sched_in, &sid);
3328 ctx_flexible_sched_in(struct perf_event_context *ctx,
3329 struct perf_cpu_context *cpuctx)
3331 struct sched_in_data sid = {
3337 visit_groups_merge(&ctx->flexible_groups,
3339 flexible_sched_in, &sid);
3343 ctx_sched_in(struct perf_event_context *ctx,
3344 struct perf_cpu_context *cpuctx,
3345 enum event_type_t event_type,
3346 struct task_struct *task)
3348 int is_active = ctx->is_active;
3351 lockdep_assert_held(&ctx->lock);
3353 if (likely(!ctx->nr_events))
3356 ctx->is_active |= (event_type | EVENT_TIME);
3359 cpuctx->task_ctx = ctx;
3361 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3364 is_active ^= ctx->is_active; /* changed bits */
3366 if (is_active & EVENT_TIME) {
3367 /* start ctx time */
3369 ctx->timestamp = now;
3370 perf_cgroup_set_timestamp(task, ctx);
3374 * First go through the list and put on any pinned groups
3375 * in order to give them the best chance of going on.
3377 if (is_active & EVENT_PINNED)
3378 ctx_pinned_sched_in(ctx, cpuctx);
3380 /* Then walk through the lower prio flexible groups */
3381 if (is_active & EVENT_FLEXIBLE)
3382 ctx_flexible_sched_in(ctx, cpuctx);
3385 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3386 enum event_type_t event_type,
3387 struct task_struct *task)
3389 struct perf_event_context *ctx = &cpuctx->ctx;
3391 ctx_sched_in(ctx, cpuctx, event_type, task);
3394 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3395 struct task_struct *task)
3397 struct perf_cpu_context *cpuctx;
3399 cpuctx = __get_cpu_context(ctx);
3400 if (cpuctx->task_ctx == ctx)
3403 perf_ctx_lock(cpuctx, ctx);
3405 * We must check ctx->nr_events while holding ctx->lock, such
3406 * that we serialize against perf_install_in_context().
3408 if (!ctx->nr_events)
3411 perf_pmu_disable(ctx->pmu);
3413 * We want to keep the following priority order:
3414 * cpu pinned (that don't need to move), task pinned,
3415 * cpu flexible, task flexible.
3417 * However, if task's ctx is not carrying any pinned
3418 * events, no need to flip the cpuctx's events around.
3420 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3421 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3422 perf_event_sched_in(cpuctx, ctx, task);
3423 perf_pmu_enable(ctx->pmu);
3426 perf_ctx_unlock(cpuctx, ctx);
3430 * Called from scheduler to add the events of the current task
3431 * with interrupts disabled.
3433 * We restore the event value and then enable it.
3435 * This does not protect us against NMI, but enable()
3436 * sets the enabled bit in the control field of event _before_
3437 * accessing the event control register. If a NMI hits, then it will
3438 * keep the event running.
3440 void __perf_event_task_sched_in(struct task_struct *prev,
3441 struct task_struct *task)
3443 struct perf_event_context *ctx;
3447 * If cgroup events exist on this CPU, then we need to check if we have
3448 * to switch in PMU state; cgroup event are system-wide mode only.
3450 * Since cgroup events are CPU events, we must schedule these in before
3451 * we schedule in the task events.
3453 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3454 perf_cgroup_sched_in(prev, task);
3456 for_each_task_context_nr(ctxn) {
3457 ctx = task->perf_event_ctxp[ctxn];
3461 perf_event_context_sched_in(ctx, task);
3464 if (atomic_read(&nr_switch_events))
3465 perf_event_switch(task, prev, true);
3467 if (__this_cpu_read(perf_sched_cb_usages))
3468 perf_pmu_sched_task(prev, task, true);
3471 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3473 u64 frequency = event->attr.sample_freq;
3474 u64 sec = NSEC_PER_SEC;
3475 u64 divisor, dividend;
3477 int count_fls, nsec_fls, frequency_fls, sec_fls;
3479 count_fls = fls64(count);
3480 nsec_fls = fls64(nsec);
3481 frequency_fls = fls64(frequency);
3485 * We got @count in @nsec, with a target of sample_freq HZ
3486 * the target period becomes:
3489 * period = -------------------
3490 * @nsec * sample_freq
3495 * Reduce accuracy by one bit such that @a and @b converge
3496 * to a similar magnitude.
3498 #define REDUCE_FLS(a, b) \
3500 if (a##_fls > b##_fls) { \
3510 * Reduce accuracy until either term fits in a u64, then proceed with
3511 * the other, so that finally we can do a u64/u64 division.
3513 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3514 REDUCE_FLS(nsec, frequency);
3515 REDUCE_FLS(sec, count);
3518 if (count_fls + sec_fls > 64) {
3519 divisor = nsec * frequency;
3521 while (count_fls + sec_fls > 64) {
3522 REDUCE_FLS(count, sec);
3526 dividend = count * sec;
3528 dividend = count * sec;
3530 while (nsec_fls + frequency_fls > 64) {
3531 REDUCE_FLS(nsec, frequency);
3535 divisor = nsec * frequency;
3541 return div64_u64(dividend, divisor);
3544 static DEFINE_PER_CPU(int, perf_throttled_count);
3545 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3547 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3549 struct hw_perf_event *hwc = &event->hw;
3550 s64 period, sample_period;
3553 period = perf_calculate_period(event, nsec, count);
3555 delta = (s64)(period - hwc->sample_period);
3556 delta = (delta + 7) / 8; /* low pass filter */
3558 sample_period = hwc->sample_period + delta;
3563 hwc->sample_period = sample_period;
3565 if (local64_read(&hwc->period_left) > 8*sample_period) {
3567 event->pmu->stop(event, PERF_EF_UPDATE);
3569 local64_set(&hwc->period_left, 0);
3572 event->pmu->start(event, PERF_EF_RELOAD);
3577 * combine freq adjustment with unthrottling to avoid two passes over the
3578 * events. At the same time, make sure, having freq events does not change
3579 * the rate of unthrottling as that would introduce bias.
3581 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3584 struct perf_event *event;
3585 struct hw_perf_event *hwc;
3586 u64 now, period = TICK_NSEC;
3590 * only need to iterate over all events iff:
3591 * - context have events in frequency mode (needs freq adjust)
3592 * - there are events to unthrottle on this cpu
3594 if (!(ctx->nr_freq || needs_unthr))
3597 raw_spin_lock(&ctx->lock);
3598 perf_pmu_disable(ctx->pmu);
3600 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3601 if (event->state != PERF_EVENT_STATE_ACTIVE)
3604 if (!event_filter_match(event))
3607 perf_pmu_disable(event->pmu);
3611 if (hwc->interrupts == MAX_INTERRUPTS) {
3612 hwc->interrupts = 0;
3613 perf_log_throttle(event, 1);
3614 event->pmu->start(event, 0);
3617 if (!event->attr.freq || !event->attr.sample_freq)
3621 * stop the event and update event->count
3623 event->pmu->stop(event, PERF_EF_UPDATE);
3625 now = local64_read(&event->count);
3626 delta = now - hwc->freq_count_stamp;
3627 hwc->freq_count_stamp = now;
3631 * reload only if value has changed
3632 * we have stopped the event so tell that
3633 * to perf_adjust_period() to avoid stopping it
3637 perf_adjust_period(event, period, delta, false);
3639 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3641 perf_pmu_enable(event->pmu);
3644 perf_pmu_enable(ctx->pmu);
3645 raw_spin_unlock(&ctx->lock);
3649 * Move @event to the tail of the @ctx's elegible events.
3651 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
3654 * Rotate the first entry last of non-pinned groups. Rotation might be
3655 * disabled by the inheritance code.
3657 if (ctx->rotate_disable)
3660 perf_event_groups_delete(&ctx->flexible_groups, event);
3661 perf_event_groups_insert(&ctx->flexible_groups, event);
3664 static inline struct perf_event *
3665 ctx_first_active(struct perf_event_context *ctx)
3667 return list_first_entry_or_null(&ctx->flexible_active,
3668 struct perf_event, active_list);
3671 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
3673 struct perf_event *cpu_event = NULL, *task_event = NULL;
3674 bool cpu_rotate = false, task_rotate = false;
3675 struct perf_event_context *ctx = NULL;
3678 * Since we run this from IRQ context, nobody can install new
3679 * events, thus the event count values are stable.
3682 if (cpuctx->ctx.nr_events) {
3683 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3687 ctx = cpuctx->task_ctx;
3688 if (ctx && ctx->nr_events) {
3689 if (ctx->nr_events != ctx->nr_active)
3693 if (!(cpu_rotate || task_rotate))
3696 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3697 perf_pmu_disable(cpuctx->ctx.pmu);
3700 task_event = ctx_first_active(ctx);
3702 cpu_event = ctx_first_active(&cpuctx->ctx);
3705 * As per the order given at ctx_resched() first 'pop' task flexible
3706 * and then, if needed CPU flexible.
3708 if (task_event || (ctx && cpu_event))
3709 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3711 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3714 rotate_ctx(ctx, task_event);
3716 rotate_ctx(&cpuctx->ctx, cpu_event);
3718 perf_event_sched_in(cpuctx, ctx, current);
3720 perf_pmu_enable(cpuctx->ctx.pmu);
3721 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3726 void perf_event_task_tick(void)
3728 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3729 struct perf_event_context *ctx, *tmp;
3732 lockdep_assert_irqs_disabled();
3734 __this_cpu_inc(perf_throttled_seq);
3735 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3736 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3738 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3739 perf_adjust_freq_unthr_context(ctx, throttled);
3742 static int event_enable_on_exec(struct perf_event *event,
3743 struct perf_event_context *ctx)
3745 if (!event->attr.enable_on_exec)
3748 event->attr.enable_on_exec = 0;
3749 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3752 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3758 * Enable all of a task's events that have been marked enable-on-exec.
3759 * This expects task == current.
3761 static void perf_event_enable_on_exec(int ctxn)
3763 struct perf_event_context *ctx, *clone_ctx = NULL;
3764 enum event_type_t event_type = 0;
3765 struct perf_cpu_context *cpuctx;
3766 struct perf_event *event;
3767 unsigned long flags;
3770 local_irq_save(flags);
3771 ctx = current->perf_event_ctxp[ctxn];
3772 if (!ctx || !ctx->nr_events)
3775 cpuctx = __get_cpu_context(ctx);
3776 perf_ctx_lock(cpuctx, ctx);
3777 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3778 list_for_each_entry(event, &ctx->event_list, event_entry) {
3779 enabled |= event_enable_on_exec(event, ctx);
3780 event_type |= get_event_type(event);
3784 * Unclone and reschedule this context if we enabled any event.
3787 clone_ctx = unclone_ctx(ctx);
3788 ctx_resched(cpuctx, ctx, event_type);
3790 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3792 perf_ctx_unlock(cpuctx, ctx);
3795 local_irq_restore(flags);
3801 struct perf_read_data {
3802 struct perf_event *event;
3807 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
3809 u16 local_pkg, event_pkg;
3811 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
3812 int local_cpu = smp_processor_id();
3814 event_pkg = topology_physical_package_id(event_cpu);
3815 local_pkg = topology_physical_package_id(local_cpu);
3817 if (event_pkg == local_pkg)
3825 * Cross CPU call to read the hardware event
3827 static void __perf_event_read(void *info)
3829 struct perf_read_data *data = info;
3830 struct perf_event *sub, *event = data->event;
3831 struct perf_event_context *ctx = event->ctx;
3832 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3833 struct pmu *pmu = event->pmu;
3836 * If this is a task context, we need to check whether it is
3837 * the current task context of this cpu. If not it has been
3838 * scheduled out before the smp call arrived. In that case
3839 * event->count would have been updated to a recent sample
3840 * when the event was scheduled out.
3842 if (ctx->task && cpuctx->task_ctx != ctx)
3845 raw_spin_lock(&ctx->lock);
3846 if (ctx->is_active & EVENT_TIME) {
3847 update_context_time(ctx);
3848 update_cgrp_time_from_event(event);
3851 perf_event_update_time(event);
3853 perf_event_update_sibling_time(event);
3855 if (event->state != PERF_EVENT_STATE_ACTIVE)
3864 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3868 for_each_sibling_event(sub, event) {
3869 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3871 * Use sibling's PMU rather than @event's since
3872 * sibling could be on different (eg: software) PMU.
3874 sub->pmu->read(sub);
3878 data->ret = pmu->commit_txn(pmu);
3881 raw_spin_unlock(&ctx->lock);
3884 static inline u64 perf_event_count(struct perf_event *event)
3886 return local64_read(&event->count) + atomic64_read(&event->child_count);
3890 * NMI-safe method to read a local event, that is an event that
3892 * - either for the current task, or for this CPU
3893 * - does not have inherit set, for inherited task events
3894 * will not be local and we cannot read them atomically
3895 * - must not have a pmu::count method
3897 int perf_event_read_local(struct perf_event *event, u64 *value,
3898 u64 *enabled, u64 *running)
3900 unsigned long flags;
3904 * Disabling interrupts avoids all counter scheduling (context
3905 * switches, timer based rotation and IPIs).
3907 local_irq_save(flags);
3910 * It must not be an event with inherit set, we cannot read
3911 * all child counters from atomic context.
3913 if (event->attr.inherit) {
3918 /* If this is a per-task event, it must be for current */
3919 if ((event->attach_state & PERF_ATTACH_TASK) &&
3920 event->hw.target != current) {
3925 /* If this is a per-CPU event, it must be for this CPU */
3926 if (!(event->attach_state & PERF_ATTACH_TASK) &&
3927 event->cpu != smp_processor_id()) {
3933 * If the event is currently on this CPU, its either a per-task event,
3934 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3937 if (event->oncpu == smp_processor_id())
3938 event->pmu->read(event);
3940 *value = local64_read(&event->count);
3941 if (enabled || running) {
3942 u64 now = event->shadow_ctx_time + perf_clock();
3943 u64 __enabled, __running;
3945 __perf_update_times(event, now, &__enabled, &__running);
3947 *enabled = __enabled;
3949 *running = __running;
3952 local_irq_restore(flags);
3957 static int perf_event_read(struct perf_event *event, bool group)
3959 enum perf_event_state state = READ_ONCE(event->state);
3960 int event_cpu, ret = 0;
3963 * If event is enabled and currently active on a CPU, update the
3964 * value in the event structure:
3967 if (state == PERF_EVENT_STATE_ACTIVE) {
3968 struct perf_read_data data;
3971 * Orders the ->state and ->oncpu loads such that if we see
3972 * ACTIVE we must also see the right ->oncpu.
3974 * Matches the smp_wmb() from event_sched_in().
3978 event_cpu = READ_ONCE(event->oncpu);
3979 if ((unsigned)event_cpu >= nr_cpu_ids)
3982 data = (struct perf_read_data){
3989 event_cpu = __perf_event_read_cpu(event, event_cpu);
3992 * Purposely ignore the smp_call_function_single() return
3995 * If event_cpu isn't a valid CPU it means the event got
3996 * scheduled out and that will have updated the event count.
3998 * Therefore, either way, we'll have an up-to-date event count
4001 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4005 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4006 struct perf_event_context *ctx = event->ctx;
4007 unsigned long flags;
4009 raw_spin_lock_irqsave(&ctx->lock, flags);
4010 state = event->state;
4011 if (state != PERF_EVENT_STATE_INACTIVE) {
4012 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4017 * May read while context is not active (e.g., thread is
4018 * blocked), in that case we cannot update context time
4020 if (ctx->is_active & EVENT_TIME) {
4021 update_context_time(ctx);
4022 update_cgrp_time_from_event(event);
4025 perf_event_update_time(event);
4027 perf_event_update_sibling_time(event);
4028 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4035 * Initialize the perf_event context in a task_struct:
4037 static void __perf_event_init_context(struct perf_event_context *ctx)
4039 raw_spin_lock_init(&ctx->lock);
4040 mutex_init(&ctx->mutex);
4041 INIT_LIST_HEAD(&ctx->active_ctx_list);
4042 perf_event_groups_init(&ctx->pinned_groups);
4043 perf_event_groups_init(&ctx->flexible_groups);
4044 INIT_LIST_HEAD(&ctx->event_list);
4045 INIT_LIST_HEAD(&ctx->pinned_active);
4046 INIT_LIST_HEAD(&ctx->flexible_active);
4047 atomic_set(&ctx->refcount, 1);
4050 static struct perf_event_context *
4051 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4053 struct perf_event_context *ctx;
4055 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4059 __perf_event_init_context(ctx);
4062 get_task_struct(task);
4069 static struct task_struct *
4070 find_lively_task_by_vpid(pid_t vpid)
4072 struct task_struct *task;
4078 task = find_task_by_vpid(vpid);
4080 get_task_struct(task);
4084 return ERR_PTR(-ESRCH);
4090 * Returns a matching context with refcount and pincount.
4092 static struct perf_event_context *
4093 find_get_context(struct pmu *pmu, struct task_struct *task,
4094 struct perf_event *event)
4096 struct perf_event_context *ctx, *clone_ctx = NULL;
4097 struct perf_cpu_context *cpuctx;
4098 void *task_ctx_data = NULL;
4099 unsigned long flags;
4101 int cpu = event->cpu;
4104 /* Must be root to operate on a CPU event: */
4105 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
4106 return ERR_PTR(-EACCES);
4108 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4117 ctxn = pmu->task_ctx_nr;
4121 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4122 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
4123 if (!task_ctx_data) {
4130 ctx = perf_lock_task_context(task, ctxn, &flags);
4132 clone_ctx = unclone_ctx(ctx);
4135 if (task_ctx_data && !ctx->task_ctx_data) {
4136 ctx->task_ctx_data = task_ctx_data;
4137 task_ctx_data = NULL;
4139 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4144 ctx = alloc_perf_context(pmu, task);
4149 if (task_ctx_data) {
4150 ctx->task_ctx_data = task_ctx_data;
4151 task_ctx_data = NULL;
4155 mutex_lock(&task->perf_event_mutex);
4157 * If it has already passed perf_event_exit_task().
4158 * we must see PF_EXITING, it takes this mutex too.
4160 if (task->flags & PF_EXITING)
4162 else if (task->perf_event_ctxp[ctxn])
4167 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4169 mutex_unlock(&task->perf_event_mutex);
4171 if (unlikely(err)) {
4180 kfree(task_ctx_data);
4184 kfree(task_ctx_data);
4185 return ERR_PTR(err);
4188 static void perf_event_free_filter(struct perf_event *event);
4189 static void perf_event_free_bpf_prog(struct perf_event *event);
4191 static void free_event_rcu(struct rcu_head *head)
4193 struct perf_event *event;
4195 event = container_of(head, struct perf_event, rcu_head);
4197 put_pid_ns(event->ns);
4198 perf_event_free_filter(event);
4202 static void ring_buffer_attach(struct perf_event *event,
4203 struct ring_buffer *rb);
4205 static void detach_sb_event(struct perf_event *event)
4207 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4209 raw_spin_lock(&pel->lock);
4210 list_del_rcu(&event->sb_list);
4211 raw_spin_unlock(&pel->lock);
4214 static bool is_sb_event(struct perf_event *event)
4216 struct perf_event_attr *attr = &event->attr;
4221 if (event->attach_state & PERF_ATTACH_TASK)
4224 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4225 attr->comm || attr->comm_exec ||
4227 attr->context_switch)
4232 static void unaccount_pmu_sb_event(struct perf_event *event)
4234 if (is_sb_event(event))
4235 detach_sb_event(event);
4238 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4243 if (is_cgroup_event(event))
4244 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4247 #ifdef CONFIG_NO_HZ_FULL
4248 static DEFINE_SPINLOCK(nr_freq_lock);
4251 static void unaccount_freq_event_nohz(void)
4253 #ifdef CONFIG_NO_HZ_FULL
4254 spin_lock(&nr_freq_lock);
4255 if (atomic_dec_and_test(&nr_freq_events))
4256 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4257 spin_unlock(&nr_freq_lock);
4261 static void unaccount_freq_event(void)
4263 if (tick_nohz_full_enabled())
4264 unaccount_freq_event_nohz();
4266 atomic_dec(&nr_freq_events);
4269 static void unaccount_event(struct perf_event *event)
4276 if (event->attach_state & PERF_ATTACH_TASK)
4278 if (event->attr.mmap || event->attr.mmap_data)
4279 atomic_dec(&nr_mmap_events);
4280 if (event->attr.comm)
4281 atomic_dec(&nr_comm_events);
4282 if (event->attr.namespaces)
4283 atomic_dec(&nr_namespaces_events);
4284 if (event->attr.task)
4285 atomic_dec(&nr_task_events);
4286 if (event->attr.freq)
4287 unaccount_freq_event();
4288 if (event->attr.context_switch) {
4290 atomic_dec(&nr_switch_events);
4292 if (is_cgroup_event(event))
4294 if (has_branch_stack(event))
4298 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4299 schedule_delayed_work(&perf_sched_work, HZ);
4302 unaccount_event_cpu(event, event->cpu);
4304 unaccount_pmu_sb_event(event);
4307 static void perf_sched_delayed(struct work_struct *work)
4309 mutex_lock(&perf_sched_mutex);
4310 if (atomic_dec_and_test(&perf_sched_count))
4311 static_branch_disable(&perf_sched_events);
4312 mutex_unlock(&perf_sched_mutex);
4316 * The following implement mutual exclusion of events on "exclusive" pmus
4317 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4318 * at a time, so we disallow creating events that might conflict, namely:
4320 * 1) cpu-wide events in the presence of per-task events,
4321 * 2) per-task events in the presence of cpu-wide events,
4322 * 3) two matching events on the same context.
4324 * The former two cases are handled in the allocation path (perf_event_alloc(),
4325 * _free_event()), the latter -- before the first perf_install_in_context().
4327 static int exclusive_event_init(struct perf_event *event)
4329 struct pmu *pmu = event->pmu;
4331 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4335 * Prevent co-existence of per-task and cpu-wide events on the
4336 * same exclusive pmu.
4338 * Negative pmu::exclusive_cnt means there are cpu-wide
4339 * events on this "exclusive" pmu, positive means there are
4342 * Since this is called in perf_event_alloc() path, event::ctx
4343 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4344 * to mean "per-task event", because unlike other attach states it
4345 * never gets cleared.
4347 if (event->attach_state & PERF_ATTACH_TASK) {
4348 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4351 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4358 static void exclusive_event_destroy(struct perf_event *event)
4360 struct pmu *pmu = event->pmu;
4362 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4365 /* see comment in exclusive_event_init() */
4366 if (event->attach_state & PERF_ATTACH_TASK)
4367 atomic_dec(&pmu->exclusive_cnt);
4369 atomic_inc(&pmu->exclusive_cnt);
4372 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4374 if ((e1->pmu == e2->pmu) &&
4375 (e1->cpu == e2->cpu ||
4382 /* Called under the same ctx::mutex as perf_install_in_context() */
4383 static bool exclusive_event_installable(struct perf_event *event,
4384 struct perf_event_context *ctx)
4386 struct perf_event *iter_event;
4387 struct pmu *pmu = event->pmu;
4389 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4392 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4393 if (exclusive_event_match(iter_event, event))
4400 static void perf_addr_filters_splice(struct perf_event *event,
4401 struct list_head *head);
4403 static void _free_event(struct perf_event *event)
4405 irq_work_sync(&event->pending);
4407 unaccount_event(event);
4411 * Can happen when we close an event with re-directed output.
4413 * Since we have a 0 refcount, perf_mmap_close() will skip
4414 * over us; possibly making our ring_buffer_put() the last.
4416 mutex_lock(&event->mmap_mutex);
4417 ring_buffer_attach(event, NULL);
4418 mutex_unlock(&event->mmap_mutex);
4421 if (is_cgroup_event(event))
4422 perf_detach_cgroup(event);
4424 if (!event->parent) {
4425 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4426 put_callchain_buffers();
4429 perf_event_free_bpf_prog(event);
4430 perf_addr_filters_splice(event, NULL);
4431 kfree(event->addr_filters_offs);
4434 event->destroy(event);
4437 put_ctx(event->ctx);
4439 exclusive_event_destroy(event);
4440 module_put(event->pmu->module);
4442 call_rcu(&event->rcu_head, free_event_rcu);
4446 * Used to free events which have a known refcount of 1, such as in error paths
4447 * where the event isn't exposed yet and inherited events.
4449 static void free_event(struct perf_event *event)
4451 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4452 "unexpected event refcount: %ld; ptr=%p\n",
4453 atomic_long_read(&event->refcount), event)) {
4454 /* leak to avoid use-after-free */
4462 * Remove user event from the owner task.
4464 static void perf_remove_from_owner(struct perf_event *event)
4466 struct task_struct *owner;
4470 * Matches the smp_store_release() in perf_event_exit_task(). If we
4471 * observe !owner it means the list deletion is complete and we can
4472 * indeed free this event, otherwise we need to serialize on
4473 * owner->perf_event_mutex.
4475 owner = READ_ONCE(event->owner);
4478 * Since delayed_put_task_struct() also drops the last
4479 * task reference we can safely take a new reference
4480 * while holding the rcu_read_lock().
4482 get_task_struct(owner);
4488 * If we're here through perf_event_exit_task() we're already
4489 * holding ctx->mutex which would be an inversion wrt. the
4490 * normal lock order.
4492 * However we can safely take this lock because its the child
4495 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4498 * We have to re-check the event->owner field, if it is cleared
4499 * we raced with perf_event_exit_task(), acquiring the mutex
4500 * ensured they're done, and we can proceed with freeing the
4504 list_del_init(&event->owner_entry);
4505 smp_store_release(&event->owner, NULL);
4507 mutex_unlock(&owner->perf_event_mutex);
4508 put_task_struct(owner);
4512 static void put_event(struct perf_event *event)
4514 if (!atomic_long_dec_and_test(&event->refcount))
4521 * Kill an event dead; while event:refcount will preserve the event
4522 * object, it will not preserve its functionality. Once the last 'user'
4523 * gives up the object, we'll destroy the thing.
4525 int perf_event_release_kernel(struct perf_event *event)
4527 struct perf_event_context *ctx = event->ctx;
4528 struct perf_event *child, *tmp;
4529 LIST_HEAD(free_list);
4532 * If we got here through err_file: fput(event_file); we will not have
4533 * attached to a context yet.
4536 WARN_ON_ONCE(event->attach_state &
4537 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4541 if (!is_kernel_event(event))
4542 perf_remove_from_owner(event);
4544 ctx = perf_event_ctx_lock(event);
4545 WARN_ON_ONCE(ctx->parent_ctx);
4546 perf_remove_from_context(event, DETACH_GROUP);
4548 raw_spin_lock_irq(&ctx->lock);
4550 * Mark this event as STATE_DEAD, there is no external reference to it
4553 * Anybody acquiring event->child_mutex after the below loop _must_
4554 * also see this, most importantly inherit_event() which will avoid
4555 * placing more children on the list.
4557 * Thus this guarantees that we will in fact observe and kill _ALL_
4560 event->state = PERF_EVENT_STATE_DEAD;
4561 raw_spin_unlock_irq(&ctx->lock);
4563 perf_event_ctx_unlock(event, ctx);
4566 mutex_lock(&event->child_mutex);
4567 list_for_each_entry(child, &event->child_list, child_list) {
4570 * Cannot change, child events are not migrated, see the
4571 * comment with perf_event_ctx_lock_nested().
4573 ctx = READ_ONCE(child->ctx);
4575 * Since child_mutex nests inside ctx::mutex, we must jump
4576 * through hoops. We start by grabbing a reference on the ctx.
4578 * Since the event cannot get freed while we hold the
4579 * child_mutex, the context must also exist and have a !0
4585 * Now that we have a ctx ref, we can drop child_mutex, and
4586 * acquire ctx::mutex without fear of it going away. Then we
4587 * can re-acquire child_mutex.
4589 mutex_unlock(&event->child_mutex);
4590 mutex_lock(&ctx->mutex);
4591 mutex_lock(&event->child_mutex);
4594 * Now that we hold ctx::mutex and child_mutex, revalidate our
4595 * state, if child is still the first entry, it didn't get freed
4596 * and we can continue doing so.
4598 tmp = list_first_entry_or_null(&event->child_list,
4599 struct perf_event, child_list);
4601 perf_remove_from_context(child, DETACH_GROUP);
4602 list_move(&child->child_list, &free_list);
4604 * This matches the refcount bump in inherit_event();
4605 * this can't be the last reference.
4610 mutex_unlock(&event->child_mutex);
4611 mutex_unlock(&ctx->mutex);
4615 mutex_unlock(&event->child_mutex);
4617 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
4618 list_del(&child->child_list);
4623 put_event(event); /* Must be the 'last' reference */
4626 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4629 * Called when the last reference to the file is gone.
4631 static int perf_release(struct inode *inode, struct file *file)
4633 perf_event_release_kernel(file->private_data);
4637 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4639 struct perf_event *child;
4645 mutex_lock(&event->child_mutex);
4647 (void)perf_event_read(event, false);
4648 total += perf_event_count(event);
4650 *enabled += event->total_time_enabled +
4651 atomic64_read(&event->child_total_time_enabled);
4652 *running += event->total_time_running +
4653 atomic64_read(&event->child_total_time_running);
4655 list_for_each_entry(child, &event->child_list, child_list) {
4656 (void)perf_event_read(child, false);
4657 total += perf_event_count(child);
4658 *enabled += child->total_time_enabled;
4659 *running += child->total_time_running;
4661 mutex_unlock(&event->child_mutex);
4666 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4668 struct perf_event_context *ctx;
4671 ctx = perf_event_ctx_lock(event);
4672 count = __perf_event_read_value(event, enabled, running);
4673 perf_event_ctx_unlock(event, ctx);
4677 EXPORT_SYMBOL_GPL(perf_event_read_value);
4679 static int __perf_read_group_add(struct perf_event *leader,
4680 u64 read_format, u64 *values)
4682 struct perf_event_context *ctx = leader->ctx;
4683 struct perf_event *sub;
4684 unsigned long flags;
4685 int n = 1; /* skip @nr */
4688 ret = perf_event_read(leader, true);
4692 raw_spin_lock_irqsave(&ctx->lock, flags);
4695 * Since we co-schedule groups, {enabled,running} times of siblings
4696 * will be identical to those of the leader, so we only publish one
4699 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4700 values[n++] += leader->total_time_enabled +
4701 atomic64_read(&leader->child_total_time_enabled);
4704 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4705 values[n++] += leader->total_time_running +
4706 atomic64_read(&leader->child_total_time_running);
4710 * Write {count,id} tuples for every sibling.
4712 values[n++] += perf_event_count(leader);
4713 if (read_format & PERF_FORMAT_ID)
4714 values[n++] = primary_event_id(leader);
4716 for_each_sibling_event(sub, leader) {
4717 values[n++] += perf_event_count(sub);
4718 if (read_format & PERF_FORMAT_ID)
4719 values[n++] = primary_event_id(sub);
4722 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4726 static int perf_read_group(struct perf_event *event,
4727 u64 read_format, char __user *buf)
4729 struct perf_event *leader = event->group_leader, *child;
4730 struct perf_event_context *ctx = leader->ctx;
4734 lockdep_assert_held(&ctx->mutex);
4736 values = kzalloc(event->read_size, GFP_KERNEL);
4740 values[0] = 1 + leader->nr_siblings;
4743 * By locking the child_mutex of the leader we effectively
4744 * lock the child list of all siblings.. XXX explain how.
4746 mutex_lock(&leader->child_mutex);
4748 ret = __perf_read_group_add(leader, read_format, values);
4752 list_for_each_entry(child, &leader->child_list, child_list) {
4753 ret = __perf_read_group_add(child, read_format, values);
4758 mutex_unlock(&leader->child_mutex);
4760 ret = event->read_size;
4761 if (copy_to_user(buf, values, event->read_size))
4766 mutex_unlock(&leader->child_mutex);
4772 static int perf_read_one(struct perf_event *event,
4773 u64 read_format, char __user *buf)
4775 u64 enabled, running;
4779 values[n++] = __perf_event_read_value(event, &enabled, &running);
4780 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4781 values[n++] = enabled;
4782 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4783 values[n++] = running;
4784 if (read_format & PERF_FORMAT_ID)
4785 values[n++] = primary_event_id(event);
4787 if (copy_to_user(buf, values, n * sizeof(u64)))
4790 return n * sizeof(u64);
4793 static bool is_event_hup(struct perf_event *event)
4797 if (event->state > PERF_EVENT_STATE_EXIT)
4800 mutex_lock(&event->child_mutex);
4801 no_children = list_empty(&event->child_list);
4802 mutex_unlock(&event->child_mutex);
4807 * Read the performance event - simple non blocking version for now
4810 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4812 u64 read_format = event->attr.read_format;
4816 * Return end-of-file for a read on a event that is in
4817 * error state (i.e. because it was pinned but it couldn't be
4818 * scheduled on to the CPU at some point).
4820 if (event->state == PERF_EVENT_STATE_ERROR)
4823 if (count < event->read_size)
4826 WARN_ON_ONCE(event->ctx->parent_ctx);
4827 if (read_format & PERF_FORMAT_GROUP)
4828 ret = perf_read_group(event, read_format, buf);
4830 ret = perf_read_one(event, read_format, buf);
4836 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4838 struct perf_event *event = file->private_data;
4839 struct perf_event_context *ctx;
4842 ctx = perf_event_ctx_lock(event);
4843 ret = __perf_read(event, buf, count);
4844 perf_event_ctx_unlock(event, ctx);
4849 static __poll_t perf_poll(struct file *file, poll_table *wait)
4851 struct perf_event *event = file->private_data;
4852 struct ring_buffer *rb;
4853 __poll_t events = EPOLLHUP;
4855 poll_wait(file, &event->waitq, wait);
4857 if (is_event_hup(event))
4861 * Pin the event->rb by taking event->mmap_mutex; otherwise
4862 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4864 mutex_lock(&event->mmap_mutex);
4867 events = atomic_xchg(&rb->poll, 0);
4868 mutex_unlock(&event->mmap_mutex);
4872 static void _perf_event_reset(struct perf_event *event)
4874 (void)perf_event_read(event, false);
4875 local64_set(&event->count, 0);
4876 perf_event_update_userpage(event);
4880 * Holding the top-level event's child_mutex means that any
4881 * descendant process that has inherited this event will block
4882 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4883 * task existence requirements of perf_event_enable/disable.
4885 static void perf_event_for_each_child(struct perf_event *event,
4886 void (*func)(struct perf_event *))
4888 struct perf_event *child;
4890 WARN_ON_ONCE(event->ctx->parent_ctx);
4892 mutex_lock(&event->child_mutex);
4894 list_for_each_entry(child, &event->child_list, child_list)
4896 mutex_unlock(&event->child_mutex);
4899 static void perf_event_for_each(struct perf_event *event,
4900 void (*func)(struct perf_event *))
4902 struct perf_event_context *ctx = event->ctx;
4903 struct perf_event *sibling;
4905 lockdep_assert_held(&ctx->mutex);
4907 event = event->group_leader;
4909 perf_event_for_each_child(event, func);
4910 for_each_sibling_event(sibling, event)
4911 perf_event_for_each_child(sibling, func);
4914 static void __perf_event_period(struct perf_event *event,
4915 struct perf_cpu_context *cpuctx,
4916 struct perf_event_context *ctx,
4919 u64 value = *((u64 *)info);
4922 if (event->attr.freq) {
4923 event->attr.sample_freq = value;
4925 event->attr.sample_period = value;
4926 event->hw.sample_period = value;
4929 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4931 perf_pmu_disable(ctx->pmu);
4933 * We could be throttled; unthrottle now to avoid the tick
4934 * trying to unthrottle while we already re-started the event.
4936 if (event->hw.interrupts == MAX_INTERRUPTS) {
4937 event->hw.interrupts = 0;
4938 perf_log_throttle(event, 1);
4940 event->pmu->stop(event, PERF_EF_UPDATE);
4943 local64_set(&event->hw.period_left, 0);
4946 event->pmu->start(event, PERF_EF_RELOAD);
4947 perf_pmu_enable(ctx->pmu);
4951 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4955 if (!is_sampling_event(event))
4958 if (copy_from_user(&value, arg, sizeof(value)))
4964 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4967 event_function_call(event, __perf_event_period, &value);
4972 static const struct file_operations perf_fops;
4974 static inline int perf_fget_light(int fd, struct fd *p)
4976 struct fd f = fdget(fd);
4980 if (f.file->f_op != &perf_fops) {
4988 static int perf_event_set_output(struct perf_event *event,
4989 struct perf_event *output_event);
4990 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4991 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4992 static int perf_copy_attr(struct perf_event_attr __user *uattr,
4993 struct perf_event_attr *attr);
4995 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4997 void (*func)(struct perf_event *);
5001 case PERF_EVENT_IOC_ENABLE:
5002 func = _perf_event_enable;
5004 case PERF_EVENT_IOC_DISABLE:
5005 func = _perf_event_disable;
5007 case PERF_EVENT_IOC_RESET:
5008 func = _perf_event_reset;
5011 case PERF_EVENT_IOC_REFRESH:
5012 return _perf_event_refresh(event, arg);
5014 case PERF_EVENT_IOC_PERIOD:
5015 return perf_event_period(event, (u64 __user *)arg);
5017 case PERF_EVENT_IOC_ID:
5019 u64 id = primary_event_id(event);
5021 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5026 case PERF_EVENT_IOC_SET_OUTPUT:
5030 struct perf_event *output_event;
5032 ret = perf_fget_light(arg, &output);
5035 output_event = output.file->private_data;
5036 ret = perf_event_set_output(event, output_event);
5039 ret = perf_event_set_output(event, NULL);
5044 case PERF_EVENT_IOC_SET_FILTER:
5045 return perf_event_set_filter(event, (void __user *)arg);
5047 case PERF_EVENT_IOC_SET_BPF:
5048 return perf_event_set_bpf_prog(event, arg);
5050 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5051 struct ring_buffer *rb;
5054 rb = rcu_dereference(event->rb);
5055 if (!rb || !rb->nr_pages) {
5059 rb_toggle_paused(rb, !!arg);
5064 case PERF_EVENT_IOC_QUERY_BPF:
5065 return perf_event_query_prog_array(event, (void __user *)arg);
5067 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5068 struct perf_event_attr new_attr;
5069 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5075 return perf_event_modify_attr(event, &new_attr);
5081 if (flags & PERF_IOC_FLAG_GROUP)
5082 perf_event_for_each(event, func);
5084 perf_event_for_each_child(event, func);
5089 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5091 struct perf_event *event = file->private_data;
5092 struct perf_event_context *ctx;
5095 ctx = perf_event_ctx_lock(event);
5096 ret = _perf_ioctl(event, cmd, arg);
5097 perf_event_ctx_unlock(event, ctx);
5102 #ifdef CONFIG_COMPAT
5103 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5106 switch (_IOC_NR(cmd)) {
5107 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5108 case _IOC_NR(PERF_EVENT_IOC_ID):
5109 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5110 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5111 cmd &= ~IOCSIZE_MASK;
5112 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5116 return perf_ioctl(file, cmd, arg);
5119 # define perf_compat_ioctl NULL
5122 int perf_event_task_enable(void)
5124 struct perf_event_context *ctx;
5125 struct perf_event *event;
5127 mutex_lock(¤t->perf_event_mutex);
5128 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5129 ctx = perf_event_ctx_lock(event);
5130 perf_event_for_each_child(event, _perf_event_enable);
5131 perf_event_ctx_unlock(event, ctx);
5133 mutex_unlock(¤t->perf_event_mutex);
5138 int perf_event_task_disable(void)
5140 struct perf_event_context *ctx;
5141 struct perf_event *event;
5143 mutex_lock(¤t->perf_event_mutex);
5144 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5145 ctx = perf_event_ctx_lock(event);
5146 perf_event_for_each_child(event, _perf_event_disable);
5147 perf_event_ctx_unlock(event, ctx);
5149 mutex_unlock(¤t->perf_event_mutex);
5154 static int perf_event_index(struct perf_event *event)
5156 if (event->hw.state & PERF_HES_STOPPED)
5159 if (event->state != PERF_EVENT_STATE_ACTIVE)
5162 return event->pmu->event_idx(event);
5165 static void calc_timer_values(struct perf_event *event,
5172 *now = perf_clock();
5173 ctx_time = event->shadow_ctx_time + *now;
5174 __perf_update_times(event, ctx_time, enabled, running);
5177 static void perf_event_init_userpage(struct perf_event *event)
5179 struct perf_event_mmap_page *userpg;
5180 struct ring_buffer *rb;
5183 rb = rcu_dereference(event->rb);
5187 userpg = rb->user_page;
5189 /* Allow new userspace to detect that bit 0 is deprecated */
5190 userpg->cap_bit0_is_deprecated = 1;
5191 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5192 userpg->data_offset = PAGE_SIZE;
5193 userpg->data_size = perf_data_size(rb);
5199 void __weak arch_perf_update_userpage(
5200 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5205 * Callers need to ensure there can be no nesting of this function, otherwise
5206 * the seqlock logic goes bad. We can not serialize this because the arch
5207 * code calls this from NMI context.
5209 void perf_event_update_userpage(struct perf_event *event)
5211 struct perf_event_mmap_page *userpg;
5212 struct ring_buffer *rb;
5213 u64 enabled, running, now;
5216 rb = rcu_dereference(event->rb);
5221 * compute total_time_enabled, total_time_running
5222 * based on snapshot values taken when the event
5223 * was last scheduled in.
5225 * we cannot simply called update_context_time()
5226 * because of locking issue as we can be called in
5229 calc_timer_values(event, &now, &enabled, &running);
5231 userpg = rb->user_page;
5233 * Disable preemption so as to not let the corresponding user-space
5234 * spin too long if we get preempted.
5239 userpg->index = perf_event_index(event);
5240 userpg->offset = perf_event_count(event);
5242 userpg->offset -= local64_read(&event->hw.prev_count);
5244 userpg->time_enabled = enabled +
5245 atomic64_read(&event->child_total_time_enabled);
5247 userpg->time_running = running +
5248 atomic64_read(&event->child_total_time_running);
5250 arch_perf_update_userpage(event, userpg, now);
5258 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5260 static int perf_mmap_fault(struct vm_fault *vmf)
5262 struct perf_event *event = vmf->vma->vm_file->private_data;
5263 struct ring_buffer *rb;
5264 int ret = VM_FAULT_SIGBUS;
5266 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5267 if (vmf->pgoff == 0)
5273 rb = rcu_dereference(event->rb);
5277 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5280 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5284 get_page(vmf->page);
5285 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5286 vmf->page->index = vmf->pgoff;
5295 static void ring_buffer_attach(struct perf_event *event,
5296 struct ring_buffer *rb)
5298 struct ring_buffer *old_rb = NULL;
5299 unsigned long flags;
5303 * Should be impossible, we set this when removing
5304 * event->rb_entry and wait/clear when adding event->rb_entry.
5306 WARN_ON_ONCE(event->rcu_pending);
5309 spin_lock_irqsave(&old_rb->event_lock, flags);
5310 list_del_rcu(&event->rb_entry);
5311 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5313 event->rcu_batches = get_state_synchronize_rcu();
5314 event->rcu_pending = 1;
5318 if (event->rcu_pending) {
5319 cond_synchronize_rcu(event->rcu_batches);
5320 event->rcu_pending = 0;
5323 spin_lock_irqsave(&rb->event_lock, flags);
5324 list_add_rcu(&event->rb_entry, &rb->event_list);
5325 spin_unlock_irqrestore(&rb->event_lock, flags);
5329 * Avoid racing with perf_mmap_close(AUX): stop the event
5330 * before swizzling the event::rb pointer; if it's getting
5331 * unmapped, its aux_mmap_count will be 0 and it won't
5332 * restart. See the comment in __perf_pmu_output_stop().
5334 * Data will inevitably be lost when set_output is done in
5335 * mid-air, but then again, whoever does it like this is
5336 * not in for the data anyway.
5339 perf_event_stop(event, 0);
5341 rcu_assign_pointer(event->rb, rb);
5344 ring_buffer_put(old_rb);
5346 * Since we detached before setting the new rb, so that we
5347 * could attach the new rb, we could have missed a wakeup.
5350 wake_up_all(&event->waitq);
5354 static void ring_buffer_wakeup(struct perf_event *event)
5356 struct ring_buffer *rb;
5359 rb = rcu_dereference(event->rb);
5361 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5362 wake_up_all(&event->waitq);
5367 struct ring_buffer *ring_buffer_get(struct perf_event *event)
5369 struct ring_buffer *rb;
5372 rb = rcu_dereference(event->rb);
5374 if (!atomic_inc_not_zero(&rb->refcount))
5382 void ring_buffer_put(struct ring_buffer *rb)
5384 if (!atomic_dec_and_test(&rb->refcount))
5387 WARN_ON_ONCE(!list_empty(&rb->event_list));
5389 call_rcu(&rb->rcu_head, rb_free_rcu);
5392 static void perf_mmap_open(struct vm_area_struct *vma)
5394 struct perf_event *event = vma->vm_file->private_data;
5396 atomic_inc(&event->mmap_count);
5397 atomic_inc(&event->rb->mmap_count);
5400 atomic_inc(&event->rb->aux_mmap_count);
5402 if (event->pmu->event_mapped)
5403 event->pmu->event_mapped(event, vma->vm_mm);
5406 static void perf_pmu_output_stop(struct perf_event *event);
5409 * A buffer can be mmap()ed multiple times; either directly through the same
5410 * event, or through other events by use of perf_event_set_output().
5412 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5413 * the buffer here, where we still have a VM context. This means we need
5414 * to detach all events redirecting to us.
5416 static void perf_mmap_close(struct vm_area_struct *vma)
5418 struct perf_event *event = vma->vm_file->private_data;
5420 struct ring_buffer *rb = ring_buffer_get(event);
5421 struct user_struct *mmap_user = rb->mmap_user;
5422 int mmap_locked = rb->mmap_locked;
5423 unsigned long size = perf_data_size(rb);
5425 if (event->pmu->event_unmapped)
5426 event->pmu->event_unmapped(event, vma->vm_mm);
5429 * rb->aux_mmap_count will always drop before rb->mmap_count and
5430 * event->mmap_count, so it is ok to use event->mmap_mutex to
5431 * serialize with perf_mmap here.
5433 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5434 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5436 * Stop all AUX events that are writing to this buffer,
5437 * so that we can free its AUX pages and corresponding PMU
5438 * data. Note that after rb::aux_mmap_count dropped to zero,
5439 * they won't start any more (see perf_aux_output_begin()).
5441 perf_pmu_output_stop(event);
5443 /* now it's safe to free the pages */
5444 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
5445 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
5447 /* this has to be the last one */
5449 WARN_ON_ONCE(atomic_read(&rb->aux_refcount));
5451 mutex_unlock(&event->mmap_mutex);
5454 atomic_dec(&rb->mmap_count);
5456 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5459 ring_buffer_attach(event, NULL);
5460 mutex_unlock(&event->mmap_mutex);
5462 /* If there's still other mmap()s of this buffer, we're done. */
5463 if (atomic_read(&rb->mmap_count))
5467 * No other mmap()s, detach from all other events that might redirect
5468 * into the now unreachable buffer. Somewhat complicated by the
5469 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5473 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5474 if (!atomic_long_inc_not_zero(&event->refcount)) {
5476 * This event is en-route to free_event() which will
5477 * detach it and remove it from the list.
5483 mutex_lock(&event->mmap_mutex);
5485 * Check we didn't race with perf_event_set_output() which can
5486 * swizzle the rb from under us while we were waiting to
5487 * acquire mmap_mutex.
5489 * If we find a different rb; ignore this event, a next
5490 * iteration will no longer find it on the list. We have to
5491 * still restart the iteration to make sure we're not now
5492 * iterating the wrong list.
5494 if (event->rb == rb)
5495 ring_buffer_attach(event, NULL);
5497 mutex_unlock(&event->mmap_mutex);
5501 * Restart the iteration; either we're on the wrong list or
5502 * destroyed its integrity by doing a deletion.
5509 * It could be there's still a few 0-ref events on the list; they'll
5510 * get cleaned up by free_event() -- they'll also still have their
5511 * ref on the rb and will free it whenever they are done with it.
5513 * Aside from that, this buffer is 'fully' detached and unmapped,
5514 * undo the VM accounting.
5517 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
5518 vma->vm_mm->pinned_vm -= mmap_locked;
5519 free_uid(mmap_user);
5522 ring_buffer_put(rb); /* could be last */
5525 static const struct vm_operations_struct perf_mmap_vmops = {
5526 .open = perf_mmap_open,
5527 .close = perf_mmap_close, /* non mergable */
5528 .fault = perf_mmap_fault,
5529 .page_mkwrite = perf_mmap_fault,
5532 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5534 struct perf_event *event = file->private_data;
5535 unsigned long user_locked, user_lock_limit;
5536 struct user_struct *user = current_user();
5537 unsigned long locked, lock_limit;
5538 struct ring_buffer *rb = NULL;
5539 unsigned long vma_size;
5540 unsigned long nr_pages;
5541 long user_extra = 0, extra = 0;
5542 int ret = 0, flags = 0;
5545 * Don't allow mmap() of inherited per-task counters. This would
5546 * create a performance issue due to all children writing to the
5549 if (event->cpu == -1 && event->attr.inherit)
5552 if (!(vma->vm_flags & VM_SHARED))
5555 vma_size = vma->vm_end - vma->vm_start;
5557 if (vma->vm_pgoff == 0) {
5558 nr_pages = (vma_size / PAGE_SIZE) - 1;
5561 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5562 * mapped, all subsequent mappings should have the same size
5563 * and offset. Must be above the normal perf buffer.
5565 u64 aux_offset, aux_size;
5570 nr_pages = vma_size / PAGE_SIZE;
5572 mutex_lock(&event->mmap_mutex);
5579 aux_offset = READ_ONCE(rb->user_page->aux_offset);
5580 aux_size = READ_ONCE(rb->user_page->aux_size);
5582 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5585 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5588 /* already mapped with a different offset */
5589 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5592 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5595 /* already mapped with a different size */
5596 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5599 if (!is_power_of_2(nr_pages))
5602 if (!atomic_inc_not_zero(&rb->mmap_count))
5605 if (rb_has_aux(rb)) {
5606 atomic_inc(&rb->aux_mmap_count);
5611 atomic_set(&rb->aux_mmap_count, 1);
5612 user_extra = nr_pages;
5618 * If we have rb pages ensure they're a power-of-two number, so we
5619 * can do bitmasks instead of modulo.
5621 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5624 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5627 WARN_ON_ONCE(event->ctx->parent_ctx);
5629 mutex_lock(&event->mmap_mutex);
5631 if (event->rb->nr_pages != nr_pages) {
5636 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5638 * Raced against perf_mmap_close() through
5639 * perf_event_set_output(). Try again, hope for better
5642 mutex_unlock(&event->mmap_mutex);
5649 user_extra = nr_pages + 1;
5652 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5655 * Increase the limit linearly with more CPUs:
5657 user_lock_limit *= num_online_cpus();
5659 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5661 if (user_locked > user_lock_limit)
5662 extra = user_locked - user_lock_limit;
5664 lock_limit = rlimit(RLIMIT_MEMLOCK);
5665 lock_limit >>= PAGE_SHIFT;
5666 locked = vma->vm_mm->pinned_vm + extra;
5668 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5669 !capable(CAP_IPC_LOCK)) {
5674 WARN_ON(!rb && event->rb);
5676 if (vma->vm_flags & VM_WRITE)
5677 flags |= RING_BUFFER_WRITABLE;
5680 rb = rb_alloc(nr_pages,
5681 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5689 atomic_set(&rb->mmap_count, 1);
5690 rb->mmap_user = get_current_user();
5691 rb->mmap_locked = extra;
5693 ring_buffer_attach(event, rb);
5695 perf_event_init_userpage(event);
5696 perf_event_update_userpage(event);
5698 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5699 event->attr.aux_watermark, flags);
5701 rb->aux_mmap_locked = extra;
5706 atomic_long_add(user_extra, &user->locked_vm);
5707 vma->vm_mm->pinned_vm += extra;
5709 atomic_inc(&event->mmap_count);
5711 atomic_dec(&rb->mmap_count);
5714 mutex_unlock(&event->mmap_mutex);
5717 * Since pinned accounting is per vm we cannot allow fork() to copy our
5720 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5721 vma->vm_ops = &perf_mmap_vmops;
5723 if (event->pmu->event_mapped)
5724 event->pmu->event_mapped(event, vma->vm_mm);
5729 static int perf_fasync(int fd, struct file *filp, int on)
5731 struct inode *inode = file_inode(filp);
5732 struct perf_event *event = filp->private_data;
5736 retval = fasync_helper(fd, filp, on, &event->fasync);
5737 inode_unlock(inode);
5745 static const struct file_operations perf_fops = {
5746 .llseek = no_llseek,
5747 .release = perf_release,
5750 .unlocked_ioctl = perf_ioctl,
5751 .compat_ioctl = perf_compat_ioctl,
5753 .fasync = perf_fasync,
5759 * If there's data, ensure we set the poll() state and publish everything
5760 * to user-space before waking everybody up.
5763 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5765 /* only the parent has fasync state */
5767 event = event->parent;
5768 return &event->fasync;
5771 void perf_event_wakeup(struct perf_event *event)
5773 ring_buffer_wakeup(event);
5775 if (event->pending_kill) {
5776 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5777 event->pending_kill = 0;
5781 static void perf_pending_event(struct irq_work *entry)
5783 struct perf_event *event = container_of(entry,
5784 struct perf_event, pending);
5787 rctx = perf_swevent_get_recursion_context();
5789 * If we 'fail' here, that's OK, it means recursion is already disabled
5790 * and we won't recurse 'further'.
5793 if (event->pending_disable) {
5794 event->pending_disable = 0;
5795 perf_event_disable_local(event);
5798 if (event->pending_wakeup) {
5799 event->pending_wakeup = 0;
5800 perf_event_wakeup(event);
5804 perf_swevent_put_recursion_context(rctx);
5808 * We assume there is only KVM supporting the callbacks.
5809 * Later on, we might change it to a list if there is
5810 * another virtualization implementation supporting the callbacks.
5812 struct perf_guest_info_callbacks *perf_guest_cbs;
5814 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5816 perf_guest_cbs = cbs;
5819 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5821 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5823 perf_guest_cbs = NULL;
5826 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5829 perf_output_sample_regs(struct perf_output_handle *handle,
5830 struct pt_regs *regs, u64 mask)
5833 DECLARE_BITMAP(_mask, 64);
5835 bitmap_from_u64(_mask, mask);
5836 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
5839 val = perf_reg_value(regs, bit);
5840 perf_output_put(handle, val);
5844 static void perf_sample_regs_user(struct perf_regs *regs_user,
5845 struct pt_regs *regs,
5846 struct pt_regs *regs_user_copy)
5848 if (user_mode(regs)) {
5849 regs_user->abi = perf_reg_abi(current);
5850 regs_user->regs = regs;
5851 } else if (current->mm) {
5852 perf_get_regs_user(regs_user, regs, regs_user_copy);
5854 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5855 regs_user->regs = NULL;
5859 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5860 struct pt_regs *regs)
5862 regs_intr->regs = regs;
5863 regs_intr->abi = perf_reg_abi(current);
5868 * Get remaining task size from user stack pointer.
5870 * It'd be better to take stack vma map and limit this more
5871 * precisly, but there's no way to get it safely under interrupt,
5872 * so using TASK_SIZE as limit.
5874 static u64 perf_ustack_task_size(struct pt_regs *regs)
5876 unsigned long addr = perf_user_stack_pointer(regs);
5878 if (!addr || addr >= TASK_SIZE)
5881 return TASK_SIZE - addr;
5885 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5886 struct pt_regs *regs)
5890 /* No regs, no stack pointer, no dump. */
5895 * Check if we fit in with the requested stack size into the:
5897 * If we don't, we limit the size to the TASK_SIZE.
5899 * - remaining sample size
5900 * If we don't, we customize the stack size to
5901 * fit in to the remaining sample size.
5904 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5905 stack_size = min(stack_size, (u16) task_size);
5907 /* Current header size plus static size and dynamic size. */
5908 header_size += 2 * sizeof(u64);
5910 /* Do we fit in with the current stack dump size? */
5911 if ((u16) (header_size + stack_size) < header_size) {
5913 * If we overflow the maximum size for the sample,
5914 * we customize the stack dump size to fit in.
5916 stack_size = USHRT_MAX - header_size - sizeof(u64);
5917 stack_size = round_up(stack_size, sizeof(u64));
5924 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5925 struct pt_regs *regs)
5927 /* Case of a kernel thread, nothing to dump */
5930 perf_output_put(handle, size);
5939 * - the size requested by user or the best one we can fit
5940 * in to the sample max size
5942 * - user stack dump data
5944 * - the actual dumped size
5948 perf_output_put(handle, dump_size);
5951 sp = perf_user_stack_pointer(regs);
5952 rem = __output_copy_user(handle, (void *) sp, dump_size);
5953 dyn_size = dump_size - rem;
5955 perf_output_skip(handle, rem);
5958 perf_output_put(handle, dyn_size);
5962 static void __perf_event_header__init_id(struct perf_event_header *header,
5963 struct perf_sample_data *data,
5964 struct perf_event *event)
5966 u64 sample_type = event->attr.sample_type;
5968 data->type = sample_type;
5969 header->size += event->id_header_size;
5971 if (sample_type & PERF_SAMPLE_TID) {
5972 /* namespace issues */
5973 data->tid_entry.pid = perf_event_pid(event, current);
5974 data->tid_entry.tid = perf_event_tid(event, current);
5977 if (sample_type & PERF_SAMPLE_TIME)
5978 data->time = perf_event_clock(event);
5980 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5981 data->id = primary_event_id(event);
5983 if (sample_type & PERF_SAMPLE_STREAM_ID)
5984 data->stream_id = event->id;
5986 if (sample_type & PERF_SAMPLE_CPU) {
5987 data->cpu_entry.cpu = raw_smp_processor_id();
5988 data->cpu_entry.reserved = 0;
5992 void perf_event_header__init_id(struct perf_event_header *header,
5993 struct perf_sample_data *data,
5994 struct perf_event *event)
5996 if (event->attr.sample_id_all)
5997 __perf_event_header__init_id(header, data, event);
6000 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6001 struct perf_sample_data *data)
6003 u64 sample_type = data->type;
6005 if (sample_type & PERF_SAMPLE_TID)
6006 perf_output_put(handle, data->tid_entry);
6008 if (sample_type & PERF_SAMPLE_TIME)
6009 perf_output_put(handle, data->time);
6011 if (sample_type & PERF_SAMPLE_ID)
6012 perf_output_put(handle, data->id);
6014 if (sample_type & PERF_SAMPLE_STREAM_ID)
6015 perf_output_put(handle, data->stream_id);
6017 if (sample_type & PERF_SAMPLE_CPU)
6018 perf_output_put(handle, data->cpu_entry);
6020 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6021 perf_output_put(handle, data->id);
6024 void perf_event__output_id_sample(struct perf_event *event,
6025 struct perf_output_handle *handle,
6026 struct perf_sample_data *sample)
6028 if (event->attr.sample_id_all)
6029 __perf_event__output_id_sample(handle, sample);
6032 static void perf_output_read_one(struct perf_output_handle *handle,
6033 struct perf_event *event,
6034 u64 enabled, u64 running)
6036 u64 read_format = event->attr.read_format;
6040 values[n++] = perf_event_count(event);
6041 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6042 values[n++] = enabled +
6043 atomic64_read(&event->child_total_time_enabled);
6045 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6046 values[n++] = running +
6047 atomic64_read(&event->child_total_time_running);
6049 if (read_format & PERF_FORMAT_ID)
6050 values[n++] = primary_event_id(event);
6052 __output_copy(handle, values, n * sizeof(u64));
6055 static void perf_output_read_group(struct perf_output_handle *handle,
6056 struct perf_event *event,
6057 u64 enabled, u64 running)
6059 struct perf_event *leader = event->group_leader, *sub;
6060 u64 read_format = event->attr.read_format;
6064 values[n++] = 1 + leader->nr_siblings;
6066 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6067 values[n++] = enabled;
6069 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6070 values[n++] = running;
6072 if ((leader != event) &&
6073 (leader->state == PERF_EVENT_STATE_ACTIVE))
6074 leader->pmu->read(leader);
6076 values[n++] = perf_event_count(leader);
6077 if (read_format & PERF_FORMAT_ID)
6078 values[n++] = primary_event_id(leader);
6080 __output_copy(handle, values, n * sizeof(u64));
6082 for_each_sibling_event(sub, leader) {
6085 if ((sub != event) &&
6086 (sub->state == PERF_EVENT_STATE_ACTIVE))
6087 sub->pmu->read(sub);
6089 values[n++] = perf_event_count(sub);
6090 if (read_format & PERF_FORMAT_ID)
6091 values[n++] = primary_event_id(sub);
6093 __output_copy(handle, values, n * sizeof(u64));
6097 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6098 PERF_FORMAT_TOTAL_TIME_RUNNING)
6101 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6103 * The problem is that its both hard and excessively expensive to iterate the
6104 * child list, not to mention that its impossible to IPI the children running
6105 * on another CPU, from interrupt/NMI context.
6107 static void perf_output_read(struct perf_output_handle *handle,
6108 struct perf_event *event)
6110 u64 enabled = 0, running = 0, now;
6111 u64 read_format = event->attr.read_format;
6114 * compute total_time_enabled, total_time_running
6115 * based on snapshot values taken when the event
6116 * was last scheduled in.
6118 * we cannot simply called update_context_time()
6119 * because of locking issue as we are called in
6122 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6123 calc_timer_values(event, &now, &enabled, &running);
6125 if (event->attr.read_format & PERF_FORMAT_GROUP)
6126 perf_output_read_group(handle, event, enabled, running);
6128 perf_output_read_one(handle, event, enabled, running);
6131 void perf_output_sample(struct perf_output_handle *handle,
6132 struct perf_event_header *header,
6133 struct perf_sample_data *data,
6134 struct perf_event *event)
6136 u64 sample_type = data->type;
6138 perf_output_put(handle, *header);
6140 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6141 perf_output_put(handle, data->id);
6143 if (sample_type & PERF_SAMPLE_IP)
6144 perf_output_put(handle, data->ip);
6146 if (sample_type & PERF_SAMPLE_TID)
6147 perf_output_put(handle, data->tid_entry);
6149 if (sample_type & PERF_SAMPLE_TIME)
6150 perf_output_put(handle, data->time);
6152 if (sample_type & PERF_SAMPLE_ADDR)
6153 perf_output_put(handle, data->addr);
6155 if (sample_type & PERF_SAMPLE_ID)
6156 perf_output_put(handle, data->id);
6158 if (sample_type & PERF_SAMPLE_STREAM_ID)
6159 perf_output_put(handle, data->stream_id);
6161 if (sample_type & PERF_SAMPLE_CPU)
6162 perf_output_put(handle, data->cpu_entry);
6164 if (sample_type & PERF_SAMPLE_PERIOD)
6165 perf_output_put(handle, data->period);
6167 if (sample_type & PERF_SAMPLE_READ)
6168 perf_output_read(handle, event);
6170 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6173 size += data->callchain->nr;
6174 size *= sizeof(u64);
6175 __output_copy(handle, data->callchain, size);
6178 if (sample_type & PERF_SAMPLE_RAW) {
6179 struct perf_raw_record *raw = data->raw;
6182 struct perf_raw_frag *frag = &raw->frag;
6184 perf_output_put(handle, raw->size);
6187 __output_custom(handle, frag->copy,
6188 frag->data, frag->size);
6190 __output_copy(handle, frag->data,
6193 if (perf_raw_frag_last(frag))
6198 __output_skip(handle, NULL, frag->pad);
6204 .size = sizeof(u32),
6207 perf_output_put(handle, raw);
6211 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6212 if (data->br_stack) {
6215 size = data->br_stack->nr
6216 * sizeof(struct perf_branch_entry);
6218 perf_output_put(handle, data->br_stack->nr);
6219 perf_output_copy(handle, data->br_stack->entries, size);
6222 * we always store at least the value of nr
6225 perf_output_put(handle, nr);
6229 if (sample_type & PERF_SAMPLE_REGS_USER) {
6230 u64 abi = data->regs_user.abi;
6233 * If there are no regs to dump, notice it through
6234 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6236 perf_output_put(handle, abi);
6239 u64 mask = event->attr.sample_regs_user;
6240 perf_output_sample_regs(handle,
6241 data->regs_user.regs,
6246 if (sample_type & PERF_SAMPLE_STACK_USER) {
6247 perf_output_sample_ustack(handle,
6248 data->stack_user_size,
6249 data->regs_user.regs);
6252 if (sample_type & PERF_SAMPLE_WEIGHT)
6253 perf_output_put(handle, data->weight);
6255 if (sample_type & PERF_SAMPLE_DATA_SRC)
6256 perf_output_put(handle, data->data_src.val);
6258 if (sample_type & PERF_SAMPLE_TRANSACTION)
6259 perf_output_put(handle, data->txn);
6261 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6262 u64 abi = data->regs_intr.abi;
6264 * If there are no regs to dump, notice it through
6265 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6267 perf_output_put(handle, abi);
6270 u64 mask = event->attr.sample_regs_intr;
6272 perf_output_sample_regs(handle,
6273 data->regs_intr.regs,
6278 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6279 perf_output_put(handle, data->phys_addr);
6281 if (!event->attr.watermark) {
6282 int wakeup_events = event->attr.wakeup_events;
6284 if (wakeup_events) {
6285 struct ring_buffer *rb = handle->rb;
6286 int events = local_inc_return(&rb->events);
6288 if (events >= wakeup_events) {
6289 local_sub(wakeup_events, &rb->events);
6290 local_inc(&rb->wakeup);
6296 static u64 perf_virt_to_phys(u64 virt)
6299 struct page *p = NULL;
6304 if (virt >= TASK_SIZE) {
6305 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6306 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6307 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6308 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6311 * Walking the pages tables for user address.
6312 * Interrupts are disabled, so it prevents any tear down
6313 * of the page tables.
6314 * Try IRQ-safe __get_user_pages_fast first.
6315 * If failed, leave phys_addr as 0.
6317 if ((current->mm != NULL) &&
6318 (__get_user_pages_fast(virt, 1, 0, &p) == 1))
6319 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6328 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6330 static struct perf_callchain_entry *
6331 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6333 bool kernel = !event->attr.exclude_callchain_kernel;
6334 bool user = !event->attr.exclude_callchain_user;
6335 /* Disallow cross-task user callchains. */
6336 bool crosstask = event->ctx->task && event->ctx->task != current;
6337 const u32 max_stack = event->attr.sample_max_stack;
6338 struct perf_callchain_entry *callchain;
6340 if (!kernel && !user)
6341 return &__empty_callchain;
6343 callchain = get_perf_callchain(regs, 0, kernel, user,
6344 max_stack, crosstask, true);
6345 return callchain ?: &__empty_callchain;
6348 void perf_prepare_sample(struct perf_event_header *header,
6349 struct perf_sample_data *data,
6350 struct perf_event *event,
6351 struct pt_regs *regs)
6353 u64 sample_type = event->attr.sample_type;
6355 header->type = PERF_RECORD_SAMPLE;
6356 header->size = sizeof(*header) + event->header_size;
6359 header->misc |= perf_misc_flags(regs);
6361 __perf_event_header__init_id(header, data, event);
6363 if (sample_type & PERF_SAMPLE_IP)
6364 data->ip = perf_instruction_pointer(regs);
6366 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6369 data->callchain = perf_callchain(event, regs);
6370 size += data->callchain->nr;
6372 header->size += size * sizeof(u64);
6375 if (sample_type & PERF_SAMPLE_RAW) {
6376 struct perf_raw_record *raw = data->raw;
6380 struct perf_raw_frag *frag = &raw->frag;
6385 if (perf_raw_frag_last(frag))
6390 size = round_up(sum + sizeof(u32), sizeof(u64));
6391 raw->size = size - sizeof(u32);
6392 frag->pad = raw->size - sum;
6397 header->size += size;
6400 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6401 int size = sizeof(u64); /* nr */
6402 if (data->br_stack) {
6403 size += data->br_stack->nr
6404 * sizeof(struct perf_branch_entry);
6406 header->size += size;
6409 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
6410 perf_sample_regs_user(&data->regs_user, regs,
6411 &data->regs_user_copy);
6413 if (sample_type & PERF_SAMPLE_REGS_USER) {
6414 /* regs dump ABI info */
6415 int size = sizeof(u64);
6417 if (data->regs_user.regs) {
6418 u64 mask = event->attr.sample_regs_user;
6419 size += hweight64(mask) * sizeof(u64);
6422 header->size += size;
6425 if (sample_type & PERF_SAMPLE_STACK_USER) {
6427 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
6428 * processed as the last one or have additional check added
6429 * in case new sample type is added, because we could eat
6430 * up the rest of the sample size.
6432 u16 stack_size = event->attr.sample_stack_user;
6433 u16 size = sizeof(u64);
6435 stack_size = perf_sample_ustack_size(stack_size, header->size,
6436 data->regs_user.regs);
6439 * If there is something to dump, add space for the dump
6440 * itself and for the field that tells the dynamic size,
6441 * which is how many have been actually dumped.
6444 size += sizeof(u64) + stack_size;
6446 data->stack_user_size = stack_size;
6447 header->size += size;
6450 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6451 /* regs dump ABI info */
6452 int size = sizeof(u64);
6454 perf_sample_regs_intr(&data->regs_intr, regs);
6456 if (data->regs_intr.regs) {
6457 u64 mask = event->attr.sample_regs_intr;
6459 size += hweight64(mask) * sizeof(u64);
6462 header->size += size;
6465 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6466 data->phys_addr = perf_virt_to_phys(data->addr);
6469 static void __always_inline
6470 __perf_event_output(struct perf_event *event,
6471 struct perf_sample_data *data,
6472 struct pt_regs *regs,
6473 int (*output_begin)(struct perf_output_handle *,
6474 struct perf_event *,
6477 struct perf_output_handle handle;
6478 struct perf_event_header header;
6480 /* protect the callchain buffers */
6483 perf_prepare_sample(&header, data, event, regs);
6485 if (output_begin(&handle, event, header.size))
6488 perf_output_sample(&handle, &header, data, event);
6490 perf_output_end(&handle);
6497 perf_event_output_forward(struct perf_event *event,
6498 struct perf_sample_data *data,
6499 struct pt_regs *regs)
6501 __perf_event_output(event, data, regs, perf_output_begin_forward);
6505 perf_event_output_backward(struct perf_event *event,
6506 struct perf_sample_data *data,
6507 struct pt_regs *regs)
6509 __perf_event_output(event, data, regs, perf_output_begin_backward);
6513 perf_event_output(struct perf_event *event,
6514 struct perf_sample_data *data,
6515 struct pt_regs *regs)
6517 __perf_event_output(event, data, regs, perf_output_begin);
6524 struct perf_read_event {
6525 struct perf_event_header header;
6532 perf_event_read_event(struct perf_event *event,
6533 struct task_struct *task)
6535 struct perf_output_handle handle;
6536 struct perf_sample_data sample;
6537 struct perf_read_event read_event = {
6539 .type = PERF_RECORD_READ,
6541 .size = sizeof(read_event) + event->read_size,
6543 .pid = perf_event_pid(event, task),
6544 .tid = perf_event_tid(event, task),
6548 perf_event_header__init_id(&read_event.header, &sample, event);
6549 ret = perf_output_begin(&handle, event, read_event.header.size);
6553 perf_output_put(&handle, read_event);
6554 perf_output_read(&handle, event);
6555 perf_event__output_id_sample(event, &handle, &sample);
6557 perf_output_end(&handle);
6560 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
6563 perf_iterate_ctx(struct perf_event_context *ctx,
6564 perf_iterate_f output,
6565 void *data, bool all)
6567 struct perf_event *event;
6569 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6571 if (event->state < PERF_EVENT_STATE_INACTIVE)
6573 if (!event_filter_match(event))
6577 output(event, data);
6581 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
6583 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
6584 struct perf_event *event;
6586 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6588 * Skip events that are not fully formed yet; ensure that
6589 * if we observe event->ctx, both event and ctx will be
6590 * complete enough. See perf_install_in_context().
6592 if (!smp_load_acquire(&event->ctx))
6595 if (event->state < PERF_EVENT_STATE_INACTIVE)
6597 if (!event_filter_match(event))
6599 output(event, data);
6604 * Iterate all events that need to receive side-band events.
6606 * For new callers; ensure that account_pmu_sb_event() includes
6607 * your event, otherwise it might not get delivered.
6610 perf_iterate_sb(perf_iterate_f output, void *data,
6611 struct perf_event_context *task_ctx)
6613 struct perf_event_context *ctx;
6620 * If we have task_ctx != NULL we only notify the task context itself.
6621 * The task_ctx is set only for EXIT events before releasing task
6625 perf_iterate_ctx(task_ctx, output, data, false);
6629 perf_iterate_sb_cpu(output, data);
6631 for_each_task_context_nr(ctxn) {
6632 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6634 perf_iterate_ctx(ctx, output, data, false);
6642 * Clear all file-based filters at exec, they'll have to be
6643 * re-instated when/if these objects are mmapped again.
6645 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6647 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6648 struct perf_addr_filter *filter;
6649 unsigned int restart = 0, count = 0;
6650 unsigned long flags;
6652 if (!has_addr_filter(event))
6655 raw_spin_lock_irqsave(&ifh->lock, flags);
6656 list_for_each_entry(filter, &ifh->list, entry) {
6657 if (filter->inode) {
6658 event->addr_filters_offs[count] = 0;
6666 event->addr_filters_gen++;
6667 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6670 perf_event_stop(event, 1);
6673 void perf_event_exec(void)
6675 struct perf_event_context *ctx;
6679 for_each_task_context_nr(ctxn) {
6680 ctx = current->perf_event_ctxp[ctxn];
6684 perf_event_enable_on_exec(ctxn);
6686 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6692 struct remote_output {
6693 struct ring_buffer *rb;
6697 static void __perf_event_output_stop(struct perf_event *event, void *data)
6699 struct perf_event *parent = event->parent;
6700 struct remote_output *ro = data;
6701 struct ring_buffer *rb = ro->rb;
6702 struct stop_event_data sd = {
6706 if (!has_aux(event))
6713 * In case of inheritance, it will be the parent that links to the
6714 * ring-buffer, but it will be the child that's actually using it.
6716 * We are using event::rb to determine if the event should be stopped,
6717 * however this may race with ring_buffer_attach() (through set_output),
6718 * which will make us skip the event that actually needs to be stopped.
6719 * So ring_buffer_attach() has to stop an aux event before re-assigning
6722 if (rcu_dereference(parent->rb) == rb)
6723 ro->err = __perf_event_stop(&sd);
6726 static int __perf_pmu_output_stop(void *info)
6728 struct perf_event *event = info;
6729 struct pmu *pmu = event->pmu;
6730 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6731 struct remote_output ro = {
6736 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6737 if (cpuctx->task_ctx)
6738 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6745 static void perf_pmu_output_stop(struct perf_event *event)
6747 struct perf_event *iter;
6752 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6754 * For per-CPU events, we need to make sure that neither they
6755 * nor their children are running; for cpu==-1 events it's
6756 * sufficient to stop the event itself if it's active, since
6757 * it can't have children.
6761 cpu = READ_ONCE(iter->oncpu);
6766 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6767 if (err == -EAGAIN) {
6776 * task tracking -- fork/exit
6778 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6781 struct perf_task_event {
6782 struct task_struct *task;
6783 struct perf_event_context *task_ctx;
6786 struct perf_event_header header;
6796 static int perf_event_task_match(struct perf_event *event)
6798 return event->attr.comm || event->attr.mmap ||
6799 event->attr.mmap2 || event->attr.mmap_data ||
6803 static void perf_event_task_output(struct perf_event *event,
6806 struct perf_task_event *task_event = data;
6807 struct perf_output_handle handle;
6808 struct perf_sample_data sample;
6809 struct task_struct *task = task_event->task;
6810 int ret, size = task_event->event_id.header.size;
6812 if (!perf_event_task_match(event))
6815 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6817 ret = perf_output_begin(&handle, event,
6818 task_event->event_id.header.size);
6822 task_event->event_id.pid = perf_event_pid(event, task);
6823 task_event->event_id.ppid = perf_event_pid(event, current);
6825 task_event->event_id.tid = perf_event_tid(event, task);
6826 task_event->event_id.ptid = perf_event_tid(event, current);
6828 task_event->event_id.time = perf_event_clock(event);
6830 perf_output_put(&handle, task_event->event_id);
6832 perf_event__output_id_sample(event, &handle, &sample);
6834 perf_output_end(&handle);
6836 task_event->event_id.header.size = size;
6839 static void perf_event_task(struct task_struct *task,
6840 struct perf_event_context *task_ctx,
6843 struct perf_task_event task_event;
6845 if (!atomic_read(&nr_comm_events) &&
6846 !atomic_read(&nr_mmap_events) &&
6847 !atomic_read(&nr_task_events))
6850 task_event = (struct perf_task_event){
6852 .task_ctx = task_ctx,
6855 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6857 .size = sizeof(task_event.event_id),
6867 perf_iterate_sb(perf_event_task_output,
6872 void perf_event_fork(struct task_struct *task)
6874 perf_event_task(task, NULL, 1);
6875 perf_event_namespaces(task);
6882 struct perf_comm_event {
6883 struct task_struct *task;
6888 struct perf_event_header header;
6895 static int perf_event_comm_match(struct perf_event *event)
6897 return event->attr.comm;
6900 static void perf_event_comm_output(struct perf_event *event,
6903 struct perf_comm_event *comm_event = data;
6904 struct perf_output_handle handle;
6905 struct perf_sample_data sample;
6906 int size = comm_event->event_id.header.size;
6909 if (!perf_event_comm_match(event))
6912 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6913 ret = perf_output_begin(&handle, event,
6914 comm_event->event_id.header.size);
6919 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6920 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6922 perf_output_put(&handle, comm_event->event_id);
6923 __output_copy(&handle, comm_event->comm,
6924 comm_event->comm_size);
6926 perf_event__output_id_sample(event, &handle, &sample);
6928 perf_output_end(&handle);
6930 comm_event->event_id.header.size = size;
6933 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6935 char comm[TASK_COMM_LEN];
6938 memset(comm, 0, sizeof(comm));
6939 strlcpy(comm, comm_event->task->comm, sizeof(comm));
6940 size = ALIGN(strlen(comm)+1, sizeof(u64));
6942 comm_event->comm = comm;
6943 comm_event->comm_size = size;
6945 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6947 perf_iterate_sb(perf_event_comm_output,
6952 void perf_event_comm(struct task_struct *task, bool exec)
6954 struct perf_comm_event comm_event;
6956 if (!atomic_read(&nr_comm_events))
6959 comm_event = (struct perf_comm_event){
6965 .type = PERF_RECORD_COMM,
6966 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6974 perf_event_comm_event(&comm_event);
6978 * namespaces tracking
6981 struct perf_namespaces_event {
6982 struct task_struct *task;
6985 struct perf_event_header header;
6990 struct perf_ns_link_info link_info[NR_NAMESPACES];
6994 static int perf_event_namespaces_match(struct perf_event *event)
6996 return event->attr.namespaces;
6999 static void perf_event_namespaces_output(struct perf_event *event,
7002 struct perf_namespaces_event *namespaces_event = data;
7003 struct perf_output_handle handle;
7004 struct perf_sample_data sample;
7005 u16 header_size = namespaces_event->event_id.header.size;
7008 if (!perf_event_namespaces_match(event))
7011 perf_event_header__init_id(&namespaces_event->event_id.header,
7013 ret = perf_output_begin(&handle, event,
7014 namespaces_event->event_id.header.size);
7018 namespaces_event->event_id.pid = perf_event_pid(event,
7019 namespaces_event->task);
7020 namespaces_event->event_id.tid = perf_event_tid(event,
7021 namespaces_event->task);
7023 perf_output_put(&handle, namespaces_event->event_id);
7025 perf_event__output_id_sample(event, &handle, &sample);
7027 perf_output_end(&handle);
7029 namespaces_event->event_id.header.size = header_size;
7032 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7033 struct task_struct *task,
7034 const struct proc_ns_operations *ns_ops)
7036 struct path ns_path;
7037 struct inode *ns_inode;
7040 error = ns_get_path(&ns_path, task, ns_ops);
7042 ns_inode = ns_path.dentry->d_inode;
7043 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7044 ns_link_info->ino = ns_inode->i_ino;
7049 void perf_event_namespaces(struct task_struct *task)
7051 struct perf_namespaces_event namespaces_event;
7052 struct perf_ns_link_info *ns_link_info;
7054 if (!atomic_read(&nr_namespaces_events))
7057 namespaces_event = (struct perf_namespaces_event){
7061 .type = PERF_RECORD_NAMESPACES,
7063 .size = sizeof(namespaces_event.event_id),
7067 .nr_namespaces = NR_NAMESPACES,
7068 /* .link_info[NR_NAMESPACES] */
7072 ns_link_info = namespaces_event.event_id.link_info;
7074 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7075 task, &mntns_operations);
7077 #ifdef CONFIG_USER_NS
7078 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7079 task, &userns_operations);
7081 #ifdef CONFIG_NET_NS
7082 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7083 task, &netns_operations);
7085 #ifdef CONFIG_UTS_NS
7086 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7087 task, &utsns_operations);
7089 #ifdef CONFIG_IPC_NS
7090 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7091 task, &ipcns_operations);
7093 #ifdef CONFIG_PID_NS
7094 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7095 task, &pidns_operations);
7097 #ifdef CONFIG_CGROUPS
7098 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7099 task, &cgroupns_operations);
7102 perf_iterate_sb(perf_event_namespaces_output,
7111 struct perf_mmap_event {
7112 struct vm_area_struct *vma;
7114 const char *file_name;
7122 struct perf_event_header header;
7132 static int perf_event_mmap_match(struct perf_event *event,
7135 struct perf_mmap_event *mmap_event = data;
7136 struct vm_area_struct *vma = mmap_event->vma;
7137 int executable = vma->vm_flags & VM_EXEC;
7139 return (!executable && event->attr.mmap_data) ||
7140 (executable && (event->attr.mmap || event->attr.mmap2));
7143 static void perf_event_mmap_output(struct perf_event *event,
7146 struct perf_mmap_event *mmap_event = data;
7147 struct perf_output_handle handle;
7148 struct perf_sample_data sample;
7149 int size = mmap_event->event_id.header.size;
7152 if (!perf_event_mmap_match(event, data))
7155 if (event->attr.mmap2) {
7156 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7157 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7158 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7159 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7160 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7161 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7162 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7165 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7166 ret = perf_output_begin(&handle, event,
7167 mmap_event->event_id.header.size);
7171 mmap_event->event_id.pid = perf_event_pid(event, current);
7172 mmap_event->event_id.tid = perf_event_tid(event, current);
7174 perf_output_put(&handle, mmap_event->event_id);
7176 if (event->attr.mmap2) {
7177 perf_output_put(&handle, mmap_event->maj);
7178 perf_output_put(&handle, mmap_event->min);
7179 perf_output_put(&handle, mmap_event->ino);
7180 perf_output_put(&handle, mmap_event->ino_generation);
7181 perf_output_put(&handle, mmap_event->prot);
7182 perf_output_put(&handle, mmap_event->flags);
7185 __output_copy(&handle, mmap_event->file_name,
7186 mmap_event->file_size);
7188 perf_event__output_id_sample(event, &handle, &sample);
7190 perf_output_end(&handle);
7192 mmap_event->event_id.header.size = size;
7195 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7197 struct vm_area_struct *vma = mmap_event->vma;
7198 struct file *file = vma->vm_file;
7199 int maj = 0, min = 0;
7200 u64 ino = 0, gen = 0;
7201 u32 prot = 0, flags = 0;
7207 if (vma->vm_flags & VM_READ)
7209 if (vma->vm_flags & VM_WRITE)
7211 if (vma->vm_flags & VM_EXEC)
7214 if (vma->vm_flags & VM_MAYSHARE)
7217 flags = MAP_PRIVATE;
7219 if (vma->vm_flags & VM_DENYWRITE)
7220 flags |= MAP_DENYWRITE;
7221 if (vma->vm_flags & VM_MAYEXEC)
7222 flags |= MAP_EXECUTABLE;
7223 if (vma->vm_flags & VM_LOCKED)
7224 flags |= MAP_LOCKED;
7225 if (vma->vm_flags & VM_HUGETLB)
7226 flags |= MAP_HUGETLB;
7229 struct inode *inode;
7232 buf = kmalloc(PATH_MAX, GFP_KERNEL);
7238 * d_path() works from the end of the rb backwards, so we
7239 * need to add enough zero bytes after the string to handle
7240 * the 64bit alignment we do later.
7242 name = file_path(file, buf, PATH_MAX - sizeof(u64));
7247 inode = file_inode(vma->vm_file);
7248 dev = inode->i_sb->s_dev;
7250 gen = inode->i_generation;
7256 if (vma->vm_ops && vma->vm_ops->name) {
7257 name = (char *) vma->vm_ops->name(vma);
7262 name = (char *)arch_vma_name(vma);
7266 if (vma->vm_start <= vma->vm_mm->start_brk &&
7267 vma->vm_end >= vma->vm_mm->brk) {
7271 if (vma->vm_start <= vma->vm_mm->start_stack &&
7272 vma->vm_end >= vma->vm_mm->start_stack) {
7282 strlcpy(tmp, name, sizeof(tmp));
7286 * Since our buffer works in 8 byte units we need to align our string
7287 * size to a multiple of 8. However, we must guarantee the tail end is
7288 * zero'd out to avoid leaking random bits to userspace.
7290 size = strlen(name)+1;
7291 while (!IS_ALIGNED(size, sizeof(u64)))
7292 name[size++] = '\0';
7294 mmap_event->file_name = name;
7295 mmap_event->file_size = size;
7296 mmap_event->maj = maj;
7297 mmap_event->min = min;
7298 mmap_event->ino = ino;
7299 mmap_event->ino_generation = gen;
7300 mmap_event->prot = prot;
7301 mmap_event->flags = flags;
7303 if (!(vma->vm_flags & VM_EXEC))
7304 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
7306 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
7308 perf_iterate_sb(perf_event_mmap_output,
7316 * Check whether inode and address range match filter criteria.
7318 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
7319 struct file *file, unsigned long offset,
7322 if (filter->inode != file_inode(file))
7325 if (filter->offset > offset + size)
7328 if (filter->offset + filter->size < offset)
7334 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
7336 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7337 struct vm_area_struct *vma = data;
7338 unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags;
7339 struct file *file = vma->vm_file;
7340 struct perf_addr_filter *filter;
7341 unsigned int restart = 0, count = 0;
7343 if (!has_addr_filter(event))
7349 raw_spin_lock_irqsave(&ifh->lock, flags);
7350 list_for_each_entry(filter, &ifh->list, entry) {
7351 if (perf_addr_filter_match(filter, file, off,
7352 vma->vm_end - vma->vm_start)) {
7353 event->addr_filters_offs[count] = vma->vm_start;
7361 event->addr_filters_gen++;
7362 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7365 perf_event_stop(event, 1);
7369 * Adjust all task's events' filters to the new vma
7371 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
7373 struct perf_event_context *ctx;
7377 * Data tracing isn't supported yet and as such there is no need
7378 * to keep track of anything that isn't related to executable code:
7380 if (!(vma->vm_flags & VM_EXEC))
7384 for_each_task_context_nr(ctxn) {
7385 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7389 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
7394 void perf_event_mmap(struct vm_area_struct *vma)
7396 struct perf_mmap_event mmap_event;
7398 if (!atomic_read(&nr_mmap_events))
7401 mmap_event = (struct perf_mmap_event){
7407 .type = PERF_RECORD_MMAP,
7408 .misc = PERF_RECORD_MISC_USER,
7413 .start = vma->vm_start,
7414 .len = vma->vm_end - vma->vm_start,
7415 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
7417 /* .maj (attr_mmap2 only) */
7418 /* .min (attr_mmap2 only) */
7419 /* .ino (attr_mmap2 only) */
7420 /* .ino_generation (attr_mmap2 only) */
7421 /* .prot (attr_mmap2 only) */
7422 /* .flags (attr_mmap2 only) */
7425 perf_addr_filters_adjust(vma);
7426 perf_event_mmap_event(&mmap_event);
7429 void perf_event_aux_event(struct perf_event *event, unsigned long head,
7430 unsigned long size, u64 flags)
7432 struct perf_output_handle handle;
7433 struct perf_sample_data sample;
7434 struct perf_aux_event {
7435 struct perf_event_header header;
7441 .type = PERF_RECORD_AUX,
7443 .size = sizeof(rec),
7451 perf_event_header__init_id(&rec.header, &sample, event);
7452 ret = perf_output_begin(&handle, event, rec.header.size);
7457 perf_output_put(&handle, rec);
7458 perf_event__output_id_sample(event, &handle, &sample);
7460 perf_output_end(&handle);
7464 * Lost/dropped samples logging
7466 void perf_log_lost_samples(struct perf_event *event, u64 lost)
7468 struct perf_output_handle handle;
7469 struct perf_sample_data sample;
7473 struct perf_event_header header;
7475 } lost_samples_event = {
7477 .type = PERF_RECORD_LOST_SAMPLES,
7479 .size = sizeof(lost_samples_event),
7484 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
7486 ret = perf_output_begin(&handle, event,
7487 lost_samples_event.header.size);
7491 perf_output_put(&handle, lost_samples_event);
7492 perf_event__output_id_sample(event, &handle, &sample);
7493 perf_output_end(&handle);
7497 * context_switch tracking
7500 struct perf_switch_event {
7501 struct task_struct *task;
7502 struct task_struct *next_prev;
7505 struct perf_event_header header;
7511 static int perf_event_switch_match(struct perf_event *event)
7513 return event->attr.context_switch;
7516 static void perf_event_switch_output(struct perf_event *event, void *data)
7518 struct perf_switch_event *se = data;
7519 struct perf_output_handle handle;
7520 struct perf_sample_data sample;
7523 if (!perf_event_switch_match(event))
7526 /* Only CPU-wide events are allowed to see next/prev pid/tid */
7527 if (event->ctx->task) {
7528 se->event_id.header.type = PERF_RECORD_SWITCH;
7529 se->event_id.header.size = sizeof(se->event_id.header);
7531 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
7532 se->event_id.header.size = sizeof(se->event_id);
7533 se->event_id.next_prev_pid =
7534 perf_event_pid(event, se->next_prev);
7535 se->event_id.next_prev_tid =
7536 perf_event_tid(event, se->next_prev);
7539 perf_event_header__init_id(&se->event_id.header, &sample, event);
7541 ret = perf_output_begin(&handle, event, se->event_id.header.size);
7545 if (event->ctx->task)
7546 perf_output_put(&handle, se->event_id.header);
7548 perf_output_put(&handle, se->event_id);
7550 perf_event__output_id_sample(event, &handle, &sample);
7552 perf_output_end(&handle);
7555 static void perf_event_switch(struct task_struct *task,
7556 struct task_struct *next_prev, bool sched_in)
7558 struct perf_switch_event switch_event;
7560 /* N.B. caller checks nr_switch_events != 0 */
7562 switch_event = (struct perf_switch_event){
7564 .next_prev = next_prev,
7568 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
7571 /* .next_prev_pid */
7572 /* .next_prev_tid */
7576 perf_iterate_sb(perf_event_switch_output,
7582 * IRQ throttle logging
7585 static void perf_log_throttle(struct perf_event *event, int enable)
7587 struct perf_output_handle handle;
7588 struct perf_sample_data sample;
7592 struct perf_event_header header;
7596 } throttle_event = {
7598 .type = PERF_RECORD_THROTTLE,
7600 .size = sizeof(throttle_event),
7602 .time = perf_event_clock(event),
7603 .id = primary_event_id(event),
7604 .stream_id = event->id,
7608 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
7610 perf_event_header__init_id(&throttle_event.header, &sample, event);
7612 ret = perf_output_begin(&handle, event,
7613 throttle_event.header.size);
7617 perf_output_put(&handle, throttle_event);
7618 perf_event__output_id_sample(event, &handle, &sample);
7619 perf_output_end(&handle);
7622 void perf_event_itrace_started(struct perf_event *event)
7624 event->attach_state |= PERF_ATTACH_ITRACE;
7627 static void perf_log_itrace_start(struct perf_event *event)
7629 struct perf_output_handle handle;
7630 struct perf_sample_data sample;
7631 struct perf_aux_event {
7632 struct perf_event_header header;
7639 event = event->parent;
7641 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
7642 event->attach_state & PERF_ATTACH_ITRACE)
7645 rec.header.type = PERF_RECORD_ITRACE_START;
7646 rec.header.misc = 0;
7647 rec.header.size = sizeof(rec);
7648 rec.pid = perf_event_pid(event, current);
7649 rec.tid = perf_event_tid(event, current);
7651 perf_event_header__init_id(&rec.header, &sample, event);
7652 ret = perf_output_begin(&handle, event, rec.header.size);
7657 perf_output_put(&handle, rec);
7658 perf_event__output_id_sample(event, &handle, &sample);
7660 perf_output_end(&handle);
7664 __perf_event_account_interrupt(struct perf_event *event, int throttle)
7666 struct hw_perf_event *hwc = &event->hw;
7670 seq = __this_cpu_read(perf_throttled_seq);
7671 if (seq != hwc->interrupts_seq) {
7672 hwc->interrupts_seq = seq;
7673 hwc->interrupts = 1;
7676 if (unlikely(throttle
7677 && hwc->interrupts >= max_samples_per_tick)) {
7678 __this_cpu_inc(perf_throttled_count);
7679 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
7680 hwc->interrupts = MAX_INTERRUPTS;
7681 perf_log_throttle(event, 0);
7686 if (event->attr.freq) {
7687 u64 now = perf_clock();
7688 s64 delta = now - hwc->freq_time_stamp;
7690 hwc->freq_time_stamp = now;
7692 if (delta > 0 && delta < 2*TICK_NSEC)
7693 perf_adjust_period(event, delta, hwc->last_period, true);
7699 int perf_event_account_interrupt(struct perf_event *event)
7701 return __perf_event_account_interrupt(event, 1);
7705 * Generic event overflow handling, sampling.
7708 static int __perf_event_overflow(struct perf_event *event,
7709 int throttle, struct perf_sample_data *data,
7710 struct pt_regs *regs)
7712 int events = atomic_read(&event->event_limit);
7716 * Non-sampling counters might still use the PMI to fold short
7717 * hardware counters, ignore those.
7719 if (unlikely(!is_sampling_event(event)))
7722 ret = __perf_event_account_interrupt(event, throttle);
7725 * XXX event_limit might not quite work as expected on inherited
7729 event->pending_kill = POLL_IN;
7730 if (events && atomic_dec_and_test(&event->event_limit)) {
7732 event->pending_kill = POLL_HUP;
7734 perf_event_disable_inatomic(event);
7737 READ_ONCE(event->overflow_handler)(event, data, regs);
7739 if (*perf_event_fasync(event) && event->pending_kill) {
7740 event->pending_wakeup = 1;
7741 irq_work_queue(&event->pending);
7747 int perf_event_overflow(struct perf_event *event,
7748 struct perf_sample_data *data,
7749 struct pt_regs *regs)
7751 return __perf_event_overflow(event, 1, data, regs);
7755 * Generic software event infrastructure
7758 struct swevent_htable {
7759 struct swevent_hlist *swevent_hlist;
7760 struct mutex hlist_mutex;
7763 /* Recursion avoidance in each contexts */
7764 int recursion[PERF_NR_CONTEXTS];
7767 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
7770 * We directly increment event->count and keep a second value in
7771 * event->hw.period_left to count intervals. This period event
7772 * is kept in the range [-sample_period, 0] so that we can use the
7776 u64 perf_swevent_set_period(struct perf_event *event)
7778 struct hw_perf_event *hwc = &event->hw;
7779 u64 period = hwc->last_period;
7783 hwc->last_period = hwc->sample_period;
7786 old = val = local64_read(&hwc->period_left);
7790 nr = div64_u64(period + val, period);
7791 offset = nr * period;
7793 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7799 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
7800 struct perf_sample_data *data,
7801 struct pt_regs *regs)
7803 struct hw_perf_event *hwc = &event->hw;
7807 overflow = perf_swevent_set_period(event);
7809 if (hwc->interrupts == MAX_INTERRUPTS)
7812 for (; overflow; overflow--) {
7813 if (__perf_event_overflow(event, throttle,
7816 * We inhibit the overflow from happening when
7817 * hwc->interrupts == MAX_INTERRUPTS.
7825 static void perf_swevent_event(struct perf_event *event, u64 nr,
7826 struct perf_sample_data *data,
7827 struct pt_regs *regs)
7829 struct hw_perf_event *hwc = &event->hw;
7831 local64_add(nr, &event->count);
7836 if (!is_sampling_event(event))
7839 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
7841 return perf_swevent_overflow(event, 1, data, regs);
7843 data->period = event->hw.last_period;
7845 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
7846 return perf_swevent_overflow(event, 1, data, regs);
7848 if (local64_add_negative(nr, &hwc->period_left))
7851 perf_swevent_overflow(event, 0, data, regs);
7854 static int perf_exclude_event(struct perf_event *event,
7855 struct pt_regs *regs)
7857 if (event->hw.state & PERF_HES_STOPPED)
7861 if (event->attr.exclude_user && user_mode(regs))
7864 if (event->attr.exclude_kernel && !user_mode(regs))
7871 static int perf_swevent_match(struct perf_event *event,
7872 enum perf_type_id type,
7874 struct perf_sample_data *data,
7875 struct pt_regs *regs)
7877 if (event->attr.type != type)
7880 if (event->attr.config != event_id)
7883 if (perf_exclude_event(event, regs))
7889 static inline u64 swevent_hash(u64 type, u32 event_id)
7891 u64 val = event_id | (type << 32);
7893 return hash_64(val, SWEVENT_HLIST_BITS);
7896 static inline struct hlist_head *
7897 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
7899 u64 hash = swevent_hash(type, event_id);
7901 return &hlist->heads[hash];
7904 /* For the read side: events when they trigger */
7905 static inline struct hlist_head *
7906 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
7908 struct swevent_hlist *hlist;
7910 hlist = rcu_dereference(swhash->swevent_hlist);
7914 return __find_swevent_head(hlist, type, event_id);
7917 /* For the event head insertion and removal in the hlist */
7918 static inline struct hlist_head *
7919 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
7921 struct swevent_hlist *hlist;
7922 u32 event_id = event->attr.config;
7923 u64 type = event->attr.type;
7926 * Event scheduling is always serialized against hlist allocation
7927 * and release. Which makes the protected version suitable here.
7928 * The context lock guarantees that.
7930 hlist = rcu_dereference_protected(swhash->swevent_hlist,
7931 lockdep_is_held(&event->ctx->lock));
7935 return __find_swevent_head(hlist, type, event_id);
7938 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
7940 struct perf_sample_data *data,
7941 struct pt_regs *regs)
7943 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7944 struct perf_event *event;
7945 struct hlist_head *head;
7948 head = find_swevent_head_rcu(swhash, type, event_id);
7952 hlist_for_each_entry_rcu(event, head, hlist_entry) {
7953 if (perf_swevent_match(event, type, event_id, data, regs))
7954 perf_swevent_event(event, nr, data, regs);
7960 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
7962 int perf_swevent_get_recursion_context(void)
7964 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7966 return get_recursion_context(swhash->recursion);
7968 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
7970 void perf_swevent_put_recursion_context(int rctx)
7972 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
7974 put_recursion_context(swhash->recursion, rctx);
7977 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7979 struct perf_sample_data data;
7981 if (WARN_ON_ONCE(!regs))
7984 perf_sample_data_init(&data, addr, 0);
7985 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
7988 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
7992 preempt_disable_notrace();
7993 rctx = perf_swevent_get_recursion_context();
7994 if (unlikely(rctx < 0))
7997 ___perf_sw_event(event_id, nr, regs, addr);
7999 perf_swevent_put_recursion_context(rctx);
8001 preempt_enable_notrace();
8004 static void perf_swevent_read(struct perf_event *event)
8008 static int perf_swevent_add(struct perf_event *event, int flags)
8010 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8011 struct hw_perf_event *hwc = &event->hw;
8012 struct hlist_head *head;
8014 if (is_sampling_event(event)) {
8015 hwc->last_period = hwc->sample_period;
8016 perf_swevent_set_period(event);
8019 hwc->state = !(flags & PERF_EF_START);
8021 head = find_swevent_head(swhash, event);
8022 if (WARN_ON_ONCE(!head))
8025 hlist_add_head_rcu(&event->hlist_entry, head);
8026 perf_event_update_userpage(event);
8031 static void perf_swevent_del(struct perf_event *event, int flags)
8033 hlist_del_rcu(&event->hlist_entry);
8036 static void perf_swevent_start(struct perf_event *event, int flags)
8038 event->hw.state = 0;
8041 static void perf_swevent_stop(struct perf_event *event, int flags)
8043 event->hw.state = PERF_HES_STOPPED;
8046 /* Deref the hlist from the update side */
8047 static inline struct swevent_hlist *
8048 swevent_hlist_deref(struct swevent_htable *swhash)
8050 return rcu_dereference_protected(swhash->swevent_hlist,
8051 lockdep_is_held(&swhash->hlist_mutex));
8054 static void swevent_hlist_release(struct swevent_htable *swhash)
8056 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
8061 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
8062 kfree_rcu(hlist, rcu_head);
8065 static void swevent_hlist_put_cpu(int cpu)
8067 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8069 mutex_lock(&swhash->hlist_mutex);
8071 if (!--swhash->hlist_refcount)
8072 swevent_hlist_release(swhash);
8074 mutex_unlock(&swhash->hlist_mutex);
8077 static void swevent_hlist_put(void)
8081 for_each_possible_cpu(cpu)
8082 swevent_hlist_put_cpu(cpu);
8085 static int swevent_hlist_get_cpu(int cpu)
8087 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8090 mutex_lock(&swhash->hlist_mutex);
8091 if (!swevent_hlist_deref(swhash) &&
8092 cpumask_test_cpu(cpu, perf_online_mask)) {
8093 struct swevent_hlist *hlist;
8095 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
8100 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8102 swhash->hlist_refcount++;
8104 mutex_unlock(&swhash->hlist_mutex);
8109 static int swevent_hlist_get(void)
8111 int err, cpu, failed_cpu;
8113 mutex_lock(&pmus_lock);
8114 for_each_possible_cpu(cpu) {
8115 err = swevent_hlist_get_cpu(cpu);
8121 mutex_unlock(&pmus_lock);
8124 for_each_possible_cpu(cpu) {
8125 if (cpu == failed_cpu)
8127 swevent_hlist_put_cpu(cpu);
8129 mutex_unlock(&pmus_lock);
8133 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
8135 static void sw_perf_event_destroy(struct perf_event *event)
8137 u64 event_id = event->attr.config;
8139 WARN_ON(event->parent);
8141 static_key_slow_dec(&perf_swevent_enabled[event_id]);
8142 swevent_hlist_put();
8145 static int perf_swevent_init(struct perf_event *event)
8147 u64 event_id = event->attr.config;
8149 if (event->attr.type != PERF_TYPE_SOFTWARE)
8153 * no branch sampling for software events
8155 if (has_branch_stack(event))
8159 case PERF_COUNT_SW_CPU_CLOCK:
8160 case PERF_COUNT_SW_TASK_CLOCK:
8167 if (event_id >= PERF_COUNT_SW_MAX)
8170 if (!event->parent) {
8173 err = swevent_hlist_get();
8177 static_key_slow_inc(&perf_swevent_enabled[event_id]);
8178 event->destroy = sw_perf_event_destroy;
8184 static struct pmu perf_swevent = {
8185 .task_ctx_nr = perf_sw_context,
8187 .capabilities = PERF_PMU_CAP_NO_NMI,
8189 .event_init = perf_swevent_init,
8190 .add = perf_swevent_add,
8191 .del = perf_swevent_del,
8192 .start = perf_swevent_start,
8193 .stop = perf_swevent_stop,
8194 .read = perf_swevent_read,
8197 #ifdef CONFIG_EVENT_TRACING
8199 static int perf_tp_filter_match(struct perf_event *event,
8200 struct perf_sample_data *data)
8202 void *record = data->raw->frag.data;
8204 /* only top level events have filters set */
8206 event = event->parent;
8208 if (likely(!event->filter) || filter_match_preds(event->filter, record))
8213 static int perf_tp_event_match(struct perf_event *event,
8214 struct perf_sample_data *data,
8215 struct pt_regs *regs)
8217 if (event->hw.state & PERF_HES_STOPPED)
8220 * All tracepoints are from kernel-space.
8222 if (event->attr.exclude_kernel)
8225 if (!perf_tp_filter_match(event, data))
8231 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
8232 struct trace_event_call *call, u64 count,
8233 struct pt_regs *regs, struct hlist_head *head,
8234 struct task_struct *task)
8236 if (bpf_prog_array_valid(call)) {
8237 *(struct pt_regs **)raw_data = regs;
8238 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
8239 perf_swevent_put_recursion_context(rctx);
8243 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
8246 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
8248 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
8249 struct pt_regs *regs, struct hlist_head *head, int rctx,
8250 struct task_struct *task)
8252 struct perf_sample_data data;
8253 struct perf_event *event;
8255 struct perf_raw_record raw = {
8262 perf_sample_data_init(&data, 0, 0);
8265 perf_trace_buf_update(record, event_type);
8267 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8268 if (perf_tp_event_match(event, &data, regs))
8269 perf_swevent_event(event, count, &data, regs);
8273 * If we got specified a target task, also iterate its context and
8274 * deliver this event there too.
8276 if (task && task != current) {
8277 struct perf_event_context *ctx;
8278 struct trace_entry *entry = record;
8281 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
8285 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8286 if (event->attr.type != PERF_TYPE_TRACEPOINT)
8288 if (event->attr.config != entry->type)
8290 if (perf_tp_event_match(event, &data, regs))
8291 perf_swevent_event(event, count, &data, regs);
8297 perf_swevent_put_recursion_context(rctx);
8299 EXPORT_SYMBOL_GPL(perf_tp_event);
8301 static void tp_perf_event_destroy(struct perf_event *event)
8303 perf_trace_destroy(event);
8306 static int perf_tp_event_init(struct perf_event *event)
8310 if (event->attr.type != PERF_TYPE_TRACEPOINT)
8314 * no branch sampling for tracepoint events
8316 if (has_branch_stack(event))
8319 err = perf_trace_init(event);
8323 event->destroy = tp_perf_event_destroy;
8328 static struct pmu perf_tracepoint = {
8329 .task_ctx_nr = perf_sw_context,
8331 .event_init = perf_tp_event_init,
8332 .add = perf_trace_add,
8333 .del = perf_trace_del,
8334 .start = perf_swevent_start,
8335 .stop = perf_swevent_stop,
8336 .read = perf_swevent_read,
8339 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
8341 * Flags in config, used by dynamic PMU kprobe and uprobe
8342 * The flags should match following PMU_FORMAT_ATTR().
8344 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
8345 * if not set, create kprobe/uprobe
8347 enum perf_probe_config {
8348 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
8351 PMU_FORMAT_ATTR(retprobe, "config:0");
8353 static struct attribute *probe_attrs[] = {
8354 &format_attr_retprobe.attr,
8358 static struct attribute_group probe_format_group = {
8360 .attrs = probe_attrs,
8363 static const struct attribute_group *probe_attr_groups[] = {
8364 &probe_format_group,
8369 #ifdef CONFIG_KPROBE_EVENTS
8370 static int perf_kprobe_event_init(struct perf_event *event);
8371 static struct pmu perf_kprobe = {
8372 .task_ctx_nr = perf_sw_context,
8373 .event_init = perf_kprobe_event_init,
8374 .add = perf_trace_add,
8375 .del = perf_trace_del,
8376 .start = perf_swevent_start,
8377 .stop = perf_swevent_stop,
8378 .read = perf_swevent_read,
8379 .attr_groups = probe_attr_groups,
8382 static int perf_kprobe_event_init(struct perf_event *event)
8387 if (event->attr.type != perf_kprobe.type)
8390 * no branch sampling for probe events
8392 if (has_branch_stack(event))
8395 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
8396 err = perf_kprobe_init(event, is_retprobe);
8400 event->destroy = perf_kprobe_destroy;
8404 #endif /* CONFIG_KPROBE_EVENTS */
8406 #ifdef CONFIG_UPROBE_EVENTS
8407 static int perf_uprobe_event_init(struct perf_event *event);
8408 static struct pmu perf_uprobe = {
8409 .task_ctx_nr = perf_sw_context,
8410 .event_init = perf_uprobe_event_init,
8411 .add = perf_trace_add,
8412 .del = perf_trace_del,
8413 .start = perf_swevent_start,
8414 .stop = perf_swevent_stop,
8415 .read = perf_swevent_read,
8416 .attr_groups = probe_attr_groups,
8419 static int perf_uprobe_event_init(struct perf_event *event)
8424 if (event->attr.type != perf_uprobe.type)
8427 * no branch sampling for probe events
8429 if (has_branch_stack(event))
8432 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
8433 err = perf_uprobe_init(event, is_retprobe);
8437 event->destroy = perf_uprobe_destroy;
8441 #endif /* CONFIG_UPROBE_EVENTS */
8443 static inline void perf_tp_register(void)
8445 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
8446 #ifdef CONFIG_KPROBE_EVENTS
8447 perf_pmu_register(&perf_kprobe, "kprobe", -1);
8449 #ifdef CONFIG_UPROBE_EVENTS
8450 perf_pmu_register(&perf_uprobe, "uprobe", -1);
8454 static void perf_event_free_filter(struct perf_event *event)
8456 ftrace_profile_free_filter(event);
8459 #ifdef CONFIG_BPF_SYSCALL
8460 static void bpf_overflow_handler(struct perf_event *event,
8461 struct perf_sample_data *data,
8462 struct pt_regs *regs)
8464 struct bpf_perf_event_data_kern ctx = {
8470 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
8472 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
8475 ret = BPF_PROG_RUN(event->prog, &ctx);
8478 __this_cpu_dec(bpf_prog_active);
8483 event->orig_overflow_handler(event, data, regs);
8486 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
8488 struct bpf_prog *prog;
8490 if (event->overflow_handler_context)
8491 /* hw breakpoint or kernel counter */
8497 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
8499 return PTR_ERR(prog);
8502 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
8503 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
8507 static void perf_event_free_bpf_handler(struct perf_event *event)
8509 struct bpf_prog *prog = event->prog;
8514 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
8519 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
8523 static void perf_event_free_bpf_handler(struct perf_event *event)
8529 * returns true if the event is a tracepoint, or a kprobe/upprobe created
8530 * with perf_event_open()
8532 static inline bool perf_event_is_tracing(struct perf_event *event)
8534 if (event->pmu == &perf_tracepoint)
8536 #ifdef CONFIG_KPROBE_EVENTS
8537 if (event->pmu == &perf_kprobe)
8540 #ifdef CONFIG_UPROBE_EVENTS
8541 if (event->pmu == &perf_uprobe)
8547 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
8549 bool is_kprobe, is_tracepoint, is_syscall_tp;
8550 struct bpf_prog *prog;
8553 if (!perf_event_is_tracing(event))
8554 return perf_event_set_bpf_handler(event, prog_fd);
8556 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
8557 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
8558 is_syscall_tp = is_syscall_trace_event(event->tp_event);
8559 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
8560 /* bpf programs can only be attached to u/kprobe or tracepoint */
8563 prog = bpf_prog_get(prog_fd);
8565 return PTR_ERR(prog);
8567 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
8568 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
8569 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
8570 /* valid fd, but invalid bpf program type */
8575 /* Kprobe override only works for kprobes, not uprobes. */
8576 if (prog->kprobe_override &&
8577 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
8582 if (is_tracepoint || is_syscall_tp) {
8583 int off = trace_event_get_offsets(event->tp_event);
8585 if (prog->aux->max_ctx_offset > off) {
8591 ret = perf_event_attach_bpf_prog(event, prog);
8597 static void perf_event_free_bpf_prog(struct perf_event *event)
8599 if (!perf_event_is_tracing(event)) {
8600 perf_event_free_bpf_handler(event);
8603 perf_event_detach_bpf_prog(event);
8608 static inline void perf_tp_register(void)
8612 static void perf_event_free_filter(struct perf_event *event)
8616 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
8621 static void perf_event_free_bpf_prog(struct perf_event *event)
8624 #endif /* CONFIG_EVENT_TRACING */
8626 #ifdef CONFIG_HAVE_HW_BREAKPOINT
8627 void perf_bp_event(struct perf_event *bp, void *data)
8629 struct perf_sample_data sample;
8630 struct pt_regs *regs = data;
8632 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
8634 if (!bp->hw.state && !perf_exclude_event(bp, regs))
8635 perf_swevent_event(bp, 1, &sample, regs);
8640 * Allocate a new address filter
8642 static struct perf_addr_filter *
8643 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
8645 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
8646 struct perf_addr_filter *filter;
8648 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
8652 INIT_LIST_HEAD(&filter->entry);
8653 list_add_tail(&filter->entry, filters);
8658 static void free_filters_list(struct list_head *filters)
8660 struct perf_addr_filter *filter, *iter;
8662 list_for_each_entry_safe(filter, iter, filters, entry) {
8664 iput(filter->inode);
8665 list_del(&filter->entry);
8671 * Free existing address filters and optionally install new ones
8673 static void perf_addr_filters_splice(struct perf_event *event,
8674 struct list_head *head)
8676 unsigned long flags;
8679 if (!has_addr_filter(event))
8682 /* don't bother with children, they don't have their own filters */
8686 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
8688 list_splice_init(&event->addr_filters.list, &list);
8690 list_splice(head, &event->addr_filters.list);
8692 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
8694 free_filters_list(&list);
8698 * Scan through mm's vmas and see if one of them matches the
8699 * @filter; if so, adjust filter's address range.
8700 * Called with mm::mmap_sem down for reading.
8702 static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter,
8703 struct mm_struct *mm)
8705 struct vm_area_struct *vma;
8707 for (vma = mm->mmap; vma; vma = vma->vm_next) {
8708 struct file *file = vma->vm_file;
8709 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8710 unsigned long vma_size = vma->vm_end - vma->vm_start;
8715 if (!perf_addr_filter_match(filter, file, off, vma_size))
8718 return vma->vm_start;
8725 * Update event's address range filters based on the
8726 * task's existing mappings, if any.
8728 static void perf_event_addr_filters_apply(struct perf_event *event)
8730 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8731 struct task_struct *task = READ_ONCE(event->ctx->task);
8732 struct perf_addr_filter *filter;
8733 struct mm_struct *mm = NULL;
8734 unsigned int count = 0;
8735 unsigned long flags;
8738 * We may observe TASK_TOMBSTONE, which means that the event tear-down
8739 * will stop on the parent's child_mutex that our caller is also holding
8741 if (task == TASK_TOMBSTONE)
8744 if (!ifh->nr_file_filters)
8747 mm = get_task_mm(event->ctx->task);
8751 down_read(&mm->mmap_sem);
8753 raw_spin_lock_irqsave(&ifh->lock, flags);
8754 list_for_each_entry(filter, &ifh->list, entry) {
8755 event->addr_filters_offs[count] = 0;
8758 * Adjust base offset if the filter is associated to a binary
8759 * that needs to be mapped:
8762 event->addr_filters_offs[count] =
8763 perf_addr_filter_apply(filter, mm);
8768 event->addr_filters_gen++;
8769 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8771 up_read(&mm->mmap_sem);
8776 perf_event_stop(event, 1);
8780 * Address range filtering: limiting the data to certain
8781 * instruction address ranges. Filters are ioctl()ed to us from
8782 * userspace as ascii strings.
8784 * Filter string format:
8787 * where ACTION is one of the
8788 * * "filter": limit the trace to this region
8789 * * "start": start tracing from this address
8790 * * "stop": stop tracing at this address/region;
8792 * * for kernel addresses: <start address>[/<size>]
8793 * * for object files: <start address>[/<size>]@</path/to/object/file>
8795 * if <size> is not specified, the range is treated as a single address.
8809 IF_STATE_ACTION = 0,
8814 static const match_table_t if_tokens = {
8815 { IF_ACT_FILTER, "filter" },
8816 { IF_ACT_START, "start" },
8817 { IF_ACT_STOP, "stop" },
8818 { IF_SRC_FILE, "%u/%u@%s" },
8819 { IF_SRC_KERNEL, "%u/%u" },
8820 { IF_SRC_FILEADDR, "%u@%s" },
8821 { IF_SRC_KERNELADDR, "%u" },
8822 { IF_ACT_NONE, NULL },
8826 * Address filter string parser
8829 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
8830 struct list_head *filters)
8832 struct perf_addr_filter *filter = NULL;
8833 char *start, *orig, *filename = NULL;
8835 substring_t args[MAX_OPT_ARGS];
8836 int state = IF_STATE_ACTION, token;
8837 unsigned int kernel = 0;
8840 orig = fstr = kstrdup(fstr, GFP_KERNEL);
8844 while ((start = strsep(&fstr, " ,\n")) != NULL) {
8850 /* filter definition begins */
8851 if (state == IF_STATE_ACTION) {
8852 filter = perf_addr_filter_new(event, filters);
8857 token = match_token(start, if_tokens, args);
8864 if (state != IF_STATE_ACTION)
8867 state = IF_STATE_SOURCE;
8870 case IF_SRC_KERNELADDR:
8874 case IF_SRC_FILEADDR:
8876 if (state != IF_STATE_SOURCE)
8879 if (token == IF_SRC_FILE || token == IF_SRC_KERNEL)
8883 ret = kstrtoul(args[0].from, 0, &filter->offset);
8887 if (filter->range) {
8889 ret = kstrtoul(args[1].from, 0, &filter->size);
8894 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
8895 int fpos = filter->range ? 2 : 1;
8897 filename = match_strdup(&args[fpos]);
8904 state = IF_STATE_END;
8912 * Filter definition is fully parsed, validate and install it.
8913 * Make sure that it doesn't contradict itself or the event's
8916 if (state == IF_STATE_END) {
8918 if (kernel && event->attr.exclude_kernel)
8926 * For now, we only support file-based filters
8927 * in per-task events; doing so for CPU-wide
8928 * events requires additional context switching
8929 * trickery, since same object code will be
8930 * mapped at different virtual addresses in
8931 * different processes.
8934 if (!event->ctx->task)
8935 goto fail_free_name;
8937 /* look up the path and grab its inode */
8938 ret = kern_path(filename, LOOKUP_FOLLOW, &path);
8940 goto fail_free_name;
8942 filter->inode = igrab(d_inode(path.dentry));
8948 if (!filter->inode ||
8949 !S_ISREG(filter->inode->i_mode))
8950 /* free_filters_list() will iput() */
8953 event->addr_filters.nr_file_filters++;
8956 /* ready to consume more filters */
8957 state = IF_STATE_ACTION;
8962 if (state != IF_STATE_ACTION)
8972 free_filters_list(filters);
8979 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
8985 * Since this is called in perf_ioctl() path, we're already holding
8988 lockdep_assert_held(&event->ctx->mutex);
8990 if (WARN_ON_ONCE(event->parent))
8993 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
8995 goto fail_clear_files;
8997 ret = event->pmu->addr_filters_validate(&filters);
8999 goto fail_free_filters;
9001 /* remove existing filters, if any */
9002 perf_addr_filters_splice(event, &filters);
9004 /* install new filters */
9005 perf_event_for_each_child(event, perf_event_addr_filters_apply);
9010 free_filters_list(&filters);
9013 event->addr_filters.nr_file_filters = 0;
9018 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
9023 filter_str = strndup_user(arg, PAGE_SIZE);
9024 if (IS_ERR(filter_str))
9025 return PTR_ERR(filter_str);
9027 #ifdef CONFIG_EVENT_TRACING
9028 if (perf_event_is_tracing(event)) {
9029 struct perf_event_context *ctx = event->ctx;
9032 * Beware, here be dragons!!
9034 * the tracepoint muck will deadlock against ctx->mutex, but
9035 * the tracepoint stuff does not actually need it. So
9036 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
9037 * already have a reference on ctx.
9039 * This can result in event getting moved to a different ctx,
9040 * but that does not affect the tracepoint state.
9042 mutex_unlock(&ctx->mutex);
9043 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
9044 mutex_lock(&ctx->mutex);
9047 if (has_addr_filter(event))
9048 ret = perf_event_set_addr_filter(event, filter_str);
9055 * hrtimer based swevent callback
9058 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
9060 enum hrtimer_restart ret = HRTIMER_RESTART;
9061 struct perf_sample_data data;
9062 struct pt_regs *regs;
9063 struct perf_event *event;
9066 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
9068 if (event->state != PERF_EVENT_STATE_ACTIVE)
9069 return HRTIMER_NORESTART;
9071 event->pmu->read(event);
9073 perf_sample_data_init(&data, 0, event->hw.last_period);
9074 regs = get_irq_regs();
9076 if (regs && !perf_exclude_event(event, regs)) {
9077 if (!(event->attr.exclude_idle && is_idle_task(current)))
9078 if (__perf_event_overflow(event, 1, &data, regs))
9079 ret = HRTIMER_NORESTART;
9082 period = max_t(u64, 10000, event->hw.sample_period);
9083 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
9088 static void perf_swevent_start_hrtimer(struct perf_event *event)
9090 struct hw_perf_event *hwc = &event->hw;
9093 if (!is_sampling_event(event))
9096 period = local64_read(&hwc->period_left);
9101 local64_set(&hwc->period_left, 0);
9103 period = max_t(u64, 10000, hwc->sample_period);
9105 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
9106 HRTIMER_MODE_REL_PINNED);
9109 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
9111 struct hw_perf_event *hwc = &event->hw;
9113 if (is_sampling_event(event)) {
9114 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
9115 local64_set(&hwc->period_left, ktime_to_ns(remaining));
9117 hrtimer_cancel(&hwc->hrtimer);
9121 static void perf_swevent_init_hrtimer(struct perf_event *event)
9123 struct hw_perf_event *hwc = &event->hw;
9125 if (!is_sampling_event(event))
9128 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
9129 hwc->hrtimer.function = perf_swevent_hrtimer;
9132 * Since hrtimers have a fixed rate, we can do a static freq->period
9133 * mapping and avoid the whole period adjust feedback stuff.
9135 if (event->attr.freq) {
9136 long freq = event->attr.sample_freq;
9138 event->attr.sample_period = NSEC_PER_SEC / freq;
9139 hwc->sample_period = event->attr.sample_period;
9140 local64_set(&hwc->period_left, hwc->sample_period);
9141 hwc->last_period = hwc->sample_period;
9142 event->attr.freq = 0;
9147 * Software event: cpu wall time clock
9150 static void cpu_clock_event_update(struct perf_event *event)
9155 now = local_clock();
9156 prev = local64_xchg(&event->hw.prev_count, now);
9157 local64_add(now - prev, &event->count);
9160 static void cpu_clock_event_start(struct perf_event *event, int flags)
9162 local64_set(&event->hw.prev_count, local_clock());
9163 perf_swevent_start_hrtimer(event);
9166 static void cpu_clock_event_stop(struct perf_event *event, int flags)
9168 perf_swevent_cancel_hrtimer(event);
9169 cpu_clock_event_update(event);
9172 static int cpu_clock_event_add(struct perf_event *event, int flags)
9174 if (flags & PERF_EF_START)
9175 cpu_clock_event_start(event, flags);
9176 perf_event_update_userpage(event);
9181 static void cpu_clock_event_del(struct perf_event *event, int flags)
9183 cpu_clock_event_stop(event, flags);
9186 static void cpu_clock_event_read(struct perf_event *event)
9188 cpu_clock_event_update(event);
9191 static int cpu_clock_event_init(struct perf_event *event)
9193 if (event->attr.type != PERF_TYPE_SOFTWARE)
9196 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
9200 * no branch sampling for software events
9202 if (has_branch_stack(event))
9205 perf_swevent_init_hrtimer(event);
9210 static struct pmu perf_cpu_clock = {
9211 .task_ctx_nr = perf_sw_context,
9213 .capabilities = PERF_PMU_CAP_NO_NMI,
9215 .event_init = cpu_clock_event_init,
9216 .add = cpu_clock_event_add,
9217 .del = cpu_clock_event_del,
9218 .start = cpu_clock_event_start,
9219 .stop = cpu_clock_event_stop,
9220 .read = cpu_clock_event_read,
9224 * Software event: task time clock
9227 static void task_clock_event_update(struct perf_event *event, u64 now)
9232 prev = local64_xchg(&event->hw.prev_count, now);
9234 local64_add(delta, &event->count);
9237 static void task_clock_event_start(struct perf_event *event, int flags)
9239 local64_set(&event->hw.prev_count, event->ctx->time);
9240 perf_swevent_start_hrtimer(event);
9243 static void task_clock_event_stop(struct perf_event *event, int flags)
9245 perf_swevent_cancel_hrtimer(event);
9246 task_clock_event_update(event, event->ctx->time);
9249 static int task_clock_event_add(struct perf_event *event, int flags)
9251 if (flags & PERF_EF_START)
9252 task_clock_event_start(event, flags);
9253 perf_event_update_userpage(event);
9258 static void task_clock_event_del(struct perf_event *event, int flags)
9260 task_clock_event_stop(event, PERF_EF_UPDATE);
9263 static void task_clock_event_read(struct perf_event *event)
9265 u64 now = perf_clock();
9266 u64 delta = now - event->ctx->timestamp;
9267 u64 time = event->ctx->time + delta;
9269 task_clock_event_update(event, time);
9272 static int task_clock_event_init(struct perf_event *event)
9274 if (event->attr.type != PERF_TYPE_SOFTWARE)
9277 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
9281 * no branch sampling for software events
9283 if (has_branch_stack(event))
9286 perf_swevent_init_hrtimer(event);
9291 static struct pmu perf_task_clock = {
9292 .task_ctx_nr = perf_sw_context,
9294 .capabilities = PERF_PMU_CAP_NO_NMI,
9296 .event_init = task_clock_event_init,
9297 .add = task_clock_event_add,
9298 .del = task_clock_event_del,
9299 .start = task_clock_event_start,
9300 .stop = task_clock_event_stop,
9301 .read = task_clock_event_read,
9304 static void perf_pmu_nop_void(struct pmu *pmu)
9308 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
9312 static int perf_pmu_nop_int(struct pmu *pmu)
9317 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
9319 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
9321 __this_cpu_write(nop_txn_flags, flags);
9323 if (flags & ~PERF_PMU_TXN_ADD)
9326 perf_pmu_disable(pmu);
9329 static int perf_pmu_commit_txn(struct pmu *pmu)
9331 unsigned int flags = __this_cpu_read(nop_txn_flags);
9333 __this_cpu_write(nop_txn_flags, 0);
9335 if (flags & ~PERF_PMU_TXN_ADD)
9338 perf_pmu_enable(pmu);
9342 static void perf_pmu_cancel_txn(struct pmu *pmu)
9344 unsigned int flags = __this_cpu_read(nop_txn_flags);
9346 __this_cpu_write(nop_txn_flags, 0);
9348 if (flags & ~PERF_PMU_TXN_ADD)
9351 perf_pmu_enable(pmu);
9354 static int perf_event_idx_default(struct perf_event *event)
9360 * Ensures all contexts with the same task_ctx_nr have the same
9361 * pmu_cpu_context too.
9363 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
9370 list_for_each_entry(pmu, &pmus, entry) {
9371 if (pmu->task_ctx_nr == ctxn)
9372 return pmu->pmu_cpu_context;
9378 static void free_pmu_context(struct pmu *pmu)
9381 * Static contexts such as perf_sw_context have a global lifetime
9382 * and may be shared between different PMUs. Avoid freeing them
9383 * when a single PMU is going away.
9385 if (pmu->task_ctx_nr > perf_invalid_context)
9388 mutex_lock(&pmus_lock);
9389 free_percpu(pmu->pmu_cpu_context);
9390 mutex_unlock(&pmus_lock);
9394 * Let userspace know that this PMU supports address range filtering:
9396 static ssize_t nr_addr_filters_show(struct device *dev,
9397 struct device_attribute *attr,
9400 struct pmu *pmu = dev_get_drvdata(dev);
9402 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
9404 DEVICE_ATTR_RO(nr_addr_filters);
9406 static struct idr pmu_idr;
9409 type_show(struct device *dev, struct device_attribute *attr, char *page)
9411 struct pmu *pmu = dev_get_drvdata(dev);
9413 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
9415 static DEVICE_ATTR_RO(type);
9418 perf_event_mux_interval_ms_show(struct device *dev,
9419 struct device_attribute *attr,
9422 struct pmu *pmu = dev_get_drvdata(dev);
9424 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
9427 static DEFINE_MUTEX(mux_interval_mutex);
9430 perf_event_mux_interval_ms_store(struct device *dev,
9431 struct device_attribute *attr,
9432 const char *buf, size_t count)
9434 struct pmu *pmu = dev_get_drvdata(dev);
9435 int timer, cpu, ret;
9437 ret = kstrtoint(buf, 0, &timer);
9444 /* same value, noting to do */
9445 if (timer == pmu->hrtimer_interval_ms)
9448 mutex_lock(&mux_interval_mutex);
9449 pmu->hrtimer_interval_ms = timer;
9451 /* update all cpuctx for this PMU */
9453 for_each_online_cpu(cpu) {
9454 struct perf_cpu_context *cpuctx;
9455 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9456 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
9458 cpu_function_call(cpu,
9459 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
9462 mutex_unlock(&mux_interval_mutex);
9466 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
9468 static struct attribute *pmu_dev_attrs[] = {
9469 &dev_attr_type.attr,
9470 &dev_attr_perf_event_mux_interval_ms.attr,
9473 ATTRIBUTE_GROUPS(pmu_dev);
9475 static int pmu_bus_running;
9476 static struct bus_type pmu_bus = {
9477 .name = "event_source",
9478 .dev_groups = pmu_dev_groups,
9481 static void pmu_dev_release(struct device *dev)
9486 static int pmu_dev_alloc(struct pmu *pmu)
9490 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
9494 pmu->dev->groups = pmu->attr_groups;
9495 device_initialize(pmu->dev);
9496 ret = dev_set_name(pmu->dev, "%s", pmu->name);
9500 dev_set_drvdata(pmu->dev, pmu);
9501 pmu->dev->bus = &pmu_bus;
9502 pmu->dev->release = pmu_dev_release;
9503 ret = device_add(pmu->dev);
9507 /* For PMUs with address filters, throw in an extra attribute: */
9508 if (pmu->nr_addr_filters)
9509 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
9518 device_del(pmu->dev);
9521 put_device(pmu->dev);
9525 static struct lock_class_key cpuctx_mutex;
9526 static struct lock_class_key cpuctx_lock;
9528 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
9532 mutex_lock(&pmus_lock);
9534 pmu->pmu_disable_count = alloc_percpu(int);
9535 if (!pmu->pmu_disable_count)
9544 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
9552 if (pmu_bus_running) {
9553 ret = pmu_dev_alloc(pmu);
9559 if (pmu->task_ctx_nr == perf_hw_context) {
9560 static int hw_context_taken = 0;
9563 * Other than systems with heterogeneous CPUs, it never makes
9564 * sense for two PMUs to share perf_hw_context. PMUs which are
9565 * uncore must use perf_invalid_context.
9567 if (WARN_ON_ONCE(hw_context_taken &&
9568 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
9569 pmu->task_ctx_nr = perf_invalid_context;
9571 hw_context_taken = 1;
9574 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
9575 if (pmu->pmu_cpu_context)
9576 goto got_cpu_context;
9579 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
9580 if (!pmu->pmu_cpu_context)
9583 for_each_possible_cpu(cpu) {
9584 struct perf_cpu_context *cpuctx;
9586 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9587 __perf_event_init_context(&cpuctx->ctx);
9588 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
9589 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
9590 cpuctx->ctx.pmu = pmu;
9591 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
9593 __perf_mux_hrtimer_init(cpuctx, cpu);
9597 if (!pmu->start_txn) {
9598 if (pmu->pmu_enable) {
9600 * If we have pmu_enable/pmu_disable calls, install
9601 * transaction stubs that use that to try and batch
9602 * hardware accesses.
9604 pmu->start_txn = perf_pmu_start_txn;
9605 pmu->commit_txn = perf_pmu_commit_txn;
9606 pmu->cancel_txn = perf_pmu_cancel_txn;
9608 pmu->start_txn = perf_pmu_nop_txn;
9609 pmu->commit_txn = perf_pmu_nop_int;
9610 pmu->cancel_txn = perf_pmu_nop_void;
9614 if (!pmu->pmu_enable) {
9615 pmu->pmu_enable = perf_pmu_nop_void;
9616 pmu->pmu_disable = perf_pmu_nop_void;
9619 if (!pmu->event_idx)
9620 pmu->event_idx = perf_event_idx_default;
9622 list_add_rcu(&pmu->entry, &pmus);
9623 atomic_set(&pmu->exclusive_cnt, 0);
9626 mutex_unlock(&pmus_lock);
9631 device_del(pmu->dev);
9632 put_device(pmu->dev);
9635 if (pmu->type >= PERF_TYPE_MAX)
9636 idr_remove(&pmu_idr, pmu->type);
9639 free_percpu(pmu->pmu_disable_count);
9642 EXPORT_SYMBOL_GPL(perf_pmu_register);
9644 void perf_pmu_unregister(struct pmu *pmu)
9648 mutex_lock(&pmus_lock);
9649 remove_device = pmu_bus_running;
9650 list_del_rcu(&pmu->entry);
9651 mutex_unlock(&pmus_lock);
9654 * We dereference the pmu list under both SRCU and regular RCU, so
9655 * synchronize against both of those.
9657 synchronize_srcu(&pmus_srcu);
9660 free_percpu(pmu->pmu_disable_count);
9661 if (pmu->type >= PERF_TYPE_MAX)
9662 idr_remove(&pmu_idr, pmu->type);
9663 if (remove_device) {
9664 if (pmu->nr_addr_filters)
9665 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
9666 device_del(pmu->dev);
9667 put_device(pmu->dev);
9669 free_pmu_context(pmu);
9671 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
9673 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
9675 struct perf_event_context *ctx = NULL;
9678 if (!try_module_get(pmu->module))
9682 * A number of pmu->event_init() methods iterate the sibling_list to,
9683 * for example, validate if the group fits on the PMU. Therefore,
9684 * if this is a sibling event, acquire the ctx->mutex to protect
9687 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
9689 * This ctx->mutex can nest when we're called through
9690 * inheritance. See the perf_event_ctx_lock_nested() comment.
9692 ctx = perf_event_ctx_lock_nested(event->group_leader,
9693 SINGLE_DEPTH_NESTING);
9698 ret = pmu->event_init(event);
9701 perf_event_ctx_unlock(event->group_leader, ctx);
9704 module_put(pmu->module);
9709 static struct pmu *perf_init_event(struct perf_event *event)
9715 idx = srcu_read_lock(&pmus_srcu);
9717 /* Try parent's PMU first: */
9718 if (event->parent && event->parent->pmu) {
9719 pmu = event->parent->pmu;
9720 ret = perf_try_init_event(pmu, event);
9726 pmu = idr_find(&pmu_idr, event->attr.type);
9729 ret = perf_try_init_event(pmu, event);
9735 list_for_each_entry_rcu(pmu, &pmus, entry) {
9736 ret = perf_try_init_event(pmu, event);
9740 if (ret != -ENOENT) {
9745 pmu = ERR_PTR(-ENOENT);
9747 srcu_read_unlock(&pmus_srcu, idx);
9752 static void attach_sb_event(struct perf_event *event)
9754 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
9756 raw_spin_lock(&pel->lock);
9757 list_add_rcu(&event->sb_list, &pel->list);
9758 raw_spin_unlock(&pel->lock);
9762 * We keep a list of all !task (and therefore per-cpu) events
9763 * that need to receive side-band records.
9765 * This avoids having to scan all the various PMU per-cpu contexts
9768 static void account_pmu_sb_event(struct perf_event *event)
9770 if (is_sb_event(event))
9771 attach_sb_event(event);
9774 static void account_event_cpu(struct perf_event *event, int cpu)
9779 if (is_cgroup_event(event))
9780 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
9783 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
9784 static void account_freq_event_nohz(void)
9786 #ifdef CONFIG_NO_HZ_FULL
9787 /* Lock so we don't race with concurrent unaccount */
9788 spin_lock(&nr_freq_lock);
9789 if (atomic_inc_return(&nr_freq_events) == 1)
9790 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
9791 spin_unlock(&nr_freq_lock);
9795 static void account_freq_event(void)
9797 if (tick_nohz_full_enabled())
9798 account_freq_event_nohz();
9800 atomic_inc(&nr_freq_events);
9804 static void account_event(struct perf_event *event)
9811 if (event->attach_state & PERF_ATTACH_TASK)
9813 if (event->attr.mmap || event->attr.mmap_data)
9814 atomic_inc(&nr_mmap_events);
9815 if (event->attr.comm)
9816 atomic_inc(&nr_comm_events);
9817 if (event->attr.namespaces)
9818 atomic_inc(&nr_namespaces_events);
9819 if (event->attr.task)
9820 atomic_inc(&nr_task_events);
9821 if (event->attr.freq)
9822 account_freq_event();
9823 if (event->attr.context_switch) {
9824 atomic_inc(&nr_switch_events);
9827 if (has_branch_stack(event))
9829 if (is_cgroup_event(event))
9834 * We need the mutex here because static_branch_enable()
9835 * must complete *before* the perf_sched_count increment
9838 if (atomic_inc_not_zero(&perf_sched_count))
9841 mutex_lock(&perf_sched_mutex);
9842 if (!atomic_read(&perf_sched_count)) {
9843 static_branch_enable(&perf_sched_events);
9845 * Guarantee that all CPUs observe they key change and
9846 * call the perf scheduling hooks before proceeding to
9847 * install events that need them.
9849 synchronize_sched();
9852 * Now that we have waited for the sync_sched(), allow further
9853 * increments to by-pass the mutex.
9855 atomic_inc(&perf_sched_count);
9856 mutex_unlock(&perf_sched_mutex);
9860 account_event_cpu(event, event->cpu);
9862 account_pmu_sb_event(event);
9866 * Allocate and initialize a event structure
9868 static struct perf_event *
9869 perf_event_alloc(struct perf_event_attr *attr, int cpu,
9870 struct task_struct *task,
9871 struct perf_event *group_leader,
9872 struct perf_event *parent_event,
9873 perf_overflow_handler_t overflow_handler,
9874 void *context, int cgroup_fd)
9877 struct perf_event *event;
9878 struct hw_perf_event *hwc;
9881 if ((unsigned)cpu >= nr_cpu_ids) {
9882 if (!task || cpu != -1)
9883 return ERR_PTR(-EINVAL);
9886 event = kzalloc(sizeof(*event), GFP_KERNEL);
9888 return ERR_PTR(-ENOMEM);
9891 * Single events are their own group leaders, with an
9892 * empty sibling list:
9895 group_leader = event;
9897 mutex_init(&event->child_mutex);
9898 INIT_LIST_HEAD(&event->child_list);
9900 INIT_LIST_HEAD(&event->event_entry);
9901 INIT_LIST_HEAD(&event->sibling_list);
9902 INIT_LIST_HEAD(&event->active_list);
9903 init_event_group(event);
9904 INIT_LIST_HEAD(&event->rb_entry);
9905 INIT_LIST_HEAD(&event->active_entry);
9906 INIT_LIST_HEAD(&event->addr_filters.list);
9907 INIT_HLIST_NODE(&event->hlist_entry);
9910 init_waitqueue_head(&event->waitq);
9911 init_irq_work(&event->pending, perf_pending_event);
9913 mutex_init(&event->mmap_mutex);
9914 raw_spin_lock_init(&event->addr_filters.lock);
9916 atomic_long_set(&event->refcount, 1);
9918 event->attr = *attr;
9919 event->group_leader = group_leader;
9923 event->parent = parent_event;
9925 event->ns = get_pid_ns(task_active_pid_ns(current));
9926 event->id = atomic64_inc_return(&perf_event_id);
9928 event->state = PERF_EVENT_STATE_INACTIVE;
9931 event->attach_state = PERF_ATTACH_TASK;
9933 * XXX pmu::event_init needs to know what task to account to
9934 * and we cannot use the ctx information because we need the
9935 * pmu before we get a ctx.
9937 event->hw.target = task;
9940 event->clock = &local_clock;
9942 event->clock = parent_event->clock;
9944 if (!overflow_handler && parent_event) {
9945 overflow_handler = parent_event->overflow_handler;
9946 context = parent_event->overflow_handler_context;
9947 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
9948 if (overflow_handler == bpf_overflow_handler) {
9949 struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
9952 err = PTR_ERR(prog);
9956 event->orig_overflow_handler =
9957 parent_event->orig_overflow_handler;
9962 if (overflow_handler) {
9963 event->overflow_handler = overflow_handler;
9964 event->overflow_handler_context = context;
9965 } else if (is_write_backward(event)){
9966 event->overflow_handler = perf_event_output_backward;
9967 event->overflow_handler_context = NULL;
9969 event->overflow_handler = perf_event_output_forward;
9970 event->overflow_handler_context = NULL;
9973 perf_event__state_init(event);
9978 hwc->sample_period = attr->sample_period;
9979 if (attr->freq && attr->sample_freq)
9980 hwc->sample_period = 1;
9981 hwc->last_period = hwc->sample_period;
9983 local64_set(&hwc->period_left, hwc->sample_period);
9986 * We currently do not support PERF_SAMPLE_READ on inherited events.
9987 * See perf_output_read().
9989 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
9992 if (!has_branch_stack(event))
9993 event->attr.branch_sample_type = 0;
9995 if (cgroup_fd != -1) {
9996 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
10001 pmu = perf_init_event(event);
10003 err = PTR_ERR(pmu);
10007 err = exclusive_event_init(event);
10011 if (has_addr_filter(event)) {
10012 event->addr_filters_offs = kcalloc(pmu->nr_addr_filters,
10013 sizeof(unsigned long),
10015 if (!event->addr_filters_offs) {
10020 /* force hw sync on the address filters */
10021 event->addr_filters_gen = 1;
10024 if (!event->parent) {
10025 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
10026 err = get_callchain_buffers(attr->sample_max_stack);
10028 goto err_addr_filters;
10032 /* symmetric to unaccount_event() in _free_event() */
10033 account_event(event);
10038 kfree(event->addr_filters_offs);
10041 exclusive_event_destroy(event);
10044 if (event->destroy)
10045 event->destroy(event);
10046 module_put(pmu->module);
10048 if (is_cgroup_event(event))
10049 perf_detach_cgroup(event);
10051 put_pid_ns(event->ns);
10054 return ERR_PTR(err);
10057 static int perf_copy_attr(struct perf_event_attr __user *uattr,
10058 struct perf_event_attr *attr)
10063 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
10067 * zero the full structure, so that a short copy will be nice.
10069 memset(attr, 0, sizeof(*attr));
10071 ret = get_user(size, &uattr->size);
10075 if (size > PAGE_SIZE) /* silly large */
10078 if (!size) /* abi compat */
10079 size = PERF_ATTR_SIZE_VER0;
10081 if (size < PERF_ATTR_SIZE_VER0)
10085 * If we're handed a bigger struct than we know of,
10086 * ensure all the unknown bits are 0 - i.e. new
10087 * user-space does not rely on any kernel feature
10088 * extensions we dont know about yet.
10090 if (size > sizeof(*attr)) {
10091 unsigned char __user *addr;
10092 unsigned char __user *end;
10095 addr = (void __user *)uattr + sizeof(*attr);
10096 end = (void __user *)uattr + size;
10098 for (; addr < end; addr++) {
10099 ret = get_user(val, addr);
10105 size = sizeof(*attr);
10108 ret = copy_from_user(attr, uattr, size);
10114 if (attr->__reserved_1)
10117 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
10120 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
10123 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
10124 u64 mask = attr->branch_sample_type;
10126 /* only using defined bits */
10127 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
10130 /* at least one branch bit must be set */
10131 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
10134 /* propagate priv level, when not set for branch */
10135 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
10137 /* exclude_kernel checked on syscall entry */
10138 if (!attr->exclude_kernel)
10139 mask |= PERF_SAMPLE_BRANCH_KERNEL;
10141 if (!attr->exclude_user)
10142 mask |= PERF_SAMPLE_BRANCH_USER;
10144 if (!attr->exclude_hv)
10145 mask |= PERF_SAMPLE_BRANCH_HV;
10147 * adjust user setting (for HW filter setup)
10149 attr->branch_sample_type = mask;
10151 /* privileged levels capture (kernel, hv): check permissions */
10152 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
10153 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
10157 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
10158 ret = perf_reg_validate(attr->sample_regs_user);
10163 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
10164 if (!arch_perf_have_user_stack_dump())
10168 * We have __u32 type for the size, but so far
10169 * we can only use __u16 as maximum due to the
10170 * __u16 sample size limit.
10172 if (attr->sample_stack_user >= USHRT_MAX)
10174 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
10178 if (!attr->sample_max_stack)
10179 attr->sample_max_stack = sysctl_perf_event_max_stack;
10181 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
10182 ret = perf_reg_validate(attr->sample_regs_intr);
10187 put_user(sizeof(*attr), &uattr->size);
10193 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
10195 struct ring_buffer *rb = NULL;
10201 /* don't allow circular references */
10202 if (event == output_event)
10206 * Don't allow cross-cpu buffers
10208 if (output_event->cpu != event->cpu)
10212 * If its not a per-cpu rb, it must be the same task.
10214 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
10218 * Mixing clocks in the same buffer is trouble you don't need.
10220 if (output_event->clock != event->clock)
10224 * Either writing ring buffer from beginning or from end.
10225 * Mixing is not allowed.
10227 if (is_write_backward(output_event) != is_write_backward(event))
10231 * If both events generate aux data, they must be on the same PMU
10233 if (has_aux(event) && has_aux(output_event) &&
10234 event->pmu != output_event->pmu)
10238 mutex_lock(&event->mmap_mutex);
10239 /* Can't redirect output if we've got an active mmap() */
10240 if (atomic_read(&event->mmap_count))
10243 if (output_event) {
10244 /* get the rb we want to redirect to */
10245 rb = ring_buffer_get(output_event);
10250 ring_buffer_attach(event, rb);
10254 mutex_unlock(&event->mmap_mutex);
10260 static void mutex_lock_double(struct mutex *a, struct mutex *b)
10266 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
10269 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
10271 bool nmi_safe = false;
10274 case CLOCK_MONOTONIC:
10275 event->clock = &ktime_get_mono_fast_ns;
10279 case CLOCK_MONOTONIC_RAW:
10280 event->clock = &ktime_get_raw_fast_ns;
10284 case CLOCK_REALTIME:
10285 event->clock = &ktime_get_real_ns;
10288 case CLOCK_BOOTTIME:
10289 event->clock = &ktime_get_boot_ns;
10293 event->clock = &ktime_get_tai_ns;
10300 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
10307 * Variation on perf_event_ctx_lock_nested(), except we take two context
10310 static struct perf_event_context *
10311 __perf_event_ctx_lock_double(struct perf_event *group_leader,
10312 struct perf_event_context *ctx)
10314 struct perf_event_context *gctx;
10318 gctx = READ_ONCE(group_leader->ctx);
10319 if (!atomic_inc_not_zero(&gctx->refcount)) {
10325 mutex_lock_double(&gctx->mutex, &ctx->mutex);
10327 if (group_leader->ctx != gctx) {
10328 mutex_unlock(&ctx->mutex);
10329 mutex_unlock(&gctx->mutex);
10338 * sys_perf_event_open - open a performance event, associate it to a task/cpu
10340 * @attr_uptr: event_id type attributes for monitoring/sampling
10343 * @group_fd: group leader event fd
10345 SYSCALL_DEFINE5(perf_event_open,
10346 struct perf_event_attr __user *, attr_uptr,
10347 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
10349 struct perf_event *group_leader = NULL, *output_event = NULL;
10350 struct perf_event *event, *sibling;
10351 struct perf_event_attr attr;
10352 struct perf_event_context *ctx, *uninitialized_var(gctx);
10353 struct file *event_file = NULL;
10354 struct fd group = {NULL, 0};
10355 struct task_struct *task = NULL;
10358 int move_group = 0;
10360 int f_flags = O_RDWR;
10361 int cgroup_fd = -1;
10363 /* for future expandability... */
10364 if (flags & ~PERF_FLAG_ALL)
10367 err = perf_copy_attr(attr_uptr, &attr);
10371 if (!attr.exclude_kernel) {
10372 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
10376 if (attr.namespaces) {
10377 if (!capable(CAP_SYS_ADMIN))
10382 if (attr.sample_freq > sysctl_perf_event_sample_rate)
10385 if (attr.sample_period & (1ULL << 63))
10389 /* Only privileged users can get physical addresses */
10390 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR) &&
10391 perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
10395 * In cgroup mode, the pid argument is used to pass the fd
10396 * opened to the cgroup directory in cgroupfs. The cpu argument
10397 * designates the cpu on which to monitor threads from that
10400 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
10403 if (flags & PERF_FLAG_FD_CLOEXEC)
10404 f_flags |= O_CLOEXEC;
10406 event_fd = get_unused_fd_flags(f_flags);
10410 if (group_fd != -1) {
10411 err = perf_fget_light(group_fd, &group);
10414 group_leader = group.file->private_data;
10415 if (flags & PERF_FLAG_FD_OUTPUT)
10416 output_event = group_leader;
10417 if (flags & PERF_FLAG_FD_NO_GROUP)
10418 group_leader = NULL;
10421 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
10422 task = find_lively_task_by_vpid(pid);
10423 if (IS_ERR(task)) {
10424 err = PTR_ERR(task);
10429 if (task && group_leader &&
10430 group_leader->attr.inherit != attr.inherit) {
10436 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
10441 * Reuse ptrace permission checks for now.
10443 * We must hold cred_guard_mutex across this and any potential
10444 * perf_install_in_context() call for this new event to
10445 * serialize against exec() altering our credentials (and the
10446 * perf_event_exit_task() that could imply).
10449 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
10453 if (flags & PERF_FLAG_PID_CGROUP)
10456 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
10457 NULL, NULL, cgroup_fd);
10458 if (IS_ERR(event)) {
10459 err = PTR_ERR(event);
10463 if (is_sampling_event(event)) {
10464 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
10471 * Special case software events and allow them to be part of
10472 * any hardware group.
10476 if (attr.use_clockid) {
10477 err = perf_event_set_clock(event, attr.clockid);
10482 if (pmu->task_ctx_nr == perf_sw_context)
10483 event->event_caps |= PERF_EV_CAP_SOFTWARE;
10485 if (group_leader &&
10486 (is_software_event(event) != is_software_event(group_leader))) {
10487 if (is_software_event(event)) {
10489 * If event and group_leader are not both a software
10490 * event, and event is, then group leader is not.
10492 * Allow the addition of software events to !software
10493 * groups, this is safe because software events never
10494 * fail to schedule.
10496 pmu = group_leader->pmu;
10497 } else if (is_software_event(group_leader) &&
10498 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
10500 * In case the group is a pure software group, and we
10501 * try to add a hardware event, move the whole group to
10502 * the hardware context.
10509 * Get the target context (task or percpu):
10511 ctx = find_get_context(pmu, task, event);
10513 err = PTR_ERR(ctx);
10517 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
10523 * Look up the group leader (we will attach this event to it):
10525 if (group_leader) {
10529 * Do not allow a recursive hierarchy (this new sibling
10530 * becoming part of another group-sibling):
10532 if (group_leader->group_leader != group_leader)
10535 /* All events in a group should have the same clock */
10536 if (group_leader->clock != event->clock)
10540 * Make sure we're both events for the same CPU;
10541 * grouping events for different CPUs is broken; since
10542 * you can never concurrently schedule them anyhow.
10544 if (group_leader->cpu != event->cpu)
10548 * Make sure we're both on the same task, or both
10551 if (group_leader->ctx->task != ctx->task)
10555 * Do not allow to attach to a group in a different task
10556 * or CPU context. If we're moving SW events, we'll fix
10557 * this up later, so allow that.
10559 if (!move_group && group_leader->ctx != ctx)
10563 * Only a group leader can be exclusive or pinned
10565 if (attr.exclusive || attr.pinned)
10569 if (output_event) {
10570 err = perf_event_set_output(event, output_event);
10575 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
10577 if (IS_ERR(event_file)) {
10578 err = PTR_ERR(event_file);
10584 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
10586 if (gctx->task == TASK_TOMBSTONE) {
10592 * Check if we raced against another sys_perf_event_open() call
10593 * moving the software group underneath us.
10595 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
10597 * If someone moved the group out from under us, check
10598 * if this new event wound up on the same ctx, if so
10599 * its the regular !move_group case, otherwise fail.
10605 perf_event_ctx_unlock(group_leader, gctx);
10610 mutex_lock(&ctx->mutex);
10613 if (ctx->task == TASK_TOMBSTONE) {
10618 if (!perf_event_validate_size(event)) {
10625 * Check if the @cpu we're creating an event for is online.
10627 * We use the perf_cpu_context::ctx::mutex to serialize against
10628 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
10630 struct perf_cpu_context *cpuctx =
10631 container_of(ctx, struct perf_cpu_context, ctx);
10633 if (!cpuctx->online) {
10641 * Must be under the same ctx::mutex as perf_install_in_context(),
10642 * because we need to serialize with concurrent event creation.
10644 if (!exclusive_event_installable(event, ctx)) {
10645 /* exclusive and group stuff are assumed mutually exclusive */
10646 WARN_ON_ONCE(move_group);
10652 WARN_ON_ONCE(ctx->parent_ctx);
10655 * This is the point on no return; we cannot fail hereafter. This is
10656 * where we start modifying current state.
10661 * See perf_event_ctx_lock() for comments on the details
10662 * of swizzling perf_event::ctx.
10664 perf_remove_from_context(group_leader, 0);
10667 for_each_sibling_event(sibling, group_leader) {
10668 perf_remove_from_context(sibling, 0);
10673 * Wait for everybody to stop referencing the events through
10674 * the old lists, before installing it on new lists.
10679 * Install the group siblings before the group leader.
10681 * Because a group leader will try and install the entire group
10682 * (through the sibling list, which is still in-tact), we can
10683 * end up with siblings installed in the wrong context.
10685 * By installing siblings first we NO-OP because they're not
10686 * reachable through the group lists.
10688 for_each_sibling_event(sibling, group_leader) {
10689 perf_event__state_init(sibling);
10690 perf_install_in_context(ctx, sibling, sibling->cpu);
10695 * Removing from the context ends up with disabled
10696 * event. What we want here is event in the initial
10697 * startup state, ready to be add into new context.
10699 perf_event__state_init(group_leader);
10700 perf_install_in_context(ctx, group_leader, group_leader->cpu);
10705 * Precalculate sample_data sizes; do while holding ctx::mutex such
10706 * that we're serialized against further additions and before
10707 * perf_install_in_context() which is the point the event is active and
10708 * can use these values.
10710 perf_event__header_size(event);
10711 perf_event__id_header_size(event);
10713 event->owner = current;
10715 perf_install_in_context(ctx, event, event->cpu);
10716 perf_unpin_context(ctx);
10719 perf_event_ctx_unlock(group_leader, gctx);
10720 mutex_unlock(&ctx->mutex);
10723 mutex_unlock(&task->signal->cred_guard_mutex);
10724 put_task_struct(task);
10727 mutex_lock(¤t->perf_event_mutex);
10728 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
10729 mutex_unlock(¤t->perf_event_mutex);
10732 * Drop the reference on the group_event after placing the
10733 * new event on the sibling_list. This ensures destruction
10734 * of the group leader will find the pointer to itself in
10735 * perf_group_detach().
10738 fd_install(event_fd, event_file);
10743 perf_event_ctx_unlock(group_leader, gctx);
10744 mutex_unlock(&ctx->mutex);
10748 perf_unpin_context(ctx);
10752 * If event_file is set, the fput() above will have called ->release()
10753 * and that will take care of freeing the event.
10759 mutex_unlock(&task->signal->cred_guard_mutex);
10762 put_task_struct(task);
10766 put_unused_fd(event_fd);
10771 * perf_event_create_kernel_counter
10773 * @attr: attributes of the counter to create
10774 * @cpu: cpu in which the counter is bound
10775 * @task: task to profile (NULL for percpu)
10777 struct perf_event *
10778 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
10779 struct task_struct *task,
10780 perf_overflow_handler_t overflow_handler,
10783 struct perf_event_context *ctx;
10784 struct perf_event *event;
10788 * Get the target context (task or percpu):
10791 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
10792 overflow_handler, context, -1);
10793 if (IS_ERR(event)) {
10794 err = PTR_ERR(event);
10798 /* Mark owner so we could distinguish it from user events. */
10799 event->owner = TASK_TOMBSTONE;
10801 ctx = find_get_context(event->pmu, task, event);
10803 err = PTR_ERR(ctx);
10807 WARN_ON_ONCE(ctx->parent_ctx);
10808 mutex_lock(&ctx->mutex);
10809 if (ctx->task == TASK_TOMBSTONE) {
10816 * Check if the @cpu we're creating an event for is online.
10818 * We use the perf_cpu_context::ctx::mutex to serialize against
10819 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
10821 struct perf_cpu_context *cpuctx =
10822 container_of(ctx, struct perf_cpu_context, ctx);
10823 if (!cpuctx->online) {
10829 if (!exclusive_event_installable(event, ctx)) {
10834 perf_install_in_context(ctx, event, cpu);
10835 perf_unpin_context(ctx);
10836 mutex_unlock(&ctx->mutex);
10841 mutex_unlock(&ctx->mutex);
10842 perf_unpin_context(ctx);
10847 return ERR_PTR(err);
10849 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
10851 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
10853 struct perf_event_context *src_ctx;
10854 struct perf_event_context *dst_ctx;
10855 struct perf_event *event, *tmp;
10858 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
10859 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
10862 * See perf_event_ctx_lock() for comments on the details
10863 * of swizzling perf_event::ctx.
10865 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
10866 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
10868 perf_remove_from_context(event, 0);
10869 unaccount_event_cpu(event, src_cpu);
10871 list_add(&event->migrate_entry, &events);
10875 * Wait for the events to quiesce before re-instating them.
10880 * Re-instate events in 2 passes.
10882 * Skip over group leaders and only install siblings on this first
10883 * pass, siblings will not get enabled without a leader, however a
10884 * leader will enable its siblings, even if those are still on the old
10887 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10888 if (event->group_leader == event)
10891 list_del(&event->migrate_entry);
10892 if (event->state >= PERF_EVENT_STATE_OFF)
10893 event->state = PERF_EVENT_STATE_INACTIVE;
10894 account_event_cpu(event, dst_cpu);
10895 perf_install_in_context(dst_ctx, event, dst_cpu);
10900 * Once all the siblings are setup properly, install the group leaders
10903 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
10904 list_del(&event->migrate_entry);
10905 if (event->state >= PERF_EVENT_STATE_OFF)
10906 event->state = PERF_EVENT_STATE_INACTIVE;
10907 account_event_cpu(event, dst_cpu);
10908 perf_install_in_context(dst_ctx, event, dst_cpu);
10911 mutex_unlock(&dst_ctx->mutex);
10912 mutex_unlock(&src_ctx->mutex);
10914 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
10916 static void sync_child_event(struct perf_event *child_event,
10917 struct task_struct *child)
10919 struct perf_event *parent_event = child_event->parent;
10922 if (child_event->attr.inherit_stat)
10923 perf_event_read_event(child_event, child);
10925 child_val = perf_event_count(child_event);
10928 * Add back the child's count to the parent's count:
10930 atomic64_add(child_val, &parent_event->child_count);
10931 atomic64_add(child_event->total_time_enabled,
10932 &parent_event->child_total_time_enabled);
10933 atomic64_add(child_event->total_time_running,
10934 &parent_event->child_total_time_running);
10938 perf_event_exit_event(struct perf_event *child_event,
10939 struct perf_event_context *child_ctx,
10940 struct task_struct *child)
10942 struct perf_event *parent_event = child_event->parent;
10945 * Do not destroy the 'original' grouping; because of the context
10946 * switch optimization the original events could've ended up in a
10947 * random child task.
10949 * If we were to destroy the original group, all group related
10950 * operations would cease to function properly after this random
10953 * Do destroy all inherited groups, we don't care about those
10954 * and being thorough is better.
10956 raw_spin_lock_irq(&child_ctx->lock);
10957 WARN_ON_ONCE(child_ctx->is_active);
10960 perf_group_detach(child_event);
10961 list_del_event(child_event, child_ctx);
10962 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
10963 raw_spin_unlock_irq(&child_ctx->lock);
10966 * Parent events are governed by their filedesc, retain them.
10968 if (!parent_event) {
10969 perf_event_wakeup(child_event);
10973 * Child events can be cleaned up.
10976 sync_child_event(child_event, child);
10979 * Remove this event from the parent's list
10981 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
10982 mutex_lock(&parent_event->child_mutex);
10983 list_del_init(&child_event->child_list);
10984 mutex_unlock(&parent_event->child_mutex);
10987 * Kick perf_poll() for is_event_hup().
10989 perf_event_wakeup(parent_event);
10990 free_event(child_event);
10991 put_event(parent_event);
10994 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
10996 struct perf_event_context *child_ctx, *clone_ctx = NULL;
10997 struct perf_event *child_event, *next;
10999 WARN_ON_ONCE(child != current);
11001 child_ctx = perf_pin_task_context(child, ctxn);
11006 * In order to reduce the amount of tricky in ctx tear-down, we hold
11007 * ctx::mutex over the entire thing. This serializes against almost
11008 * everything that wants to access the ctx.
11010 * The exception is sys_perf_event_open() /
11011 * perf_event_create_kernel_count() which does find_get_context()
11012 * without ctx::mutex (it cannot because of the move_group double mutex
11013 * lock thing). See the comments in perf_install_in_context().
11015 mutex_lock(&child_ctx->mutex);
11018 * In a single ctx::lock section, de-schedule the events and detach the
11019 * context from the task such that we cannot ever get it scheduled back
11022 raw_spin_lock_irq(&child_ctx->lock);
11023 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
11026 * Now that the context is inactive, destroy the task <-> ctx relation
11027 * and mark the context dead.
11029 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
11030 put_ctx(child_ctx); /* cannot be last */
11031 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
11032 put_task_struct(current); /* cannot be last */
11034 clone_ctx = unclone_ctx(child_ctx);
11035 raw_spin_unlock_irq(&child_ctx->lock);
11038 put_ctx(clone_ctx);
11041 * Report the task dead after unscheduling the events so that we
11042 * won't get any samples after PERF_RECORD_EXIT. We can however still
11043 * get a few PERF_RECORD_READ events.
11045 perf_event_task(child, child_ctx, 0);
11047 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
11048 perf_event_exit_event(child_event, child_ctx, child);
11050 mutex_unlock(&child_ctx->mutex);
11052 put_ctx(child_ctx);
11056 * When a child task exits, feed back event values to parent events.
11058 * Can be called with cred_guard_mutex held when called from
11059 * install_exec_creds().
11061 void perf_event_exit_task(struct task_struct *child)
11063 struct perf_event *event, *tmp;
11066 mutex_lock(&child->perf_event_mutex);
11067 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
11069 list_del_init(&event->owner_entry);
11072 * Ensure the list deletion is visible before we clear
11073 * the owner, closes a race against perf_release() where
11074 * we need to serialize on the owner->perf_event_mutex.
11076 smp_store_release(&event->owner, NULL);
11078 mutex_unlock(&child->perf_event_mutex);
11080 for_each_task_context_nr(ctxn)
11081 perf_event_exit_task_context(child, ctxn);
11084 * The perf_event_exit_task_context calls perf_event_task
11085 * with child's task_ctx, which generates EXIT events for
11086 * child contexts and sets child->perf_event_ctxp[] to NULL.
11087 * At this point we need to send EXIT events to cpu contexts.
11089 perf_event_task(child, NULL, 0);
11092 static void perf_free_event(struct perf_event *event,
11093 struct perf_event_context *ctx)
11095 struct perf_event *parent = event->parent;
11097 if (WARN_ON_ONCE(!parent))
11100 mutex_lock(&parent->child_mutex);
11101 list_del_init(&event->child_list);
11102 mutex_unlock(&parent->child_mutex);
11106 raw_spin_lock_irq(&ctx->lock);
11107 perf_group_detach(event);
11108 list_del_event(event, ctx);
11109 raw_spin_unlock_irq(&ctx->lock);
11114 * Free an unexposed, unused context as created by inheritance by
11115 * perf_event_init_task below, used by fork() in case of fail.
11117 * Not all locks are strictly required, but take them anyway to be nice and
11118 * help out with the lockdep assertions.
11120 void perf_event_free_task(struct task_struct *task)
11122 struct perf_event_context *ctx;
11123 struct perf_event *event, *tmp;
11126 for_each_task_context_nr(ctxn) {
11127 ctx = task->perf_event_ctxp[ctxn];
11131 mutex_lock(&ctx->mutex);
11132 raw_spin_lock_irq(&ctx->lock);
11134 * Destroy the task <-> ctx relation and mark the context dead.
11136 * This is important because even though the task hasn't been
11137 * exposed yet the context has been (through child_list).
11139 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
11140 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
11141 put_task_struct(task); /* cannot be last */
11142 raw_spin_unlock_irq(&ctx->lock);
11144 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
11145 perf_free_event(event, ctx);
11147 mutex_unlock(&ctx->mutex);
11152 void perf_event_delayed_put(struct task_struct *task)
11156 for_each_task_context_nr(ctxn)
11157 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
11160 struct file *perf_event_get(unsigned int fd)
11164 file = fget_raw(fd);
11166 return ERR_PTR(-EBADF);
11168 if (file->f_op != &perf_fops) {
11170 return ERR_PTR(-EBADF);
11176 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
11179 return ERR_PTR(-EINVAL);
11181 return &event->attr;
11185 * Inherit a event from parent task to child task.
11188 * - valid pointer on success
11189 * - NULL for orphaned events
11190 * - IS_ERR() on error
11192 static struct perf_event *
11193 inherit_event(struct perf_event *parent_event,
11194 struct task_struct *parent,
11195 struct perf_event_context *parent_ctx,
11196 struct task_struct *child,
11197 struct perf_event *group_leader,
11198 struct perf_event_context *child_ctx)
11200 enum perf_event_state parent_state = parent_event->state;
11201 struct perf_event *child_event;
11202 unsigned long flags;
11205 * Instead of creating recursive hierarchies of events,
11206 * we link inherited events back to the original parent,
11207 * which has a filp for sure, which we use as the reference
11210 if (parent_event->parent)
11211 parent_event = parent_event->parent;
11213 child_event = perf_event_alloc(&parent_event->attr,
11216 group_leader, parent_event,
11218 if (IS_ERR(child_event))
11219 return child_event;
11222 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
11223 !child_ctx->task_ctx_data) {
11224 struct pmu *pmu = child_event->pmu;
11226 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
11228 if (!child_ctx->task_ctx_data) {
11229 free_event(child_event);
11235 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
11236 * must be under the same lock in order to serialize against
11237 * perf_event_release_kernel(), such that either we must observe
11238 * is_orphaned_event() or they will observe us on the child_list.
11240 mutex_lock(&parent_event->child_mutex);
11241 if (is_orphaned_event(parent_event) ||
11242 !atomic_long_inc_not_zero(&parent_event->refcount)) {
11243 mutex_unlock(&parent_event->child_mutex);
11244 /* task_ctx_data is freed with child_ctx */
11245 free_event(child_event);
11249 get_ctx(child_ctx);
11252 * Make the child state follow the state of the parent event,
11253 * not its attr.disabled bit. We hold the parent's mutex,
11254 * so we won't race with perf_event_{en, dis}able_family.
11256 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
11257 child_event->state = PERF_EVENT_STATE_INACTIVE;
11259 child_event->state = PERF_EVENT_STATE_OFF;
11261 if (parent_event->attr.freq) {
11262 u64 sample_period = parent_event->hw.sample_period;
11263 struct hw_perf_event *hwc = &child_event->hw;
11265 hwc->sample_period = sample_period;
11266 hwc->last_period = sample_period;
11268 local64_set(&hwc->period_left, sample_period);
11271 child_event->ctx = child_ctx;
11272 child_event->overflow_handler = parent_event->overflow_handler;
11273 child_event->overflow_handler_context
11274 = parent_event->overflow_handler_context;
11277 * Precalculate sample_data sizes
11279 perf_event__header_size(child_event);
11280 perf_event__id_header_size(child_event);
11283 * Link it up in the child's context:
11285 raw_spin_lock_irqsave(&child_ctx->lock, flags);
11286 add_event_to_ctx(child_event, child_ctx);
11287 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
11290 * Link this into the parent event's child list
11292 list_add_tail(&child_event->child_list, &parent_event->child_list);
11293 mutex_unlock(&parent_event->child_mutex);
11295 return child_event;
11299 * Inherits an event group.
11301 * This will quietly suppress orphaned events; !inherit_event() is not an error.
11302 * This matches with perf_event_release_kernel() removing all child events.
11308 static int inherit_group(struct perf_event *parent_event,
11309 struct task_struct *parent,
11310 struct perf_event_context *parent_ctx,
11311 struct task_struct *child,
11312 struct perf_event_context *child_ctx)
11314 struct perf_event *leader;
11315 struct perf_event *sub;
11316 struct perf_event *child_ctr;
11318 leader = inherit_event(parent_event, parent, parent_ctx,
11319 child, NULL, child_ctx);
11320 if (IS_ERR(leader))
11321 return PTR_ERR(leader);
11323 * @leader can be NULL here because of is_orphaned_event(). In this
11324 * case inherit_event() will create individual events, similar to what
11325 * perf_group_detach() would do anyway.
11327 for_each_sibling_event(sub, parent_event) {
11328 child_ctr = inherit_event(sub, parent, parent_ctx,
11329 child, leader, child_ctx);
11330 if (IS_ERR(child_ctr))
11331 return PTR_ERR(child_ctr);
11337 * Creates the child task context and tries to inherit the event-group.
11339 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
11340 * inherited_all set when we 'fail' to inherit an orphaned event; this is
11341 * consistent with perf_event_release_kernel() removing all child events.
11348 inherit_task_group(struct perf_event *event, struct task_struct *parent,
11349 struct perf_event_context *parent_ctx,
11350 struct task_struct *child, int ctxn,
11351 int *inherited_all)
11354 struct perf_event_context *child_ctx;
11356 if (!event->attr.inherit) {
11357 *inherited_all = 0;
11361 child_ctx = child->perf_event_ctxp[ctxn];
11364 * This is executed from the parent task context, so
11365 * inherit events that have been marked for cloning.
11366 * First allocate and initialize a context for the
11369 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
11373 child->perf_event_ctxp[ctxn] = child_ctx;
11376 ret = inherit_group(event, parent, parent_ctx,
11380 *inherited_all = 0;
11386 * Initialize the perf_event context in task_struct
11388 static int perf_event_init_context(struct task_struct *child, int ctxn)
11390 struct perf_event_context *child_ctx, *parent_ctx;
11391 struct perf_event_context *cloned_ctx;
11392 struct perf_event *event;
11393 struct task_struct *parent = current;
11394 int inherited_all = 1;
11395 unsigned long flags;
11398 if (likely(!parent->perf_event_ctxp[ctxn]))
11402 * If the parent's context is a clone, pin it so it won't get
11403 * swapped under us.
11405 parent_ctx = perf_pin_task_context(parent, ctxn);
11410 * No need to check if parent_ctx != NULL here; since we saw
11411 * it non-NULL earlier, the only reason for it to become NULL
11412 * is if we exit, and since we're currently in the middle of
11413 * a fork we can't be exiting at the same time.
11417 * Lock the parent list. No need to lock the child - not PID
11418 * hashed yet and not running, so nobody can access it.
11420 mutex_lock(&parent_ctx->mutex);
11423 * We dont have to disable NMIs - we are only looking at
11424 * the list, not manipulating it:
11426 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
11427 ret = inherit_task_group(event, parent, parent_ctx,
11428 child, ctxn, &inherited_all);
11434 * We can't hold ctx->lock when iterating the ->flexible_group list due
11435 * to allocations, but we need to prevent rotation because
11436 * rotate_ctx() will change the list from interrupt context.
11438 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
11439 parent_ctx->rotate_disable = 1;
11440 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
11442 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
11443 ret = inherit_task_group(event, parent, parent_ctx,
11444 child, ctxn, &inherited_all);
11449 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
11450 parent_ctx->rotate_disable = 0;
11452 child_ctx = child->perf_event_ctxp[ctxn];
11454 if (child_ctx && inherited_all) {
11456 * Mark the child context as a clone of the parent
11457 * context, or of whatever the parent is a clone of.
11459 * Note that if the parent is a clone, the holding of
11460 * parent_ctx->lock avoids it from being uncloned.
11462 cloned_ctx = parent_ctx->parent_ctx;
11464 child_ctx->parent_ctx = cloned_ctx;
11465 child_ctx->parent_gen = parent_ctx->parent_gen;
11467 child_ctx->parent_ctx = parent_ctx;
11468 child_ctx->parent_gen = parent_ctx->generation;
11470 get_ctx(child_ctx->parent_ctx);
11473 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
11475 mutex_unlock(&parent_ctx->mutex);
11477 perf_unpin_context(parent_ctx);
11478 put_ctx(parent_ctx);
11484 * Initialize the perf_event context in task_struct
11486 int perf_event_init_task(struct task_struct *child)
11490 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
11491 mutex_init(&child->perf_event_mutex);
11492 INIT_LIST_HEAD(&child->perf_event_list);
11494 for_each_task_context_nr(ctxn) {
11495 ret = perf_event_init_context(child, ctxn);
11497 perf_event_free_task(child);
11505 static void __init perf_event_init_all_cpus(void)
11507 struct swevent_htable *swhash;
11510 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
11512 for_each_possible_cpu(cpu) {
11513 swhash = &per_cpu(swevent_htable, cpu);
11514 mutex_init(&swhash->hlist_mutex);
11515 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
11517 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
11518 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
11520 #ifdef CONFIG_CGROUP_PERF
11521 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
11523 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
11527 void perf_swevent_init_cpu(unsigned int cpu)
11529 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
11531 mutex_lock(&swhash->hlist_mutex);
11532 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
11533 struct swevent_hlist *hlist;
11535 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
11537 rcu_assign_pointer(swhash->swevent_hlist, hlist);
11539 mutex_unlock(&swhash->hlist_mutex);
11542 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
11543 static void __perf_event_exit_context(void *__info)
11545 struct perf_event_context *ctx = __info;
11546 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
11547 struct perf_event *event;
11549 raw_spin_lock(&ctx->lock);
11550 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
11551 list_for_each_entry(event, &ctx->event_list, event_entry)
11552 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
11553 raw_spin_unlock(&ctx->lock);
11556 static void perf_event_exit_cpu_context(int cpu)
11558 struct perf_cpu_context *cpuctx;
11559 struct perf_event_context *ctx;
11562 mutex_lock(&pmus_lock);
11563 list_for_each_entry(pmu, &pmus, entry) {
11564 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11565 ctx = &cpuctx->ctx;
11567 mutex_lock(&ctx->mutex);
11568 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
11569 cpuctx->online = 0;
11570 mutex_unlock(&ctx->mutex);
11572 cpumask_clear_cpu(cpu, perf_online_mask);
11573 mutex_unlock(&pmus_lock);
11577 static void perf_event_exit_cpu_context(int cpu) { }
11581 int perf_event_init_cpu(unsigned int cpu)
11583 struct perf_cpu_context *cpuctx;
11584 struct perf_event_context *ctx;
11587 perf_swevent_init_cpu(cpu);
11589 mutex_lock(&pmus_lock);
11590 cpumask_set_cpu(cpu, perf_online_mask);
11591 list_for_each_entry(pmu, &pmus, entry) {
11592 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11593 ctx = &cpuctx->ctx;
11595 mutex_lock(&ctx->mutex);
11596 cpuctx->online = 1;
11597 mutex_unlock(&ctx->mutex);
11599 mutex_unlock(&pmus_lock);
11604 int perf_event_exit_cpu(unsigned int cpu)
11606 perf_event_exit_cpu_context(cpu);
11611 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
11615 for_each_online_cpu(cpu)
11616 perf_event_exit_cpu(cpu);
11622 * Run the perf reboot notifier at the very last possible moment so that
11623 * the generic watchdog code runs as long as possible.
11625 static struct notifier_block perf_reboot_notifier = {
11626 .notifier_call = perf_reboot,
11627 .priority = INT_MIN,
11630 void __init perf_event_init(void)
11634 idr_init(&pmu_idr);
11636 perf_event_init_all_cpus();
11637 init_srcu_struct(&pmus_srcu);
11638 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
11639 perf_pmu_register(&perf_cpu_clock, NULL, -1);
11640 perf_pmu_register(&perf_task_clock, NULL, -1);
11641 perf_tp_register();
11642 perf_event_init_cpu(smp_processor_id());
11643 register_reboot_notifier(&perf_reboot_notifier);
11645 ret = init_hw_breakpoint();
11646 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
11649 * Build time assertion that we keep the data_head at the intended
11650 * location. IOW, validation we got the __reserved[] size right.
11652 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
11656 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
11659 struct perf_pmu_events_attr *pmu_attr =
11660 container_of(attr, struct perf_pmu_events_attr, attr);
11662 if (pmu_attr->event_str)
11663 return sprintf(page, "%s\n", pmu_attr->event_str);
11667 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
11669 static int __init perf_event_sysfs_init(void)
11674 mutex_lock(&pmus_lock);
11676 ret = bus_register(&pmu_bus);
11680 list_for_each_entry(pmu, &pmus, entry) {
11681 if (!pmu->name || pmu->type < 0)
11684 ret = pmu_dev_alloc(pmu);
11685 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
11687 pmu_bus_running = 1;
11691 mutex_unlock(&pmus_lock);
11695 device_initcall(perf_event_sysfs_init);
11697 #ifdef CONFIG_CGROUP_PERF
11698 static struct cgroup_subsys_state *
11699 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
11701 struct perf_cgroup *jc;
11703 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
11705 return ERR_PTR(-ENOMEM);
11707 jc->info = alloc_percpu(struct perf_cgroup_info);
11710 return ERR_PTR(-ENOMEM);
11716 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
11718 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
11720 free_percpu(jc->info);
11724 static int __perf_cgroup_move(void *info)
11726 struct task_struct *task = info;
11728 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
11733 static void perf_cgroup_attach(struct cgroup_taskset *tset)
11735 struct task_struct *task;
11736 struct cgroup_subsys_state *css;
11738 cgroup_taskset_for_each(task, css, tset)
11739 task_function_call(task, __perf_cgroup_move, task);
11742 struct cgroup_subsys perf_event_cgrp_subsys = {
11743 .css_alloc = perf_cgroup_css_alloc,
11744 .css_free = perf_cgroup_css_free,
11745 .attach = perf_cgroup_attach,
11747 * Implicitly enable on dfl hierarchy so that perf events can
11748 * always be filtered by cgroup2 path as long as perf_event
11749 * controller is not mounted on a legacy hierarchy.
11751 .implicit_on_dfl = true,
11754 #endif /* CONFIG_CGROUP_PERF */