1 // SPDX-License-Identifier: GPL-2.0
3 * Performance events core code:
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/rculist.h>
32 #include <linux/uaccess.h>
33 #include <linux/syscalls.h>
34 #include <linux/anon_inodes.h>
35 #include <linux/kernel_stat.h>
36 #include <linux/cgroup.h>
37 #include <linux/perf_event.h>
38 #include <linux/trace_events.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/module.h>
42 #include <linux/mman.h>
43 #include <linux/compat.h>
44 #include <linux/bpf.h>
45 #include <linux/filter.h>
46 #include <linux/namei.h>
47 #include <linux/parser.h>
48 #include <linux/sched/clock.h>
49 #include <linux/sched/mm.h>
50 #include <linux/proc_ns.h>
51 #include <linux/mount.h>
55 #include <asm/irq_regs.h>
57 typedef int (*remote_function_f)(void *);
59 struct remote_function_call {
60 struct task_struct *p;
61 remote_function_f func;
66 static void remote_function(void *data)
68 struct remote_function_call *tfc = data;
69 struct task_struct *p = tfc->p;
73 if (task_cpu(p) != smp_processor_id())
77 * Now that we're on right CPU with IRQs disabled, we can test
78 * if we hit the right task without races.
81 tfc->ret = -ESRCH; /* No such (running) process */
86 tfc->ret = tfc->func(tfc->info);
90 * task_function_call - call a function on the cpu on which a task runs
91 * @p: the task to evaluate
92 * @func: the function to be called
93 * @info: the function call argument
95 * Calls the function @func when the task is currently running. This might
96 * be on the current CPU, which just calls the function directly
98 * returns: @func return value, or
99 * -ESRCH - when the process isn't running
100 * -EAGAIN - when the process moved away
103 task_function_call(struct task_struct *p, remote_function_f func, void *info)
105 struct remote_function_call data = {
114 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
117 } while (ret == -EAGAIN);
123 * cpu_function_call - call a function on the cpu
124 * @func: the function to be called
125 * @info: the function call argument
127 * Calls the function @func on the remote cpu.
129 * returns: @func return value or -ENXIO when the cpu is offline
131 static int cpu_function_call(int cpu, remote_function_f func, void *info)
133 struct remote_function_call data = {
137 .ret = -ENXIO, /* No such CPU */
140 smp_call_function_single(cpu, remote_function, &data, 1);
145 static inline struct perf_cpu_context *
146 __get_cpu_context(struct perf_event_context *ctx)
148 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
151 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
152 struct perf_event_context *ctx)
154 raw_spin_lock(&cpuctx->ctx.lock);
156 raw_spin_lock(&ctx->lock);
159 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
160 struct perf_event_context *ctx)
163 raw_spin_unlock(&ctx->lock);
164 raw_spin_unlock(&cpuctx->ctx.lock);
167 #define TASK_TOMBSTONE ((void *)-1L)
169 static bool is_kernel_event(struct perf_event *event)
171 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
175 * On task ctx scheduling...
177 * When !ctx->nr_events a task context will not be scheduled. This means
178 * we can disable the scheduler hooks (for performance) without leaving
179 * pending task ctx state.
181 * This however results in two special cases:
183 * - removing the last event from a task ctx; this is relatively straight
184 * forward and is done in __perf_remove_from_context.
186 * - adding the first event to a task ctx; this is tricky because we cannot
187 * rely on ctx->is_active and therefore cannot use event_function_call().
188 * See perf_install_in_context().
190 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
193 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
194 struct perf_event_context *, void *);
196 struct event_function_struct {
197 struct perf_event *event;
202 static int event_function(void *info)
204 struct event_function_struct *efs = info;
205 struct perf_event *event = efs->event;
206 struct perf_event_context *ctx = event->ctx;
207 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
208 struct perf_event_context *task_ctx = cpuctx->task_ctx;
211 lockdep_assert_irqs_disabled();
213 perf_ctx_lock(cpuctx, task_ctx);
215 * Since we do the IPI call without holding ctx->lock things can have
216 * changed, double check we hit the task we set out to hit.
219 if (ctx->task != current) {
225 * We only use event_function_call() on established contexts,
226 * and event_function() is only ever called when active (or
227 * rather, we'll have bailed in task_function_call() or the
228 * above ctx->task != current test), therefore we must have
229 * ctx->is_active here.
231 WARN_ON_ONCE(!ctx->is_active);
233 * And since we have ctx->is_active, cpuctx->task_ctx must
236 WARN_ON_ONCE(task_ctx != ctx);
238 WARN_ON_ONCE(&cpuctx->ctx != ctx);
241 efs->func(event, cpuctx, ctx, efs->data);
243 perf_ctx_unlock(cpuctx, task_ctx);
248 static void event_function_call(struct perf_event *event, event_f func, void *data)
250 struct perf_event_context *ctx = event->ctx;
251 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
252 struct event_function_struct efs = {
258 if (!event->parent) {
260 * If this is a !child event, we must hold ctx::mutex to
261 * stabilize the the event->ctx relation. See
262 * perf_event_ctx_lock().
264 lockdep_assert_held(&ctx->mutex);
268 cpu_function_call(event->cpu, event_function, &efs);
272 if (task == TASK_TOMBSTONE)
276 if (!task_function_call(task, event_function, &efs))
279 raw_spin_lock_irq(&ctx->lock);
281 * Reload the task pointer, it might have been changed by
282 * a concurrent perf_event_context_sched_out().
285 if (task == TASK_TOMBSTONE) {
286 raw_spin_unlock_irq(&ctx->lock);
289 if (ctx->is_active) {
290 raw_spin_unlock_irq(&ctx->lock);
293 func(event, NULL, ctx, data);
294 raw_spin_unlock_irq(&ctx->lock);
298 * Similar to event_function_call() + event_function(), but hard assumes IRQs
299 * are already disabled and we're on the right CPU.
301 static void event_function_local(struct perf_event *event, event_f func, void *data)
303 struct perf_event_context *ctx = event->ctx;
304 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
305 struct task_struct *task = READ_ONCE(ctx->task);
306 struct perf_event_context *task_ctx = NULL;
308 lockdep_assert_irqs_disabled();
311 if (task == TASK_TOMBSTONE)
317 perf_ctx_lock(cpuctx, task_ctx);
320 if (task == TASK_TOMBSTONE)
325 * We must be either inactive or active and the right task,
326 * otherwise we're screwed, since we cannot IPI to somewhere
329 if (ctx->is_active) {
330 if (WARN_ON_ONCE(task != current))
333 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
337 WARN_ON_ONCE(&cpuctx->ctx != ctx);
340 func(event, cpuctx, ctx, data);
342 perf_ctx_unlock(cpuctx, task_ctx);
345 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
346 PERF_FLAG_FD_OUTPUT |\
347 PERF_FLAG_PID_CGROUP |\
348 PERF_FLAG_FD_CLOEXEC)
351 * branch priv levels that need permission checks
353 #define PERF_SAMPLE_BRANCH_PERM_PLM \
354 (PERF_SAMPLE_BRANCH_KERNEL |\
355 PERF_SAMPLE_BRANCH_HV)
358 EVENT_FLEXIBLE = 0x1,
361 /* see ctx_resched() for details */
363 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
367 * perf_sched_events : >0 events exist
368 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
371 static void perf_sched_delayed(struct work_struct *work);
372 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
373 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
374 static DEFINE_MUTEX(perf_sched_mutex);
375 static atomic_t perf_sched_count;
377 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
378 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
379 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
381 static atomic_t nr_mmap_events __read_mostly;
382 static atomic_t nr_comm_events __read_mostly;
383 static atomic_t nr_namespaces_events __read_mostly;
384 static atomic_t nr_task_events __read_mostly;
385 static atomic_t nr_freq_events __read_mostly;
386 static atomic_t nr_switch_events __read_mostly;
387 static atomic_t nr_ksymbol_events __read_mostly;
388 static atomic_t nr_bpf_events __read_mostly;
390 static LIST_HEAD(pmus);
391 static DEFINE_MUTEX(pmus_lock);
392 static struct srcu_struct pmus_srcu;
393 static cpumask_var_t perf_online_mask;
396 * perf event paranoia level:
397 * -1 - not paranoid at all
398 * 0 - disallow raw tracepoint access for unpriv
399 * 1 - disallow cpu events for unpriv
400 * 2 - disallow kernel profiling for unpriv
402 int sysctl_perf_event_paranoid __read_mostly = 2;
404 /* Minimum for 512 kiB + 1 user control page */
405 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
408 * max perf event sample rate
410 #define DEFAULT_MAX_SAMPLE_RATE 100000
411 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
412 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
414 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
416 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
417 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
419 static int perf_sample_allowed_ns __read_mostly =
420 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
422 static void update_perf_cpu_limits(void)
424 u64 tmp = perf_sample_period_ns;
426 tmp *= sysctl_perf_cpu_time_max_percent;
427 tmp = div_u64(tmp, 100);
431 WRITE_ONCE(perf_sample_allowed_ns, tmp);
434 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
436 int perf_proc_update_handler(struct ctl_table *table, int write,
437 void __user *buffer, size_t *lenp,
441 int perf_cpu = sysctl_perf_cpu_time_max_percent;
443 * If throttling is disabled don't allow the write:
445 if (write && (perf_cpu == 100 || perf_cpu == 0))
448 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
452 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
453 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
454 update_perf_cpu_limits();
459 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
461 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
462 void __user *buffer, size_t *lenp,
465 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
470 if (sysctl_perf_cpu_time_max_percent == 100 ||
471 sysctl_perf_cpu_time_max_percent == 0) {
473 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
474 WRITE_ONCE(perf_sample_allowed_ns, 0);
476 update_perf_cpu_limits();
483 * perf samples are done in some very critical code paths (NMIs).
484 * If they take too much CPU time, the system can lock up and not
485 * get any real work done. This will drop the sample rate when
486 * we detect that events are taking too long.
488 #define NR_ACCUMULATED_SAMPLES 128
489 static DEFINE_PER_CPU(u64, running_sample_length);
491 static u64 __report_avg;
492 static u64 __report_allowed;
494 static void perf_duration_warn(struct irq_work *w)
496 printk_ratelimited(KERN_INFO
497 "perf: interrupt took too long (%lld > %lld), lowering "
498 "kernel.perf_event_max_sample_rate to %d\n",
499 __report_avg, __report_allowed,
500 sysctl_perf_event_sample_rate);
503 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
505 void perf_sample_event_took(u64 sample_len_ns)
507 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
515 /* Decay the counter by 1 average sample. */
516 running_len = __this_cpu_read(running_sample_length);
517 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
518 running_len += sample_len_ns;
519 __this_cpu_write(running_sample_length, running_len);
522 * Note: this will be biased artifically low until we have
523 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
524 * from having to maintain a count.
526 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
527 if (avg_len <= max_len)
530 __report_avg = avg_len;
531 __report_allowed = max_len;
534 * Compute a throttle threshold 25% below the current duration.
536 avg_len += avg_len / 4;
537 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
543 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
544 WRITE_ONCE(max_samples_per_tick, max);
546 sysctl_perf_event_sample_rate = max * HZ;
547 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
549 if (!irq_work_queue(&perf_duration_work)) {
550 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
551 "kernel.perf_event_max_sample_rate to %d\n",
552 __report_avg, __report_allowed,
553 sysctl_perf_event_sample_rate);
557 static atomic64_t perf_event_id;
559 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
560 enum event_type_t event_type);
562 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
563 enum event_type_t event_type,
564 struct task_struct *task);
566 static void update_context_time(struct perf_event_context *ctx);
567 static u64 perf_event_time(struct perf_event *event);
569 void __weak perf_event_print_debug(void) { }
571 extern __weak const char *perf_pmu_name(void)
576 static inline u64 perf_clock(void)
578 return local_clock();
581 static inline u64 perf_event_clock(struct perf_event *event)
583 return event->clock();
587 * State based event timekeeping...
589 * The basic idea is to use event->state to determine which (if any) time
590 * fields to increment with the current delta. This means we only need to
591 * update timestamps when we change state or when they are explicitly requested
594 * Event groups make things a little more complicated, but not terribly so. The
595 * rules for a group are that if the group leader is OFF the entire group is
596 * OFF, irrespecive of what the group member states are. This results in
597 * __perf_effective_state().
599 * A futher ramification is that when a group leader flips between OFF and
600 * !OFF, we need to update all group member times.
603 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
604 * need to make sure the relevant context time is updated before we try and
605 * update our timestamps.
608 static __always_inline enum perf_event_state
609 __perf_effective_state(struct perf_event *event)
611 struct perf_event *leader = event->group_leader;
613 if (leader->state <= PERF_EVENT_STATE_OFF)
614 return leader->state;
619 static __always_inline void
620 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
622 enum perf_event_state state = __perf_effective_state(event);
623 u64 delta = now - event->tstamp;
625 *enabled = event->total_time_enabled;
626 if (state >= PERF_EVENT_STATE_INACTIVE)
629 *running = event->total_time_running;
630 if (state >= PERF_EVENT_STATE_ACTIVE)
634 static void perf_event_update_time(struct perf_event *event)
636 u64 now = perf_event_time(event);
638 __perf_update_times(event, now, &event->total_time_enabled,
639 &event->total_time_running);
643 static void perf_event_update_sibling_time(struct perf_event *leader)
645 struct perf_event *sibling;
647 for_each_sibling_event(sibling, leader)
648 perf_event_update_time(sibling);
652 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
654 if (event->state == state)
657 perf_event_update_time(event);
659 * If a group leader gets enabled/disabled all its siblings
662 if ((event->state < 0) ^ (state < 0))
663 perf_event_update_sibling_time(event);
665 WRITE_ONCE(event->state, state);
668 #ifdef CONFIG_CGROUP_PERF
671 perf_cgroup_match(struct perf_event *event)
673 struct perf_event_context *ctx = event->ctx;
674 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
676 /* @event doesn't care about cgroup */
680 /* wants specific cgroup scope but @cpuctx isn't associated with any */
685 * Cgroup scoping is recursive. An event enabled for a cgroup is
686 * also enabled for all its descendant cgroups. If @cpuctx's
687 * cgroup is a descendant of @event's (the test covers identity
688 * case), it's a match.
690 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
691 event->cgrp->css.cgroup);
694 static inline void perf_detach_cgroup(struct perf_event *event)
696 css_put(&event->cgrp->css);
700 static inline int is_cgroup_event(struct perf_event *event)
702 return event->cgrp != NULL;
705 static inline u64 perf_cgroup_event_time(struct perf_event *event)
707 struct perf_cgroup_info *t;
709 t = per_cpu_ptr(event->cgrp->info, event->cpu);
713 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
715 struct perf_cgroup_info *info;
720 info = this_cpu_ptr(cgrp->info);
722 info->time += now - info->timestamp;
723 info->timestamp = now;
726 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
728 struct perf_cgroup *cgrp = cpuctx->cgrp;
729 struct cgroup_subsys_state *css;
732 for (css = &cgrp->css; css; css = css->parent) {
733 cgrp = container_of(css, struct perf_cgroup, css);
734 __update_cgrp_time(cgrp);
739 static inline void update_cgrp_time_from_event(struct perf_event *event)
741 struct perf_cgroup *cgrp;
744 * ensure we access cgroup data only when needed and
745 * when we know the cgroup is pinned (css_get)
747 if (!is_cgroup_event(event))
750 cgrp = perf_cgroup_from_task(current, event->ctx);
752 * Do not update time when cgroup is not active
754 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
755 __update_cgrp_time(event->cgrp);
759 perf_cgroup_set_timestamp(struct task_struct *task,
760 struct perf_event_context *ctx)
762 struct perf_cgroup *cgrp;
763 struct perf_cgroup_info *info;
764 struct cgroup_subsys_state *css;
767 * ctx->lock held by caller
768 * ensure we do not access cgroup data
769 * unless we have the cgroup pinned (css_get)
771 if (!task || !ctx->nr_cgroups)
774 cgrp = perf_cgroup_from_task(task, ctx);
776 for (css = &cgrp->css; css; css = css->parent) {
777 cgrp = container_of(css, struct perf_cgroup, css);
778 info = this_cpu_ptr(cgrp->info);
779 info->timestamp = ctx->timestamp;
783 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
785 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
786 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
789 * reschedule events based on the cgroup constraint of task.
791 * mode SWOUT : schedule out everything
792 * mode SWIN : schedule in based on cgroup for next
794 static void perf_cgroup_switch(struct task_struct *task, int mode)
796 struct perf_cpu_context *cpuctx;
797 struct list_head *list;
801 * Disable interrupts and preemption to avoid this CPU's
802 * cgrp_cpuctx_entry to change under us.
804 local_irq_save(flags);
806 list = this_cpu_ptr(&cgrp_cpuctx_list);
807 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
808 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
810 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
811 perf_pmu_disable(cpuctx->ctx.pmu);
813 if (mode & PERF_CGROUP_SWOUT) {
814 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
816 * must not be done before ctxswout due
817 * to event_filter_match() in event_sched_out()
822 if (mode & PERF_CGROUP_SWIN) {
823 WARN_ON_ONCE(cpuctx->cgrp);
825 * set cgrp before ctxsw in to allow
826 * event_filter_match() to not have to pass
828 * we pass the cpuctx->ctx to perf_cgroup_from_task()
829 * because cgorup events are only per-cpu
831 cpuctx->cgrp = perf_cgroup_from_task(task,
833 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
835 perf_pmu_enable(cpuctx->ctx.pmu);
836 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
839 local_irq_restore(flags);
842 static inline void perf_cgroup_sched_out(struct task_struct *task,
843 struct task_struct *next)
845 struct perf_cgroup *cgrp1;
846 struct perf_cgroup *cgrp2 = NULL;
850 * we come here when we know perf_cgroup_events > 0
851 * we do not need to pass the ctx here because we know
852 * we are holding the rcu lock
854 cgrp1 = perf_cgroup_from_task(task, NULL);
855 cgrp2 = perf_cgroup_from_task(next, NULL);
858 * only schedule out current cgroup events if we know
859 * that we are switching to a different cgroup. Otherwise,
860 * do no touch the cgroup events.
863 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
868 static inline void perf_cgroup_sched_in(struct task_struct *prev,
869 struct task_struct *task)
871 struct perf_cgroup *cgrp1;
872 struct perf_cgroup *cgrp2 = NULL;
876 * we come here when we know perf_cgroup_events > 0
877 * we do not need to pass the ctx here because we know
878 * we are holding the rcu lock
880 cgrp1 = perf_cgroup_from_task(task, NULL);
881 cgrp2 = perf_cgroup_from_task(prev, NULL);
884 * only need to schedule in cgroup events if we are changing
885 * cgroup during ctxsw. Cgroup events were not scheduled
886 * out of ctxsw out if that was not the case.
889 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
894 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
895 struct perf_event_attr *attr,
896 struct perf_event *group_leader)
898 struct perf_cgroup *cgrp;
899 struct cgroup_subsys_state *css;
900 struct fd f = fdget(fd);
906 css = css_tryget_online_from_dir(f.file->f_path.dentry,
907 &perf_event_cgrp_subsys);
913 cgrp = container_of(css, struct perf_cgroup, css);
917 * all events in a group must monitor
918 * the same cgroup because a task belongs
919 * to only one perf cgroup at a time
921 if (group_leader && group_leader->cgrp != cgrp) {
922 perf_detach_cgroup(event);
931 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
933 struct perf_cgroup_info *t;
934 t = per_cpu_ptr(event->cgrp->info, event->cpu);
935 event->shadow_ctx_time = now - t->timestamp;
939 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
940 * cleared when last cgroup event is removed.
943 list_update_cgroup_event(struct perf_event *event,
944 struct perf_event_context *ctx, bool add)
946 struct perf_cpu_context *cpuctx;
947 struct list_head *cpuctx_entry;
949 if (!is_cgroup_event(event))
953 * Because cgroup events are always per-cpu events,
954 * this will always be called from the right CPU.
956 cpuctx = __get_cpu_context(ctx);
959 * Since setting cpuctx->cgrp is conditional on the current @cgrp
960 * matching the event's cgroup, we must do this for every new event,
961 * because if the first would mismatch, the second would not try again
962 * and we would leave cpuctx->cgrp unset.
964 if (add && !cpuctx->cgrp) {
965 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
967 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
971 if (add && ctx->nr_cgroups++)
973 else if (!add && --ctx->nr_cgroups)
976 /* no cgroup running */
980 cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
982 list_add(cpuctx_entry, this_cpu_ptr(&cgrp_cpuctx_list));
984 list_del(cpuctx_entry);
987 #else /* !CONFIG_CGROUP_PERF */
990 perf_cgroup_match(struct perf_event *event)
995 static inline void perf_detach_cgroup(struct perf_event *event)
998 static inline int is_cgroup_event(struct perf_event *event)
1003 static inline void update_cgrp_time_from_event(struct perf_event *event)
1007 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1011 static inline void perf_cgroup_sched_out(struct task_struct *task,
1012 struct task_struct *next)
1016 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1017 struct task_struct *task)
1021 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1022 struct perf_event_attr *attr,
1023 struct perf_event *group_leader)
1029 perf_cgroup_set_timestamp(struct task_struct *task,
1030 struct perf_event_context *ctx)
1035 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1040 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1044 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1050 list_update_cgroup_event(struct perf_event *event,
1051 struct perf_event_context *ctx, bool add)
1058 * set default to be dependent on timer tick just
1059 * like original code
1061 #define PERF_CPU_HRTIMER (1000 / HZ)
1063 * function must be called with interrupts disabled
1065 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1067 struct perf_cpu_context *cpuctx;
1070 lockdep_assert_irqs_disabled();
1072 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1073 rotations = perf_rotate_context(cpuctx);
1075 raw_spin_lock(&cpuctx->hrtimer_lock);
1077 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1079 cpuctx->hrtimer_active = 0;
1080 raw_spin_unlock(&cpuctx->hrtimer_lock);
1082 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1085 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1087 struct hrtimer *timer = &cpuctx->hrtimer;
1088 struct pmu *pmu = cpuctx->ctx.pmu;
1091 /* no multiplexing needed for SW PMU */
1092 if (pmu->task_ctx_nr == perf_sw_context)
1096 * check default is sane, if not set then force to
1097 * default interval (1/tick)
1099 interval = pmu->hrtimer_interval_ms;
1101 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1103 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1105 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1106 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
1107 timer->function = perf_mux_hrtimer_handler;
1110 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1112 struct hrtimer *timer = &cpuctx->hrtimer;
1113 struct pmu *pmu = cpuctx->ctx.pmu;
1114 unsigned long flags;
1116 /* not for SW PMU */
1117 if (pmu->task_ctx_nr == perf_sw_context)
1120 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1121 if (!cpuctx->hrtimer_active) {
1122 cpuctx->hrtimer_active = 1;
1123 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1124 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
1126 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1131 void perf_pmu_disable(struct pmu *pmu)
1133 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1135 pmu->pmu_disable(pmu);
1138 void perf_pmu_enable(struct pmu *pmu)
1140 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1142 pmu->pmu_enable(pmu);
1145 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1148 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1149 * perf_event_task_tick() are fully serialized because they're strictly cpu
1150 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1151 * disabled, while perf_event_task_tick is called from IRQ context.
1153 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1155 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1157 lockdep_assert_irqs_disabled();
1159 WARN_ON(!list_empty(&ctx->active_ctx_list));
1161 list_add(&ctx->active_ctx_list, head);
1164 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1166 lockdep_assert_irqs_disabled();
1168 WARN_ON(list_empty(&ctx->active_ctx_list));
1170 list_del_init(&ctx->active_ctx_list);
1173 static void get_ctx(struct perf_event_context *ctx)
1175 refcount_inc(&ctx->refcount);
1178 static void free_ctx(struct rcu_head *head)
1180 struct perf_event_context *ctx;
1182 ctx = container_of(head, struct perf_event_context, rcu_head);
1183 kfree(ctx->task_ctx_data);
1187 static void put_ctx(struct perf_event_context *ctx)
1189 if (refcount_dec_and_test(&ctx->refcount)) {
1190 if (ctx->parent_ctx)
1191 put_ctx(ctx->parent_ctx);
1192 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1193 put_task_struct(ctx->task);
1194 call_rcu(&ctx->rcu_head, free_ctx);
1199 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1200 * perf_pmu_migrate_context() we need some magic.
1202 * Those places that change perf_event::ctx will hold both
1203 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1205 * Lock ordering is by mutex address. There are two other sites where
1206 * perf_event_context::mutex nests and those are:
1208 * - perf_event_exit_task_context() [ child , 0 ]
1209 * perf_event_exit_event()
1210 * put_event() [ parent, 1 ]
1212 * - perf_event_init_context() [ parent, 0 ]
1213 * inherit_task_group()
1216 * perf_event_alloc()
1218 * perf_try_init_event() [ child , 1 ]
1220 * While it appears there is an obvious deadlock here -- the parent and child
1221 * nesting levels are inverted between the two. This is in fact safe because
1222 * life-time rules separate them. That is an exiting task cannot fork, and a
1223 * spawning task cannot (yet) exit.
1225 * But remember that that these are parent<->child context relations, and
1226 * migration does not affect children, therefore these two orderings should not
1229 * The change in perf_event::ctx does not affect children (as claimed above)
1230 * because the sys_perf_event_open() case will install a new event and break
1231 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1232 * concerned with cpuctx and that doesn't have children.
1234 * The places that change perf_event::ctx will issue:
1236 * perf_remove_from_context();
1237 * synchronize_rcu();
1238 * perf_install_in_context();
1240 * to affect the change. The remove_from_context() + synchronize_rcu() should
1241 * quiesce the event, after which we can install it in the new location. This
1242 * means that only external vectors (perf_fops, prctl) can perturb the event
1243 * while in transit. Therefore all such accessors should also acquire
1244 * perf_event_context::mutex to serialize against this.
1246 * However; because event->ctx can change while we're waiting to acquire
1247 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1252 * task_struct::perf_event_mutex
1253 * perf_event_context::mutex
1254 * perf_event::child_mutex;
1255 * perf_event_context::lock
1256 * perf_event::mmap_mutex
1258 * perf_addr_filters_head::lock
1262 * cpuctx->mutex / perf_event_context::mutex
1264 static struct perf_event_context *
1265 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1267 struct perf_event_context *ctx;
1271 ctx = READ_ONCE(event->ctx);
1272 if (!refcount_inc_not_zero(&ctx->refcount)) {
1278 mutex_lock_nested(&ctx->mutex, nesting);
1279 if (event->ctx != ctx) {
1280 mutex_unlock(&ctx->mutex);
1288 static inline struct perf_event_context *
1289 perf_event_ctx_lock(struct perf_event *event)
1291 return perf_event_ctx_lock_nested(event, 0);
1294 static void perf_event_ctx_unlock(struct perf_event *event,
1295 struct perf_event_context *ctx)
1297 mutex_unlock(&ctx->mutex);
1302 * This must be done under the ctx->lock, such as to serialize against
1303 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1304 * calling scheduler related locks and ctx->lock nests inside those.
1306 static __must_check struct perf_event_context *
1307 unclone_ctx(struct perf_event_context *ctx)
1309 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1311 lockdep_assert_held(&ctx->lock);
1314 ctx->parent_ctx = NULL;
1320 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1325 * only top level events have the pid namespace they were created in
1328 event = event->parent;
1330 nr = __task_pid_nr_ns(p, type, event->ns);
1331 /* avoid -1 if it is idle thread or runs in another ns */
1332 if (!nr && !pid_alive(p))
1337 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1339 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1342 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1344 return perf_event_pid_type(event, p, PIDTYPE_PID);
1348 * If we inherit events we want to return the parent event id
1351 static u64 primary_event_id(struct perf_event *event)
1356 id = event->parent->id;
1362 * Get the perf_event_context for a task and lock it.
1364 * This has to cope with with the fact that until it is locked,
1365 * the context could get moved to another task.
1367 static struct perf_event_context *
1368 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1370 struct perf_event_context *ctx;
1374 * One of the few rules of preemptible RCU is that one cannot do
1375 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1376 * part of the read side critical section was irqs-enabled -- see
1377 * rcu_read_unlock_special().
1379 * Since ctx->lock nests under rq->lock we must ensure the entire read
1380 * side critical section has interrupts disabled.
1382 local_irq_save(*flags);
1384 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1387 * If this context is a clone of another, it might
1388 * get swapped for another underneath us by
1389 * perf_event_task_sched_out, though the
1390 * rcu_read_lock() protects us from any context
1391 * getting freed. Lock the context and check if it
1392 * got swapped before we could get the lock, and retry
1393 * if so. If we locked the right context, then it
1394 * can't get swapped on us any more.
1396 raw_spin_lock(&ctx->lock);
1397 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1398 raw_spin_unlock(&ctx->lock);
1400 local_irq_restore(*flags);
1404 if (ctx->task == TASK_TOMBSTONE ||
1405 !refcount_inc_not_zero(&ctx->refcount)) {
1406 raw_spin_unlock(&ctx->lock);
1409 WARN_ON_ONCE(ctx->task != task);
1414 local_irq_restore(*flags);
1419 * Get the context for a task and increment its pin_count so it
1420 * can't get swapped to another task. This also increments its
1421 * reference count so that the context can't get freed.
1423 static struct perf_event_context *
1424 perf_pin_task_context(struct task_struct *task, int ctxn)
1426 struct perf_event_context *ctx;
1427 unsigned long flags;
1429 ctx = perf_lock_task_context(task, ctxn, &flags);
1432 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1437 static void perf_unpin_context(struct perf_event_context *ctx)
1439 unsigned long flags;
1441 raw_spin_lock_irqsave(&ctx->lock, flags);
1443 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1447 * Update the record of the current time in a context.
1449 static void update_context_time(struct perf_event_context *ctx)
1451 u64 now = perf_clock();
1453 ctx->time += now - ctx->timestamp;
1454 ctx->timestamp = now;
1457 static u64 perf_event_time(struct perf_event *event)
1459 struct perf_event_context *ctx = event->ctx;
1461 if (is_cgroup_event(event))
1462 return perf_cgroup_event_time(event);
1464 return ctx ? ctx->time : 0;
1467 static enum event_type_t get_event_type(struct perf_event *event)
1469 struct perf_event_context *ctx = event->ctx;
1470 enum event_type_t event_type;
1472 lockdep_assert_held(&ctx->lock);
1475 * It's 'group type', really, because if our group leader is
1476 * pinned, so are we.
1478 if (event->group_leader != event)
1479 event = event->group_leader;
1481 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1483 event_type |= EVENT_CPU;
1489 * Helper function to initialize event group nodes.
1491 static void init_event_group(struct perf_event *event)
1493 RB_CLEAR_NODE(&event->group_node);
1494 event->group_index = 0;
1498 * Extract pinned or flexible groups from the context
1499 * based on event attrs bits.
1501 static struct perf_event_groups *
1502 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1504 if (event->attr.pinned)
1505 return &ctx->pinned_groups;
1507 return &ctx->flexible_groups;
1511 * Helper function to initializes perf_event_group trees.
1513 static void perf_event_groups_init(struct perf_event_groups *groups)
1515 groups->tree = RB_ROOT;
1520 * Compare function for event groups;
1522 * Implements complex key that first sorts by CPU and then by virtual index
1523 * which provides ordering when rotating groups for the same CPU.
1526 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1528 if (left->cpu < right->cpu)
1530 if (left->cpu > right->cpu)
1533 if (left->group_index < right->group_index)
1535 if (left->group_index > right->group_index)
1542 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1543 * key (see perf_event_groups_less). This places it last inside the CPU
1547 perf_event_groups_insert(struct perf_event_groups *groups,
1548 struct perf_event *event)
1550 struct perf_event *node_event;
1551 struct rb_node *parent;
1552 struct rb_node **node;
1554 event->group_index = ++groups->index;
1556 node = &groups->tree.rb_node;
1561 node_event = container_of(*node, struct perf_event, group_node);
1563 if (perf_event_groups_less(event, node_event))
1564 node = &parent->rb_left;
1566 node = &parent->rb_right;
1569 rb_link_node(&event->group_node, parent, node);
1570 rb_insert_color(&event->group_node, &groups->tree);
1574 * Helper function to insert event into the pinned or flexible groups.
1577 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1579 struct perf_event_groups *groups;
1581 groups = get_event_groups(event, ctx);
1582 perf_event_groups_insert(groups, event);
1586 * Delete a group from a tree.
1589 perf_event_groups_delete(struct perf_event_groups *groups,
1590 struct perf_event *event)
1592 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1593 RB_EMPTY_ROOT(&groups->tree));
1595 rb_erase(&event->group_node, &groups->tree);
1596 init_event_group(event);
1600 * Helper function to delete event from its groups.
1603 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1605 struct perf_event_groups *groups;
1607 groups = get_event_groups(event, ctx);
1608 perf_event_groups_delete(groups, event);
1612 * Get the leftmost event in the @cpu subtree.
1614 static struct perf_event *
1615 perf_event_groups_first(struct perf_event_groups *groups, int cpu)
1617 struct perf_event *node_event = NULL, *match = NULL;
1618 struct rb_node *node = groups->tree.rb_node;
1621 node_event = container_of(node, struct perf_event, group_node);
1623 if (cpu < node_event->cpu) {
1624 node = node->rb_left;
1625 } else if (cpu > node_event->cpu) {
1626 node = node->rb_right;
1629 node = node->rb_left;
1637 * Like rb_entry_next_safe() for the @cpu subtree.
1639 static struct perf_event *
1640 perf_event_groups_next(struct perf_event *event)
1642 struct perf_event *next;
1644 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1645 if (next && next->cpu == event->cpu)
1652 * Iterate through the whole groups tree.
1654 #define perf_event_groups_for_each(event, groups) \
1655 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1656 typeof(*event), group_node); event; \
1657 event = rb_entry_safe(rb_next(&event->group_node), \
1658 typeof(*event), group_node))
1661 * Add an event from the lists for its context.
1662 * Must be called with ctx->mutex and ctx->lock held.
1665 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1667 lockdep_assert_held(&ctx->lock);
1669 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1670 event->attach_state |= PERF_ATTACH_CONTEXT;
1672 event->tstamp = perf_event_time(event);
1675 * If we're a stand alone event or group leader, we go to the context
1676 * list, group events are kept attached to the group so that
1677 * perf_group_detach can, at all times, locate all siblings.
1679 if (event->group_leader == event) {
1680 event->group_caps = event->event_caps;
1681 add_event_to_groups(event, ctx);
1684 list_update_cgroup_event(event, ctx, true);
1686 list_add_rcu(&event->event_entry, &ctx->event_list);
1688 if (event->attr.inherit_stat)
1695 * Initialize event state based on the perf_event_attr::disabled.
1697 static inline void perf_event__state_init(struct perf_event *event)
1699 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1700 PERF_EVENT_STATE_INACTIVE;
1703 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1705 int entry = sizeof(u64); /* value */
1709 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1710 size += sizeof(u64);
1712 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1713 size += sizeof(u64);
1715 if (event->attr.read_format & PERF_FORMAT_ID)
1716 entry += sizeof(u64);
1718 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1720 size += sizeof(u64);
1724 event->read_size = size;
1727 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1729 struct perf_sample_data *data;
1732 if (sample_type & PERF_SAMPLE_IP)
1733 size += sizeof(data->ip);
1735 if (sample_type & PERF_SAMPLE_ADDR)
1736 size += sizeof(data->addr);
1738 if (sample_type & PERF_SAMPLE_PERIOD)
1739 size += sizeof(data->period);
1741 if (sample_type & PERF_SAMPLE_WEIGHT)
1742 size += sizeof(data->weight);
1744 if (sample_type & PERF_SAMPLE_READ)
1745 size += event->read_size;
1747 if (sample_type & PERF_SAMPLE_DATA_SRC)
1748 size += sizeof(data->data_src.val);
1750 if (sample_type & PERF_SAMPLE_TRANSACTION)
1751 size += sizeof(data->txn);
1753 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1754 size += sizeof(data->phys_addr);
1756 event->header_size = size;
1760 * Called at perf_event creation and when events are attached/detached from a
1763 static void perf_event__header_size(struct perf_event *event)
1765 __perf_event_read_size(event,
1766 event->group_leader->nr_siblings);
1767 __perf_event_header_size(event, event->attr.sample_type);
1770 static void perf_event__id_header_size(struct perf_event *event)
1772 struct perf_sample_data *data;
1773 u64 sample_type = event->attr.sample_type;
1776 if (sample_type & PERF_SAMPLE_TID)
1777 size += sizeof(data->tid_entry);
1779 if (sample_type & PERF_SAMPLE_TIME)
1780 size += sizeof(data->time);
1782 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1783 size += sizeof(data->id);
1785 if (sample_type & PERF_SAMPLE_ID)
1786 size += sizeof(data->id);
1788 if (sample_type & PERF_SAMPLE_STREAM_ID)
1789 size += sizeof(data->stream_id);
1791 if (sample_type & PERF_SAMPLE_CPU)
1792 size += sizeof(data->cpu_entry);
1794 event->id_header_size = size;
1797 static bool perf_event_validate_size(struct perf_event *event)
1800 * The values computed here will be over-written when we actually
1803 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1804 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1805 perf_event__id_header_size(event);
1808 * Sum the lot; should not exceed the 64k limit we have on records.
1809 * Conservative limit to allow for callchains and other variable fields.
1811 if (event->read_size + event->header_size +
1812 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1818 static void perf_group_attach(struct perf_event *event)
1820 struct perf_event *group_leader = event->group_leader, *pos;
1822 lockdep_assert_held(&event->ctx->lock);
1825 * We can have double attach due to group movement in perf_event_open.
1827 if (event->attach_state & PERF_ATTACH_GROUP)
1830 event->attach_state |= PERF_ATTACH_GROUP;
1832 if (group_leader == event)
1835 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1837 group_leader->group_caps &= event->event_caps;
1839 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1840 group_leader->nr_siblings++;
1842 perf_event__header_size(group_leader);
1844 for_each_sibling_event(pos, group_leader)
1845 perf_event__header_size(pos);
1849 * Remove an event from the lists for its context.
1850 * Must be called with ctx->mutex and ctx->lock held.
1853 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1855 WARN_ON_ONCE(event->ctx != ctx);
1856 lockdep_assert_held(&ctx->lock);
1859 * We can have double detach due to exit/hot-unplug + close.
1861 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1864 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1866 list_update_cgroup_event(event, ctx, false);
1869 if (event->attr.inherit_stat)
1872 list_del_rcu(&event->event_entry);
1874 if (event->group_leader == event)
1875 del_event_from_groups(event, ctx);
1878 * If event was in error state, then keep it
1879 * that way, otherwise bogus counts will be
1880 * returned on read(). The only way to get out
1881 * of error state is by explicit re-enabling
1884 if (event->state > PERF_EVENT_STATE_OFF)
1885 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
1890 static void perf_group_detach(struct perf_event *event)
1892 struct perf_event *sibling, *tmp;
1893 struct perf_event_context *ctx = event->ctx;
1895 lockdep_assert_held(&ctx->lock);
1898 * We can have double detach due to exit/hot-unplug + close.
1900 if (!(event->attach_state & PERF_ATTACH_GROUP))
1903 event->attach_state &= ~PERF_ATTACH_GROUP;
1906 * If this is a sibling, remove it from its group.
1908 if (event->group_leader != event) {
1909 list_del_init(&event->sibling_list);
1910 event->group_leader->nr_siblings--;
1915 * If this was a group event with sibling events then
1916 * upgrade the siblings to singleton events by adding them
1917 * to whatever list we are on.
1919 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
1921 sibling->group_leader = sibling;
1922 list_del_init(&sibling->sibling_list);
1924 /* Inherit group flags from the previous leader */
1925 sibling->group_caps = event->group_caps;
1927 if (!RB_EMPTY_NODE(&event->group_node)) {
1928 add_event_to_groups(sibling, event->ctx);
1930 if (sibling->state == PERF_EVENT_STATE_ACTIVE) {
1931 struct list_head *list = sibling->attr.pinned ?
1932 &ctx->pinned_active : &ctx->flexible_active;
1934 list_add_tail(&sibling->active_list, list);
1938 WARN_ON_ONCE(sibling->ctx != event->ctx);
1942 perf_event__header_size(event->group_leader);
1944 for_each_sibling_event(tmp, event->group_leader)
1945 perf_event__header_size(tmp);
1948 static bool is_orphaned_event(struct perf_event *event)
1950 return event->state == PERF_EVENT_STATE_DEAD;
1953 static inline int __pmu_filter_match(struct perf_event *event)
1955 struct pmu *pmu = event->pmu;
1956 return pmu->filter_match ? pmu->filter_match(event) : 1;
1960 * Check whether we should attempt to schedule an event group based on
1961 * PMU-specific filtering. An event group can consist of HW and SW events,
1962 * potentially with a SW leader, so we must check all the filters, to
1963 * determine whether a group is schedulable:
1965 static inline int pmu_filter_match(struct perf_event *event)
1967 struct perf_event *sibling;
1969 if (!__pmu_filter_match(event))
1972 for_each_sibling_event(sibling, event) {
1973 if (!__pmu_filter_match(sibling))
1981 event_filter_match(struct perf_event *event)
1983 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
1984 perf_cgroup_match(event) && pmu_filter_match(event);
1988 event_sched_out(struct perf_event *event,
1989 struct perf_cpu_context *cpuctx,
1990 struct perf_event_context *ctx)
1992 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
1994 WARN_ON_ONCE(event->ctx != ctx);
1995 lockdep_assert_held(&ctx->lock);
1997 if (event->state != PERF_EVENT_STATE_ACTIVE)
2001 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2002 * we can schedule events _OUT_ individually through things like
2003 * __perf_remove_from_context().
2005 list_del_init(&event->active_list);
2007 perf_pmu_disable(event->pmu);
2009 event->pmu->del(event, 0);
2012 if (READ_ONCE(event->pending_disable) >= 0) {
2013 WRITE_ONCE(event->pending_disable, -1);
2014 state = PERF_EVENT_STATE_OFF;
2016 perf_event_set_state(event, state);
2018 if (!is_software_event(event))
2019 cpuctx->active_oncpu--;
2020 if (!--ctx->nr_active)
2021 perf_event_ctx_deactivate(ctx);
2022 if (event->attr.freq && event->attr.sample_freq)
2024 if (event->attr.exclusive || !cpuctx->active_oncpu)
2025 cpuctx->exclusive = 0;
2027 perf_pmu_enable(event->pmu);
2031 group_sched_out(struct perf_event *group_event,
2032 struct perf_cpu_context *cpuctx,
2033 struct perf_event_context *ctx)
2035 struct perf_event *event;
2037 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2040 perf_pmu_disable(ctx->pmu);
2042 event_sched_out(group_event, cpuctx, ctx);
2045 * Schedule out siblings (if any):
2047 for_each_sibling_event(event, group_event)
2048 event_sched_out(event, cpuctx, ctx);
2050 perf_pmu_enable(ctx->pmu);
2052 if (group_event->attr.exclusive)
2053 cpuctx->exclusive = 0;
2056 #define DETACH_GROUP 0x01UL
2059 * Cross CPU call to remove a performance event
2061 * We disable the event on the hardware level first. After that we
2062 * remove it from the context list.
2065 __perf_remove_from_context(struct perf_event *event,
2066 struct perf_cpu_context *cpuctx,
2067 struct perf_event_context *ctx,
2070 unsigned long flags = (unsigned long)info;
2072 if (ctx->is_active & EVENT_TIME) {
2073 update_context_time(ctx);
2074 update_cgrp_time_from_cpuctx(cpuctx);
2077 event_sched_out(event, cpuctx, ctx);
2078 if (flags & DETACH_GROUP)
2079 perf_group_detach(event);
2080 list_del_event(event, ctx);
2082 if (!ctx->nr_events && ctx->is_active) {
2085 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2086 cpuctx->task_ctx = NULL;
2092 * Remove the event from a task's (or a CPU's) list of events.
2094 * If event->ctx is a cloned context, callers must make sure that
2095 * every task struct that event->ctx->task could possibly point to
2096 * remains valid. This is OK when called from perf_release since
2097 * that only calls us on the top-level context, which can't be a clone.
2098 * When called from perf_event_exit_task, it's OK because the
2099 * context has been detached from its task.
2101 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2103 struct perf_event_context *ctx = event->ctx;
2105 lockdep_assert_held(&ctx->mutex);
2107 event_function_call(event, __perf_remove_from_context, (void *)flags);
2110 * The above event_function_call() can NO-OP when it hits
2111 * TASK_TOMBSTONE. In that case we must already have been detached
2112 * from the context (by perf_event_exit_event()) but the grouping
2113 * might still be in-tact.
2115 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2116 if ((flags & DETACH_GROUP) &&
2117 (event->attach_state & PERF_ATTACH_GROUP)) {
2119 * Since in that case we cannot possibly be scheduled, simply
2122 raw_spin_lock_irq(&ctx->lock);
2123 perf_group_detach(event);
2124 raw_spin_unlock_irq(&ctx->lock);
2129 * Cross CPU call to disable a performance event
2131 static void __perf_event_disable(struct perf_event *event,
2132 struct perf_cpu_context *cpuctx,
2133 struct perf_event_context *ctx,
2136 if (event->state < PERF_EVENT_STATE_INACTIVE)
2139 if (ctx->is_active & EVENT_TIME) {
2140 update_context_time(ctx);
2141 update_cgrp_time_from_event(event);
2144 if (event == event->group_leader)
2145 group_sched_out(event, cpuctx, ctx);
2147 event_sched_out(event, cpuctx, ctx);
2149 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2155 * If event->ctx is a cloned context, callers must make sure that
2156 * every task struct that event->ctx->task could possibly point to
2157 * remains valid. This condition is satisifed when called through
2158 * perf_event_for_each_child or perf_event_for_each because they
2159 * hold the top-level event's child_mutex, so any descendant that
2160 * goes to exit will block in perf_event_exit_event().
2162 * When called from perf_pending_event it's OK because event->ctx
2163 * is the current context on this CPU and preemption is disabled,
2164 * hence we can't get into perf_event_task_sched_out for this context.
2166 static void _perf_event_disable(struct perf_event *event)
2168 struct perf_event_context *ctx = event->ctx;
2170 raw_spin_lock_irq(&ctx->lock);
2171 if (event->state <= PERF_EVENT_STATE_OFF) {
2172 raw_spin_unlock_irq(&ctx->lock);
2175 raw_spin_unlock_irq(&ctx->lock);
2177 event_function_call(event, __perf_event_disable, NULL);
2180 void perf_event_disable_local(struct perf_event *event)
2182 event_function_local(event, __perf_event_disable, NULL);
2186 * Strictly speaking kernel users cannot create groups and therefore this
2187 * interface does not need the perf_event_ctx_lock() magic.
2189 void perf_event_disable(struct perf_event *event)
2191 struct perf_event_context *ctx;
2193 ctx = perf_event_ctx_lock(event);
2194 _perf_event_disable(event);
2195 perf_event_ctx_unlock(event, ctx);
2197 EXPORT_SYMBOL_GPL(perf_event_disable);
2199 void perf_event_disable_inatomic(struct perf_event *event)
2201 WRITE_ONCE(event->pending_disable, smp_processor_id());
2202 /* can fail, see perf_pending_event_disable() */
2203 irq_work_queue(&event->pending);
2206 static void perf_set_shadow_time(struct perf_event *event,
2207 struct perf_event_context *ctx)
2210 * use the correct time source for the time snapshot
2212 * We could get by without this by leveraging the
2213 * fact that to get to this function, the caller
2214 * has most likely already called update_context_time()
2215 * and update_cgrp_time_xx() and thus both timestamp
2216 * are identical (or very close). Given that tstamp is,
2217 * already adjusted for cgroup, we could say that:
2218 * tstamp - ctx->timestamp
2220 * tstamp - cgrp->timestamp.
2222 * Then, in perf_output_read(), the calculation would
2223 * work with no changes because:
2224 * - event is guaranteed scheduled in
2225 * - no scheduled out in between
2226 * - thus the timestamp would be the same
2228 * But this is a bit hairy.
2230 * So instead, we have an explicit cgroup call to remain
2231 * within the time time source all along. We believe it
2232 * is cleaner and simpler to understand.
2234 if (is_cgroup_event(event))
2235 perf_cgroup_set_shadow_time(event, event->tstamp);
2237 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2240 #define MAX_INTERRUPTS (~0ULL)
2242 static void perf_log_throttle(struct perf_event *event, int enable);
2243 static void perf_log_itrace_start(struct perf_event *event);
2246 event_sched_in(struct perf_event *event,
2247 struct perf_cpu_context *cpuctx,
2248 struct perf_event_context *ctx)
2252 lockdep_assert_held(&ctx->lock);
2254 if (event->state <= PERF_EVENT_STATE_OFF)
2257 WRITE_ONCE(event->oncpu, smp_processor_id());
2259 * Order event::oncpu write to happen before the ACTIVE state is
2260 * visible. This allows perf_event_{stop,read}() to observe the correct
2261 * ->oncpu if it sees ACTIVE.
2264 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2267 * Unthrottle events, since we scheduled we might have missed several
2268 * ticks already, also for a heavily scheduling task there is little
2269 * guarantee it'll get a tick in a timely manner.
2271 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2272 perf_log_throttle(event, 1);
2273 event->hw.interrupts = 0;
2276 perf_pmu_disable(event->pmu);
2278 perf_set_shadow_time(event, ctx);
2280 perf_log_itrace_start(event);
2282 if (event->pmu->add(event, PERF_EF_START)) {
2283 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2289 if (!is_software_event(event))
2290 cpuctx->active_oncpu++;
2291 if (!ctx->nr_active++)
2292 perf_event_ctx_activate(ctx);
2293 if (event->attr.freq && event->attr.sample_freq)
2296 if (event->attr.exclusive)
2297 cpuctx->exclusive = 1;
2300 perf_pmu_enable(event->pmu);
2306 group_sched_in(struct perf_event *group_event,
2307 struct perf_cpu_context *cpuctx,
2308 struct perf_event_context *ctx)
2310 struct perf_event *event, *partial_group = NULL;
2311 struct pmu *pmu = ctx->pmu;
2313 if (group_event->state == PERF_EVENT_STATE_OFF)
2316 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2318 if (event_sched_in(group_event, cpuctx, ctx)) {
2319 pmu->cancel_txn(pmu);
2320 perf_mux_hrtimer_restart(cpuctx);
2325 * Schedule in siblings as one group (if any):
2327 for_each_sibling_event(event, group_event) {
2328 if (event_sched_in(event, cpuctx, ctx)) {
2329 partial_group = event;
2334 if (!pmu->commit_txn(pmu))
2339 * Groups can be scheduled in as one unit only, so undo any
2340 * partial group before returning:
2341 * The events up to the failed event are scheduled out normally.
2343 for_each_sibling_event(event, group_event) {
2344 if (event == partial_group)
2347 event_sched_out(event, cpuctx, ctx);
2349 event_sched_out(group_event, cpuctx, ctx);
2351 pmu->cancel_txn(pmu);
2353 perf_mux_hrtimer_restart(cpuctx);
2359 * Work out whether we can put this event group on the CPU now.
2361 static int group_can_go_on(struct perf_event *event,
2362 struct perf_cpu_context *cpuctx,
2366 * Groups consisting entirely of software events can always go on.
2368 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2371 * If an exclusive group is already on, no other hardware
2374 if (cpuctx->exclusive)
2377 * If this group is exclusive and there are already
2378 * events on the CPU, it can't go on.
2380 if (event->attr.exclusive && cpuctx->active_oncpu)
2383 * Otherwise, try to add it if all previous groups were able
2389 static void add_event_to_ctx(struct perf_event *event,
2390 struct perf_event_context *ctx)
2392 list_add_event(event, ctx);
2393 perf_group_attach(event);
2396 static void ctx_sched_out(struct perf_event_context *ctx,
2397 struct perf_cpu_context *cpuctx,
2398 enum event_type_t event_type);
2400 ctx_sched_in(struct perf_event_context *ctx,
2401 struct perf_cpu_context *cpuctx,
2402 enum event_type_t event_type,
2403 struct task_struct *task);
2405 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2406 struct perf_event_context *ctx,
2407 enum event_type_t event_type)
2409 if (!cpuctx->task_ctx)
2412 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2415 ctx_sched_out(ctx, cpuctx, event_type);
2418 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2419 struct perf_event_context *ctx,
2420 struct task_struct *task)
2422 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2424 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2425 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2427 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2431 * We want to maintain the following priority of scheduling:
2432 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2433 * - task pinned (EVENT_PINNED)
2434 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2435 * - task flexible (EVENT_FLEXIBLE).
2437 * In order to avoid unscheduling and scheduling back in everything every
2438 * time an event is added, only do it for the groups of equal priority and
2441 * This can be called after a batch operation on task events, in which case
2442 * event_type is a bit mask of the types of events involved. For CPU events,
2443 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2445 static void ctx_resched(struct perf_cpu_context *cpuctx,
2446 struct perf_event_context *task_ctx,
2447 enum event_type_t event_type)
2449 enum event_type_t ctx_event_type;
2450 bool cpu_event = !!(event_type & EVENT_CPU);
2453 * If pinned groups are involved, flexible groups also need to be
2456 if (event_type & EVENT_PINNED)
2457 event_type |= EVENT_FLEXIBLE;
2459 ctx_event_type = event_type & EVENT_ALL;
2461 perf_pmu_disable(cpuctx->ctx.pmu);
2463 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2466 * Decide which cpu ctx groups to schedule out based on the types
2467 * of events that caused rescheduling:
2468 * - EVENT_CPU: schedule out corresponding groups;
2469 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2470 * - otherwise, do nothing more.
2473 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2474 else if (ctx_event_type & EVENT_PINNED)
2475 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2477 perf_event_sched_in(cpuctx, task_ctx, current);
2478 perf_pmu_enable(cpuctx->ctx.pmu);
2482 * Cross CPU call to install and enable a performance event
2484 * Very similar to remote_function() + event_function() but cannot assume that
2485 * things like ctx->is_active and cpuctx->task_ctx are set.
2487 static int __perf_install_in_context(void *info)
2489 struct perf_event *event = info;
2490 struct perf_event_context *ctx = event->ctx;
2491 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2492 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2493 bool reprogram = true;
2496 raw_spin_lock(&cpuctx->ctx.lock);
2498 raw_spin_lock(&ctx->lock);
2501 reprogram = (ctx->task == current);
2504 * If the task is running, it must be running on this CPU,
2505 * otherwise we cannot reprogram things.
2507 * If its not running, we don't care, ctx->lock will
2508 * serialize against it becoming runnable.
2510 if (task_curr(ctx->task) && !reprogram) {
2515 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2516 } else if (task_ctx) {
2517 raw_spin_lock(&task_ctx->lock);
2520 #ifdef CONFIG_CGROUP_PERF
2521 if (is_cgroup_event(event)) {
2523 * If the current cgroup doesn't match the event's
2524 * cgroup, we should not try to schedule it.
2526 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2527 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2528 event->cgrp->css.cgroup);
2533 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2534 add_event_to_ctx(event, ctx);
2535 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2537 add_event_to_ctx(event, ctx);
2541 perf_ctx_unlock(cpuctx, task_ctx);
2547 * Attach a performance event to a context.
2549 * Very similar to event_function_call, see comment there.
2552 perf_install_in_context(struct perf_event_context *ctx,
2553 struct perf_event *event,
2556 struct task_struct *task = READ_ONCE(ctx->task);
2558 lockdep_assert_held(&ctx->mutex);
2560 if (event->cpu != -1)
2564 * Ensures that if we can observe event->ctx, both the event and ctx
2565 * will be 'complete'. See perf_iterate_sb_cpu().
2567 smp_store_release(&event->ctx, ctx);
2570 cpu_function_call(cpu, __perf_install_in_context, event);
2575 * Should not happen, we validate the ctx is still alive before calling.
2577 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2581 * Installing events is tricky because we cannot rely on ctx->is_active
2582 * to be set in case this is the nr_events 0 -> 1 transition.
2584 * Instead we use task_curr(), which tells us if the task is running.
2585 * However, since we use task_curr() outside of rq::lock, we can race
2586 * against the actual state. This means the result can be wrong.
2588 * If we get a false positive, we retry, this is harmless.
2590 * If we get a false negative, things are complicated. If we are after
2591 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2592 * value must be correct. If we're before, it doesn't matter since
2593 * perf_event_context_sched_in() will program the counter.
2595 * However, this hinges on the remote context switch having observed
2596 * our task->perf_event_ctxp[] store, such that it will in fact take
2597 * ctx::lock in perf_event_context_sched_in().
2599 * We do this by task_function_call(), if the IPI fails to hit the task
2600 * we know any future context switch of task must see the
2601 * perf_event_ctpx[] store.
2605 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2606 * task_cpu() load, such that if the IPI then does not find the task
2607 * running, a future context switch of that task must observe the
2612 if (!task_function_call(task, __perf_install_in_context, event))
2615 raw_spin_lock_irq(&ctx->lock);
2617 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2619 * Cannot happen because we already checked above (which also
2620 * cannot happen), and we hold ctx->mutex, which serializes us
2621 * against perf_event_exit_task_context().
2623 raw_spin_unlock_irq(&ctx->lock);
2627 * If the task is not running, ctx->lock will avoid it becoming so,
2628 * thus we can safely install the event.
2630 if (task_curr(task)) {
2631 raw_spin_unlock_irq(&ctx->lock);
2634 add_event_to_ctx(event, ctx);
2635 raw_spin_unlock_irq(&ctx->lock);
2639 * Cross CPU call to enable a performance event
2641 static void __perf_event_enable(struct perf_event *event,
2642 struct perf_cpu_context *cpuctx,
2643 struct perf_event_context *ctx,
2646 struct perf_event *leader = event->group_leader;
2647 struct perf_event_context *task_ctx;
2649 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2650 event->state <= PERF_EVENT_STATE_ERROR)
2654 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2656 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2658 if (!ctx->is_active)
2661 if (!event_filter_match(event)) {
2662 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2667 * If the event is in a group and isn't the group leader,
2668 * then don't put it on unless the group is on.
2670 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2671 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2675 task_ctx = cpuctx->task_ctx;
2677 WARN_ON_ONCE(task_ctx != ctx);
2679 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2685 * If event->ctx is a cloned context, callers must make sure that
2686 * every task struct that event->ctx->task could possibly point to
2687 * remains valid. This condition is satisfied when called through
2688 * perf_event_for_each_child or perf_event_for_each as described
2689 * for perf_event_disable.
2691 static void _perf_event_enable(struct perf_event *event)
2693 struct perf_event_context *ctx = event->ctx;
2695 raw_spin_lock_irq(&ctx->lock);
2696 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2697 event->state < PERF_EVENT_STATE_ERROR) {
2698 raw_spin_unlock_irq(&ctx->lock);
2703 * If the event is in error state, clear that first.
2705 * That way, if we see the event in error state below, we know that it
2706 * has gone back into error state, as distinct from the task having
2707 * been scheduled away before the cross-call arrived.
2709 if (event->state == PERF_EVENT_STATE_ERROR)
2710 event->state = PERF_EVENT_STATE_OFF;
2711 raw_spin_unlock_irq(&ctx->lock);
2713 event_function_call(event, __perf_event_enable, NULL);
2717 * See perf_event_disable();
2719 void perf_event_enable(struct perf_event *event)
2721 struct perf_event_context *ctx;
2723 ctx = perf_event_ctx_lock(event);
2724 _perf_event_enable(event);
2725 perf_event_ctx_unlock(event, ctx);
2727 EXPORT_SYMBOL_GPL(perf_event_enable);
2729 struct stop_event_data {
2730 struct perf_event *event;
2731 unsigned int restart;
2734 static int __perf_event_stop(void *info)
2736 struct stop_event_data *sd = info;
2737 struct perf_event *event = sd->event;
2739 /* if it's already INACTIVE, do nothing */
2740 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2743 /* matches smp_wmb() in event_sched_in() */
2747 * There is a window with interrupts enabled before we get here,
2748 * so we need to check again lest we try to stop another CPU's event.
2750 if (READ_ONCE(event->oncpu) != smp_processor_id())
2753 event->pmu->stop(event, PERF_EF_UPDATE);
2756 * May race with the actual stop (through perf_pmu_output_stop()),
2757 * but it is only used for events with AUX ring buffer, and such
2758 * events will refuse to restart because of rb::aux_mmap_count==0,
2759 * see comments in perf_aux_output_begin().
2761 * Since this is happening on an event-local CPU, no trace is lost
2765 event->pmu->start(event, 0);
2770 static int perf_event_stop(struct perf_event *event, int restart)
2772 struct stop_event_data sd = {
2779 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2782 /* matches smp_wmb() in event_sched_in() */
2786 * We only want to restart ACTIVE events, so if the event goes
2787 * inactive here (event->oncpu==-1), there's nothing more to do;
2788 * fall through with ret==-ENXIO.
2790 ret = cpu_function_call(READ_ONCE(event->oncpu),
2791 __perf_event_stop, &sd);
2792 } while (ret == -EAGAIN);
2798 * In order to contain the amount of racy and tricky in the address filter
2799 * configuration management, it is a two part process:
2801 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2802 * we update the addresses of corresponding vmas in
2803 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
2804 * (p2) when an event is scheduled in (pmu::add), it calls
2805 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2806 * if the generation has changed since the previous call.
2808 * If (p1) happens while the event is active, we restart it to force (p2).
2810 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2811 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2813 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2814 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2816 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2819 void perf_event_addr_filters_sync(struct perf_event *event)
2821 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2823 if (!has_addr_filter(event))
2826 raw_spin_lock(&ifh->lock);
2827 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2828 event->pmu->addr_filters_sync(event);
2829 event->hw.addr_filters_gen = event->addr_filters_gen;
2831 raw_spin_unlock(&ifh->lock);
2833 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2835 static int _perf_event_refresh(struct perf_event *event, int refresh)
2838 * not supported on inherited events
2840 if (event->attr.inherit || !is_sampling_event(event))
2843 atomic_add(refresh, &event->event_limit);
2844 _perf_event_enable(event);
2850 * See perf_event_disable()
2852 int perf_event_refresh(struct perf_event *event, int refresh)
2854 struct perf_event_context *ctx;
2857 ctx = perf_event_ctx_lock(event);
2858 ret = _perf_event_refresh(event, refresh);
2859 perf_event_ctx_unlock(event, ctx);
2863 EXPORT_SYMBOL_GPL(perf_event_refresh);
2865 static int perf_event_modify_breakpoint(struct perf_event *bp,
2866 struct perf_event_attr *attr)
2870 _perf_event_disable(bp);
2872 err = modify_user_hw_breakpoint_check(bp, attr, true);
2874 if (!bp->attr.disabled)
2875 _perf_event_enable(bp);
2880 static int perf_event_modify_attr(struct perf_event *event,
2881 struct perf_event_attr *attr)
2883 if (event->attr.type != attr->type)
2886 switch (event->attr.type) {
2887 case PERF_TYPE_BREAKPOINT:
2888 return perf_event_modify_breakpoint(event, attr);
2890 /* Place holder for future additions. */
2895 static void ctx_sched_out(struct perf_event_context *ctx,
2896 struct perf_cpu_context *cpuctx,
2897 enum event_type_t event_type)
2899 struct perf_event *event, *tmp;
2900 int is_active = ctx->is_active;
2902 lockdep_assert_held(&ctx->lock);
2904 if (likely(!ctx->nr_events)) {
2906 * See __perf_remove_from_context().
2908 WARN_ON_ONCE(ctx->is_active);
2910 WARN_ON_ONCE(cpuctx->task_ctx);
2914 ctx->is_active &= ~event_type;
2915 if (!(ctx->is_active & EVENT_ALL))
2919 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2920 if (!ctx->is_active)
2921 cpuctx->task_ctx = NULL;
2925 * Always update time if it was set; not only when it changes.
2926 * Otherwise we can 'forget' to update time for any but the last
2927 * context we sched out. For example:
2929 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
2930 * ctx_sched_out(.event_type = EVENT_PINNED)
2932 * would only update time for the pinned events.
2934 if (is_active & EVENT_TIME) {
2935 /* update (and stop) ctx time */
2936 update_context_time(ctx);
2937 update_cgrp_time_from_cpuctx(cpuctx);
2940 is_active ^= ctx->is_active; /* changed bits */
2942 if (!ctx->nr_active || !(is_active & EVENT_ALL))
2945 perf_pmu_disable(ctx->pmu);
2946 if (is_active & EVENT_PINNED) {
2947 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
2948 group_sched_out(event, cpuctx, ctx);
2951 if (is_active & EVENT_FLEXIBLE) {
2952 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
2953 group_sched_out(event, cpuctx, ctx);
2955 perf_pmu_enable(ctx->pmu);
2959 * Test whether two contexts are equivalent, i.e. whether they have both been
2960 * cloned from the same version of the same context.
2962 * Equivalence is measured using a generation number in the context that is
2963 * incremented on each modification to it; see unclone_ctx(), list_add_event()
2964 * and list_del_event().
2966 static int context_equiv(struct perf_event_context *ctx1,
2967 struct perf_event_context *ctx2)
2969 lockdep_assert_held(&ctx1->lock);
2970 lockdep_assert_held(&ctx2->lock);
2972 /* Pinning disables the swap optimization */
2973 if (ctx1->pin_count || ctx2->pin_count)
2976 /* If ctx1 is the parent of ctx2 */
2977 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2980 /* If ctx2 is the parent of ctx1 */
2981 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2985 * If ctx1 and ctx2 have the same parent; we flatten the parent
2986 * hierarchy, see perf_event_init_context().
2988 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2989 ctx1->parent_gen == ctx2->parent_gen)
2996 static void __perf_event_sync_stat(struct perf_event *event,
2997 struct perf_event *next_event)
3001 if (!event->attr.inherit_stat)
3005 * Update the event value, we cannot use perf_event_read()
3006 * because we're in the middle of a context switch and have IRQs
3007 * disabled, which upsets smp_call_function_single(), however
3008 * we know the event must be on the current CPU, therefore we
3009 * don't need to use it.
3011 if (event->state == PERF_EVENT_STATE_ACTIVE)
3012 event->pmu->read(event);
3014 perf_event_update_time(event);
3017 * In order to keep per-task stats reliable we need to flip the event
3018 * values when we flip the contexts.
3020 value = local64_read(&next_event->count);
3021 value = local64_xchg(&event->count, value);
3022 local64_set(&next_event->count, value);
3024 swap(event->total_time_enabled, next_event->total_time_enabled);
3025 swap(event->total_time_running, next_event->total_time_running);
3028 * Since we swizzled the values, update the user visible data too.
3030 perf_event_update_userpage(event);
3031 perf_event_update_userpage(next_event);
3034 static void perf_event_sync_stat(struct perf_event_context *ctx,
3035 struct perf_event_context *next_ctx)
3037 struct perf_event *event, *next_event;
3042 update_context_time(ctx);
3044 event = list_first_entry(&ctx->event_list,
3045 struct perf_event, event_entry);
3047 next_event = list_first_entry(&next_ctx->event_list,
3048 struct perf_event, event_entry);
3050 while (&event->event_entry != &ctx->event_list &&
3051 &next_event->event_entry != &next_ctx->event_list) {
3053 __perf_event_sync_stat(event, next_event);
3055 event = list_next_entry(event, event_entry);
3056 next_event = list_next_entry(next_event, event_entry);
3060 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3061 struct task_struct *next)
3063 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3064 struct perf_event_context *next_ctx;
3065 struct perf_event_context *parent, *next_parent;
3066 struct perf_cpu_context *cpuctx;
3072 cpuctx = __get_cpu_context(ctx);
3073 if (!cpuctx->task_ctx)
3077 next_ctx = next->perf_event_ctxp[ctxn];
3081 parent = rcu_dereference(ctx->parent_ctx);
3082 next_parent = rcu_dereference(next_ctx->parent_ctx);
3084 /* If neither context have a parent context; they cannot be clones. */
3085 if (!parent && !next_parent)
3088 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3090 * Looks like the two contexts are clones, so we might be
3091 * able to optimize the context switch. We lock both
3092 * contexts and check that they are clones under the
3093 * lock (including re-checking that neither has been
3094 * uncloned in the meantime). It doesn't matter which
3095 * order we take the locks because no other cpu could
3096 * be trying to lock both of these tasks.
3098 raw_spin_lock(&ctx->lock);
3099 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3100 if (context_equiv(ctx, next_ctx)) {
3101 WRITE_ONCE(ctx->task, next);
3102 WRITE_ONCE(next_ctx->task, task);
3104 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3107 * RCU_INIT_POINTER here is safe because we've not
3108 * modified the ctx and the above modification of
3109 * ctx->task and ctx->task_ctx_data are immaterial
3110 * since those values are always verified under
3111 * ctx->lock which we're now holding.
3113 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3114 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3118 perf_event_sync_stat(ctx, next_ctx);
3120 raw_spin_unlock(&next_ctx->lock);
3121 raw_spin_unlock(&ctx->lock);
3127 raw_spin_lock(&ctx->lock);
3128 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3129 raw_spin_unlock(&ctx->lock);
3133 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3135 void perf_sched_cb_dec(struct pmu *pmu)
3137 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3139 this_cpu_dec(perf_sched_cb_usages);
3141 if (!--cpuctx->sched_cb_usage)
3142 list_del(&cpuctx->sched_cb_entry);
3146 void perf_sched_cb_inc(struct pmu *pmu)
3148 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3150 if (!cpuctx->sched_cb_usage++)
3151 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3153 this_cpu_inc(perf_sched_cb_usages);
3157 * This function provides the context switch callback to the lower code
3158 * layer. It is invoked ONLY when the context switch callback is enabled.
3160 * This callback is relevant even to per-cpu events; for example multi event
3161 * PEBS requires this to provide PID/TID information. This requires we flush
3162 * all queued PEBS records before we context switch to a new task.
3164 static void perf_pmu_sched_task(struct task_struct *prev,
3165 struct task_struct *next,
3168 struct perf_cpu_context *cpuctx;
3174 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3175 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3177 if (WARN_ON_ONCE(!pmu->sched_task))
3180 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3181 perf_pmu_disable(pmu);
3183 pmu->sched_task(cpuctx->task_ctx, sched_in);
3185 perf_pmu_enable(pmu);
3186 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3190 static void perf_event_switch(struct task_struct *task,
3191 struct task_struct *next_prev, bool sched_in);
3193 #define for_each_task_context_nr(ctxn) \
3194 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3197 * Called from scheduler to remove the events of the current task,
3198 * with interrupts disabled.
3200 * We stop each event and update the event value in event->count.
3202 * This does not protect us against NMI, but disable()
3203 * sets the disabled bit in the control field of event _before_
3204 * accessing the event control register. If a NMI hits, then it will
3205 * not restart the event.
3207 void __perf_event_task_sched_out(struct task_struct *task,
3208 struct task_struct *next)
3212 if (__this_cpu_read(perf_sched_cb_usages))
3213 perf_pmu_sched_task(task, next, false);
3215 if (atomic_read(&nr_switch_events))
3216 perf_event_switch(task, next, false);
3218 for_each_task_context_nr(ctxn)
3219 perf_event_context_sched_out(task, ctxn, next);
3222 * if cgroup events exist on this CPU, then we need
3223 * to check if we have to switch out PMU state.
3224 * cgroup event are system-wide mode only
3226 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3227 perf_cgroup_sched_out(task, next);
3231 * Called with IRQs disabled
3233 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3234 enum event_type_t event_type)
3236 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3239 static int visit_groups_merge(struct perf_event_groups *groups, int cpu,
3240 int (*func)(struct perf_event *, void *), void *data)
3242 struct perf_event **evt, *evt1, *evt2;
3245 evt1 = perf_event_groups_first(groups, -1);
3246 evt2 = perf_event_groups_first(groups, cpu);
3248 while (evt1 || evt2) {
3250 if (evt1->group_index < evt2->group_index)
3260 ret = func(*evt, data);
3264 *evt = perf_event_groups_next(*evt);
3270 struct sched_in_data {
3271 struct perf_event_context *ctx;
3272 struct perf_cpu_context *cpuctx;
3276 static int pinned_sched_in(struct perf_event *event, void *data)
3278 struct sched_in_data *sid = data;
3280 if (event->state <= PERF_EVENT_STATE_OFF)
3283 if (!event_filter_match(event))
3286 if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
3287 if (!group_sched_in(event, sid->cpuctx, sid->ctx))
3288 list_add_tail(&event->active_list, &sid->ctx->pinned_active);
3292 * If this pinned group hasn't been scheduled,
3293 * put it in error state.
3295 if (event->state == PERF_EVENT_STATE_INACTIVE)
3296 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3301 static int flexible_sched_in(struct perf_event *event, void *data)
3303 struct sched_in_data *sid = data;
3305 if (event->state <= PERF_EVENT_STATE_OFF)
3308 if (!event_filter_match(event))
3311 if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
3312 if (!group_sched_in(event, sid->cpuctx, sid->ctx))
3313 list_add_tail(&event->active_list, &sid->ctx->flexible_active);
3315 sid->can_add_hw = 0;
3322 ctx_pinned_sched_in(struct perf_event_context *ctx,
3323 struct perf_cpu_context *cpuctx)
3325 struct sched_in_data sid = {
3331 visit_groups_merge(&ctx->pinned_groups,
3333 pinned_sched_in, &sid);
3337 ctx_flexible_sched_in(struct perf_event_context *ctx,
3338 struct perf_cpu_context *cpuctx)
3340 struct sched_in_data sid = {
3346 visit_groups_merge(&ctx->flexible_groups,
3348 flexible_sched_in, &sid);
3352 ctx_sched_in(struct perf_event_context *ctx,
3353 struct perf_cpu_context *cpuctx,
3354 enum event_type_t event_type,
3355 struct task_struct *task)
3357 int is_active = ctx->is_active;
3360 lockdep_assert_held(&ctx->lock);
3362 if (likely(!ctx->nr_events))
3365 ctx->is_active |= (event_type | EVENT_TIME);
3368 cpuctx->task_ctx = ctx;
3370 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3373 is_active ^= ctx->is_active; /* changed bits */
3375 if (is_active & EVENT_TIME) {
3376 /* start ctx time */
3378 ctx->timestamp = now;
3379 perf_cgroup_set_timestamp(task, ctx);
3383 * First go through the list and put on any pinned groups
3384 * in order to give them the best chance of going on.
3386 if (is_active & EVENT_PINNED)
3387 ctx_pinned_sched_in(ctx, cpuctx);
3389 /* Then walk through the lower prio flexible groups */
3390 if (is_active & EVENT_FLEXIBLE)
3391 ctx_flexible_sched_in(ctx, cpuctx);
3394 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3395 enum event_type_t event_type,
3396 struct task_struct *task)
3398 struct perf_event_context *ctx = &cpuctx->ctx;
3400 ctx_sched_in(ctx, cpuctx, event_type, task);
3403 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3404 struct task_struct *task)
3406 struct perf_cpu_context *cpuctx;
3408 cpuctx = __get_cpu_context(ctx);
3409 if (cpuctx->task_ctx == ctx)
3412 perf_ctx_lock(cpuctx, ctx);
3414 * We must check ctx->nr_events while holding ctx->lock, such
3415 * that we serialize against perf_install_in_context().
3417 if (!ctx->nr_events)
3420 perf_pmu_disable(ctx->pmu);
3422 * We want to keep the following priority order:
3423 * cpu pinned (that don't need to move), task pinned,
3424 * cpu flexible, task flexible.
3426 * However, if task's ctx is not carrying any pinned
3427 * events, no need to flip the cpuctx's events around.
3429 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3430 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3431 perf_event_sched_in(cpuctx, ctx, task);
3432 perf_pmu_enable(ctx->pmu);
3435 perf_ctx_unlock(cpuctx, ctx);
3439 * Called from scheduler to add the events of the current task
3440 * with interrupts disabled.
3442 * We restore the event value and then enable it.
3444 * This does not protect us against NMI, but enable()
3445 * sets the enabled bit in the control field of event _before_
3446 * accessing the event control register. If a NMI hits, then it will
3447 * keep the event running.
3449 void __perf_event_task_sched_in(struct task_struct *prev,
3450 struct task_struct *task)
3452 struct perf_event_context *ctx;
3456 * If cgroup events exist on this CPU, then we need to check if we have
3457 * to switch in PMU state; cgroup event are system-wide mode only.
3459 * Since cgroup events are CPU events, we must schedule these in before
3460 * we schedule in the task events.
3462 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3463 perf_cgroup_sched_in(prev, task);
3465 for_each_task_context_nr(ctxn) {
3466 ctx = task->perf_event_ctxp[ctxn];
3470 perf_event_context_sched_in(ctx, task);
3473 if (atomic_read(&nr_switch_events))
3474 perf_event_switch(task, prev, true);
3476 if (__this_cpu_read(perf_sched_cb_usages))
3477 perf_pmu_sched_task(prev, task, true);
3480 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3482 u64 frequency = event->attr.sample_freq;
3483 u64 sec = NSEC_PER_SEC;
3484 u64 divisor, dividend;
3486 int count_fls, nsec_fls, frequency_fls, sec_fls;
3488 count_fls = fls64(count);
3489 nsec_fls = fls64(nsec);
3490 frequency_fls = fls64(frequency);
3494 * We got @count in @nsec, with a target of sample_freq HZ
3495 * the target period becomes:
3498 * period = -------------------
3499 * @nsec * sample_freq
3504 * Reduce accuracy by one bit such that @a and @b converge
3505 * to a similar magnitude.
3507 #define REDUCE_FLS(a, b) \
3509 if (a##_fls > b##_fls) { \
3519 * Reduce accuracy until either term fits in a u64, then proceed with
3520 * the other, so that finally we can do a u64/u64 division.
3522 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3523 REDUCE_FLS(nsec, frequency);
3524 REDUCE_FLS(sec, count);
3527 if (count_fls + sec_fls > 64) {
3528 divisor = nsec * frequency;
3530 while (count_fls + sec_fls > 64) {
3531 REDUCE_FLS(count, sec);
3535 dividend = count * sec;
3537 dividend = count * sec;
3539 while (nsec_fls + frequency_fls > 64) {
3540 REDUCE_FLS(nsec, frequency);
3544 divisor = nsec * frequency;
3550 return div64_u64(dividend, divisor);
3553 static DEFINE_PER_CPU(int, perf_throttled_count);
3554 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3556 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3558 struct hw_perf_event *hwc = &event->hw;
3559 s64 period, sample_period;
3562 period = perf_calculate_period(event, nsec, count);
3564 delta = (s64)(period - hwc->sample_period);
3565 delta = (delta + 7) / 8; /* low pass filter */
3567 sample_period = hwc->sample_period + delta;
3572 hwc->sample_period = sample_period;
3574 if (local64_read(&hwc->period_left) > 8*sample_period) {
3576 event->pmu->stop(event, PERF_EF_UPDATE);
3578 local64_set(&hwc->period_left, 0);
3581 event->pmu->start(event, PERF_EF_RELOAD);
3586 * combine freq adjustment with unthrottling to avoid two passes over the
3587 * events. At the same time, make sure, having freq events does not change
3588 * the rate of unthrottling as that would introduce bias.
3590 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3593 struct perf_event *event;
3594 struct hw_perf_event *hwc;
3595 u64 now, period = TICK_NSEC;
3599 * only need to iterate over all events iff:
3600 * - context have events in frequency mode (needs freq adjust)
3601 * - there are events to unthrottle on this cpu
3603 if (!(ctx->nr_freq || needs_unthr))
3606 raw_spin_lock(&ctx->lock);
3607 perf_pmu_disable(ctx->pmu);
3609 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3610 if (event->state != PERF_EVENT_STATE_ACTIVE)
3613 if (!event_filter_match(event))
3616 perf_pmu_disable(event->pmu);
3620 if (hwc->interrupts == MAX_INTERRUPTS) {
3621 hwc->interrupts = 0;
3622 perf_log_throttle(event, 1);
3623 event->pmu->start(event, 0);
3626 if (!event->attr.freq || !event->attr.sample_freq)
3630 * stop the event and update event->count
3632 event->pmu->stop(event, PERF_EF_UPDATE);
3634 now = local64_read(&event->count);
3635 delta = now - hwc->freq_count_stamp;
3636 hwc->freq_count_stamp = now;
3640 * reload only if value has changed
3641 * we have stopped the event so tell that
3642 * to perf_adjust_period() to avoid stopping it
3646 perf_adjust_period(event, period, delta, false);
3648 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3650 perf_pmu_enable(event->pmu);
3653 perf_pmu_enable(ctx->pmu);
3654 raw_spin_unlock(&ctx->lock);
3658 * Move @event to the tail of the @ctx's elegible events.
3660 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
3663 * Rotate the first entry last of non-pinned groups. Rotation might be
3664 * disabled by the inheritance code.
3666 if (ctx->rotate_disable)
3669 perf_event_groups_delete(&ctx->flexible_groups, event);
3670 perf_event_groups_insert(&ctx->flexible_groups, event);
3673 static inline struct perf_event *
3674 ctx_first_active(struct perf_event_context *ctx)
3676 return list_first_entry_or_null(&ctx->flexible_active,
3677 struct perf_event, active_list);
3680 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
3682 struct perf_event *cpu_event = NULL, *task_event = NULL;
3683 bool cpu_rotate = false, task_rotate = false;
3684 struct perf_event_context *ctx = NULL;
3687 * Since we run this from IRQ context, nobody can install new
3688 * events, thus the event count values are stable.
3691 if (cpuctx->ctx.nr_events) {
3692 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
3696 ctx = cpuctx->task_ctx;
3697 if (ctx && ctx->nr_events) {
3698 if (ctx->nr_events != ctx->nr_active)
3702 if (!(cpu_rotate || task_rotate))
3705 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3706 perf_pmu_disable(cpuctx->ctx.pmu);
3709 task_event = ctx_first_active(ctx);
3711 cpu_event = ctx_first_active(&cpuctx->ctx);
3714 * As per the order given at ctx_resched() first 'pop' task flexible
3715 * and then, if needed CPU flexible.
3717 if (task_event || (ctx && cpu_event))
3718 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
3720 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3723 rotate_ctx(ctx, task_event);
3725 rotate_ctx(&cpuctx->ctx, cpu_event);
3727 perf_event_sched_in(cpuctx, ctx, current);
3729 perf_pmu_enable(cpuctx->ctx.pmu);
3730 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3735 void perf_event_task_tick(void)
3737 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3738 struct perf_event_context *ctx, *tmp;
3741 lockdep_assert_irqs_disabled();
3743 __this_cpu_inc(perf_throttled_seq);
3744 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3745 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3747 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3748 perf_adjust_freq_unthr_context(ctx, throttled);
3751 static int event_enable_on_exec(struct perf_event *event,
3752 struct perf_event_context *ctx)
3754 if (!event->attr.enable_on_exec)
3757 event->attr.enable_on_exec = 0;
3758 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3761 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3767 * Enable all of a task's events that have been marked enable-on-exec.
3768 * This expects task == current.
3770 static void perf_event_enable_on_exec(int ctxn)
3772 struct perf_event_context *ctx, *clone_ctx = NULL;
3773 enum event_type_t event_type = 0;
3774 struct perf_cpu_context *cpuctx;
3775 struct perf_event *event;
3776 unsigned long flags;
3779 local_irq_save(flags);
3780 ctx = current->perf_event_ctxp[ctxn];
3781 if (!ctx || !ctx->nr_events)
3784 cpuctx = __get_cpu_context(ctx);
3785 perf_ctx_lock(cpuctx, ctx);
3786 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3787 list_for_each_entry(event, &ctx->event_list, event_entry) {
3788 enabled |= event_enable_on_exec(event, ctx);
3789 event_type |= get_event_type(event);
3793 * Unclone and reschedule this context if we enabled any event.
3796 clone_ctx = unclone_ctx(ctx);
3797 ctx_resched(cpuctx, ctx, event_type);
3799 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3801 perf_ctx_unlock(cpuctx, ctx);
3804 local_irq_restore(flags);
3810 struct perf_read_data {
3811 struct perf_event *event;
3816 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
3818 u16 local_pkg, event_pkg;
3820 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
3821 int local_cpu = smp_processor_id();
3823 event_pkg = topology_physical_package_id(event_cpu);
3824 local_pkg = topology_physical_package_id(local_cpu);
3826 if (event_pkg == local_pkg)
3834 * Cross CPU call to read the hardware event
3836 static void __perf_event_read(void *info)
3838 struct perf_read_data *data = info;
3839 struct perf_event *sub, *event = data->event;
3840 struct perf_event_context *ctx = event->ctx;
3841 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3842 struct pmu *pmu = event->pmu;
3845 * If this is a task context, we need to check whether it is
3846 * the current task context of this cpu. If not it has been
3847 * scheduled out before the smp call arrived. In that case
3848 * event->count would have been updated to a recent sample
3849 * when the event was scheduled out.
3851 if (ctx->task && cpuctx->task_ctx != ctx)
3854 raw_spin_lock(&ctx->lock);
3855 if (ctx->is_active & EVENT_TIME) {
3856 update_context_time(ctx);
3857 update_cgrp_time_from_event(event);
3860 perf_event_update_time(event);
3862 perf_event_update_sibling_time(event);
3864 if (event->state != PERF_EVENT_STATE_ACTIVE)
3873 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3877 for_each_sibling_event(sub, event) {
3878 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3880 * Use sibling's PMU rather than @event's since
3881 * sibling could be on different (eg: software) PMU.
3883 sub->pmu->read(sub);
3887 data->ret = pmu->commit_txn(pmu);
3890 raw_spin_unlock(&ctx->lock);
3893 static inline u64 perf_event_count(struct perf_event *event)
3895 return local64_read(&event->count) + atomic64_read(&event->child_count);
3899 * NMI-safe method to read a local event, that is an event that
3901 * - either for the current task, or for this CPU
3902 * - does not have inherit set, for inherited task events
3903 * will not be local and we cannot read them atomically
3904 * - must not have a pmu::count method
3906 int perf_event_read_local(struct perf_event *event, u64 *value,
3907 u64 *enabled, u64 *running)
3909 unsigned long flags;
3913 * Disabling interrupts avoids all counter scheduling (context
3914 * switches, timer based rotation and IPIs).
3916 local_irq_save(flags);
3919 * It must not be an event with inherit set, we cannot read
3920 * all child counters from atomic context.
3922 if (event->attr.inherit) {
3927 /* If this is a per-task event, it must be for current */
3928 if ((event->attach_state & PERF_ATTACH_TASK) &&
3929 event->hw.target != current) {
3934 /* If this is a per-CPU event, it must be for this CPU */
3935 if (!(event->attach_state & PERF_ATTACH_TASK) &&
3936 event->cpu != smp_processor_id()) {
3941 /* If this is a pinned event it must be running on this CPU */
3942 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
3948 * If the event is currently on this CPU, its either a per-task event,
3949 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3952 if (event->oncpu == smp_processor_id())
3953 event->pmu->read(event);
3955 *value = local64_read(&event->count);
3956 if (enabled || running) {
3957 u64 now = event->shadow_ctx_time + perf_clock();
3958 u64 __enabled, __running;
3960 __perf_update_times(event, now, &__enabled, &__running);
3962 *enabled = __enabled;
3964 *running = __running;
3967 local_irq_restore(flags);
3972 static int perf_event_read(struct perf_event *event, bool group)
3974 enum perf_event_state state = READ_ONCE(event->state);
3975 int event_cpu, ret = 0;
3978 * If event is enabled and currently active on a CPU, update the
3979 * value in the event structure:
3982 if (state == PERF_EVENT_STATE_ACTIVE) {
3983 struct perf_read_data data;
3986 * Orders the ->state and ->oncpu loads such that if we see
3987 * ACTIVE we must also see the right ->oncpu.
3989 * Matches the smp_wmb() from event_sched_in().
3993 event_cpu = READ_ONCE(event->oncpu);
3994 if ((unsigned)event_cpu >= nr_cpu_ids)
3997 data = (struct perf_read_data){
4004 event_cpu = __perf_event_read_cpu(event, event_cpu);
4007 * Purposely ignore the smp_call_function_single() return
4010 * If event_cpu isn't a valid CPU it means the event got
4011 * scheduled out and that will have updated the event count.
4013 * Therefore, either way, we'll have an up-to-date event count
4016 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4020 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4021 struct perf_event_context *ctx = event->ctx;
4022 unsigned long flags;
4024 raw_spin_lock_irqsave(&ctx->lock, flags);
4025 state = event->state;
4026 if (state != PERF_EVENT_STATE_INACTIVE) {
4027 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4032 * May read while context is not active (e.g., thread is
4033 * blocked), in that case we cannot update context time
4035 if (ctx->is_active & EVENT_TIME) {
4036 update_context_time(ctx);
4037 update_cgrp_time_from_event(event);
4040 perf_event_update_time(event);
4042 perf_event_update_sibling_time(event);
4043 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4050 * Initialize the perf_event context in a task_struct:
4052 static void __perf_event_init_context(struct perf_event_context *ctx)
4054 raw_spin_lock_init(&ctx->lock);
4055 mutex_init(&ctx->mutex);
4056 INIT_LIST_HEAD(&ctx->active_ctx_list);
4057 perf_event_groups_init(&ctx->pinned_groups);
4058 perf_event_groups_init(&ctx->flexible_groups);
4059 INIT_LIST_HEAD(&ctx->event_list);
4060 INIT_LIST_HEAD(&ctx->pinned_active);
4061 INIT_LIST_HEAD(&ctx->flexible_active);
4062 refcount_set(&ctx->refcount, 1);
4065 static struct perf_event_context *
4066 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4068 struct perf_event_context *ctx;
4070 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4074 __perf_event_init_context(ctx);
4077 get_task_struct(task);
4084 static struct task_struct *
4085 find_lively_task_by_vpid(pid_t vpid)
4087 struct task_struct *task;
4093 task = find_task_by_vpid(vpid);
4095 get_task_struct(task);
4099 return ERR_PTR(-ESRCH);
4105 * Returns a matching context with refcount and pincount.
4107 static struct perf_event_context *
4108 find_get_context(struct pmu *pmu, struct task_struct *task,
4109 struct perf_event *event)
4111 struct perf_event_context *ctx, *clone_ctx = NULL;
4112 struct perf_cpu_context *cpuctx;
4113 void *task_ctx_data = NULL;
4114 unsigned long flags;
4116 int cpu = event->cpu;
4119 /* Must be root to operate on a CPU event: */
4120 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
4121 return ERR_PTR(-EACCES);
4123 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4132 ctxn = pmu->task_ctx_nr;
4136 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4137 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
4138 if (!task_ctx_data) {
4145 ctx = perf_lock_task_context(task, ctxn, &flags);
4147 clone_ctx = unclone_ctx(ctx);
4150 if (task_ctx_data && !ctx->task_ctx_data) {
4151 ctx->task_ctx_data = task_ctx_data;
4152 task_ctx_data = NULL;
4154 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4159 ctx = alloc_perf_context(pmu, task);
4164 if (task_ctx_data) {
4165 ctx->task_ctx_data = task_ctx_data;
4166 task_ctx_data = NULL;
4170 mutex_lock(&task->perf_event_mutex);
4172 * If it has already passed perf_event_exit_task().
4173 * we must see PF_EXITING, it takes this mutex too.
4175 if (task->flags & PF_EXITING)
4177 else if (task->perf_event_ctxp[ctxn])
4182 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4184 mutex_unlock(&task->perf_event_mutex);
4186 if (unlikely(err)) {
4195 kfree(task_ctx_data);
4199 kfree(task_ctx_data);
4200 return ERR_PTR(err);
4203 static void perf_event_free_filter(struct perf_event *event);
4204 static void perf_event_free_bpf_prog(struct perf_event *event);
4206 static void free_event_rcu(struct rcu_head *head)
4208 struct perf_event *event;
4210 event = container_of(head, struct perf_event, rcu_head);
4212 put_pid_ns(event->ns);
4213 perf_event_free_filter(event);
4217 static void ring_buffer_attach(struct perf_event *event,
4218 struct ring_buffer *rb);
4220 static void detach_sb_event(struct perf_event *event)
4222 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4224 raw_spin_lock(&pel->lock);
4225 list_del_rcu(&event->sb_list);
4226 raw_spin_unlock(&pel->lock);
4229 static bool is_sb_event(struct perf_event *event)
4231 struct perf_event_attr *attr = &event->attr;
4236 if (event->attach_state & PERF_ATTACH_TASK)
4239 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4240 attr->comm || attr->comm_exec ||
4241 attr->task || attr->ksymbol ||
4242 attr->context_switch ||
4248 static void unaccount_pmu_sb_event(struct perf_event *event)
4250 if (is_sb_event(event))
4251 detach_sb_event(event);
4254 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4259 if (is_cgroup_event(event))
4260 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4263 #ifdef CONFIG_NO_HZ_FULL
4264 static DEFINE_SPINLOCK(nr_freq_lock);
4267 static void unaccount_freq_event_nohz(void)
4269 #ifdef CONFIG_NO_HZ_FULL
4270 spin_lock(&nr_freq_lock);
4271 if (atomic_dec_and_test(&nr_freq_events))
4272 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4273 spin_unlock(&nr_freq_lock);
4277 static void unaccount_freq_event(void)
4279 if (tick_nohz_full_enabled())
4280 unaccount_freq_event_nohz();
4282 atomic_dec(&nr_freq_events);
4285 static void unaccount_event(struct perf_event *event)
4292 if (event->attach_state & PERF_ATTACH_TASK)
4294 if (event->attr.mmap || event->attr.mmap_data)
4295 atomic_dec(&nr_mmap_events);
4296 if (event->attr.comm)
4297 atomic_dec(&nr_comm_events);
4298 if (event->attr.namespaces)
4299 atomic_dec(&nr_namespaces_events);
4300 if (event->attr.task)
4301 atomic_dec(&nr_task_events);
4302 if (event->attr.freq)
4303 unaccount_freq_event();
4304 if (event->attr.context_switch) {
4306 atomic_dec(&nr_switch_events);
4308 if (is_cgroup_event(event))
4310 if (has_branch_stack(event))
4312 if (event->attr.ksymbol)
4313 atomic_dec(&nr_ksymbol_events);
4314 if (event->attr.bpf_event)
4315 atomic_dec(&nr_bpf_events);
4318 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4319 schedule_delayed_work(&perf_sched_work, HZ);
4322 unaccount_event_cpu(event, event->cpu);
4324 unaccount_pmu_sb_event(event);
4327 static void perf_sched_delayed(struct work_struct *work)
4329 mutex_lock(&perf_sched_mutex);
4330 if (atomic_dec_and_test(&perf_sched_count))
4331 static_branch_disable(&perf_sched_events);
4332 mutex_unlock(&perf_sched_mutex);
4336 * The following implement mutual exclusion of events on "exclusive" pmus
4337 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4338 * at a time, so we disallow creating events that might conflict, namely:
4340 * 1) cpu-wide events in the presence of per-task events,
4341 * 2) per-task events in the presence of cpu-wide events,
4342 * 3) two matching events on the same context.
4344 * The former two cases are handled in the allocation path (perf_event_alloc(),
4345 * _free_event()), the latter -- before the first perf_install_in_context().
4347 static int exclusive_event_init(struct perf_event *event)
4349 struct pmu *pmu = event->pmu;
4351 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4355 * Prevent co-existence of per-task and cpu-wide events on the
4356 * same exclusive pmu.
4358 * Negative pmu::exclusive_cnt means there are cpu-wide
4359 * events on this "exclusive" pmu, positive means there are
4362 * Since this is called in perf_event_alloc() path, event::ctx
4363 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4364 * to mean "per-task event", because unlike other attach states it
4365 * never gets cleared.
4367 if (event->attach_state & PERF_ATTACH_TASK) {
4368 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4371 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4378 static void exclusive_event_destroy(struct perf_event *event)
4380 struct pmu *pmu = event->pmu;
4382 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4385 /* see comment in exclusive_event_init() */
4386 if (event->attach_state & PERF_ATTACH_TASK)
4387 atomic_dec(&pmu->exclusive_cnt);
4389 atomic_inc(&pmu->exclusive_cnt);
4392 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4394 if ((e1->pmu == e2->pmu) &&
4395 (e1->cpu == e2->cpu ||
4402 /* Called under the same ctx::mutex as perf_install_in_context() */
4403 static bool exclusive_event_installable(struct perf_event *event,
4404 struct perf_event_context *ctx)
4406 struct perf_event *iter_event;
4407 struct pmu *pmu = event->pmu;
4409 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
4412 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4413 if (exclusive_event_match(iter_event, event))
4420 static void perf_addr_filters_splice(struct perf_event *event,
4421 struct list_head *head);
4423 static void _free_event(struct perf_event *event)
4425 irq_work_sync(&event->pending);
4427 unaccount_event(event);
4431 * Can happen when we close an event with re-directed output.
4433 * Since we have a 0 refcount, perf_mmap_close() will skip
4434 * over us; possibly making our ring_buffer_put() the last.
4436 mutex_lock(&event->mmap_mutex);
4437 ring_buffer_attach(event, NULL);
4438 mutex_unlock(&event->mmap_mutex);
4441 if (is_cgroup_event(event))
4442 perf_detach_cgroup(event);
4444 if (!event->parent) {
4445 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4446 put_callchain_buffers();
4449 perf_event_free_bpf_prog(event);
4450 perf_addr_filters_splice(event, NULL);
4451 kfree(event->addr_filter_ranges);
4454 event->destroy(event);
4457 put_ctx(event->ctx);
4459 if (event->hw.target)
4460 put_task_struct(event->hw.target);
4462 exclusive_event_destroy(event);
4463 module_put(event->pmu->module);
4465 call_rcu(&event->rcu_head, free_event_rcu);
4469 * Used to free events which have a known refcount of 1, such as in error paths
4470 * where the event isn't exposed yet and inherited events.
4472 static void free_event(struct perf_event *event)
4474 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4475 "unexpected event refcount: %ld; ptr=%p\n",
4476 atomic_long_read(&event->refcount), event)) {
4477 /* leak to avoid use-after-free */
4485 * Remove user event from the owner task.
4487 static void perf_remove_from_owner(struct perf_event *event)
4489 struct task_struct *owner;
4493 * Matches the smp_store_release() in perf_event_exit_task(). If we
4494 * observe !owner it means the list deletion is complete and we can
4495 * indeed free this event, otherwise we need to serialize on
4496 * owner->perf_event_mutex.
4498 owner = READ_ONCE(event->owner);
4501 * Since delayed_put_task_struct() also drops the last
4502 * task reference we can safely take a new reference
4503 * while holding the rcu_read_lock().
4505 get_task_struct(owner);
4511 * If we're here through perf_event_exit_task() we're already
4512 * holding ctx->mutex which would be an inversion wrt. the
4513 * normal lock order.
4515 * However we can safely take this lock because its the child
4518 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4521 * We have to re-check the event->owner field, if it is cleared
4522 * we raced with perf_event_exit_task(), acquiring the mutex
4523 * ensured they're done, and we can proceed with freeing the
4527 list_del_init(&event->owner_entry);
4528 smp_store_release(&event->owner, NULL);
4530 mutex_unlock(&owner->perf_event_mutex);
4531 put_task_struct(owner);
4535 static void put_event(struct perf_event *event)
4537 if (!atomic_long_dec_and_test(&event->refcount))
4544 * Kill an event dead; while event:refcount will preserve the event
4545 * object, it will not preserve its functionality. Once the last 'user'
4546 * gives up the object, we'll destroy the thing.
4548 int perf_event_release_kernel(struct perf_event *event)
4550 struct perf_event_context *ctx = event->ctx;
4551 struct perf_event *child, *tmp;
4552 LIST_HEAD(free_list);
4555 * If we got here through err_file: fput(event_file); we will not have
4556 * attached to a context yet.
4559 WARN_ON_ONCE(event->attach_state &
4560 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4564 if (!is_kernel_event(event))
4565 perf_remove_from_owner(event);
4567 ctx = perf_event_ctx_lock(event);
4568 WARN_ON_ONCE(ctx->parent_ctx);
4569 perf_remove_from_context(event, DETACH_GROUP);
4571 raw_spin_lock_irq(&ctx->lock);
4573 * Mark this event as STATE_DEAD, there is no external reference to it
4576 * Anybody acquiring event->child_mutex after the below loop _must_
4577 * also see this, most importantly inherit_event() which will avoid
4578 * placing more children on the list.
4580 * Thus this guarantees that we will in fact observe and kill _ALL_
4583 event->state = PERF_EVENT_STATE_DEAD;
4584 raw_spin_unlock_irq(&ctx->lock);
4586 perf_event_ctx_unlock(event, ctx);
4589 mutex_lock(&event->child_mutex);
4590 list_for_each_entry(child, &event->child_list, child_list) {
4593 * Cannot change, child events are not migrated, see the
4594 * comment with perf_event_ctx_lock_nested().
4596 ctx = READ_ONCE(child->ctx);
4598 * Since child_mutex nests inside ctx::mutex, we must jump
4599 * through hoops. We start by grabbing a reference on the ctx.
4601 * Since the event cannot get freed while we hold the
4602 * child_mutex, the context must also exist and have a !0
4608 * Now that we have a ctx ref, we can drop child_mutex, and
4609 * acquire ctx::mutex without fear of it going away. Then we
4610 * can re-acquire child_mutex.
4612 mutex_unlock(&event->child_mutex);
4613 mutex_lock(&ctx->mutex);
4614 mutex_lock(&event->child_mutex);
4617 * Now that we hold ctx::mutex and child_mutex, revalidate our
4618 * state, if child is still the first entry, it didn't get freed
4619 * and we can continue doing so.
4621 tmp = list_first_entry_or_null(&event->child_list,
4622 struct perf_event, child_list);
4624 perf_remove_from_context(child, DETACH_GROUP);
4625 list_move(&child->child_list, &free_list);
4627 * This matches the refcount bump in inherit_event();
4628 * this can't be the last reference.
4633 mutex_unlock(&event->child_mutex);
4634 mutex_unlock(&ctx->mutex);
4638 mutex_unlock(&event->child_mutex);
4640 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
4641 list_del(&child->child_list);
4646 put_event(event); /* Must be the 'last' reference */
4649 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4652 * Called when the last reference to the file is gone.
4654 static int perf_release(struct inode *inode, struct file *file)
4656 perf_event_release_kernel(file->private_data);
4660 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4662 struct perf_event *child;
4668 mutex_lock(&event->child_mutex);
4670 (void)perf_event_read(event, false);
4671 total += perf_event_count(event);
4673 *enabled += event->total_time_enabled +
4674 atomic64_read(&event->child_total_time_enabled);
4675 *running += event->total_time_running +
4676 atomic64_read(&event->child_total_time_running);
4678 list_for_each_entry(child, &event->child_list, child_list) {
4679 (void)perf_event_read(child, false);
4680 total += perf_event_count(child);
4681 *enabled += child->total_time_enabled;
4682 *running += child->total_time_running;
4684 mutex_unlock(&event->child_mutex);
4689 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4691 struct perf_event_context *ctx;
4694 ctx = perf_event_ctx_lock(event);
4695 count = __perf_event_read_value(event, enabled, running);
4696 perf_event_ctx_unlock(event, ctx);
4700 EXPORT_SYMBOL_GPL(perf_event_read_value);
4702 static int __perf_read_group_add(struct perf_event *leader,
4703 u64 read_format, u64 *values)
4705 struct perf_event_context *ctx = leader->ctx;
4706 struct perf_event *sub;
4707 unsigned long flags;
4708 int n = 1; /* skip @nr */
4711 ret = perf_event_read(leader, true);
4715 raw_spin_lock_irqsave(&ctx->lock, flags);
4718 * Since we co-schedule groups, {enabled,running} times of siblings
4719 * will be identical to those of the leader, so we only publish one
4722 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4723 values[n++] += leader->total_time_enabled +
4724 atomic64_read(&leader->child_total_time_enabled);
4727 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4728 values[n++] += leader->total_time_running +
4729 atomic64_read(&leader->child_total_time_running);
4733 * Write {count,id} tuples for every sibling.
4735 values[n++] += perf_event_count(leader);
4736 if (read_format & PERF_FORMAT_ID)
4737 values[n++] = primary_event_id(leader);
4739 for_each_sibling_event(sub, leader) {
4740 values[n++] += perf_event_count(sub);
4741 if (read_format & PERF_FORMAT_ID)
4742 values[n++] = primary_event_id(sub);
4745 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4749 static int perf_read_group(struct perf_event *event,
4750 u64 read_format, char __user *buf)
4752 struct perf_event *leader = event->group_leader, *child;
4753 struct perf_event_context *ctx = leader->ctx;
4757 lockdep_assert_held(&ctx->mutex);
4759 values = kzalloc(event->read_size, GFP_KERNEL);
4763 values[0] = 1 + leader->nr_siblings;
4766 * By locking the child_mutex of the leader we effectively
4767 * lock the child list of all siblings.. XXX explain how.
4769 mutex_lock(&leader->child_mutex);
4771 ret = __perf_read_group_add(leader, read_format, values);
4775 list_for_each_entry(child, &leader->child_list, child_list) {
4776 ret = __perf_read_group_add(child, read_format, values);
4781 mutex_unlock(&leader->child_mutex);
4783 ret = event->read_size;
4784 if (copy_to_user(buf, values, event->read_size))
4789 mutex_unlock(&leader->child_mutex);
4795 static int perf_read_one(struct perf_event *event,
4796 u64 read_format, char __user *buf)
4798 u64 enabled, running;
4802 values[n++] = __perf_event_read_value(event, &enabled, &running);
4803 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4804 values[n++] = enabled;
4805 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4806 values[n++] = running;
4807 if (read_format & PERF_FORMAT_ID)
4808 values[n++] = primary_event_id(event);
4810 if (copy_to_user(buf, values, n * sizeof(u64)))
4813 return n * sizeof(u64);
4816 static bool is_event_hup(struct perf_event *event)
4820 if (event->state > PERF_EVENT_STATE_EXIT)
4823 mutex_lock(&event->child_mutex);
4824 no_children = list_empty(&event->child_list);
4825 mutex_unlock(&event->child_mutex);
4830 * Read the performance event - simple non blocking version for now
4833 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4835 u64 read_format = event->attr.read_format;
4839 * Return end-of-file for a read on an event that is in
4840 * error state (i.e. because it was pinned but it couldn't be
4841 * scheduled on to the CPU at some point).
4843 if (event->state == PERF_EVENT_STATE_ERROR)
4846 if (count < event->read_size)
4849 WARN_ON_ONCE(event->ctx->parent_ctx);
4850 if (read_format & PERF_FORMAT_GROUP)
4851 ret = perf_read_group(event, read_format, buf);
4853 ret = perf_read_one(event, read_format, buf);
4859 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4861 struct perf_event *event = file->private_data;
4862 struct perf_event_context *ctx;
4865 ctx = perf_event_ctx_lock(event);
4866 ret = __perf_read(event, buf, count);
4867 perf_event_ctx_unlock(event, ctx);
4872 static __poll_t perf_poll(struct file *file, poll_table *wait)
4874 struct perf_event *event = file->private_data;
4875 struct ring_buffer *rb;
4876 __poll_t events = EPOLLHUP;
4878 poll_wait(file, &event->waitq, wait);
4880 if (is_event_hup(event))
4884 * Pin the event->rb by taking event->mmap_mutex; otherwise
4885 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4887 mutex_lock(&event->mmap_mutex);
4890 events = atomic_xchg(&rb->poll, 0);
4891 mutex_unlock(&event->mmap_mutex);
4895 static void _perf_event_reset(struct perf_event *event)
4897 (void)perf_event_read(event, false);
4898 local64_set(&event->count, 0);
4899 perf_event_update_userpage(event);
4903 * Holding the top-level event's child_mutex means that any
4904 * descendant process that has inherited this event will block
4905 * in perf_event_exit_event() if it goes to exit, thus satisfying the
4906 * task existence requirements of perf_event_enable/disable.
4908 static void perf_event_for_each_child(struct perf_event *event,
4909 void (*func)(struct perf_event *))
4911 struct perf_event *child;
4913 WARN_ON_ONCE(event->ctx->parent_ctx);
4915 mutex_lock(&event->child_mutex);
4917 list_for_each_entry(child, &event->child_list, child_list)
4919 mutex_unlock(&event->child_mutex);
4922 static void perf_event_for_each(struct perf_event *event,
4923 void (*func)(struct perf_event *))
4925 struct perf_event_context *ctx = event->ctx;
4926 struct perf_event *sibling;
4928 lockdep_assert_held(&ctx->mutex);
4930 event = event->group_leader;
4932 perf_event_for_each_child(event, func);
4933 for_each_sibling_event(sibling, event)
4934 perf_event_for_each_child(sibling, func);
4937 static void __perf_event_period(struct perf_event *event,
4938 struct perf_cpu_context *cpuctx,
4939 struct perf_event_context *ctx,
4942 u64 value = *((u64 *)info);
4945 if (event->attr.freq) {
4946 event->attr.sample_freq = value;
4948 event->attr.sample_period = value;
4949 event->hw.sample_period = value;
4952 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4954 perf_pmu_disable(ctx->pmu);
4956 * We could be throttled; unthrottle now to avoid the tick
4957 * trying to unthrottle while we already re-started the event.
4959 if (event->hw.interrupts == MAX_INTERRUPTS) {
4960 event->hw.interrupts = 0;
4961 perf_log_throttle(event, 1);
4963 event->pmu->stop(event, PERF_EF_UPDATE);
4966 local64_set(&event->hw.period_left, 0);
4969 event->pmu->start(event, PERF_EF_RELOAD);
4970 perf_pmu_enable(ctx->pmu);
4974 static int perf_event_check_period(struct perf_event *event, u64 value)
4976 return event->pmu->check_period(event, value);
4979 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4983 if (!is_sampling_event(event))
4986 if (copy_from_user(&value, arg, sizeof(value)))
4992 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4995 if (perf_event_check_period(event, value))
4998 event_function_call(event, __perf_event_period, &value);
5003 static const struct file_operations perf_fops;
5005 static inline int perf_fget_light(int fd, struct fd *p)
5007 struct fd f = fdget(fd);
5011 if (f.file->f_op != &perf_fops) {
5019 static int perf_event_set_output(struct perf_event *event,
5020 struct perf_event *output_event);
5021 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5022 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5023 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5024 struct perf_event_attr *attr);
5026 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5028 void (*func)(struct perf_event *);
5032 case PERF_EVENT_IOC_ENABLE:
5033 func = _perf_event_enable;
5035 case PERF_EVENT_IOC_DISABLE:
5036 func = _perf_event_disable;
5038 case PERF_EVENT_IOC_RESET:
5039 func = _perf_event_reset;
5042 case PERF_EVENT_IOC_REFRESH:
5043 return _perf_event_refresh(event, arg);
5045 case PERF_EVENT_IOC_PERIOD:
5046 return perf_event_period(event, (u64 __user *)arg);
5048 case PERF_EVENT_IOC_ID:
5050 u64 id = primary_event_id(event);
5052 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5057 case PERF_EVENT_IOC_SET_OUTPUT:
5061 struct perf_event *output_event;
5063 ret = perf_fget_light(arg, &output);
5066 output_event = output.file->private_data;
5067 ret = perf_event_set_output(event, output_event);
5070 ret = perf_event_set_output(event, NULL);
5075 case PERF_EVENT_IOC_SET_FILTER:
5076 return perf_event_set_filter(event, (void __user *)arg);
5078 case PERF_EVENT_IOC_SET_BPF:
5079 return perf_event_set_bpf_prog(event, arg);
5081 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5082 struct ring_buffer *rb;
5085 rb = rcu_dereference(event->rb);
5086 if (!rb || !rb->nr_pages) {
5090 rb_toggle_paused(rb, !!arg);
5095 case PERF_EVENT_IOC_QUERY_BPF:
5096 return perf_event_query_prog_array(event, (void __user *)arg);
5098 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5099 struct perf_event_attr new_attr;
5100 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5106 return perf_event_modify_attr(event, &new_attr);
5112 if (flags & PERF_IOC_FLAG_GROUP)
5113 perf_event_for_each(event, func);
5115 perf_event_for_each_child(event, func);
5120 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5122 struct perf_event *event = file->private_data;
5123 struct perf_event_context *ctx;
5126 ctx = perf_event_ctx_lock(event);
5127 ret = _perf_ioctl(event, cmd, arg);
5128 perf_event_ctx_unlock(event, ctx);
5133 #ifdef CONFIG_COMPAT
5134 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5137 switch (_IOC_NR(cmd)) {
5138 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5139 case _IOC_NR(PERF_EVENT_IOC_ID):
5140 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5141 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5142 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5143 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5144 cmd &= ~IOCSIZE_MASK;
5145 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5149 return perf_ioctl(file, cmd, arg);
5152 # define perf_compat_ioctl NULL
5155 int perf_event_task_enable(void)
5157 struct perf_event_context *ctx;
5158 struct perf_event *event;
5160 mutex_lock(¤t->perf_event_mutex);
5161 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5162 ctx = perf_event_ctx_lock(event);
5163 perf_event_for_each_child(event, _perf_event_enable);
5164 perf_event_ctx_unlock(event, ctx);
5166 mutex_unlock(¤t->perf_event_mutex);
5171 int perf_event_task_disable(void)
5173 struct perf_event_context *ctx;
5174 struct perf_event *event;
5176 mutex_lock(¤t->perf_event_mutex);
5177 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5178 ctx = perf_event_ctx_lock(event);
5179 perf_event_for_each_child(event, _perf_event_disable);
5180 perf_event_ctx_unlock(event, ctx);
5182 mutex_unlock(¤t->perf_event_mutex);
5187 static int perf_event_index(struct perf_event *event)
5189 if (event->hw.state & PERF_HES_STOPPED)
5192 if (event->state != PERF_EVENT_STATE_ACTIVE)
5195 return event->pmu->event_idx(event);
5198 static void calc_timer_values(struct perf_event *event,
5205 *now = perf_clock();
5206 ctx_time = event->shadow_ctx_time + *now;
5207 __perf_update_times(event, ctx_time, enabled, running);
5210 static void perf_event_init_userpage(struct perf_event *event)
5212 struct perf_event_mmap_page *userpg;
5213 struct ring_buffer *rb;
5216 rb = rcu_dereference(event->rb);
5220 userpg = rb->user_page;
5222 /* Allow new userspace to detect that bit 0 is deprecated */
5223 userpg->cap_bit0_is_deprecated = 1;
5224 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5225 userpg->data_offset = PAGE_SIZE;
5226 userpg->data_size = perf_data_size(rb);
5232 void __weak arch_perf_update_userpage(
5233 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5238 * Callers need to ensure there can be no nesting of this function, otherwise
5239 * the seqlock logic goes bad. We can not serialize this because the arch
5240 * code calls this from NMI context.
5242 void perf_event_update_userpage(struct perf_event *event)
5244 struct perf_event_mmap_page *userpg;
5245 struct ring_buffer *rb;
5246 u64 enabled, running, now;
5249 rb = rcu_dereference(event->rb);
5254 * compute total_time_enabled, total_time_running
5255 * based on snapshot values taken when the event
5256 * was last scheduled in.
5258 * we cannot simply called update_context_time()
5259 * because of locking issue as we can be called in
5262 calc_timer_values(event, &now, &enabled, &running);
5264 userpg = rb->user_page;
5266 * Disable preemption to guarantee consistent time stamps are stored to
5272 userpg->index = perf_event_index(event);
5273 userpg->offset = perf_event_count(event);
5275 userpg->offset -= local64_read(&event->hw.prev_count);
5277 userpg->time_enabled = enabled +
5278 atomic64_read(&event->child_total_time_enabled);
5280 userpg->time_running = running +
5281 atomic64_read(&event->child_total_time_running);
5283 arch_perf_update_userpage(event, userpg, now);
5291 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5293 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5295 struct perf_event *event = vmf->vma->vm_file->private_data;
5296 struct ring_buffer *rb;
5297 vm_fault_t ret = VM_FAULT_SIGBUS;
5299 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5300 if (vmf->pgoff == 0)
5306 rb = rcu_dereference(event->rb);
5310 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5313 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5317 get_page(vmf->page);
5318 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5319 vmf->page->index = vmf->pgoff;
5328 static void ring_buffer_attach(struct perf_event *event,
5329 struct ring_buffer *rb)
5331 struct ring_buffer *old_rb = NULL;
5332 unsigned long flags;
5336 * Should be impossible, we set this when removing
5337 * event->rb_entry and wait/clear when adding event->rb_entry.
5339 WARN_ON_ONCE(event->rcu_pending);
5342 spin_lock_irqsave(&old_rb->event_lock, flags);
5343 list_del_rcu(&event->rb_entry);
5344 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5346 event->rcu_batches = get_state_synchronize_rcu();
5347 event->rcu_pending = 1;
5351 if (event->rcu_pending) {
5352 cond_synchronize_rcu(event->rcu_batches);
5353 event->rcu_pending = 0;
5356 spin_lock_irqsave(&rb->event_lock, flags);
5357 list_add_rcu(&event->rb_entry, &rb->event_list);
5358 spin_unlock_irqrestore(&rb->event_lock, flags);
5362 * Avoid racing with perf_mmap_close(AUX): stop the event
5363 * before swizzling the event::rb pointer; if it's getting
5364 * unmapped, its aux_mmap_count will be 0 and it won't
5365 * restart. See the comment in __perf_pmu_output_stop().
5367 * Data will inevitably be lost when set_output is done in
5368 * mid-air, but then again, whoever does it like this is
5369 * not in for the data anyway.
5372 perf_event_stop(event, 0);
5374 rcu_assign_pointer(event->rb, rb);
5377 ring_buffer_put(old_rb);
5379 * Since we detached before setting the new rb, so that we
5380 * could attach the new rb, we could have missed a wakeup.
5383 wake_up_all(&event->waitq);
5387 static void ring_buffer_wakeup(struct perf_event *event)
5389 struct ring_buffer *rb;
5392 rb = rcu_dereference(event->rb);
5394 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5395 wake_up_all(&event->waitq);
5400 struct ring_buffer *ring_buffer_get(struct perf_event *event)
5402 struct ring_buffer *rb;
5405 rb = rcu_dereference(event->rb);
5407 if (!refcount_inc_not_zero(&rb->refcount))
5415 void ring_buffer_put(struct ring_buffer *rb)
5417 if (!refcount_dec_and_test(&rb->refcount))
5420 WARN_ON_ONCE(!list_empty(&rb->event_list));
5422 call_rcu(&rb->rcu_head, rb_free_rcu);
5425 static void perf_mmap_open(struct vm_area_struct *vma)
5427 struct perf_event *event = vma->vm_file->private_data;
5429 atomic_inc(&event->mmap_count);
5430 atomic_inc(&event->rb->mmap_count);
5433 atomic_inc(&event->rb->aux_mmap_count);
5435 if (event->pmu->event_mapped)
5436 event->pmu->event_mapped(event, vma->vm_mm);
5439 static void perf_pmu_output_stop(struct perf_event *event);
5442 * A buffer can be mmap()ed multiple times; either directly through the same
5443 * event, or through other events by use of perf_event_set_output().
5445 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5446 * the buffer here, where we still have a VM context. This means we need
5447 * to detach all events redirecting to us.
5449 static void perf_mmap_close(struct vm_area_struct *vma)
5451 struct perf_event *event = vma->vm_file->private_data;
5453 struct ring_buffer *rb = ring_buffer_get(event);
5454 struct user_struct *mmap_user = rb->mmap_user;
5455 int mmap_locked = rb->mmap_locked;
5456 unsigned long size = perf_data_size(rb);
5458 if (event->pmu->event_unmapped)
5459 event->pmu->event_unmapped(event, vma->vm_mm);
5462 * rb->aux_mmap_count will always drop before rb->mmap_count and
5463 * event->mmap_count, so it is ok to use event->mmap_mutex to
5464 * serialize with perf_mmap here.
5466 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5467 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5469 * Stop all AUX events that are writing to this buffer,
5470 * so that we can free its AUX pages and corresponding PMU
5471 * data. Note that after rb::aux_mmap_count dropped to zero,
5472 * they won't start any more (see perf_aux_output_begin()).
5474 perf_pmu_output_stop(event);
5476 /* now it's safe to free the pages */
5477 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
5478 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5480 /* this has to be the last one */
5482 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5484 mutex_unlock(&event->mmap_mutex);
5487 atomic_dec(&rb->mmap_count);
5489 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5492 ring_buffer_attach(event, NULL);
5493 mutex_unlock(&event->mmap_mutex);
5495 /* If there's still other mmap()s of this buffer, we're done. */
5496 if (atomic_read(&rb->mmap_count))
5500 * No other mmap()s, detach from all other events that might redirect
5501 * into the now unreachable buffer. Somewhat complicated by the
5502 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5506 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5507 if (!atomic_long_inc_not_zero(&event->refcount)) {
5509 * This event is en-route to free_event() which will
5510 * detach it and remove it from the list.
5516 mutex_lock(&event->mmap_mutex);
5518 * Check we didn't race with perf_event_set_output() which can
5519 * swizzle the rb from under us while we were waiting to
5520 * acquire mmap_mutex.
5522 * If we find a different rb; ignore this event, a next
5523 * iteration will no longer find it on the list. We have to
5524 * still restart the iteration to make sure we're not now
5525 * iterating the wrong list.
5527 if (event->rb == rb)
5528 ring_buffer_attach(event, NULL);
5530 mutex_unlock(&event->mmap_mutex);
5534 * Restart the iteration; either we're on the wrong list or
5535 * destroyed its integrity by doing a deletion.
5542 * It could be there's still a few 0-ref events on the list; they'll
5543 * get cleaned up by free_event() -- they'll also still have their
5544 * ref on the rb and will free it whenever they are done with it.
5546 * Aside from that, this buffer is 'fully' detached and unmapped,
5547 * undo the VM accounting.
5550 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
5551 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5552 free_uid(mmap_user);
5555 ring_buffer_put(rb); /* could be last */
5558 static const struct vm_operations_struct perf_mmap_vmops = {
5559 .open = perf_mmap_open,
5560 .close = perf_mmap_close, /* non mergeable */
5561 .fault = perf_mmap_fault,
5562 .page_mkwrite = perf_mmap_fault,
5565 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5567 struct perf_event *event = file->private_data;
5568 unsigned long user_locked, user_lock_limit;
5569 struct user_struct *user = current_user();
5570 unsigned long locked, lock_limit;
5571 struct ring_buffer *rb = NULL;
5572 unsigned long vma_size;
5573 unsigned long nr_pages;
5574 long user_extra = 0, extra = 0;
5575 int ret = 0, flags = 0;
5578 * Don't allow mmap() of inherited per-task counters. This would
5579 * create a performance issue due to all children writing to the
5582 if (event->cpu == -1 && event->attr.inherit)
5585 if (!(vma->vm_flags & VM_SHARED))
5588 vma_size = vma->vm_end - vma->vm_start;
5590 if (vma->vm_pgoff == 0) {
5591 nr_pages = (vma_size / PAGE_SIZE) - 1;
5594 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5595 * mapped, all subsequent mappings should have the same size
5596 * and offset. Must be above the normal perf buffer.
5598 u64 aux_offset, aux_size;
5603 nr_pages = vma_size / PAGE_SIZE;
5605 mutex_lock(&event->mmap_mutex);
5612 aux_offset = READ_ONCE(rb->user_page->aux_offset);
5613 aux_size = READ_ONCE(rb->user_page->aux_size);
5615 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5618 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5621 /* already mapped with a different offset */
5622 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5625 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5628 /* already mapped with a different size */
5629 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5632 if (!is_power_of_2(nr_pages))
5635 if (!atomic_inc_not_zero(&rb->mmap_count))
5638 if (rb_has_aux(rb)) {
5639 atomic_inc(&rb->aux_mmap_count);
5644 atomic_set(&rb->aux_mmap_count, 1);
5645 user_extra = nr_pages;
5651 * If we have rb pages ensure they're a power-of-two number, so we
5652 * can do bitmasks instead of modulo.
5654 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5657 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5660 WARN_ON_ONCE(event->ctx->parent_ctx);
5662 mutex_lock(&event->mmap_mutex);
5664 if (event->rb->nr_pages != nr_pages) {
5669 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5671 * Raced against perf_mmap_close() through
5672 * perf_event_set_output(). Try again, hope for better
5675 mutex_unlock(&event->mmap_mutex);
5682 user_extra = nr_pages + 1;
5685 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5688 * Increase the limit linearly with more CPUs:
5690 user_lock_limit *= num_online_cpus();
5692 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
5694 if (user_locked > user_lock_limit)
5695 extra = user_locked - user_lock_limit;
5697 lock_limit = rlimit(RLIMIT_MEMLOCK);
5698 lock_limit >>= PAGE_SHIFT;
5699 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
5701 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5702 !capable(CAP_IPC_LOCK)) {
5707 WARN_ON(!rb && event->rb);
5709 if (vma->vm_flags & VM_WRITE)
5710 flags |= RING_BUFFER_WRITABLE;
5713 rb = rb_alloc(nr_pages,
5714 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5722 atomic_set(&rb->mmap_count, 1);
5723 rb->mmap_user = get_current_user();
5724 rb->mmap_locked = extra;
5726 ring_buffer_attach(event, rb);
5728 perf_event_init_userpage(event);
5729 perf_event_update_userpage(event);
5731 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5732 event->attr.aux_watermark, flags);
5734 rb->aux_mmap_locked = extra;
5739 atomic_long_add(user_extra, &user->locked_vm);
5740 atomic64_add(extra, &vma->vm_mm->pinned_vm);
5742 atomic_inc(&event->mmap_count);
5744 atomic_dec(&rb->mmap_count);
5747 mutex_unlock(&event->mmap_mutex);
5750 * Since pinned accounting is per vm we cannot allow fork() to copy our
5753 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5754 vma->vm_ops = &perf_mmap_vmops;
5756 if (event->pmu->event_mapped)
5757 event->pmu->event_mapped(event, vma->vm_mm);
5762 static int perf_fasync(int fd, struct file *filp, int on)
5764 struct inode *inode = file_inode(filp);
5765 struct perf_event *event = filp->private_data;
5769 retval = fasync_helper(fd, filp, on, &event->fasync);
5770 inode_unlock(inode);
5778 static const struct file_operations perf_fops = {
5779 .llseek = no_llseek,
5780 .release = perf_release,
5783 .unlocked_ioctl = perf_ioctl,
5784 .compat_ioctl = perf_compat_ioctl,
5786 .fasync = perf_fasync,
5792 * If there's data, ensure we set the poll() state and publish everything
5793 * to user-space before waking everybody up.
5796 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5798 /* only the parent has fasync state */
5800 event = event->parent;
5801 return &event->fasync;
5804 void perf_event_wakeup(struct perf_event *event)
5806 ring_buffer_wakeup(event);
5808 if (event->pending_kill) {
5809 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5810 event->pending_kill = 0;
5814 static void perf_pending_event_disable(struct perf_event *event)
5816 int cpu = READ_ONCE(event->pending_disable);
5821 if (cpu == smp_processor_id()) {
5822 WRITE_ONCE(event->pending_disable, -1);
5823 perf_event_disable_local(event);
5830 * perf_event_disable_inatomic()
5831 * @pending_disable = CPU-A;
5835 * @pending_disable = -1;
5838 * perf_event_disable_inatomic()
5839 * @pending_disable = CPU-B;
5840 * irq_work_queue(); // FAILS
5843 * perf_pending_event()
5845 * But the event runs on CPU-B and wants disabling there.
5847 irq_work_queue_on(&event->pending, cpu);
5850 static void perf_pending_event(struct irq_work *entry)
5852 struct perf_event *event = container_of(entry, struct perf_event, pending);
5855 rctx = perf_swevent_get_recursion_context();
5857 * If we 'fail' here, that's OK, it means recursion is already disabled
5858 * and we won't recurse 'further'.
5861 perf_pending_event_disable(event);
5863 if (event->pending_wakeup) {
5864 event->pending_wakeup = 0;
5865 perf_event_wakeup(event);
5869 perf_swevent_put_recursion_context(rctx);
5873 * We assume there is only KVM supporting the callbacks.
5874 * Later on, we might change it to a list if there is
5875 * another virtualization implementation supporting the callbacks.
5877 struct perf_guest_info_callbacks *perf_guest_cbs;
5879 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5881 perf_guest_cbs = cbs;
5884 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5886 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5888 perf_guest_cbs = NULL;
5891 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5894 perf_output_sample_regs(struct perf_output_handle *handle,
5895 struct pt_regs *regs, u64 mask)
5898 DECLARE_BITMAP(_mask, 64);
5900 bitmap_from_u64(_mask, mask);
5901 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
5904 val = perf_reg_value(regs, bit);
5905 perf_output_put(handle, val);
5909 static void perf_sample_regs_user(struct perf_regs *regs_user,
5910 struct pt_regs *regs,
5911 struct pt_regs *regs_user_copy)
5913 if (user_mode(regs)) {
5914 regs_user->abi = perf_reg_abi(current);
5915 regs_user->regs = regs;
5916 } else if (current->mm) {
5917 perf_get_regs_user(regs_user, regs, regs_user_copy);
5919 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5920 regs_user->regs = NULL;
5924 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5925 struct pt_regs *regs)
5927 regs_intr->regs = regs;
5928 regs_intr->abi = perf_reg_abi(current);
5933 * Get remaining task size from user stack pointer.
5935 * It'd be better to take stack vma map and limit this more
5936 * precisly, but there's no way to get it safely under interrupt,
5937 * so using TASK_SIZE as limit.
5939 static u64 perf_ustack_task_size(struct pt_regs *regs)
5941 unsigned long addr = perf_user_stack_pointer(regs);
5943 if (!addr || addr >= TASK_SIZE)
5946 return TASK_SIZE - addr;
5950 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5951 struct pt_regs *regs)
5955 /* No regs, no stack pointer, no dump. */
5960 * Check if we fit in with the requested stack size into the:
5962 * If we don't, we limit the size to the TASK_SIZE.
5964 * - remaining sample size
5965 * If we don't, we customize the stack size to
5966 * fit in to the remaining sample size.
5969 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5970 stack_size = min(stack_size, (u16) task_size);
5972 /* Current header size plus static size and dynamic size. */
5973 header_size += 2 * sizeof(u64);
5975 /* Do we fit in with the current stack dump size? */
5976 if ((u16) (header_size + stack_size) < header_size) {
5978 * If we overflow the maximum size for the sample,
5979 * we customize the stack dump size to fit in.
5981 stack_size = USHRT_MAX - header_size - sizeof(u64);
5982 stack_size = round_up(stack_size, sizeof(u64));
5989 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5990 struct pt_regs *regs)
5992 /* Case of a kernel thread, nothing to dump */
5995 perf_output_put(handle, size);
6005 * - the size requested by user or the best one we can fit
6006 * in to the sample max size
6008 * - user stack dump data
6010 * - the actual dumped size
6014 perf_output_put(handle, dump_size);
6017 sp = perf_user_stack_pointer(regs);
6020 rem = __output_copy_user(handle, (void *) sp, dump_size);
6022 dyn_size = dump_size - rem;
6024 perf_output_skip(handle, rem);
6027 perf_output_put(handle, dyn_size);
6031 static void __perf_event_header__init_id(struct perf_event_header *header,
6032 struct perf_sample_data *data,
6033 struct perf_event *event)
6035 u64 sample_type = event->attr.sample_type;
6037 data->type = sample_type;
6038 header->size += event->id_header_size;
6040 if (sample_type & PERF_SAMPLE_TID) {
6041 /* namespace issues */
6042 data->tid_entry.pid = perf_event_pid(event, current);
6043 data->tid_entry.tid = perf_event_tid(event, current);
6046 if (sample_type & PERF_SAMPLE_TIME)
6047 data->time = perf_event_clock(event);
6049 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6050 data->id = primary_event_id(event);
6052 if (sample_type & PERF_SAMPLE_STREAM_ID)
6053 data->stream_id = event->id;
6055 if (sample_type & PERF_SAMPLE_CPU) {
6056 data->cpu_entry.cpu = raw_smp_processor_id();
6057 data->cpu_entry.reserved = 0;
6061 void perf_event_header__init_id(struct perf_event_header *header,
6062 struct perf_sample_data *data,
6063 struct perf_event *event)
6065 if (event->attr.sample_id_all)
6066 __perf_event_header__init_id(header, data, event);
6069 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6070 struct perf_sample_data *data)
6072 u64 sample_type = data->type;
6074 if (sample_type & PERF_SAMPLE_TID)
6075 perf_output_put(handle, data->tid_entry);
6077 if (sample_type & PERF_SAMPLE_TIME)
6078 perf_output_put(handle, data->time);
6080 if (sample_type & PERF_SAMPLE_ID)
6081 perf_output_put(handle, data->id);
6083 if (sample_type & PERF_SAMPLE_STREAM_ID)
6084 perf_output_put(handle, data->stream_id);
6086 if (sample_type & PERF_SAMPLE_CPU)
6087 perf_output_put(handle, data->cpu_entry);
6089 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6090 perf_output_put(handle, data->id);
6093 void perf_event__output_id_sample(struct perf_event *event,
6094 struct perf_output_handle *handle,
6095 struct perf_sample_data *sample)
6097 if (event->attr.sample_id_all)
6098 __perf_event__output_id_sample(handle, sample);
6101 static void perf_output_read_one(struct perf_output_handle *handle,
6102 struct perf_event *event,
6103 u64 enabled, u64 running)
6105 u64 read_format = event->attr.read_format;
6109 values[n++] = perf_event_count(event);
6110 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6111 values[n++] = enabled +
6112 atomic64_read(&event->child_total_time_enabled);
6114 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6115 values[n++] = running +
6116 atomic64_read(&event->child_total_time_running);
6118 if (read_format & PERF_FORMAT_ID)
6119 values[n++] = primary_event_id(event);
6121 __output_copy(handle, values, n * sizeof(u64));
6124 static void perf_output_read_group(struct perf_output_handle *handle,
6125 struct perf_event *event,
6126 u64 enabled, u64 running)
6128 struct perf_event *leader = event->group_leader, *sub;
6129 u64 read_format = event->attr.read_format;
6133 values[n++] = 1 + leader->nr_siblings;
6135 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6136 values[n++] = enabled;
6138 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6139 values[n++] = running;
6141 if ((leader != event) &&
6142 (leader->state == PERF_EVENT_STATE_ACTIVE))
6143 leader->pmu->read(leader);
6145 values[n++] = perf_event_count(leader);
6146 if (read_format & PERF_FORMAT_ID)
6147 values[n++] = primary_event_id(leader);
6149 __output_copy(handle, values, n * sizeof(u64));
6151 for_each_sibling_event(sub, leader) {
6154 if ((sub != event) &&
6155 (sub->state == PERF_EVENT_STATE_ACTIVE))
6156 sub->pmu->read(sub);
6158 values[n++] = perf_event_count(sub);
6159 if (read_format & PERF_FORMAT_ID)
6160 values[n++] = primary_event_id(sub);
6162 __output_copy(handle, values, n * sizeof(u64));
6166 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6167 PERF_FORMAT_TOTAL_TIME_RUNNING)
6170 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6172 * The problem is that its both hard and excessively expensive to iterate the
6173 * child list, not to mention that its impossible to IPI the children running
6174 * on another CPU, from interrupt/NMI context.
6176 static void perf_output_read(struct perf_output_handle *handle,
6177 struct perf_event *event)
6179 u64 enabled = 0, running = 0, now;
6180 u64 read_format = event->attr.read_format;
6183 * compute total_time_enabled, total_time_running
6184 * based on snapshot values taken when the event
6185 * was last scheduled in.
6187 * we cannot simply called update_context_time()
6188 * because of locking issue as we are called in
6191 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6192 calc_timer_values(event, &now, &enabled, &running);
6194 if (event->attr.read_format & PERF_FORMAT_GROUP)
6195 perf_output_read_group(handle, event, enabled, running);
6197 perf_output_read_one(handle, event, enabled, running);
6200 void perf_output_sample(struct perf_output_handle *handle,
6201 struct perf_event_header *header,
6202 struct perf_sample_data *data,
6203 struct perf_event *event)
6205 u64 sample_type = data->type;
6207 perf_output_put(handle, *header);
6209 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6210 perf_output_put(handle, data->id);
6212 if (sample_type & PERF_SAMPLE_IP)
6213 perf_output_put(handle, data->ip);
6215 if (sample_type & PERF_SAMPLE_TID)
6216 perf_output_put(handle, data->tid_entry);
6218 if (sample_type & PERF_SAMPLE_TIME)
6219 perf_output_put(handle, data->time);
6221 if (sample_type & PERF_SAMPLE_ADDR)
6222 perf_output_put(handle, data->addr);
6224 if (sample_type & PERF_SAMPLE_ID)
6225 perf_output_put(handle, data->id);
6227 if (sample_type & PERF_SAMPLE_STREAM_ID)
6228 perf_output_put(handle, data->stream_id);
6230 if (sample_type & PERF_SAMPLE_CPU)
6231 perf_output_put(handle, data->cpu_entry);
6233 if (sample_type & PERF_SAMPLE_PERIOD)
6234 perf_output_put(handle, data->period);
6236 if (sample_type & PERF_SAMPLE_READ)
6237 perf_output_read(handle, event);
6239 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6242 size += data->callchain->nr;
6243 size *= sizeof(u64);
6244 __output_copy(handle, data->callchain, size);
6247 if (sample_type & PERF_SAMPLE_RAW) {
6248 struct perf_raw_record *raw = data->raw;
6251 struct perf_raw_frag *frag = &raw->frag;
6253 perf_output_put(handle, raw->size);
6256 __output_custom(handle, frag->copy,
6257 frag->data, frag->size);
6259 __output_copy(handle, frag->data,
6262 if (perf_raw_frag_last(frag))
6267 __output_skip(handle, NULL, frag->pad);
6273 .size = sizeof(u32),
6276 perf_output_put(handle, raw);
6280 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6281 if (data->br_stack) {
6284 size = data->br_stack->nr
6285 * sizeof(struct perf_branch_entry);
6287 perf_output_put(handle, data->br_stack->nr);
6288 perf_output_copy(handle, data->br_stack->entries, size);
6291 * we always store at least the value of nr
6294 perf_output_put(handle, nr);
6298 if (sample_type & PERF_SAMPLE_REGS_USER) {
6299 u64 abi = data->regs_user.abi;
6302 * If there are no regs to dump, notice it through
6303 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6305 perf_output_put(handle, abi);
6308 u64 mask = event->attr.sample_regs_user;
6309 perf_output_sample_regs(handle,
6310 data->regs_user.regs,
6315 if (sample_type & PERF_SAMPLE_STACK_USER) {
6316 perf_output_sample_ustack(handle,
6317 data->stack_user_size,
6318 data->regs_user.regs);
6321 if (sample_type & PERF_SAMPLE_WEIGHT)
6322 perf_output_put(handle, data->weight);
6324 if (sample_type & PERF_SAMPLE_DATA_SRC)
6325 perf_output_put(handle, data->data_src.val);
6327 if (sample_type & PERF_SAMPLE_TRANSACTION)
6328 perf_output_put(handle, data->txn);
6330 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6331 u64 abi = data->regs_intr.abi;
6333 * If there are no regs to dump, notice it through
6334 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6336 perf_output_put(handle, abi);
6339 u64 mask = event->attr.sample_regs_intr;
6341 perf_output_sample_regs(handle,
6342 data->regs_intr.regs,
6347 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6348 perf_output_put(handle, data->phys_addr);
6350 if (!event->attr.watermark) {
6351 int wakeup_events = event->attr.wakeup_events;
6353 if (wakeup_events) {
6354 struct ring_buffer *rb = handle->rb;
6355 int events = local_inc_return(&rb->events);
6357 if (events >= wakeup_events) {
6358 local_sub(wakeup_events, &rb->events);
6359 local_inc(&rb->wakeup);
6365 static u64 perf_virt_to_phys(u64 virt)
6368 struct page *p = NULL;
6373 if (virt >= TASK_SIZE) {
6374 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6375 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6376 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6377 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6380 * Walking the pages tables for user address.
6381 * Interrupts are disabled, so it prevents any tear down
6382 * of the page tables.
6383 * Try IRQ-safe __get_user_pages_fast first.
6384 * If failed, leave phys_addr as 0.
6386 if ((current->mm != NULL) &&
6387 (__get_user_pages_fast(virt, 1, 0, &p) == 1))
6388 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6397 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6399 struct perf_callchain_entry *
6400 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6402 bool kernel = !event->attr.exclude_callchain_kernel;
6403 bool user = !event->attr.exclude_callchain_user;
6404 /* Disallow cross-task user callchains. */
6405 bool crosstask = event->ctx->task && event->ctx->task != current;
6406 const u32 max_stack = event->attr.sample_max_stack;
6407 struct perf_callchain_entry *callchain;
6409 if (!kernel && !user)
6410 return &__empty_callchain;
6412 callchain = get_perf_callchain(regs, 0, kernel, user,
6413 max_stack, crosstask, true);
6414 return callchain ?: &__empty_callchain;
6417 void perf_prepare_sample(struct perf_event_header *header,
6418 struct perf_sample_data *data,
6419 struct perf_event *event,
6420 struct pt_regs *regs)
6422 u64 sample_type = event->attr.sample_type;
6424 header->type = PERF_RECORD_SAMPLE;
6425 header->size = sizeof(*header) + event->header_size;
6428 header->misc |= perf_misc_flags(regs);
6430 __perf_event_header__init_id(header, data, event);
6432 if (sample_type & PERF_SAMPLE_IP)
6433 data->ip = perf_instruction_pointer(regs);
6435 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6438 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
6439 data->callchain = perf_callchain(event, regs);
6441 size += data->callchain->nr;
6443 header->size += size * sizeof(u64);
6446 if (sample_type & PERF_SAMPLE_RAW) {
6447 struct perf_raw_record *raw = data->raw;
6451 struct perf_raw_frag *frag = &raw->frag;
6456 if (perf_raw_frag_last(frag))
6461 size = round_up(sum + sizeof(u32), sizeof(u64));
6462 raw->size = size - sizeof(u32);
6463 frag->pad = raw->size - sum;
6468 header->size += size;
6471 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6472 int size = sizeof(u64); /* nr */
6473 if (data->br_stack) {
6474 size += data->br_stack->nr
6475 * sizeof(struct perf_branch_entry);
6477 header->size += size;
6480 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
6481 perf_sample_regs_user(&data->regs_user, regs,
6482 &data->regs_user_copy);
6484 if (sample_type & PERF_SAMPLE_REGS_USER) {
6485 /* regs dump ABI info */
6486 int size = sizeof(u64);
6488 if (data->regs_user.regs) {
6489 u64 mask = event->attr.sample_regs_user;
6490 size += hweight64(mask) * sizeof(u64);
6493 header->size += size;
6496 if (sample_type & PERF_SAMPLE_STACK_USER) {
6498 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
6499 * processed as the last one or have additional check added
6500 * in case new sample type is added, because we could eat
6501 * up the rest of the sample size.
6503 u16 stack_size = event->attr.sample_stack_user;
6504 u16 size = sizeof(u64);
6506 stack_size = perf_sample_ustack_size(stack_size, header->size,
6507 data->regs_user.regs);
6510 * If there is something to dump, add space for the dump
6511 * itself and for the field that tells the dynamic size,
6512 * which is how many have been actually dumped.
6515 size += sizeof(u64) + stack_size;
6517 data->stack_user_size = stack_size;
6518 header->size += size;
6521 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6522 /* regs dump ABI info */
6523 int size = sizeof(u64);
6525 perf_sample_regs_intr(&data->regs_intr, regs);
6527 if (data->regs_intr.regs) {
6528 u64 mask = event->attr.sample_regs_intr;
6530 size += hweight64(mask) * sizeof(u64);
6533 header->size += size;
6536 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6537 data->phys_addr = perf_virt_to_phys(data->addr);
6540 static __always_inline int
6541 __perf_event_output(struct perf_event *event,
6542 struct perf_sample_data *data,
6543 struct pt_regs *regs,
6544 int (*output_begin)(struct perf_output_handle *,
6545 struct perf_event *,
6548 struct perf_output_handle handle;
6549 struct perf_event_header header;
6552 /* protect the callchain buffers */
6555 perf_prepare_sample(&header, data, event, regs);
6557 err = output_begin(&handle, event, header.size);
6561 perf_output_sample(&handle, &header, data, event);
6563 perf_output_end(&handle);
6571 perf_event_output_forward(struct perf_event *event,
6572 struct perf_sample_data *data,
6573 struct pt_regs *regs)
6575 __perf_event_output(event, data, regs, perf_output_begin_forward);
6579 perf_event_output_backward(struct perf_event *event,
6580 struct perf_sample_data *data,
6581 struct pt_regs *regs)
6583 __perf_event_output(event, data, regs, perf_output_begin_backward);
6587 perf_event_output(struct perf_event *event,
6588 struct perf_sample_data *data,
6589 struct pt_regs *regs)
6591 return __perf_event_output(event, data, regs, perf_output_begin);
6598 struct perf_read_event {
6599 struct perf_event_header header;
6606 perf_event_read_event(struct perf_event *event,
6607 struct task_struct *task)
6609 struct perf_output_handle handle;
6610 struct perf_sample_data sample;
6611 struct perf_read_event read_event = {
6613 .type = PERF_RECORD_READ,
6615 .size = sizeof(read_event) + event->read_size,
6617 .pid = perf_event_pid(event, task),
6618 .tid = perf_event_tid(event, task),
6622 perf_event_header__init_id(&read_event.header, &sample, event);
6623 ret = perf_output_begin(&handle, event, read_event.header.size);
6627 perf_output_put(&handle, read_event);
6628 perf_output_read(&handle, event);
6629 perf_event__output_id_sample(event, &handle, &sample);
6631 perf_output_end(&handle);
6634 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
6637 perf_iterate_ctx(struct perf_event_context *ctx,
6638 perf_iterate_f output,
6639 void *data, bool all)
6641 struct perf_event *event;
6643 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6645 if (event->state < PERF_EVENT_STATE_INACTIVE)
6647 if (!event_filter_match(event))
6651 output(event, data);
6655 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
6657 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
6658 struct perf_event *event;
6660 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6662 * Skip events that are not fully formed yet; ensure that
6663 * if we observe event->ctx, both event and ctx will be
6664 * complete enough. See perf_install_in_context().
6666 if (!smp_load_acquire(&event->ctx))
6669 if (event->state < PERF_EVENT_STATE_INACTIVE)
6671 if (!event_filter_match(event))
6673 output(event, data);
6678 * Iterate all events that need to receive side-band events.
6680 * For new callers; ensure that account_pmu_sb_event() includes
6681 * your event, otherwise it might not get delivered.
6684 perf_iterate_sb(perf_iterate_f output, void *data,
6685 struct perf_event_context *task_ctx)
6687 struct perf_event_context *ctx;
6694 * If we have task_ctx != NULL we only notify the task context itself.
6695 * The task_ctx is set only for EXIT events before releasing task
6699 perf_iterate_ctx(task_ctx, output, data, false);
6703 perf_iterate_sb_cpu(output, data);
6705 for_each_task_context_nr(ctxn) {
6706 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6708 perf_iterate_ctx(ctx, output, data, false);
6716 * Clear all file-based filters at exec, they'll have to be
6717 * re-instated when/if these objects are mmapped again.
6719 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6721 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6722 struct perf_addr_filter *filter;
6723 unsigned int restart = 0, count = 0;
6724 unsigned long flags;
6726 if (!has_addr_filter(event))
6729 raw_spin_lock_irqsave(&ifh->lock, flags);
6730 list_for_each_entry(filter, &ifh->list, entry) {
6731 if (filter->path.dentry) {
6732 event->addr_filter_ranges[count].start = 0;
6733 event->addr_filter_ranges[count].size = 0;
6741 event->addr_filters_gen++;
6742 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6745 perf_event_stop(event, 1);
6748 void perf_event_exec(void)
6750 struct perf_event_context *ctx;
6754 for_each_task_context_nr(ctxn) {
6755 ctx = current->perf_event_ctxp[ctxn];
6759 perf_event_enable_on_exec(ctxn);
6761 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
6767 struct remote_output {
6768 struct ring_buffer *rb;
6772 static void __perf_event_output_stop(struct perf_event *event, void *data)
6774 struct perf_event *parent = event->parent;
6775 struct remote_output *ro = data;
6776 struct ring_buffer *rb = ro->rb;
6777 struct stop_event_data sd = {
6781 if (!has_aux(event))
6788 * In case of inheritance, it will be the parent that links to the
6789 * ring-buffer, but it will be the child that's actually using it.
6791 * We are using event::rb to determine if the event should be stopped,
6792 * however this may race with ring_buffer_attach() (through set_output),
6793 * which will make us skip the event that actually needs to be stopped.
6794 * So ring_buffer_attach() has to stop an aux event before re-assigning
6797 if (rcu_dereference(parent->rb) == rb)
6798 ro->err = __perf_event_stop(&sd);
6801 static int __perf_pmu_output_stop(void *info)
6803 struct perf_event *event = info;
6804 struct pmu *pmu = event->pmu;
6805 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6806 struct remote_output ro = {
6811 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
6812 if (cpuctx->task_ctx)
6813 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
6820 static void perf_pmu_output_stop(struct perf_event *event)
6822 struct perf_event *iter;
6827 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
6829 * For per-CPU events, we need to make sure that neither they
6830 * nor their children are running; for cpu==-1 events it's
6831 * sufficient to stop the event itself if it's active, since
6832 * it can't have children.
6836 cpu = READ_ONCE(iter->oncpu);
6841 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
6842 if (err == -EAGAIN) {
6851 * task tracking -- fork/exit
6853 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
6856 struct perf_task_event {
6857 struct task_struct *task;
6858 struct perf_event_context *task_ctx;
6861 struct perf_event_header header;
6871 static int perf_event_task_match(struct perf_event *event)
6873 return event->attr.comm || event->attr.mmap ||
6874 event->attr.mmap2 || event->attr.mmap_data ||
6878 static void perf_event_task_output(struct perf_event *event,
6881 struct perf_task_event *task_event = data;
6882 struct perf_output_handle handle;
6883 struct perf_sample_data sample;
6884 struct task_struct *task = task_event->task;
6885 int ret, size = task_event->event_id.header.size;
6887 if (!perf_event_task_match(event))
6890 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
6892 ret = perf_output_begin(&handle, event,
6893 task_event->event_id.header.size);
6897 task_event->event_id.pid = perf_event_pid(event, task);
6898 task_event->event_id.ppid = perf_event_pid(event, current);
6900 task_event->event_id.tid = perf_event_tid(event, task);
6901 task_event->event_id.ptid = perf_event_tid(event, current);
6903 task_event->event_id.time = perf_event_clock(event);
6905 perf_output_put(&handle, task_event->event_id);
6907 perf_event__output_id_sample(event, &handle, &sample);
6909 perf_output_end(&handle);
6911 task_event->event_id.header.size = size;
6914 static void perf_event_task(struct task_struct *task,
6915 struct perf_event_context *task_ctx,
6918 struct perf_task_event task_event;
6920 if (!atomic_read(&nr_comm_events) &&
6921 !atomic_read(&nr_mmap_events) &&
6922 !atomic_read(&nr_task_events))
6925 task_event = (struct perf_task_event){
6927 .task_ctx = task_ctx,
6930 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6932 .size = sizeof(task_event.event_id),
6942 perf_iterate_sb(perf_event_task_output,
6947 void perf_event_fork(struct task_struct *task)
6949 perf_event_task(task, NULL, 1);
6950 perf_event_namespaces(task);
6957 struct perf_comm_event {
6958 struct task_struct *task;
6963 struct perf_event_header header;
6970 static int perf_event_comm_match(struct perf_event *event)
6972 return event->attr.comm;
6975 static void perf_event_comm_output(struct perf_event *event,
6978 struct perf_comm_event *comm_event = data;
6979 struct perf_output_handle handle;
6980 struct perf_sample_data sample;
6981 int size = comm_event->event_id.header.size;
6984 if (!perf_event_comm_match(event))
6987 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6988 ret = perf_output_begin(&handle, event,
6989 comm_event->event_id.header.size);
6994 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6995 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6997 perf_output_put(&handle, comm_event->event_id);
6998 __output_copy(&handle, comm_event->comm,
6999 comm_event->comm_size);
7001 perf_event__output_id_sample(event, &handle, &sample);
7003 perf_output_end(&handle);
7005 comm_event->event_id.header.size = size;
7008 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7010 char comm[TASK_COMM_LEN];
7013 memset(comm, 0, sizeof(comm));
7014 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7015 size = ALIGN(strlen(comm)+1, sizeof(u64));
7017 comm_event->comm = comm;
7018 comm_event->comm_size = size;
7020 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7022 perf_iterate_sb(perf_event_comm_output,
7027 void perf_event_comm(struct task_struct *task, bool exec)
7029 struct perf_comm_event comm_event;
7031 if (!atomic_read(&nr_comm_events))
7034 comm_event = (struct perf_comm_event){
7040 .type = PERF_RECORD_COMM,
7041 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7049 perf_event_comm_event(&comm_event);
7053 * namespaces tracking
7056 struct perf_namespaces_event {
7057 struct task_struct *task;
7060 struct perf_event_header header;
7065 struct perf_ns_link_info link_info[NR_NAMESPACES];
7069 static int perf_event_namespaces_match(struct perf_event *event)
7071 return event->attr.namespaces;
7074 static void perf_event_namespaces_output(struct perf_event *event,
7077 struct perf_namespaces_event *namespaces_event = data;
7078 struct perf_output_handle handle;
7079 struct perf_sample_data sample;
7080 u16 header_size = namespaces_event->event_id.header.size;
7083 if (!perf_event_namespaces_match(event))
7086 perf_event_header__init_id(&namespaces_event->event_id.header,
7088 ret = perf_output_begin(&handle, event,
7089 namespaces_event->event_id.header.size);
7093 namespaces_event->event_id.pid = perf_event_pid(event,
7094 namespaces_event->task);
7095 namespaces_event->event_id.tid = perf_event_tid(event,
7096 namespaces_event->task);
7098 perf_output_put(&handle, namespaces_event->event_id);
7100 perf_event__output_id_sample(event, &handle, &sample);
7102 perf_output_end(&handle);
7104 namespaces_event->event_id.header.size = header_size;
7107 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7108 struct task_struct *task,
7109 const struct proc_ns_operations *ns_ops)
7111 struct path ns_path;
7112 struct inode *ns_inode;
7115 error = ns_get_path(&ns_path, task, ns_ops);
7117 ns_inode = ns_path.dentry->d_inode;
7118 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7119 ns_link_info->ino = ns_inode->i_ino;
7124 void perf_event_namespaces(struct task_struct *task)
7126 struct perf_namespaces_event namespaces_event;
7127 struct perf_ns_link_info *ns_link_info;
7129 if (!atomic_read(&nr_namespaces_events))
7132 namespaces_event = (struct perf_namespaces_event){
7136 .type = PERF_RECORD_NAMESPACES,
7138 .size = sizeof(namespaces_event.event_id),
7142 .nr_namespaces = NR_NAMESPACES,
7143 /* .link_info[NR_NAMESPACES] */
7147 ns_link_info = namespaces_event.event_id.link_info;
7149 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7150 task, &mntns_operations);
7152 #ifdef CONFIG_USER_NS
7153 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7154 task, &userns_operations);
7156 #ifdef CONFIG_NET_NS
7157 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7158 task, &netns_operations);
7160 #ifdef CONFIG_UTS_NS
7161 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7162 task, &utsns_operations);
7164 #ifdef CONFIG_IPC_NS
7165 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7166 task, &ipcns_operations);
7168 #ifdef CONFIG_PID_NS
7169 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7170 task, &pidns_operations);
7172 #ifdef CONFIG_CGROUPS
7173 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7174 task, &cgroupns_operations);
7177 perf_iterate_sb(perf_event_namespaces_output,
7186 struct perf_mmap_event {
7187 struct vm_area_struct *vma;
7189 const char *file_name;
7197 struct perf_event_header header;
7207 static int perf_event_mmap_match(struct perf_event *event,
7210 struct perf_mmap_event *mmap_event = data;
7211 struct vm_area_struct *vma = mmap_event->vma;
7212 int executable = vma->vm_flags & VM_EXEC;
7214 return (!executable && event->attr.mmap_data) ||
7215 (executable && (event->attr.mmap || event->attr.mmap2));
7218 static void perf_event_mmap_output(struct perf_event *event,
7221 struct perf_mmap_event *mmap_event = data;
7222 struct perf_output_handle handle;
7223 struct perf_sample_data sample;
7224 int size = mmap_event->event_id.header.size;
7225 u32 type = mmap_event->event_id.header.type;
7228 if (!perf_event_mmap_match(event, data))
7231 if (event->attr.mmap2) {
7232 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7233 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7234 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7235 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7236 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7237 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7238 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7241 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7242 ret = perf_output_begin(&handle, event,
7243 mmap_event->event_id.header.size);
7247 mmap_event->event_id.pid = perf_event_pid(event, current);
7248 mmap_event->event_id.tid = perf_event_tid(event, current);
7250 perf_output_put(&handle, mmap_event->event_id);
7252 if (event->attr.mmap2) {
7253 perf_output_put(&handle, mmap_event->maj);
7254 perf_output_put(&handle, mmap_event->min);
7255 perf_output_put(&handle, mmap_event->ino);
7256 perf_output_put(&handle, mmap_event->ino_generation);
7257 perf_output_put(&handle, mmap_event->prot);
7258 perf_output_put(&handle, mmap_event->flags);
7261 __output_copy(&handle, mmap_event->file_name,
7262 mmap_event->file_size);
7264 perf_event__output_id_sample(event, &handle, &sample);
7266 perf_output_end(&handle);
7268 mmap_event->event_id.header.size = size;
7269 mmap_event->event_id.header.type = type;
7272 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7274 struct vm_area_struct *vma = mmap_event->vma;
7275 struct file *file = vma->vm_file;
7276 int maj = 0, min = 0;
7277 u64 ino = 0, gen = 0;
7278 u32 prot = 0, flags = 0;
7284 if (vma->vm_flags & VM_READ)
7286 if (vma->vm_flags & VM_WRITE)
7288 if (vma->vm_flags & VM_EXEC)
7291 if (vma->vm_flags & VM_MAYSHARE)
7294 flags = MAP_PRIVATE;
7296 if (vma->vm_flags & VM_DENYWRITE)
7297 flags |= MAP_DENYWRITE;
7298 if (vma->vm_flags & VM_MAYEXEC)
7299 flags |= MAP_EXECUTABLE;
7300 if (vma->vm_flags & VM_LOCKED)
7301 flags |= MAP_LOCKED;
7302 if (vma->vm_flags & VM_HUGETLB)
7303 flags |= MAP_HUGETLB;
7306 struct inode *inode;
7309 buf = kmalloc(PATH_MAX, GFP_KERNEL);
7315 * d_path() works from the end of the rb backwards, so we
7316 * need to add enough zero bytes after the string to handle
7317 * the 64bit alignment we do later.
7319 name = file_path(file, buf, PATH_MAX - sizeof(u64));
7324 inode = file_inode(vma->vm_file);
7325 dev = inode->i_sb->s_dev;
7327 gen = inode->i_generation;
7333 if (vma->vm_ops && vma->vm_ops->name) {
7334 name = (char *) vma->vm_ops->name(vma);
7339 name = (char *)arch_vma_name(vma);
7343 if (vma->vm_start <= vma->vm_mm->start_brk &&
7344 vma->vm_end >= vma->vm_mm->brk) {
7348 if (vma->vm_start <= vma->vm_mm->start_stack &&
7349 vma->vm_end >= vma->vm_mm->start_stack) {
7359 strlcpy(tmp, name, sizeof(tmp));
7363 * Since our buffer works in 8 byte units we need to align our string
7364 * size to a multiple of 8. However, we must guarantee the tail end is
7365 * zero'd out to avoid leaking random bits to userspace.
7367 size = strlen(name)+1;
7368 while (!IS_ALIGNED(size, sizeof(u64)))
7369 name[size++] = '\0';
7371 mmap_event->file_name = name;
7372 mmap_event->file_size = size;
7373 mmap_event->maj = maj;
7374 mmap_event->min = min;
7375 mmap_event->ino = ino;
7376 mmap_event->ino_generation = gen;
7377 mmap_event->prot = prot;
7378 mmap_event->flags = flags;
7380 if (!(vma->vm_flags & VM_EXEC))
7381 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
7383 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
7385 perf_iterate_sb(perf_event_mmap_output,
7393 * Check whether inode and address range match filter criteria.
7395 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
7396 struct file *file, unsigned long offset,
7399 /* d_inode(NULL) won't be equal to any mapped user-space file */
7400 if (!filter->path.dentry)
7403 if (d_inode(filter->path.dentry) != file_inode(file))
7406 if (filter->offset > offset + size)
7409 if (filter->offset + filter->size < offset)
7415 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
7416 struct vm_area_struct *vma,
7417 struct perf_addr_filter_range *fr)
7419 unsigned long vma_size = vma->vm_end - vma->vm_start;
7420 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
7421 struct file *file = vma->vm_file;
7423 if (!perf_addr_filter_match(filter, file, off, vma_size))
7426 if (filter->offset < off) {
7427 fr->start = vma->vm_start;
7428 fr->size = min(vma_size, filter->size - (off - filter->offset));
7430 fr->start = vma->vm_start + filter->offset - off;
7431 fr->size = min(vma->vm_end - fr->start, filter->size);
7437 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
7439 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7440 struct vm_area_struct *vma = data;
7441 struct perf_addr_filter *filter;
7442 unsigned int restart = 0, count = 0;
7443 unsigned long flags;
7445 if (!has_addr_filter(event))
7451 raw_spin_lock_irqsave(&ifh->lock, flags);
7452 list_for_each_entry(filter, &ifh->list, entry) {
7453 if (perf_addr_filter_vma_adjust(filter, vma,
7454 &event->addr_filter_ranges[count]))
7461 event->addr_filters_gen++;
7462 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7465 perf_event_stop(event, 1);
7469 * Adjust all task's events' filters to the new vma
7471 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
7473 struct perf_event_context *ctx;
7477 * Data tracing isn't supported yet and as such there is no need
7478 * to keep track of anything that isn't related to executable code:
7480 if (!(vma->vm_flags & VM_EXEC))
7484 for_each_task_context_nr(ctxn) {
7485 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7489 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
7494 void perf_event_mmap(struct vm_area_struct *vma)
7496 struct perf_mmap_event mmap_event;
7498 if (!atomic_read(&nr_mmap_events))
7501 mmap_event = (struct perf_mmap_event){
7507 .type = PERF_RECORD_MMAP,
7508 .misc = PERF_RECORD_MISC_USER,
7513 .start = vma->vm_start,
7514 .len = vma->vm_end - vma->vm_start,
7515 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
7517 /* .maj (attr_mmap2 only) */
7518 /* .min (attr_mmap2 only) */
7519 /* .ino (attr_mmap2 only) */
7520 /* .ino_generation (attr_mmap2 only) */
7521 /* .prot (attr_mmap2 only) */
7522 /* .flags (attr_mmap2 only) */
7525 perf_addr_filters_adjust(vma);
7526 perf_event_mmap_event(&mmap_event);
7529 void perf_event_aux_event(struct perf_event *event, unsigned long head,
7530 unsigned long size, u64 flags)
7532 struct perf_output_handle handle;
7533 struct perf_sample_data sample;
7534 struct perf_aux_event {
7535 struct perf_event_header header;
7541 .type = PERF_RECORD_AUX,
7543 .size = sizeof(rec),
7551 perf_event_header__init_id(&rec.header, &sample, event);
7552 ret = perf_output_begin(&handle, event, rec.header.size);
7557 perf_output_put(&handle, rec);
7558 perf_event__output_id_sample(event, &handle, &sample);
7560 perf_output_end(&handle);
7564 * Lost/dropped samples logging
7566 void perf_log_lost_samples(struct perf_event *event, u64 lost)
7568 struct perf_output_handle handle;
7569 struct perf_sample_data sample;
7573 struct perf_event_header header;
7575 } lost_samples_event = {
7577 .type = PERF_RECORD_LOST_SAMPLES,
7579 .size = sizeof(lost_samples_event),
7584 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
7586 ret = perf_output_begin(&handle, event,
7587 lost_samples_event.header.size);
7591 perf_output_put(&handle, lost_samples_event);
7592 perf_event__output_id_sample(event, &handle, &sample);
7593 perf_output_end(&handle);
7597 * context_switch tracking
7600 struct perf_switch_event {
7601 struct task_struct *task;
7602 struct task_struct *next_prev;
7605 struct perf_event_header header;
7611 static int perf_event_switch_match(struct perf_event *event)
7613 return event->attr.context_switch;
7616 static void perf_event_switch_output(struct perf_event *event, void *data)
7618 struct perf_switch_event *se = data;
7619 struct perf_output_handle handle;
7620 struct perf_sample_data sample;
7623 if (!perf_event_switch_match(event))
7626 /* Only CPU-wide events are allowed to see next/prev pid/tid */
7627 if (event->ctx->task) {
7628 se->event_id.header.type = PERF_RECORD_SWITCH;
7629 se->event_id.header.size = sizeof(se->event_id.header);
7631 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
7632 se->event_id.header.size = sizeof(se->event_id);
7633 se->event_id.next_prev_pid =
7634 perf_event_pid(event, se->next_prev);
7635 se->event_id.next_prev_tid =
7636 perf_event_tid(event, se->next_prev);
7639 perf_event_header__init_id(&se->event_id.header, &sample, event);
7641 ret = perf_output_begin(&handle, event, se->event_id.header.size);
7645 if (event->ctx->task)
7646 perf_output_put(&handle, se->event_id.header);
7648 perf_output_put(&handle, se->event_id);
7650 perf_event__output_id_sample(event, &handle, &sample);
7652 perf_output_end(&handle);
7655 static void perf_event_switch(struct task_struct *task,
7656 struct task_struct *next_prev, bool sched_in)
7658 struct perf_switch_event switch_event;
7660 /* N.B. caller checks nr_switch_events != 0 */
7662 switch_event = (struct perf_switch_event){
7664 .next_prev = next_prev,
7668 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
7671 /* .next_prev_pid */
7672 /* .next_prev_tid */
7676 if (!sched_in && task->state == TASK_RUNNING)
7677 switch_event.event_id.header.misc |=
7678 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
7680 perf_iterate_sb(perf_event_switch_output,
7686 * IRQ throttle logging
7689 static void perf_log_throttle(struct perf_event *event, int enable)
7691 struct perf_output_handle handle;
7692 struct perf_sample_data sample;
7696 struct perf_event_header header;
7700 } throttle_event = {
7702 .type = PERF_RECORD_THROTTLE,
7704 .size = sizeof(throttle_event),
7706 .time = perf_event_clock(event),
7707 .id = primary_event_id(event),
7708 .stream_id = event->id,
7712 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
7714 perf_event_header__init_id(&throttle_event.header, &sample, event);
7716 ret = perf_output_begin(&handle, event,
7717 throttle_event.header.size);
7721 perf_output_put(&handle, throttle_event);
7722 perf_event__output_id_sample(event, &handle, &sample);
7723 perf_output_end(&handle);
7727 * ksymbol register/unregister tracking
7730 struct perf_ksymbol_event {
7734 struct perf_event_header header;
7742 static int perf_event_ksymbol_match(struct perf_event *event)
7744 return event->attr.ksymbol;
7747 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
7749 struct perf_ksymbol_event *ksymbol_event = data;
7750 struct perf_output_handle handle;
7751 struct perf_sample_data sample;
7754 if (!perf_event_ksymbol_match(event))
7757 perf_event_header__init_id(&ksymbol_event->event_id.header,
7759 ret = perf_output_begin(&handle, event,
7760 ksymbol_event->event_id.header.size);
7764 perf_output_put(&handle, ksymbol_event->event_id);
7765 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
7766 perf_event__output_id_sample(event, &handle, &sample);
7768 perf_output_end(&handle);
7771 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
7774 struct perf_ksymbol_event ksymbol_event;
7775 char name[KSYM_NAME_LEN];
7779 if (!atomic_read(&nr_ksymbol_events))
7782 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
7783 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
7786 strlcpy(name, sym, KSYM_NAME_LEN);
7787 name_len = strlen(name) + 1;
7788 while (!IS_ALIGNED(name_len, sizeof(u64)))
7789 name[name_len++] = '\0';
7790 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
7793 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
7795 ksymbol_event = (struct perf_ksymbol_event){
7797 .name_len = name_len,
7800 .type = PERF_RECORD_KSYMBOL,
7801 .size = sizeof(ksymbol_event.event_id) +
7806 .ksym_type = ksym_type,
7811 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
7814 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
7818 * bpf program load/unload tracking
7821 struct perf_bpf_event {
7822 struct bpf_prog *prog;
7824 struct perf_event_header header;
7828 u8 tag[BPF_TAG_SIZE];
7832 static int perf_event_bpf_match(struct perf_event *event)
7834 return event->attr.bpf_event;
7837 static void perf_event_bpf_output(struct perf_event *event, void *data)
7839 struct perf_bpf_event *bpf_event = data;
7840 struct perf_output_handle handle;
7841 struct perf_sample_data sample;
7844 if (!perf_event_bpf_match(event))
7847 perf_event_header__init_id(&bpf_event->event_id.header,
7849 ret = perf_output_begin(&handle, event,
7850 bpf_event->event_id.header.size);
7854 perf_output_put(&handle, bpf_event->event_id);
7855 perf_event__output_id_sample(event, &handle, &sample);
7857 perf_output_end(&handle);
7860 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
7861 enum perf_bpf_event_type type)
7863 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
7864 char sym[KSYM_NAME_LEN];
7867 if (prog->aux->func_cnt == 0) {
7868 bpf_get_prog_name(prog, sym);
7869 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
7870 (u64)(unsigned long)prog->bpf_func,
7871 prog->jited_len, unregister, sym);
7873 for (i = 0; i < prog->aux->func_cnt; i++) {
7874 struct bpf_prog *subprog = prog->aux->func[i];
7876 bpf_get_prog_name(subprog, sym);
7878 PERF_RECORD_KSYMBOL_TYPE_BPF,
7879 (u64)(unsigned long)subprog->bpf_func,
7880 subprog->jited_len, unregister, sym);
7885 void perf_event_bpf_event(struct bpf_prog *prog,
7886 enum perf_bpf_event_type type,
7889 struct perf_bpf_event bpf_event;
7891 if (type <= PERF_BPF_EVENT_UNKNOWN ||
7892 type >= PERF_BPF_EVENT_MAX)
7896 case PERF_BPF_EVENT_PROG_LOAD:
7897 case PERF_BPF_EVENT_PROG_UNLOAD:
7898 if (atomic_read(&nr_ksymbol_events))
7899 perf_event_bpf_emit_ksymbols(prog, type);
7905 if (!atomic_read(&nr_bpf_events))
7908 bpf_event = (struct perf_bpf_event){
7912 .type = PERF_RECORD_BPF_EVENT,
7913 .size = sizeof(bpf_event.event_id),
7917 .id = prog->aux->id,
7921 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
7923 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
7924 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
7927 void perf_event_itrace_started(struct perf_event *event)
7929 event->attach_state |= PERF_ATTACH_ITRACE;
7932 static void perf_log_itrace_start(struct perf_event *event)
7934 struct perf_output_handle handle;
7935 struct perf_sample_data sample;
7936 struct perf_aux_event {
7937 struct perf_event_header header;
7944 event = event->parent;
7946 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
7947 event->attach_state & PERF_ATTACH_ITRACE)
7950 rec.header.type = PERF_RECORD_ITRACE_START;
7951 rec.header.misc = 0;
7952 rec.header.size = sizeof(rec);
7953 rec.pid = perf_event_pid(event, current);
7954 rec.tid = perf_event_tid(event, current);
7956 perf_event_header__init_id(&rec.header, &sample, event);
7957 ret = perf_output_begin(&handle, event, rec.header.size);
7962 perf_output_put(&handle, rec);
7963 perf_event__output_id_sample(event, &handle, &sample);
7965 perf_output_end(&handle);
7969 __perf_event_account_interrupt(struct perf_event *event, int throttle)
7971 struct hw_perf_event *hwc = &event->hw;
7975 seq = __this_cpu_read(perf_throttled_seq);
7976 if (seq != hwc->interrupts_seq) {
7977 hwc->interrupts_seq = seq;
7978 hwc->interrupts = 1;
7981 if (unlikely(throttle
7982 && hwc->interrupts >= max_samples_per_tick)) {
7983 __this_cpu_inc(perf_throttled_count);
7984 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
7985 hwc->interrupts = MAX_INTERRUPTS;
7986 perf_log_throttle(event, 0);
7991 if (event->attr.freq) {
7992 u64 now = perf_clock();
7993 s64 delta = now - hwc->freq_time_stamp;
7995 hwc->freq_time_stamp = now;
7997 if (delta > 0 && delta < 2*TICK_NSEC)
7998 perf_adjust_period(event, delta, hwc->last_period, true);
8004 int perf_event_account_interrupt(struct perf_event *event)
8006 return __perf_event_account_interrupt(event, 1);
8010 * Generic event overflow handling, sampling.
8013 static int __perf_event_overflow(struct perf_event *event,
8014 int throttle, struct perf_sample_data *data,
8015 struct pt_regs *regs)
8017 int events = atomic_read(&event->event_limit);
8021 * Non-sampling counters might still use the PMI to fold short
8022 * hardware counters, ignore those.
8024 if (unlikely(!is_sampling_event(event)))
8027 ret = __perf_event_account_interrupt(event, throttle);
8030 * XXX event_limit might not quite work as expected on inherited
8034 event->pending_kill = POLL_IN;
8035 if (events && atomic_dec_and_test(&event->event_limit)) {
8037 event->pending_kill = POLL_HUP;
8039 perf_event_disable_inatomic(event);
8042 READ_ONCE(event->overflow_handler)(event, data, regs);
8044 if (*perf_event_fasync(event) && event->pending_kill) {
8045 event->pending_wakeup = 1;
8046 irq_work_queue(&event->pending);
8052 int perf_event_overflow(struct perf_event *event,
8053 struct perf_sample_data *data,
8054 struct pt_regs *regs)
8056 return __perf_event_overflow(event, 1, data, regs);
8060 * Generic software event infrastructure
8063 struct swevent_htable {
8064 struct swevent_hlist *swevent_hlist;
8065 struct mutex hlist_mutex;
8068 /* Recursion avoidance in each contexts */
8069 int recursion[PERF_NR_CONTEXTS];
8072 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8075 * We directly increment event->count and keep a second value in
8076 * event->hw.period_left to count intervals. This period event
8077 * is kept in the range [-sample_period, 0] so that we can use the
8081 u64 perf_swevent_set_period(struct perf_event *event)
8083 struct hw_perf_event *hwc = &event->hw;
8084 u64 period = hwc->last_period;
8088 hwc->last_period = hwc->sample_period;
8091 old = val = local64_read(&hwc->period_left);
8095 nr = div64_u64(period + val, period);
8096 offset = nr * period;
8098 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8104 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8105 struct perf_sample_data *data,
8106 struct pt_regs *regs)
8108 struct hw_perf_event *hwc = &event->hw;
8112 overflow = perf_swevent_set_period(event);
8114 if (hwc->interrupts == MAX_INTERRUPTS)
8117 for (; overflow; overflow--) {
8118 if (__perf_event_overflow(event, throttle,
8121 * We inhibit the overflow from happening when
8122 * hwc->interrupts == MAX_INTERRUPTS.
8130 static void perf_swevent_event(struct perf_event *event, u64 nr,
8131 struct perf_sample_data *data,
8132 struct pt_regs *regs)
8134 struct hw_perf_event *hwc = &event->hw;
8136 local64_add(nr, &event->count);
8141 if (!is_sampling_event(event))
8144 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8146 return perf_swevent_overflow(event, 1, data, regs);
8148 data->period = event->hw.last_period;
8150 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8151 return perf_swevent_overflow(event, 1, data, regs);
8153 if (local64_add_negative(nr, &hwc->period_left))
8156 perf_swevent_overflow(event, 0, data, regs);
8159 static int perf_exclude_event(struct perf_event *event,
8160 struct pt_regs *regs)
8162 if (event->hw.state & PERF_HES_STOPPED)
8166 if (event->attr.exclude_user && user_mode(regs))
8169 if (event->attr.exclude_kernel && !user_mode(regs))
8176 static int perf_swevent_match(struct perf_event *event,
8177 enum perf_type_id type,
8179 struct perf_sample_data *data,
8180 struct pt_regs *regs)
8182 if (event->attr.type != type)
8185 if (event->attr.config != event_id)
8188 if (perf_exclude_event(event, regs))
8194 static inline u64 swevent_hash(u64 type, u32 event_id)
8196 u64 val = event_id | (type << 32);
8198 return hash_64(val, SWEVENT_HLIST_BITS);
8201 static inline struct hlist_head *
8202 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
8204 u64 hash = swevent_hash(type, event_id);
8206 return &hlist->heads[hash];
8209 /* For the read side: events when they trigger */
8210 static inline struct hlist_head *
8211 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
8213 struct swevent_hlist *hlist;
8215 hlist = rcu_dereference(swhash->swevent_hlist);
8219 return __find_swevent_head(hlist, type, event_id);
8222 /* For the event head insertion and removal in the hlist */
8223 static inline struct hlist_head *
8224 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
8226 struct swevent_hlist *hlist;
8227 u32 event_id = event->attr.config;
8228 u64 type = event->attr.type;
8231 * Event scheduling is always serialized against hlist allocation
8232 * and release. Which makes the protected version suitable here.
8233 * The context lock guarantees that.
8235 hlist = rcu_dereference_protected(swhash->swevent_hlist,
8236 lockdep_is_held(&event->ctx->lock));
8240 return __find_swevent_head(hlist, type, event_id);
8243 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
8245 struct perf_sample_data *data,
8246 struct pt_regs *regs)
8248 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8249 struct perf_event *event;
8250 struct hlist_head *head;
8253 head = find_swevent_head_rcu(swhash, type, event_id);
8257 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8258 if (perf_swevent_match(event, type, event_id, data, regs))
8259 perf_swevent_event(event, nr, data, regs);
8265 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
8267 int perf_swevent_get_recursion_context(void)
8269 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8271 return get_recursion_context(swhash->recursion);
8273 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
8275 void perf_swevent_put_recursion_context(int rctx)
8277 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8279 put_recursion_context(swhash->recursion, rctx);
8282 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8284 struct perf_sample_data data;
8286 if (WARN_ON_ONCE(!regs))
8289 perf_sample_data_init(&data, addr, 0);
8290 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
8293 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8297 preempt_disable_notrace();
8298 rctx = perf_swevent_get_recursion_context();
8299 if (unlikely(rctx < 0))
8302 ___perf_sw_event(event_id, nr, regs, addr);
8304 perf_swevent_put_recursion_context(rctx);
8306 preempt_enable_notrace();
8309 static void perf_swevent_read(struct perf_event *event)
8313 static int perf_swevent_add(struct perf_event *event, int flags)
8315 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8316 struct hw_perf_event *hwc = &event->hw;
8317 struct hlist_head *head;
8319 if (is_sampling_event(event)) {
8320 hwc->last_period = hwc->sample_period;
8321 perf_swevent_set_period(event);
8324 hwc->state = !(flags & PERF_EF_START);
8326 head = find_swevent_head(swhash, event);
8327 if (WARN_ON_ONCE(!head))
8330 hlist_add_head_rcu(&event->hlist_entry, head);
8331 perf_event_update_userpage(event);
8336 static void perf_swevent_del(struct perf_event *event, int flags)
8338 hlist_del_rcu(&event->hlist_entry);
8341 static void perf_swevent_start(struct perf_event *event, int flags)
8343 event->hw.state = 0;
8346 static void perf_swevent_stop(struct perf_event *event, int flags)
8348 event->hw.state = PERF_HES_STOPPED;
8351 /* Deref the hlist from the update side */
8352 static inline struct swevent_hlist *
8353 swevent_hlist_deref(struct swevent_htable *swhash)
8355 return rcu_dereference_protected(swhash->swevent_hlist,
8356 lockdep_is_held(&swhash->hlist_mutex));
8359 static void swevent_hlist_release(struct swevent_htable *swhash)
8361 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
8366 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
8367 kfree_rcu(hlist, rcu_head);
8370 static void swevent_hlist_put_cpu(int cpu)
8372 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8374 mutex_lock(&swhash->hlist_mutex);
8376 if (!--swhash->hlist_refcount)
8377 swevent_hlist_release(swhash);
8379 mutex_unlock(&swhash->hlist_mutex);
8382 static void swevent_hlist_put(void)
8386 for_each_possible_cpu(cpu)
8387 swevent_hlist_put_cpu(cpu);
8390 static int swevent_hlist_get_cpu(int cpu)
8392 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8395 mutex_lock(&swhash->hlist_mutex);
8396 if (!swevent_hlist_deref(swhash) &&
8397 cpumask_test_cpu(cpu, perf_online_mask)) {
8398 struct swevent_hlist *hlist;
8400 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
8405 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8407 swhash->hlist_refcount++;
8409 mutex_unlock(&swhash->hlist_mutex);
8414 static int swevent_hlist_get(void)
8416 int err, cpu, failed_cpu;
8418 mutex_lock(&pmus_lock);
8419 for_each_possible_cpu(cpu) {
8420 err = swevent_hlist_get_cpu(cpu);
8426 mutex_unlock(&pmus_lock);
8429 for_each_possible_cpu(cpu) {
8430 if (cpu == failed_cpu)
8432 swevent_hlist_put_cpu(cpu);
8434 mutex_unlock(&pmus_lock);
8438 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
8440 static void sw_perf_event_destroy(struct perf_event *event)
8442 u64 event_id = event->attr.config;
8444 WARN_ON(event->parent);
8446 static_key_slow_dec(&perf_swevent_enabled[event_id]);
8447 swevent_hlist_put();
8450 static int perf_swevent_init(struct perf_event *event)
8452 u64 event_id = event->attr.config;
8454 if (event->attr.type != PERF_TYPE_SOFTWARE)
8458 * no branch sampling for software events
8460 if (has_branch_stack(event))
8464 case PERF_COUNT_SW_CPU_CLOCK:
8465 case PERF_COUNT_SW_TASK_CLOCK:
8472 if (event_id >= PERF_COUNT_SW_MAX)
8475 if (!event->parent) {
8478 err = swevent_hlist_get();
8482 static_key_slow_inc(&perf_swevent_enabled[event_id]);
8483 event->destroy = sw_perf_event_destroy;
8489 static struct pmu perf_swevent = {
8490 .task_ctx_nr = perf_sw_context,
8492 .capabilities = PERF_PMU_CAP_NO_NMI,
8494 .event_init = perf_swevent_init,
8495 .add = perf_swevent_add,
8496 .del = perf_swevent_del,
8497 .start = perf_swevent_start,
8498 .stop = perf_swevent_stop,
8499 .read = perf_swevent_read,
8502 #ifdef CONFIG_EVENT_TRACING
8504 static int perf_tp_filter_match(struct perf_event *event,
8505 struct perf_sample_data *data)
8507 void *record = data->raw->frag.data;
8509 /* only top level events have filters set */
8511 event = event->parent;
8513 if (likely(!event->filter) || filter_match_preds(event->filter, record))
8518 static int perf_tp_event_match(struct perf_event *event,
8519 struct perf_sample_data *data,
8520 struct pt_regs *regs)
8522 if (event->hw.state & PERF_HES_STOPPED)
8525 * All tracepoints are from kernel-space.
8527 if (event->attr.exclude_kernel)
8530 if (!perf_tp_filter_match(event, data))
8536 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
8537 struct trace_event_call *call, u64 count,
8538 struct pt_regs *regs, struct hlist_head *head,
8539 struct task_struct *task)
8541 if (bpf_prog_array_valid(call)) {
8542 *(struct pt_regs **)raw_data = regs;
8543 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
8544 perf_swevent_put_recursion_context(rctx);
8548 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
8551 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
8553 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
8554 struct pt_regs *regs, struct hlist_head *head, int rctx,
8555 struct task_struct *task)
8557 struct perf_sample_data data;
8558 struct perf_event *event;
8560 struct perf_raw_record raw = {
8567 perf_sample_data_init(&data, 0, 0);
8570 perf_trace_buf_update(record, event_type);
8572 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8573 if (perf_tp_event_match(event, &data, regs))
8574 perf_swevent_event(event, count, &data, regs);
8578 * If we got specified a target task, also iterate its context and
8579 * deliver this event there too.
8581 if (task && task != current) {
8582 struct perf_event_context *ctx;
8583 struct trace_entry *entry = record;
8586 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
8590 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8591 if (event->cpu != smp_processor_id())
8593 if (event->attr.type != PERF_TYPE_TRACEPOINT)
8595 if (event->attr.config != entry->type)
8597 if (perf_tp_event_match(event, &data, regs))
8598 perf_swevent_event(event, count, &data, regs);
8604 perf_swevent_put_recursion_context(rctx);
8606 EXPORT_SYMBOL_GPL(perf_tp_event);
8608 static void tp_perf_event_destroy(struct perf_event *event)
8610 perf_trace_destroy(event);
8613 static int perf_tp_event_init(struct perf_event *event)
8617 if (event->attr.type != PERF_TYPE_TRACEPOINT)
8621 * no branch sampling for tracepoint events
8623 if (has_branch_stack(event))
8626 err = perf_trace_init(event);
8630 event->destroy = tp_perf_event_destroy;
8635 static struct pmu perf_tracepoint = {
8636 .task_ctx_nr = perf_sw_context,
8638 .event_init = perf_tp_event_init,
8639 .add = perf_trace_add,
8640 .del = perf_trace_del,
8641 .start = perf_swevent_start,
8642 .stop = perf_swevent_stop,
8643 .read = perf_swevent_read,
8646 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
8648 * Flags in config, used by dynamic PMU kprobe and uprobe
8649 * The flags should match following PMU_FORMAT_ATTR().
8651 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
8652 * if not set, create kprobe/uprobe
8654 * The following values specify a reference counter (or semaphore in the
8655 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
8656 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
8658 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
8659 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
8661 enum perf_probe_config {
8662 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
8663 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
8664 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
8667 PMU_FORMAT_ATTR(retprobe, "config:0");
8670 #ifdef CONFIG_KPROBE_EVENTS
8671 static struct attribute *kprobe_attrs[] = {
8672 &format_attr_retprobe.attr,
8676 static struct attribute_group kprobe_format_group = {
8678 .attrs = kprobe_attrs,
8681 static const struct attribute_group *kprobe_attr_groups[] = {
8682 &kprobe_format_group,
8686 static int perf_kprobe_event_init(struct perf_event *event);
8687 static struct pmu perf_kprobe = {
8688 .task_ctx_nr = perf_sw_context,
8689 .event_init = perf_kprobe_event_init,
8690 .add = perf_trace_add,
8691 .del = perf_trace_del,
8692 .start = perf_swevent_start,
8693 .stop = perf_swevent_stop,
8694 .read = perf_swevent_read,
8695 .attr_groups = kprobe_attr_groups,
8698 static int perf_kprobe_event_init(struct perf_event *event)
8703 if (event->attr.type != perf_kprobe.type)
8706 if (!capable(CAP_SYS_ADMIN))
8710 * no branch sampling for probe events
8712 if (has_branch_stack(event))
8715 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
8716 err = perf_kprobe_init(event, is_retprobe);
8720 event->destroy = perf_kprobe_destroy;
8724 #endif /* CONFIG_KPROBE_EVENTS */
8726 #ifdef CONFIG_UPROBE_EVENTS
8727 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
8729 static struct attribute *uprobe_attrs[] = {
8730 &format_attr_retprobe.attr,
8731 &format_attr_ref_ctr_offset.attr,
8735 static struct attribute_group uprobe_format_group = {
8737 .attrs = uprobe_attrs,
8740 static const struct attribute_group *uprobe_attr_groups[] = {
8741 &uprobe_format_group,
8745 static int perf_uprobe_event_init(struct perf_event *event);
8746 static struct pmu perf_uprobe = {
8747 .task_ctx_nr = perf_sw_context,
8748 .event_init = perf_uprobe_event_init,
8749 .add = perf_trace_add,
8750 .del = perf_trace_del,
8751 .start = perf_swevent_start,
8752 .stop = perf_swevent_stop,
8753 .read = perf_swevent_read,
8754 .attr_groups = uprobe_attr_groups,
8757 static int perf_uprobe_event_init(struct perf_event *event)
8760 unsigned long ref_ctr_offset;
8763 if (event->attr.type != perf_uprobe.type)
8766 if (!capable(CAP_SYS_ADMIN))
8770 * no branch sampling for probe events
8772 if (has_branch_stack(event))
8775 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
8776 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
8777 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
8781 event->destroy = perf_uprobe_destroy;
8785 #endif /* CONFIG_UPROBE_EVENTS */
8787 static inline void perf_tp_register(void)
8789 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
8790 #ifdef CONFIG_KPROBE_EVENTS
8791 perf_pmu_register(&perf_kprobe, "kprobe", -1);
8793 #ifdef CONFIG_UPROBE_EVENTS
8794 perf_pmu_register(&perf_uprobe, "uprobe", -1);
8798 static void perf_event_free_filter(struct perf_event *event)
8800 ftrace_profile_free_filter(event);
8803 #ifdef CONFIG_BPF_SYSCALL
8804 static void bpf_overflow_handler(struct perf_event *event,
8805 struct perf_sample_data *data,
8806 struct pt_regs *regs)
8808 struct bpf_perf_event_data_kern ctx = {
8814 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
8816 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
8819 ret = BPF_PROG_RUN(event->prog, &ctx);
8822 __this_cpu_dec(bpf_prog_active);
8827 event->orig_overflow_handler(event, data, regs);
8830 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
8832 struct bpf_prog *prog;
8834 if (event->overflow_handler_context)
8835 /* hw breakpoint or kernel counter */
8841 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
8843 return PTR_ERR(prog);
8846 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
8847 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
8851 static void perf_event_free_bpf_handler(struct perf_event *event)
8853 struct bpf_prog *prog = event->prog;
8858 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
8863 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
8867 static void perf_event_free_bpf_handler(struct perf_event *event)
8873 * returns true if the event is a tracepoint, or a kprobe/upprobe created
8874 * with perf_event_open()
8876 static inline bool perf_event_is_tracing(struct perf_event *event)
8878 if (event->pmu == &perf_tracepoint)
8880 #ifdef CONFIG_KPROBE_EVENTS
8881 if (event->pmu == &perf_kprobe)
8884 #ifdef CONFIG_UPROBE_EVENTS
8885 if (event->pmu == &perf_uprobe)
8891 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
8893 bool is_kprobe, is_tracepoint, is_syscall_tp;
8894 struct bpf_prog *prog;
8897 if (!perf_event_is_tracing(event))
8898 return perf_event_set_bpf_handler(event, prog_fd);
8900 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
8901 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
8902 is_syscall_tp = is_syscall_trace_event(event->tp_event);
8903 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
8904 /* bpf programs can only be attached to u/kprobe or tracepoint */
8907 prog = bpf_prog_get(prog_fd);
8909 return PTR_ERR(prog);
8911 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
8912 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
8913 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
8914 /* valid fd, but invalid bpf program type */
8919 /* Kprobe override only works for kprobes, not uprobes. */
8920 if (prog->kprobe_override &&
8921 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
8926 if (is_tracepoint || is_syscall_tp) {
8927 int off = trace_event_get_offsets(event->tp_event);
8929 if (prog->aux->max_ctx_offset > off) {
8935 ret = perf_event_attach_bpf_prog(event, prog);
8941 static void perf_event_free_bpf_prog(struct perf_event *event)
8943 if (!perf_event_is_tracing(event)) {
8944 perf_event_free_bpf_handler(event);
8947 perf_event_detach_bpf_prog(event);
8952 static inline void perf_tp_register(void)
8956 static void perf_event_free_filter(struct perf_event *event)
8960 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
8965 static void perf_event_free_bpf_prog(struct perf_event *event)
8968 #endif /* CONFIG_EVENT_TRACING */
8970 #ifdef CONFIG_HAVE_HW_BREAKPOINT
8971 void perf_bp_event(struct perf_event *bp, void *data)
8973 struct perf_sample_data sample;
8974 struct pt_regs *regs = data;
8976 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
8978 if (!bp->hw.state && !perf_exclude_event(bp, regs))
8979 perf_swevent_event(bp, 1, &sample, regs);
8984 * Allocate a new address filter
8986 static struct perf_addr_filter *
8987 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
8989 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
8990 struct perf_addr_filter *filter;
8992 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
8996 INIT_LIST_HEAD(&filter->entry);
8997 list_add_tail(&filter->entry, filters);
9002 static void free_filters_list(struct list_head *filters)
9004 struct perf_addr_filter *filter, *iter;
9006 list_for_each_entry_safe(filter, iter, filters, entry) {
9007 path_put(&filter->path);
9008 list_del(&filter->entry);
9014 * Free existing address filters and optionally install new ones
9016 static void perf_addr_filters_splice(struct perf_event *event,
9017 struct list_head *head)
9019 unsigned long flags;
9022 if (!has_addr_filter(event))
9025 /* don't bother with children, they don't have their own filters */
9029 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9031 list_splice_init(&event->addr_filters.list, &list);
9033 list_splice(head, &event->addr_filters.list);
9035 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9037 free_filters_list(&list);
9041 * Scan through mm's vmas and see if one of them matches the
9042 * @filter; if so, adjust filter's address range.
9043 * Called with mm::mmap_sem down for reading.
9045 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9046 struct mm_struct *mm,
9047 struct perf_addr_filter_range *fr)
9049 struct vm_area_struct *vma;
9051 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9055 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9061 * Update event's address range filters based on the
9062 * task's existing mappings, if any.
9064 static void perf_event_addr_filters_apply(struct perf_event *event)
9066 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9067 struct task_struct *task = READ_ONCE(event->ctx->task);
9068 struct perf_addr_filter *filter;
9069 struct mm_struct *mm = NULL;
9070 unsigned int count = 0;
9071 unsigned long flags;
9074 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9075 * will stop on the parent's child_mutex that our caller is also holding
9077 if (task == TASK_TOMBSTONE)
9080 if (ifh->nr_file_filters) {
9081 mm = get_task_mm(event->ctx->task);
9085 down_read(&mm->mmap_sem);
9088 raw_spin_lock_irqsave(&ifh->lock, flags);
9089 list_for_each_entry(filter, &ifh->list, entry) {
9090 if (filter->path.dentry) {
9092 * Adjust base offset if the filter is associated to a
9093 * binary that needs to be mapped:
9095 event->addr_filter_ranges[count].start = 0;
9096 event->addr_filter_ranges[count].size = 0;
9098 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9100 event->addr_filter_ranges[count].start = filter->offset;
9101 event->addr_filter_ranges[count].size = filter->size;
9107 event->addr_filters_gen++;
9108 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9110 if (ifh->nr_file_filters) {
9111 up_read(&mm->mmap_sem);
9117 perf_event_stop(event, 1);
9121 * Address range filtering: limiting the data to certain
9122 * instruction address ranges. Filters are ioctl()ed to us from
9123 * userspace as ascii strings.
9125 * Filter string format:
9128 * where ACTION is one of the
9129 * * "filter": limit the trace to this region
9130 * * "start": start tracing from this address
9131 * * "stop": stop tracing at this address/region;
9133 * * for kernel addresses: <start address>[/<size>]
9134 * * for object files: <start address>[/<size>]@</path/to/object/file>
9136 * if <size> is not specified or is zero, the range is treated as a single
9137 * address; not valid for ACTION=="filter".
9151 IF_STATE_ACTION = 0,
9156 static const match_table_t if_tokens = {
9157 { IF_ACT_FILTER, "filter" },
9158 { IF_ACT_START, "start" },
9159 { IF_ACT_STOP, "stop" },
9160 { IF_SRC_FILE, "%u/%u@%s" },
9161 { IF_SRC_KERNEL, "%u/%u" },
9162 { IF_SRC_FILEADDR, "%u@%s" },
9163 { IF_SRC_KERNELADDR, "%u" },
9164 { IF_ACT_NONE, NULL },
9168 * Address filter string parser
9171 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9172 struct list_head *filters)
9174 struct perf_addr_filter *filter = NULL;
9175 char *start, *orig, *filename = NULL;
9176 substring_t args[MAX_OPT_ARGS];
9177 int state = IF_STATE_ACTION, token;
9178 unsigned int kernel = 0;
9181 orig = fstr = kstrdup(fstr, GFP_KERNEL);
9185 while ((start = strsep(&fstr, " ,\n")) != NULL) {
9186 static const enum perf_addr_filter_action_t actions[] = {
9187 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
9188 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
9189 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
9196 /* filter definition begins */
9197 if (state == IF_STATE_ACTION) {
9198 filter = perf_addr_filter_new(event, filters);
9203 token = match_token(start, if_tokens, args);
9208 if (state != IF_STATE_ACTION)
9211 filter->action = actions[token];
9212 state = IF_STATE_SOURCE;
9215 case IF_SRC_KERNELADDR:
9220 case IF_SRC_FILEADDR:
9222 if (state != IF_STATE_SOURCE)
9226 ret = kstrtoul(args[0].from, 0, &filter->offset);
9230 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
9232 ret = kstrtoul(args[1].from, 0, &filter->size);
9237 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
9238 int fpos = token == IF_SRC_FILE ? 2 : 1;
9240 filename = match_strdup(&args[fpos]);
9247 state = IF_STATE_END;
9255 * Filter definition is fully parsed, validate and install it.
9256 * Make sure that it doesn't contradict itself or the event's
9259 if (state == IF_STATE_END) {
9261 if (kernel && event->attr.exclude_kernel)
9265 * ACTION "filter" must have a non-zero length region
9268 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
9277 * For now, we only support file-based filters
9278 * in per-task events; doing so for CPU-wide
9279 * events requires additional context switching
9280 * trickery, since same object code will be
9281 * mapped at different virtual addresses in
9282 * different processes.
9285 if (!event->ctx->task)
9286 goto fail_free_name;
9288 /* look up the path and grab its inode */
9289 ret = kern_path(filename, LOOKUP_FOLLOW,
9292 goto fail_free_name;
9298 if (!filter->path.dentry ||
9299 !S_ISREG(d_inode(filter->path.dentry)
9303 event->addr_filters.nr_file_filters++;
9306 /* ready to consume more filters */
9307 state = IF_STATE_ACTION;
9312 if (state != IF_STATE_ACTION)
9322 free_filters_list(filters);
9329 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
9335 * Since this is called in perf_ioctl() path, we're already holding
9338 lockdep_assert_held(&event->ctx->mutex);
9340 if (WARN_ON_ONCE(event->parent))
9343 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
9345 goto fail_clear_files;
9347 ret = event->pmu->addr_filters_validate(&filters);
9349 goto fail_free_filters;
9351 /* remove existing filters, if any */
9352 perf_addr_filters_splice(event, &filters);
9354 /* install new filters */
9355 perf_event_for_each_child(event, perf_event_addr_filters_apply);
9360 free_filters_list(&filters);
9363 event->addr_filters.nr_file_filters = 0;
9368 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
9373 filter_str = strndup_user(arg, PAGE_SIZE);
9374 if (IS_ERR(filter_str))
9375 return PTR_ERR(filter_str);
9377 #ifdef CONFIG_EVENT_TRACING
9378 if (perf_event_is_tracing(event)) {
9379 struct perf_event_context *ctx = event->ctx;
9382 * Beware, here be dragons!!
9384 * the tracepoint muck will deadlock against ctx->mutex, but
9385 * the tracepoint stuff does not actually need it. So
9386 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
9387 * already have a reference on ctx.
9389 * This can result in event getting moved to a different ctx,
9390 * but that does not affect the tracepoint state.
9392 mutex_unlock(&ctx->mutex);
9393 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
9394 mutex_lock(&ctx->mutex);
9397 if (has_addr_filter(event))
9398 ret = perf_event_set_addr_filter(event, filter_str);
9405 * hrtimer based swevent callback
9408 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
9410 enum hrtimer_restart ret = HRTIMER_RESTART;
9411 struct perf_sample_data data;
9412 struct pt_regs *regs;
9413 struct perf_event *event;
9416 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
9418 if (event->state != PERF_EVENT_STATE_ACTIVE)
9419 return HRTIMER_NORESTART;
9421 event->pmu->read(event);
9423 perf_sample_data_init(&data, 0, event->hw.last_period);
9424 regs = get_irq_regs();
9426 if (regs && !perf_exclude_event(event, regs)) {
9427 if (!(event->attr.exclude_idle && is_idle_task(current)))
9428 if (__perf_event_overflow(event, 1, &data, regs))
9429 ret = HRTIMER_NORESTART;
9432 period = max_t(u64, 10000, event->hw.sample_period);
9433 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
9438 static void perf_swevent_start_hrtimer(struct perf_event *event)
9440 struct hw_perf_event *hwc = &event->hw;
9443 if (!is_sampling_event(event))
9446 period = local64_read(&hwc->period_left);
9451 local64_set(&hwc->period_left, 0);
9453 period = max_t(u64, 10000, hwc->sample_period);
9455 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
9456 HRTIMER_MODE_REL_PINNED);
9459 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
9461 struct hw_perf_event *hwc = &event->hw;
9463 if (is_sampling_event(event)) {
9464 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
9465 local64_set(&hwc->period_left, ktime_to_ns(remaining));
9467 hrtimer_cancel(&hwc->hrtimer);
9471 static void perf_swevent_init_hrtimer(struct perf_event *event)
9473 struct hw_perf_event *hwc = &event->hw;
9475 if (!is_sampling_event(event))
9478 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
9479 hwc->hrtimer.function = perf_swevent_hrtimer;
9482 * Since hrtimers have a fixed rate, we can do a static freq->period
9483 * mapping and avoid the whole period adjust feedback stuff.
9485 if (event->attr.freq) {
9486 long freq = event->attr.sample_freq;
9488 event->attr.sample_period = NSEC_PER_SEC / freq;
9489 hwc->sample_period = event->attr.sample_period;
9490 local64_set(&hwc->period_left, hwc->sample_period);
9491 hwc->last_period = hwc->sample_period;
9492 event->attr.freq = 0;
9497 * Software event: cpu wall time clock
9500 static void cpu_clock_event_update(struct perf_event *event)
9505 now = local_clock();
9506 prev = local64_xchg(&event->hw.prev_count, now);
9507 local64_add(now - prev, &event->count);
9510 static void cpu_clock_event_start(struct perf_event *event, int flags)
9512 local64_set(&event->hw.prev_count, local_clock());
9513 perf_swevent_start_hrtimer(event);
9516 static void cpu_clock_event_stop(struct perf_event *event, int flags)
9518 perf_swevent_cancel_hrtimer(event);
9519 cpu_clock_event_update(event);
9522 static int cpu_clock_event_add(struct perf_event *event, int flags)
9524 if (flags & PERF_EF_START)
9525 cpu_clock_event_start(event, flags);
9526 perf_event_update_userpage(event);
9531 static void cpu_clock_event_del(struct perf_event *event, int flags)
9533 cpu_clock_event_stop(event, flags);
9536 static void cpu_clock_event_read(struct perf_event *event)
9538 cpu_clock_event_update(event);
9541 static int cpu_clock_event_init(struct perf_event *event)
9543 if (event->attr.type != PERF_TYPE_SOFTWARE)
9546 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
9550 * no branch sampling for software events
9552 if (has_branch_stack(event))
9555 perf_swevent_init_hrtimer(event);
9560 static struct pmu perf_cpu_clock = {
9561 .task_ctx_nr = perf_sw_context,
9563 .capabilities = PERF_PMU_CAP_NO_NMI,
9565 .event_init = cpu_clock_event_init,
9566 .add = cpu_clock_event_add,
9567 .del = cpu_clock_event_del,
9568 .start = cpu_clock_event_start,
9569 .stop = cpu_clock_event_stop,
9570 .read = cpu_clock_event_read,
9574 * Software event: task time clock
9577 static void task_clock_event_update(struct perf_event *event, u64 now)
9582 prev = local64_xchg(&event->hw.prev_count, now);
9584 local64_add(delta, &event->count);
9587 static void task_clock_event_start(struct perf_event *event, int flags)
9589 local64_set(&event->hw.prev_count, event->ctx->time);
9590 perf_swevent_start_hrtimer(event);
9593 static void task_clock_event_stop(struct perf_event *event, int flags)
9595 perf_swevent_cancel_hrtimer(event);
9596 task_clock_event_update(event, event->ctx->time);
9599 static int task_clock_event_add(struct perf_event *event, int flags)
9601 if (flags & PERF_EF_START)
9602 task_clock_event_start(event, flags);
9603 perf_event_update_userpage(event);
9608 static void task_clock_event_del(struct perf_event *event, int flags)
9610 task_clock_event_stop(event, PERF_EF_UPDATE);
9613 static void task_clock_event_read(struct perf_event *event)
9615 u64 now = perf_clock();
9616 u64 delta = now - event->ctx->timestamp;
9617 u64 time = event->ctx->time + delta;
9619 task_clock_event_update(event, time);
9622 static int task_clock_event_init(struct perf_event *event)
9624 if (event->attr.type != PERF_TYPE_SOFTWARE)
9627 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
9631 * no branch sampling for software events
9633 if (has_branch_stack(event))
9636 perf_swevent_init_hrtimer(event);
9641 static struct pmu perf_task_clock = {
9642 .task_ctx_nr = perf_sw_context,
9644 .capabilities = PERF_PMU_CAP_NO_NMI,
9646 .event_init = task_clock_event_init,
9647 .add = task_clock_event_add,
9648 .del = task_clock_event_del,
9649 .start = task_clock_event_start,
9650 .stop = task_clock_event_stop,
9651 .read = task_clock_event_read,
9654 static void perf_pmu_nop_void(struct pmu *pmu)
9658 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
9662 static int perf_pmu_nop_int(struct pmu *pmu)
9667 static int perf_event_nop_int(struct perf_event *event, u64 value)
9672 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
9674 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
9676 __this_cpu_write(nop_txn_flags, flags);
9678 if (flags & ~PERF_PMU_TXN_ADD)
9681 perf_pmu_disable(pmu);
9684 static int perf_pmu_commit_txn(struct pmu *pmu)
9686 unsigned int flags = __this_cpu_read(nop_txn_flags);
9688 __this_cpu_write(nop_txn_flags, 0);
9690 if (flags & ~PERF_PMU_TXN_ADD)
9693 perf_pmu_enable(pmu);
9697 static void perf_pmu_cancel_txn(struct pmu *pmu)
9699 unsigned int flags = __this_cpu_read(nop_txn_flags);
9701 __this_cpu_write(nop_txn_flags, 0);
9703 if (flags & ~PERF_PMU_TXN_ADD)
9706 perf_pmu_enable(pmu);
9709 static int perf_event_idx_default(struct perf_event *event)
9715 * Ensures all contexts with the same task_ctx_nr have the same
9716 * pmu_cpu_context too.
9718 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
9725 list_for_each_entry(pmu, &pmus, entry) {
9726 if (pmu->task_ctx_nr == ctxn)
9727 return pmu->pmu_cpu_context;
9733 static void free_pmu_context(struct pmu *pmu)
9736 * Static contexts such as perf_sw_context have a global lifetime
9737 * and may be shared between different PMUs. Avoid freeing them
9738 * when a single PMU is going away.
9740 if (pmu->task_ctx_nr > perf_invalid_context)
9743 free_percpu(pmu->pmu_cpu_context);
9747 * Let userspace know that this PMU supports address range filtering:
9749 static ssize_t nr_addr_filters_show(struct device *dev,
9750 struct device_attribute *attr,
9753 struct pmu *pmu = dev_get_drvdata(dev);
9755 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
9757 DEVICE_ATTR_RO(nr_addr_filters);
9759 static struct idr pmu_idr;
9762 type_show(struct device *dev, struct device_attribute *attr, char *page)
9764 struct pmu *pmu = dev_get_drvdata(dev);
9766 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
9768 static DEVICE_ATTR_RO(type);
9771 perf_event_mux_interval_ms_show(struct device *dev,
9772 struct device_attribute *attr,
9775 struct pmu *pmu = dev_get_drvdata(dev);
9777 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
9780 static DEFINE_MUTEX(mux_interval_mutex);
9783 perf_event_mux_interval_ms_store(struct device *dev,
9784 struct device_attribute *attr,
9785 const char *buf, size_t count)
9787 struct pmu *pmu = dev_get_drvdata(dev);
9788 int timer, cpu, ret;
9790 ret = kstrtoint(buf, 0, &timer);
9797 /* same value, noting to do */
9798 if (timer == pmu->hrtimer_interval_ms)
9801 mutex_lock(&mux_interval_mutex);
9802 pmu->hrtimer_interval_ms = timer;
9804 /* update all cpuctx for this PMU */
9806 for_each_online_cpu(cpu) {
9807 struct perf_cpu_context *cpuctx;
9808 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9809 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
9811 cpu_function_call(cpu,
9812 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
9815 mutex_unlock(&mux_interval_mutex);
9819 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
9821 static struct attribute *pmu_dev_attrs[] = {
9822 &dev_attr_type.attr,
9823 &dev_attr_perf_event_mux_interval_ms.attr,
9826 ATTRIBUTE_GROUPS(pmu_dev);
9828 static int pmu_bus_running;
9829 static struct bus_type pmu_bus = {
9830 .name = "event_source",
9831 .dev_groups = pmu_dev_groups,
9834 static void pmu_dev_release(struct device *dev)
9839 static int pmu_dev_alloc(struct pmu *pmu)
9843 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
9847 pmu->dev->groups = pmu->attr_groups;
9848 device_initialize(pmu->dev);
9849 ret = dev_set_name(pmu->dev, "%s", pmu->name);
9853 dev_set_drvdata(pmu->dev, pmu);
9854 pmu->dev->bus = &pmu_bus;
9855 pmu->dev->release = pmu_dev_release;
9856 ret = device_add(pmu->dev);
9860 /* For PMUs with address filters, throw in an extra attribute: */
9861 if (pmu->nr_addr_filters)
9862 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
9871 device_del(pmu->dev);
9874 put_device(pmu->dev);
9878 static struct lock_class_key cpuctx_mutex;
9879 static struct lock_class_key cpuctx_lock;
9881 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
9885 mutex_lock(&pmus_lock);
9887 pmu->pmu_disable_count = alloc_percpu(int);
9888 if (!pmu->pmu_disable_count)
9897 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
9905 if (pmu_bus_running) {
9906 ret = pmu_dev_alloc(pmu);
9912 if (pmu->task_ctx_nr == perf_hw_context) {
9913 static int hw_context_taken = 0;
9916 * Other than systems with heterogeneous CPUs, it never makes
9917 * sense for two PMUs to share perf_hw_context. PMUs which are
9918 * uncore must use perf_invalid_context.
9920 if (WARN_ON_ONCE(hw_context_taken &&
9921 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
9922 pmu->task_ctx_nr = perf_invalid_context;
9924 hw_context_taken = 1;
9927 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
9928 if (pmu->pmu_cpu_context)
9929 goto got_cpu_context;
9932 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
9933 if (!pmu->pmu_cpu_context)
9936 for_each_possible_cpu(cpu) {
9937 struct perf_cpu_context *cpuctx;
9939 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9940 __perf_event_init_context(&cpuctx->ctx);
9941 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
9942 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
9943 cpuctx->ctx.pmu = pmu;
9944 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
9946 __perf_mux_hrtimer_init(cpuctx, cpu);
9950 if (!pmu->start_txn) {
9951 if (pmu->pmu_enable) {
9953 * If we have pmu_enable/pmu_disable calls, install
9954 * transaction stubs that use that to try and batch
9955 * hardware accesses.
9957 pmu->start_txn = perf_pmu_start_txn;
9958 pmu->commit_txn = perf_pmu_commit_txn;
9959 pmu->cancel_txn = perf_pmu_cancel_txn;
9961 pmu->start_txn = perf_pmu_nop_txn;
9962 pmu->commit_txn = perf_pmu_nop_int;
9963 pmu->cancel_txn = perf_pmu_nop_void;
9967 if (!pmu->pmu_enable) {
9968 pmu->pmu_enable = perf_pmu_nop_void;
9969 pmu->pmu_disable = perf_pmu_nop_void;
9972 if (!pmu->check_period)
9973 pmu->check_period = perf_event_nop_int;
9975 if (!pmu->event_idx)
9976 pmu->event_idx = perf_event_idx_default;
9978 list_add_rcu(&pmu->entry, &pmus);
9979 atomic_set(&pmu->exclusive_cnt, 0);
9982 mutex_unlock(&pmus_lock);
9987 device_del(pmu->dev);
9988 put_device(pmu->dev);
9991 if (pmu->type >= PERF_TYPE_MAX)
9992 idr_remove(&pmu_idr, pmu->type);
9995 free_percpu(pmu->pmu_disable_count);
9998 EXPORT_SYMBOL_GPL(perf_pmu_register);
10000 void perf_pmu_unregister(struct pmu *pmu)
10002 mutex_lock(&pmus_lock);
10003 list_del_rcu(&pmu->entry);
10006 * We dereference the pmu list under both SRCU and regular RCU, so
10007 * synchronize against both of those.
10009 synchronize_srcu(&pmus_srcu);
10012 free_percpu(pmu->pmu_disable_count);
10013 if (pmu->type >= PERF_TYPE_MAX)
10014 idr_remove(&pmu_idr, pmu->type);
10015 if (pmu_bus_running) {
10016 if (pmu->nr_addr_filters)
10017 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10018 device_del(pmu->dev);
10019 put_device(pmu->dev);
10021 free_pmu_context(pmu);
10022 mutex_unlock(&pmus_lock);
10024 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10026 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10028 struct perf_event_context *ctx = NULL;
10031 if (!try_module_get(pmu->module))
10035 * A number of pmu->event_init() methods iterate the sibling_list to,
10036 * for example, validate if the group fits on the PMU. Therefore,
10037 * if this is a sibling event, acquire the ctx->mutex to protect
10038 * the sibling_list.
10040 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10042 * This ctx->mutex can nest when we're called through
10043 * inheritance. See the perf_event_ctx_lock_nested() comment.
10045 ctx = perf_event_ctx_lock_nested(event->group_leader,
10046 SINGLE_DEPTH_NESTING);
10051 ret = pmu->event_init(event);
10054 perf_event_ctx_unlock(event->group_leader, ctx);
10057 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10058 event_has_any_exclude_flag(event)) {
10059 if (event->destroy)
10060 event->destroy(event);
10066 module_put(pmu->module);
10071 static struct pmu *perf_init_event(struct perf_event *event)
10077 idx = srcu_read_lock(&pmus_srcu);
10079 /* Try parent's PMU first: */
10080 if (event->parent && event->parent->pmu) {
10081 pmu = event->parent->pmu;
10082 ret = perf_try_init_event(pmu, event);
10088 pmu = idr_find(&pmu_idr, event->attr.type);
10091 ret = perf_try_init_event(pmu, event);
10093 pmu = ERR_PTR(ret);
10097 list_for_each_entry_rcu(pmu, &pmus, entry) {
10098 ret = perf_try_init_event(pmu, event);
10102 if (ret != -ENOENT) {
10103 pmu = ERR_PTR(ret);
10107 pmu = ERR_PTR(-ENOENT);
10109 srcu_read_unlock(&pmus_srcu, idx);
10114 static void attach_sb_event(struct perf_event *event)
10116 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10118 raw_spin_lock(&pel->lock);
10119 list_add_rcu(&event->sb_list, &pel->list);
10120 raw_spin_unlock(&pel->lock);
10124 * We keep a list of all !task (and therefore per-cpu) events
10125 * that need to receive side-band records.
10127 * This avoids having to scan all the various PMU per-cpu contexts
10128 * looking for them.
10130 static void account_pmu_sb_event(struct perf_event *event)
10132 if (is_sb_event(event))
10133 attach_sb_event(event);
10136 static void account_event_cpu(struct perf_event *event, int cpu)
10141 if (is_cgroup_event(event))
10142 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
10145 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
10146 static void account_freq_event_nohz(void)
10148 #ifdef CONFIG_NO_HZ_FULL
10149 /* Lock so we don't race with concurrent unaccount */
10150 spin_lock(&nr_freq_lock);
10151 if (atomic_inc_return(&nr_freq_events) == 1)
10152 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
10153 spin_unlock(&nr_freq_lock);
10157 static void account_freq_event(void)
10159 if (tick_nohz_full_enabled())
10160 account_freq_event_nohz();
10162 atomic_inc(&nr_freq_events);
10166 static void account_event(struct perf_event *event)
10173 if (event->attach_state & PERF_ATTACH_TASK)
10175 if (event->attr.mmap || event->attr.mmap_data)
10176 atomic_inc(&nr_mmap_events);
10177 if (event->attr.comm)
10178 atomic_inc(&nr_comm_events);
10179 if (event->attr.namespaces)
10180 atomic_inc(&nr_namespaces_events);
10181 if (event->attr.task)
10182 atomic_inc(&nr_task_events);
10183 if (event->attr.freq)
10184 account_freq_event();
10185 if (event->attr.context_switch) {
10186 atomic_inc(&nr_switch_events);
10189 if (has_branch_stack(event))
10191 if (is_cgroup_event(event))
10193 if (event->attr.ksymbol)
10194 atomic_inc(&nr_ksymbol_events);
10195 if (event->attr.bpf_event)
10196 atomic_inc(&nr_bpf_events);
10200 * We need the mutex here because static_branch_enable()
10201 * must complete *before* the perf_sched_count increment
10204 if (atomic_inc_not_zero(&perf_sched_count))
10207 mutex_lock(&perf_sched_mutex);
10208 if (!atomic_read(&perf_sched_count)) {
10209 static_branch_enable(&perf_sched_events);
10211 * Guarantee that all CPUs observe they key change and
10212 * call the perf scheduling hooks before proceeding to
10213 * install events that need them.
10218 * Now that we have waited for the sync_sched(), allow further
10219 * increments to by-pass the mutex.
10221 atomic_inc(&perf_sched_count);
10222 mutex_unlock(&perf_sched_mutex);
10226 account_event_cpu(event, event->cpu);
10228 account_pmu_sb_event(event);
10232 * Allocate and initialize an event structure
10234 static struct perf_event *
10235 perf_event_alloc(struct perf_event_attr *attr, int cpu,
10236 struct task_struct *task,
10237 struct perf_event *group_leader,
10238 struct perf_event *parent_event,
10239 perf_overflow_handler_t overflow_handler,
10240 void *context, int cgroup_fd)
10243 struct perf_event *event;
10244 struct hw_perf_event *hwc;
10245 long err = -EINVAL;
10247 if ((unsigned)cpu >= nr_cpu_ids) {
10248 if (!task || cpu != -1)
10249 return ERR_PTR(-EINVAL);
10252 event = kzalloc(sizeof(*event), GFP_KERNEL);
10254 return ERR_PTR(-ENOMEM);
10257 * Single events are their own group leaders, with an
10258 * empty sibling list:
10261 group_leader = event;
10263 mutex_init(&event->child_mutex);
10264 INIT_LIST_HEAD(&event->child_list);
10266 INIT_LIST_HEAD(&event->event_entry);
10267 INIT_LIST_HEAD(&event->sibling_list);
10268 INIT_LIST_HEAD(&event->active_list);
10269 init_event_group(event);
10270 INIT_LIST_HEAD(&event->rb_entry);
10271 INIT_LIST_HEAD(&event->active_entry);
10272 INIT_LIST_HEAD(&event->addr_filters.list);
10273 INIT_HLIST_NODE(&event->hlist_entry);
10276 init_waitqueue_head(&event->waitq);
10277 event->pending_disable = -1;
10278 init_irq_work(&event->pending, perf_pending_event);
10280 mutex_init(&event->mmap_mutex);
10281 raw_spin_lock_init(&event->addr_filters.lock);
10283 atomic_long_set(&event->refcount, 1);
10285 event->attr = *attr;
10286 event->group_leader = group_leader;
10290 event->parent = parent_event;
10292 event->ns = get_pid_ns(task_active_pid_ns(current));
10293 event->id = atomic64_inc_return(&perf_event_id);
10295 event->state = PERF_EVENT_STATE_INACTIVE;
10298 event->attach_state = PERF_ATTACH_TASK;
10300 * XXX pmu::event_init needs to know what task to account to
10301 * and we cannot use the ctx information because we need the
10302 * pmu before we get a ctx.
10304 get_task_struct(task);
10305 event->hw.target = task;
10308 event->clock = &local_clock;
10310 event->clock = parent_event->clock;
10312 if (!overflow_handler && parent_event) {
10313 overflow_handler = parent_event->overflow_handler;
10314 context = parent_event->overflow_handler_context;
10315 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
10316 if (overflow_handler == bpf_overflow_handler) {
10317 struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
10319 if (IS_ERR(prog)) {
10320 err = PTR_ERR(prog);
10323 event->prog = prog;
10324 event->orig_overflow_handler =
10325 parent_event->orig_overflow_handler;
10330 if (overflow_handler) {
10331 event->overflow_handler = overflow_handler;
10332 event->overflow_handler_context = context;
10333 } else if (is_write_backward(event)){
10334 event->overflow_handler = perf_event_output_backward;
10335 event->overflow_handler_context = NULL;
10337 event->overflow_handler = perf_event_output_forward;
10338 event->overflow_handler_context = NULL;
10341 perf_event__state_init(event);
10346 hwc->sample_period = attr->sample_period;
10347 if (attr->freq && attr->sample_freq)
10348 hwc->sample_period = 1;
10349 hwc->last_period = hwc->sample_period;
10351 local64_set(&hwc->period_left, hwc->sample_period);
10354 * We currently do not support PERF_SAMPLE_READ on inherited events.
10355 * See perf_output_read().
10357 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
10360 if (!has_branch_stack(event))
10361 event->attr.branch_sample_type = 0;
10363 if (cgroup_fd != -1) {
10364 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
10369 pmu = perf_init_event(event);
10371 err = PTR_ERR(pmu);
10375 err = exclusive_event_init(event);
10379 if (has_addr_filter(event)) {
10380 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
10381 sizeof(struct perf_addr_filter_range),
10383 if (!event->addr_filter_ranges) {
10389 * Clone the parent's vma offsets: they are valid until exec()
10390 * even if the mm is not shared with the parent.
10392 if (event->parent) {
10393 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10395 raw_spin_lock_irq(&ifh->lock);
10396 memcpy(event->addr_filter_ranges,
10397 event->parent->addr_filter_ranges,
10398 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
10399 raw_spin_unlock_irq(&ifh->lock);
10402 /* force hw sync on the address filters */
10403 event->addr_filters_gen = 1;
10406 if (!event->parent) {
10407 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
10408 err = get_callchain_buffers(attr->sample_max_stack);
10410 goto err_addr_filters;
10414 /* symmetric to unaccount_event() in _free_event() */
10415 account_event(event);
10420 kfree(event->addr_filter_ranges);
10423 exclusive_event_destroy(event);
10426 if (event->destroy)
10427 event->destroy(event);
10428 module_put(pmu->module);
10430 if (is_cgroup_event(event))
10431 perf_detach_cgroup(event);
10433 put_pid_ns(event->ns);
10434 if (event->hw.target)
10435 put_task_struct(event->hw.target);
10438 return ERR_PTR(err);
10441 static int perf_copy_attr(struct perf_event_attr __user *uattr,
10442 struct perf_event_attr *attr)
10447 if (!access_ok(uattr, PERF_ATTR_SIZE_VER0))
10451 * zero the full structure, so that a short copy will be nice.
10453 memset(attr, 0, sizeof(*attr));
10455 ret = get_user(size, &uattr->size);
10459 if (size > PAGE_SIZE) /* silly large */
10462 if (!size) /* abi compat */
10463 size = PERF_ATTR_SIZE_VER0;
10465 if (size < PERF_ATTR_SIZE_VER0)
10469 * If we're handed a bigger struct than we know of,
10470 * ensure all the unknown bits are 0 - i.e. new
10471 * user-space does not rely on any kernel feature
10472 * extensions we dont know about yet.
10474 if (size > sizeof(*attr)) {
10475 unsigned char __user *addr;
10476 unsigned char __user *end;
10479 addr = (void __user *)uattr + sizeof(*attr);
10480 end = (void __user *)uattr + size;
10482 for (; addr < end; addr++) {
10483 ret = get_user(val, addr);
10489 size = sizeof(*attr);
10492 ret = copy_from_user(attr, uattr, size);
10498 if (attr->__reserved_1)
10501 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
10504 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
10507 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
10508 u64 mask = attr->branch_sample_type;
10510 /* only using defined bits */
10511 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
10514 /* at least one branch bit must be set */
10515 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
10518 /* propagate priv level, when not set for branch */
10519 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
10521 /* exclude_kernel checked on syscall entry */
10522 if (!attr->exclude_kernel)
10523 mask |= PERF_SAMPLE_BRANCH_KERNEL;
10525 if (!attr->exclude_user)
10526 mask |= PERF_SAMPLE_BRANCH_USER;
10528 if (!attr->exclude_hv)
10529 mask |= PERF_SAMPLE_BRANCH_HV;
10531 * adjust user setting (for HW filter setup)
10533 attr->branch_sample_type = mask;
10535 /* privileged levels capture (kernel, hv): check permissions */
10536 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
10537 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
10541 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
10542 ret = perf_reg_validate(attr->sample_regs_user);
10547 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
10548 if (!arch_perf_have_user_stack_dump())
10552 * We have __u32 type for the size, but so far
10553 * we can only use __u16 as maximum due to the
10554 * __u16 sample size limit.
10556 if (attr->sample_stack_user >= USHRT_MAX)
10558 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
10562 if (!attr->sample_max_stack)
10563 attr->sample_max_stack = sysctl_perf_event_max_stack;
10565 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
10566 ret = perf_reg_validate(attr->sample_regs_intr);
10571 put_user(sizeof(*attr), &uattr->size);
10577 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
10579 struct ring_buffer *rb = NULL;
10585 /* don't allow circular references */
10586 if (event == output_event)
10590 * Don't allow cross-cpu buffers
10592 if (output_event->cpu != event->cpu)
10596 * If its not a per-cpu rb, it must be the same task.
10598 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
10602 * Mixing clocks in the same buffer is trouble you don't need.
10604 if (output_event->clock != event->clock)
10608 * Either writing ring buffer from beginning or from end.
10609 * Mixing is not allowed.
10611 if (is_write_backward(output_event) != is_write_backward(event))
10615 * If both events generate aux data, they must be on the same PMU
10617 if (has_aux(event) && has_aux(output_event) &&
10618 event->pmu != output_event->pmu)
10622 mutex_lock(&event->mmap_mutex);
10623 /* Can't redirect output if we've got an active mmap() */
10624 if (atomic_read(&event->mmap_count))
10627 if (output_event) {
10628 /* get the rb we want to redirect to */
10629 rb = ring_buffer_get(output_event);
10634 ring_buffer_attach(event, rb);
10638 mutex_unlock(&event->mmap_mutex);
10644 static void mutex_lock_double(struct mutex *a, struct mutex *b)
10650 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
10653 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
10655 bool nmi_safe = false;
10658 case CLOCK_MONOTONIC:
10659 event->clock = &ktime_get_mono_fast_ns;
10663 case CLOCK_MONOTONIC_RAW:
10664 event->clock = &ktime_get_raw_fast_ns;
10668 case CLOCK_REALTIME:
10669 event->clock = &ktime_get_real_ns;
10672 case CLOCK_BOOTTIME:
10673 event->clock = &ktime_get_boot_ns;
10677 event->clock = &ktime_get_tai_ns;
10684 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
10691 * Variation on perf_event_ctx_lock_nested(), except we take two context
10694 static struct perf_event_context *
10695 __perf_event_ctx_lock_double(struct perf_event *group_leader,
10696 struct perf_event_context *ctx)
10698 struct perf_event_context *gctx;
10702 gctx = READ_ONCE(group_leader->ctx);
10703 if (!refcount_inc_not_zero(&gctx->refcount)) {
10709 mutex_lock_double(&gctx->mutex, &ctx->mutex);
10711 if (group_leader->ctx != gctx) {
10712 mutex_unlock(&ctx->mutex);
10713 mutex_unlock(&gctx->mutex);
10722 * sys_perf_event_open - open a performance event, associate it to a task/cpu
10724 * @attr_uptr: event_id type attributes for monitoring/sampling
10727 * @group_fd: group leader event fd
10729 SYSCALL_DEFINE5(perf_event_open,
10730 struct perf_event_attr __user *, attr_uptr,
10731 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
10733 struct perf_event *group_leader = NULL, *output_event = NULL;
10734 struct perf_event *event, *sibling;
10735 struct perf_event_attr attr;
10736 struct perf_event_context *ctx, *uninitialized_var(gctx);
10737 struct file *event_file = NULL;
10738 struct fd group = {NULL, 0};
10739 struct task_struct *task = NULL;
10742 int move_group = 0;
10744 int f_flags = O_RDWR;
10745 int cgroup_fd = -1;
10747 /* for future expandability... */
10748 if (flags & ~PERF_FLAG_ALL)
10751 err = perf_copy_attr(attr_uptr, &attr);
10755 if (!attr.exclude_kernel) {
10756 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
10760 if (attr.namespaces) {
10761 if (!capable(CAP_SYS_ADMIN))
10766 if (attr.sample_freq > sysctl_perf_event_sample_rate)
10769 if (attr.sample_period & (1ULL << 63))
10773 /* Only privileged users can get physical addresses */
10774 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR) &&
10775 perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
10779 * In cgroup mode, the pid argument is used to pass the fd
10780 * opened to the cgroup directory in cgroupfs. The cpu argument
10781 * designates the cpu on which to monitor threads from that
10784 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
10787 if (flags & PERF_FLAG_FD_CLOEXEC)
10788 f_flags |= O_CLOEXEC;
10790 event_fd = get_unused_fd_flags(f_flags);
10794 if (group_fd != -1) {
10795 err = perf_fget_light(group_fd, &group);
10798 group_leader = group.file->private_data;
10799 if (flags & PERF_FLAG_FD_OUTPUT)
10800 output_event = group_leader;
10801 if (flags & PERF_FLAG_FD_NO_GROUP)
10802 group_leader = NULL;
10805 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
10806 task = find_lively_task_by_vpid(pid);
10807 if (IS_ERR(task)) {
10808 err = PTR_ERR(task);
10813 if (task && group_leader &&
10814 group_leader->attr.inherit != attr.inherit) {
10820 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
10825 * Reuse ptrace permission checks for now.
10827 * We must hold cred_guard_mutex across this and any potential
10828 * perf_install_in_context() call for this new event to
10829 * serialize against exec() altering our credentials (and the
10830 * perf_event_exit_task() that could imply).
10833 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
10837 if (flags & PERF_FLAG_PID_CGROUP)
10840 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
10841 NULL, NULL, cgroup_fd);
10842 if (IS_ERR(event)) {
10843 err = PTR_ERR(event);
10847 if (is_sampling_event(event)) {
10848 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
10855 * Special case software events and allow them to be part of
10856 * any hardware group.
10860 if (attr.use_clockid) {
10861 err = perf_event_set_clock(event, attr.clockid);
10866 if (pmu->task_ctx_nr == perf_sw_context)
10867 event->event_caps |= PERF_EV_CAP_SOFTWARE;
10869 if (group_leader) {
10870 if (is_software_event(event) &&
10871 !in_software_context(group_leader)) {
10873 * If the event is a sw event, but the group_leader
10874 * is on hw context.
10876 * Allow the addition of software events to hw
10877 * groups, this is safe because software events
10878 * never fail to schedule.
10880 pmu = group_leader->ctx->pmu;
10881 } else if (!is_software_event(event) &&
10882 is_software_event(group_leader) &&
10883 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
10885 * In case the group is a pure software group, and we
10886 * try to add a hardware event, move the whole group to
10887 * the hardware context.
10894 * Get the target context (task or percpu):
10896 ctx = find_get_context(pmu, task, event);
10898 err = PTR_ERR(ctx);
10902 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
10908 * Look up the group leader (we will attach this event to it):
10910 if (group_leader) {
10914 * Do not allow a recursive hierarchy (this new sibling
10915 * becoming part of another group-sibling):
10917 if (group_leader->group_leader != group_leader)
10920 /* All events in a group should have the same clock */
10921 if (group_leader->clock != event->clock)
10925 * Make sure we're both events for the same CPU;
10926 * grouping events for different CPUs is broken; since
10927 * you can never concurrently schedule them anyhow.
10929 if (group_leader->cpu != event->cpu)
10933 * Make sure we're both on the same task, or both
10936 if (group_leader->ctx->task != ctx->task)
10940 * Do not allow to attach to a group in a different task
10941 * or CPU context. If we're moving SW events, we'll fix
10942 * this up later, so allow that.
10944 if (!move_group && group_leader->ctx != ctx)
10948 * Only a group leader can be exclusive or pinned
10950 if (attr.exclusive || attr.pinned)
10954 if (output_event) {
10955 err = perf_event_set_output(event, output_event);
10960 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
10962 if (IS_ERR(event_file)) {
10963 err = PTR_ERR(event_file);
10969 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
10971 if (gctx->task == TASK_TOMBSTONE) {
10977 * Check if we raced against another sys_perf_event_open() call
10978 * moving the software group underneath us.
10980 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
10982 * If someone moved the group out from under us, check
10983 * if this new event wound up on the same ctx, if so
10984 * its the regular !move_group case, otherwise fail.
10990 perf_event_ctx_unlock(group_leader, gctx);
10995 mutex_lock(&ctx->mutex);
10998 if (ctx->task == TASK_TOMBSTONE) {
11003 if (!perf_event_validate_size(event)) {
11010 * Check if the @cpu we're creating an event for is online.
11012 * We use the perf_cpu_context::ctx::mutex to serialize against
11013 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11015 struct perf_cpu_context *cpuctx =
11016 container_of(ctx, struct perf_cpu_context, ctx);
11018 if (!cpuctx->online) {
11026 * Must be under the same ctx::mutex as perf_install_in_context(),
11027 * because we need to serialize with concurrent event creation.
11029 if (!exclusive_event_installable(event, ctx)) {
11030 /* exclusive and group stuff are assumed mutually exclusive */
11031 WARN_ON_ONCE(move_group);
11037 WARN_ON_ONCE(ctx->parent_ctx);
11040 * This is the point on no return; we cannot fail hereafter. This is
11041 * where we start modifying current state.
11046 * See perf_event_ctx_lock() for comments on the details
11047 * of swizzling perf_event::ctx.
11049 perf_remove_from_context(group_leader, 0);
11052 for_each_sibling_event(sibling, group_leader) {
11053 perf_remove_from_context(sibling, 0);
11058 * Wait for everybody to stop referencing the events through
11059 * the old lists, before installing it on new lists.
11064 * Install the group siblings before the group leader.
11066 * Because a group leader will try and install the entire group
11067 * (through the sibling list, which is still in-tact), we can
11068 * end up with siblings installed in the wrong context.
11070 * By installing siblings first we NO-OP because they're not
11071 * reachable through the group lists.
11073 for_each_sibling_event(sibling, group_leader) {
11074 perf_event__state_init(sibling);
11075 perf_install_in_context(ctx, sibling, sibling->cpu);
11080 * Removing from the context ends up with disabled
11081 * event. What we want here is event in the initial
11082 * startup state, ready to be add into new context.
11084 perf_event__state_init(group_leader);
11085 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11090 * Precalculate sample_data sizes; do while holding ctx::mutex such
11091 * that we're serialized against further additions and before
11092 * perf_install_in_context() which is the point the event is active and
11093 * can use these values.
11095 perf_event__header_size(event);
11096 perf_event__id_header_size(event);
11098 event->owner = current;
11100 perf_install_in_context(ctx, event, event->cpu);
11101 perf_unpin_context(ctx);
11104 perf_event_ctx_unlock(group_leader, gctx);
11105 mutex_unlock(&ctx->mutex);
11108 mutex_unlock(&task->signal->cred_guard_mutex);
11109 put_task_struct(task);
11112 mutex_lock(¤t->perf_event_mutex);
11113 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
11114 mutex_unlock(¤t->perf_event_mutex);
11117 * Drop the reference on the group_event after placing the
11118 * new event on the sibling_list. This ensures destruction
11119 * of the group leader will find the pointer to itself in
11120 * perf_group_detach().
11123 fd_install(event_fd, event_file);
11128 perf_event_ctx_unlock(group_leader, gctx);
11129 mutex_unlock(&ctx->mutex);
11133 perf_unpin_context(ctx);
11137 * If event_file is set, the fput() above will have called ->release()
11138 * and that will take care of freeing the event.
11144 mutex_unlock(&task->signal->cred_guard_mutex);
11147 put_task_struct(task);
11151 put_unused_fd(event_fd);
11156 * perf_event_create_kernel_counter
11158 * @attr: attributes of the counter to create
11159 * @cpu: cpu in which the counter is bound
11160 * @task: task to profile (NULL for percpu)
11162 struct perf_event *
11163 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
11164 struct task_struct *task,
11165 perf_overflow_handler_t overflow_handler,
11168 struct perf_event_context *ctx;
11169 struct perf_event *event;
11173 * Get the target context (task or percpu):
11176 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
11177 overflow_handler, context, -1);
11178 if (IS_ERR(event)) {
11179 err = PTR_ERR(event);
11183 /* Mark owner so we could distinguish it from user events. */
11184 event->owner = TASK_TOMBSTONE;
11186 ctx = find_get_context(event->pmu, task, event);
11188 err = PTR_ERR(ctx);
11192 WARN_ON_ONCE(ctx->parent_ctx);
11193 mutex_lock(&ctx->mutex);
11194 if (ctx->task == TASK_TOMBSTONE) {
11201 * Check if the @cpu we're creating an event for is online.
11203 * We use the perf_cpu_context::ctx::mutex to serialize against
11204 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11206 struct perf_cpu_context *cpuctx =
11207 container_of(ctx, struct perf_cpu_context, ctx);
11208 if (!cpuctx->online) {
11214 if (!exclusive_event_installable(event, ctx)) {
11219 perf_install_in_context(ctx, event, cpu);
11220 perf_unpin_context(ctx);
11221 mutex_unlock(&ctx->mutex);
11226 mutex_unlock(&ctx->mutex);
11227 perf_unpin_context(ctx);
11232 return ERR_PTR(err);
11234 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
11236 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
11238 struct perf_event_context *src_ctx;
11239 struct perf_event_context *dst_ctx;
11240 struct perf_event *event, *tmp;
11243 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
11244 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
11247 * See perf_event_ctx_lock() for comments on the details
11248 * of swizzling perf_event::ctx.
11250 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
11251 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
11253 perf_remove_from_context(event, 0);
11254 unaccount_event_cpu(event, src_cpu);
11256 list_add(&event->migrate_entry, &events);
11260 * Wait for the events to quiesce before re-instating them.
11265 * Re-instate events in 2 passes.
11267 * Skip over group leaders and only install siblings on this first
11268 * pass, siblings will not get enabled without a leader, however a
11269 * leader will enable its siblings, even if those are still on the old
11272 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
11273 if (event->group_leader == event)
11276 list_del(&event->migrate_entry);
11277 if (event->state >= PERF_EVENT_STATE_OFF)
11278 event->state = PERF_EVENT_STATE_INACTIVE;
11279 account_event_cpu(event, dst_cpu);
11280 perf_install_in_context(dst_ctx, event, dst_cpu);
11285 * Once all the siblings are setup properly, install the group leaders
11288 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
11289 list_del(&event->migrate_entry);
11290 if (event->state >= PERF_EVENT_STATE_OFF)
11291 event->state = PERF_EVENT_STATE_INACTIVE;
11292 account_event_cpu(event, dst_cpu);
11293 perf_install_in_context(dst_ctx, event, dst_cpu);
11296 mutex_unlock(&dst_ctx->mutex);
11297 mutex_unlock(&src_ctx->mutex);
11299 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
11301 static void sync_child_event(struct perf_event *child_event,
11302 struct task_struct *child)
11304 struct perf_event *parent_event = child_event->parent;
11307 if (child_event->attr.inherit_stat)
11308 perf_event_read_event(child_event, child);
11310 child_val = perf_event_count(child_event);
11313 * Add back the child's count to the parent's count:
11315 atomic64_add(child_val, &parent_event->child_count);
11316 atomic64_add(child_event->total_time_enabled,
11317 &parent_event->child_total_time_enabled);
11318 atomic64_add(child_event->total_time_running,
11319 &parent_event->child_total_time_running);
11323 perf_event_exit_event(struct perf_event *child_event,
11324 struct perf_event_context *child_ctx,
11325 struct task_struct *child)
11327 struct perf_event *parent_event = child_event->parent;
11330 * Do not destroy the 'original' grouping; because of the context
11331 * switch optimization the original events could've ended up in a
11332 * random child task.
11334 * If we were to destroy the original group, all group related
11335 * operations would cease to function properly after this random
11338 * Do destroy all inherited groups, we don't care about those
11339 * and being thorough is better.
11341 raw_spin_lock_irq(&child_ctx->lock);
11342 WARN_ON_ONCE(child_ctx->is_active);
11345 perf_group_detach(child_event);
11346 list_del_event(child_event, child_ctx);
11347 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
11348 raw_spin_unlock_irq(&child_ctx->lock);
11351 * Parent events are governed by their filedesc, retain them.
11353 if (!parent_event) {
11354 perf_event_wakeup(child_event);
11358 * Child events can be cleaned up.
11361 sync_child_event(child_event, child);
11364 * Remove this event from the parent's list
11366 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
11367 mutex_lock(&parent_event->child_mutex);
11368 list_del_init(&child_event->child_list);
11369 mutex_unlock(&parent_event->child_mutex);
11372 * Kick perf_poll() for is_event_hup().
11374 perf_event_wakeup(parent_event);
11375 free_event(child_event);
11376 put_event(parent_event);
11379 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
11381 struct perf_event_context *child_ctx, *clone_ctx = NULL;
11382 struct perf_event *child_event, *next;
11384 WARN_ON_ONCE(child != current);
11386 child_ctx = perf_pin_task_context(child, ctxn);
11391 * In order to reduce the amount of tricky in ctx tear-down, we hold
11392 * ctx::mutex over the entire thing. This serializes against almost
11393 * everything that wants to access the ctx.
11395 * The exception is sys_perf_event_open() /
11396 * perf_event_create_kernel_count() which does find_get_context()
11397 * without ctx::mutex (it cannot because of the move_group double mutex
11398 * lock thing). See the comments in perf_install_in_context().
11400 mutex_lock(&child_ctx->mutex);
11403 * In a single ctx::lock section, de-schedule the events and detach the
11404 * context from the task such that we cannot ever get it scheduled back
11407 raw_spin_lock_irq(&child_ctx->lock);
11408 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
11411 * Now that the context is inactive, destroy the task <-> ctx relation
11412 * and mark the context dead.
11414 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
11415 put_ctx(child_ctx); /* cannot be last */
11416 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
11417 put_task_struct(current); /* cannot be last */
11419 clone_ctx = unclone_ctx(child_ctx);
11420 raw_spin_unlock_irq(&child_ctx->lock);
11423 put_ctx(clone_ctx);
11426 * Report the task dead after unscheduling the events so that we
11427 * won't get any samples after PERF_RECORD_EXIT. We can however still
11428 * get a few PERF_RECORD_READ events.
11430 perf_event_task(child, child_ctx, 0);
11432 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
11433 perf_event_exit_event(child_event, child_ctx, child);
11435 mutex_unlock(&child_ctx->mutex);
11437 put_ctx(child_ctx);
11441 * When a child task exits, feed back event values to parent events.
11443 * Can be called with cred_guard_mutex held when called from
11444 * install_exec_creds().
11446 void perf_event_exit_task(struct task_struct *child)
11448 struct perf_event *event, *tmp;
11451 mutex_lock(&child->perf_event_mutex);
11452 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
11454 list_del_init(&event->owner_entry);
11457 * Ensure the list deletion is visible before we clear
11458 * the owner, closes a race against perf_release() where
11459 * we need to serialize on the owner->perf_event_mutex.
11461 smp_store_release(&event->owner, NULL);
11463 mutex_unlock(&child->perf_event_mutex);
11465 for_each_task_context_nr(ctxn)
11466 perf_event_exit_task_context(child, ctxn);
11469 * The perf_event_exit_task_context calls perf_event_task
11470 * with child's task_ctx, which generates EXIT events for
11471 * child contexts and sets child->perf_event_ctxp[] to NULL.
11472 * At this point we need to send EXIT events to cpu contexts.
11474 perf_event_task(child, NULL, 0);
11477 static void perf_free_event(struct perf_event *event,
11478 struct perf_event_context *ctx)
11480 struct perf_event *parent = event->parent;
11482 if (WARN_ON_ONCE(!parent))
11485 mutex_lock(&parent->child_mutex);
11486 list_del_init(&event->child_list);
11487 mutex_unlock(&parent->child_mutex);
11491 raw_spin_lock_irq(&ctx->lock);
11492 perf_group_detach(event);
11493 list_del_event(event, ctx);
11494 raw_spin_unlock_irq(&ctx->lock);
11499 * Free an unexposed, unused context as created by inheritance by
11500 * perf_event_init_task below, used by fork() in case of fail.
11502 * Not all locks are strictly required, but take them anyway to be nice and
11503 * help out with the lockdep assertions.
11505 void perf_event_free_task(struct task_struct *task)
11507 struct perf_event_context *ctx;
11508 struct perf_event *event, *tmp;
11511 for_each_task_context_nr(ctxn) {
11512 ctx = task->perf_event_ctxp[ctxn];
11516 mutex_lock(&ctx->mutex);
11517 raw_spin_lock_irq(&ctx->lock);
11519 * Destroy the task <-> ctx relation and mark the context dead.
11521 * This is important because even though the task hasn't been
11522 * exposed yet the context has been (through child_list).
11524 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
11525 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
11526 put_task_struct(task); /* cannot be last */
11527 raw_spin_unlock_irq(&ctx->lock);
11529 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
11530 perf_free_event(event, ctx);
11532 mutex_unlock(&ctx->mutex);
11537 void perf_event_delayed_put(struct task_struct *task)
11541 for_each_task_context_nr(ctxn)
11542 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
11545 struct file *perf_event_get(unsigned int fd)
11549 file = fget_raw(fd);
11551 return ERR_PTR(-EBADF);
11553 if (file->f_op != &perf_fops) {
11555 return ERR_PTR(-EBADF);
11561 const struct perf_event *perf_get_event(struct file *file)
11563 if (file->f_op != &perf_fops)
11564 return ERR_PTR(-EINVAL);
11566 return file->private_data;
11569 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
11572 return ERR_PTR(-EINVAL);
11574 return &event->attr;
11578 * Inherit an event from parent task to child task.
11581 * - valid pointer on success
11582 * - NULL for orphaned events
11583 * - IS_ERR() on error
11585 static struct perf_event *
11586 inherit_event(struct perf_event *parent_event,
11587 struct task_struct *parent,
11588 struct perf_event_context *parent_ctx,
11589 struct task_struct *child,
11590 struct perf_event *group_leader,
11591 struct perf_event_context *child_ctx)
11593 enum perf_event_state parent_state = parent_event->state;
11594 struct perf_event *child_event;
11595 unsigned long flags;
11598 * Instead of creating recursive hierarchies of events,
11599 * we link inherited events back to the original parent,
11600 * which has a filp for sure, which we use as the reference
11603 if (parent_event->parent)
11604 parent_event = parent_event->parent;
11606 child_event = perf_event_alloc(&parent_event->attr,
11609 group_leader, parent_event,
11611 if (IS_ERR(child_event))
11612 return child_event;
11615 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
11616 !child_ctx->task_ctx_data) {
11617 struct pmu *pmu = child_event->pmu;
11619 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
11621 if (!child_ctx->task_ctx_data) {
11622 free_event(child_event);
11628 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
11629 * must be under the same lock in order to serialize against
11630 * perf_event_release_kernel(), such that either we must observe
11631 * is_orphaned_event() or they will observe us on the child_list.
11633 mutex_lock(&parent_event->child_mutex);
11634 if (is_orphaned_event(parent_event) ||
11635 !atomic_long_inc_not_zero(&parent_event->refcount)) {
11636 mutex_unlock(&parent_event->child_mutex);
11637 /* task_ctx_data is freed with child_ctx */
11638 free_event(child_event);
11642 get_ctx(child_ctx);
11645 * Make the child state follow the state of the parent event,
11646 * not its attr.disabled bit. We hold the parent's mutex,
11647 * so we won't race with perf_event_{en, dis}able_family.
11649 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
11650 child_event->state = PERF_EVENT_STATE_INACTIVE;
11652 child_event->state = PERF_EVENT_STATE_OFF;
11654 if (parent_event->attr.freq) {
11655 u64 sample_period = parent_event->hw.sample_period;
11656 struct hw_perf_event *hwc = &child_event->hw;
11658 hwc->sample_period = sample_period;
11659 hwc->last_period = sample_period;
11661 local64_set(&hwc->period_left, sample_period);
11664 child_event->ctx = child_ctx;
11665 child_event->overflow_handler = parent_event->overflow_handler;
11666 child_event->overflow_handler_context
11667 = parent_event->overflow_handler_context;
11670 * Precalculate sample_data sizes
11672 perf_event__header_size(child_event);
11673 perf_event__id_header_size(child_event);
11676 * Link it up in the child's context:
11678 raw_spin_lock_irqsave(&child_ctx->lock, flags);
11679 add_event_to_ctx(child_event, child_ctx);
11680 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
11683 * Link this into the parent event's child list
11685 list_add_tail(&child_event->child_list, &parent_event->child_list);
11686 mutex_unlock(&parent_event->child_mutex);
11688 return child_event;
11692 * Inherits an event group.
11694 * This will quietly suppress orphaned events; !inherit_event() is not an error.
11695 * This matches with perf_event_release_kernel() removing all child events.
11701 static int inherit_group(struct perf_event *parent_event,
11702 struct task_struct *parent,
11703 struct perf_event_context *parent_ctx,
11704 struct task_struct *child,
11705 struct perf_event_context *child_ctx)
11707 struct perf_event *leader;
11708 struct perf_event *sub;
11709 struct perf_event *child_ctr;
11711 leader = inherit_event(parent_event, parent, parent_ctx,
11712 child, NULL, child_ctx);
11713 if (IS_ERR(leader))
11714 return PTR_ERR(leader);
11716 * @leader can be NULL here because of is_orphaned_event(). In this
11717 * case inherit_event() will create individual events, similar to what
11718 * perf_group_detach() would do anyway.
11720 for_each_sibling_event(sub, parent_event) {
11721 child_ctr = inherit_event(sub, parent, parent_ctx,
11722 child, leader, child_ctx);
11723 if (IS_ERR(child_ctr))
11724 return PTR_ERR(child_ctr);
11730 * Creates the child task context and tries to inherit the event-group.
11732 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
11733 * inherited_all set when we 'fail' to inherit an orphaned event; this is
11734 * consistent with perf_event_release_kernel() removing all child events.
11741 inherit_task_group(struct perf_event *event, struct task_struct *parent,
11742 struct perf_event_context *parent_ctx,
11743 struct task_struct *child, int ctxn,
11744 int *inherited_all)
11747 struct perf_event_context *child_ctx;
11749 if (!event->attr.inherit) {
11750 *inherited_all = 0;
11754 child_ctx = child->perf_event_ctxp[ctxn];
11757 * This is executed from the parent task context, so
11758 * inherit events that have been marked for cloning.
11759 * First allocate and initialize a context for the
11762 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
11766 child->perf_event_ctxp[ctxn] = child_ctx;
11769 ret = inherit_group(event, parent, parent_ctx,
11773 *inherited_all = 0;
11779 * Initialize the perf_event context in task_struct
11781 static int perf_event_init_context(struct task_struct *child, int ctxn)
11783 struct perf_event_context *child_ctx, *parent_ctx;
11784 struct perf_event_context *cloned_ctx;
11785 struct perf_event *event;
11786 struct task_struct *parent = current;
11787 int inherited_all = 1;
11788 unsigned long flags;
11791 if (likely(!parent->perf_event_ctxp[ctxn]))
11795 * If the parent's context is a clone, pin it so it won't get
11796 * swapped under us.
11798 parent_ctx = perf_pin_task_context(parent, ctxn);
11803 * No need to check if parent_ctx != NULL here; since we saw
11804 * it non-NULL earlier, the only reason for it to become NULL
11805 * is if we exit, and since we're currently in the middle of
11806 * a fork we can't be exiting at the same time.
11810 * Lock the parent list. No need to lock the child - not PID
11811 * hashed yet and not running, so nobody can access it.
11813 mutex_lock(&parent_ctx->mutex);
11816 * We dont have to disable NMIs - we are only looking at
11817 * the list, not manipulating it:
11819 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
11820 ret = inherit_task_group(event, parent, parent_ctx,
11821 child, ctxn, &inherited_all);
11827 * We can't hold ctx->lock when iterating the ->flexible_group list due
11828 * to allocations, but we need to prevent rotation because
11829 * rotate_ctx() will change the list from interrupt context.
11831 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
11832 parent_ctx->rotate_disable = 1;
11833 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
11835 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
11836 ret = inherit_task_group(event, parent, parent_ctx,
11837 child, ctxn, &inherited_all);
11842 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
11843 parent_ctx->rotate_disable = 0;
11845 child_ctx = child->perf_event_ctxp[ctxn];
11847 if (child_ctx && inherited_all) {
11849 * Mark the child context as a clone of the parent
11850 * context, or of whatever the parent is a clone of.
11852 * Note that if the parent is a clone, the holding of
11853 * parent_ctx->lock avoids it from being uncloned.
11855 cloned_ctx = parent_ctx->parent_ctx;
11857 child_ctx->parent_ctx = cloned_ctx;
11858 child_ctx->parent_gen = parent_ctx->parent_gen;
11860 child_ctx->parent_ctx = parent_ctx;
11861 child_ctx->parent_gen = parent_ctx->generation;
11863 get_ctx(child_ctx->parent_ctx);
11866 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
11868 mutex_unlock(&parent_ctx->mutex);
11870 perf_unpin_context(parent_ctx);
11871 put_ctx(parent_ctx);
11877 * Initialize the perf_event context in task_struct
11879 int perf_event_init_task(struct task_struct *child)
11883 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
11884 mutex_init(&child->perf_event_mutex);
11885 INIT_LIST_HEAD(&child->perf_event_list);
11887 for_each_task_context_nr(ctxn) {
11888 ret = perf_event_init_context(child, ctxn);
11890 perf_event_free_task(child);
11898 static void __init perf_event_init_all_cpus(void)
11900 struct swevent_htable *swhash;
11903 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
11905 for_each_possible_cpu(cpu) {
11906 swhash = &per_cpu(swevent_htable, cpu);
11907 mutex_init(&swhash->hlist_mutex);
11908 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
11910 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
11911 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
11913 #ifdef CONFIG_CGROUP_PERF
11914 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
11916 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
11920 static void perf_swevent_init_cpu(unsigned int cpu)
11922 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
11924 mutex_lock(&swhash->hlist_mutex);
11925 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
11926 struct swevent_hlist *hlist;
11928 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
11930 rcu_assign_pointer(swhash->swevent_hlist, hlist);
11932 mutex_unlock(&swhash->hlist_mutex);
11935 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
11936 static void __perf_event_exit_context(void *__info)
11938 struct perf_event_context *ctx = __info;
11939 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
11940 struct perf_event *event;
11942 raw_spin_lock(&ctx->lock);
11943 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
11944 list_for_each_entry(event, &ctx->event_list, event_entry)
11945 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
11946 raw_spin_unlock(&ctx->lock);
11949 static void perf_event_exit_cpu_context(int cpu)
11951 struct perf_cpu_context *cpuctx;
11952 struct perf_event_context *ctx;
11955 mutex_lock(&pmus_lock);
11956 list_for_each_entry(pmu, &pmus, entry) {
11957 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11958 ctx = &cpuctx->ctx;
11960 mutex_lock(&ctx->mutex);
11961 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
11962 cpuctx->online = 0;
11963 mutex_unlock(&ctx->mutex);
11965 cpumask_clear_cpu(cpu, perf_online_mask);
11966 mutex_unlock(&pmus_lock);
11970 static void perf_event_exit_cpu_context(int cpu) { }
11974 int perf_event_init_cpu(unsigned int cpu)
11976 struct perf_cpu_context *cpuctx;
11977 struct perf_event_context *ctx;
11980 perf_swevent_init_cpu(cpu);
11982 mutex_lock(&pmus_lock);
11983 cpumask_set_cpu(cpu, perf_online_mask);
11984 list_for_each_entry(pmu, &pmus, entry) {
11985 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11986 ctx = &cpuctx->ctx;
11988 mutex_lock(&ctx->mutex);
11989 cpuctx->online = 1;
11990 mutex_unlock(&ctx->mutex);
11992 mutex_unlock(&pmus_lock);
11997 int perf_event_exit_cpu(unsigned int cpu)
11999 perf_event_exit_cpu_context(cpu);
12004 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12008 for_each_online_cpu(cpu)
12009 perf_event_exit_cpu(cpu);
12015 * Run the perf reboot notifier at the very last possible moment so that
12016 * the generic watchdog code runs as long as possible.
12018 static struct notifier_block perf_reboot_notifier = {
12019 .notifier_call = perf_reboot,
12020 .priority = INT_MIN,
12023 void __init perf_event_init(void)
12027 idr_init(&pmu_idr);
12029 perf_event_init_all_cpus();
12030 init_srcu_struct(&pmus_srcu);
12031 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12032 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12033 perf_pmu_register(&perf_task_clock, NULL, -1);
12034 perf_tp_register();
12035 perf_event_init_cpu(smp_processor_id());
12036 register_reboot_notifier(&perf_reboot_notifier);
12038 ret = init_hw_breakpoint();
12039 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12042 * Build time assertion that we keep the data_head at the intended
12043 * location. IOW, validation we got the __reserved[] size right.
12045 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12049 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12052 struct perf_pmu_events_attr *pmu_attr =
12053 container_of(attr, struct perf_pmu_events_attr, attr);
12055 if (pmu_attr->event_str)
12056 return sprintf(page, "%s\n", pmu_attr->event_str);
12060 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
12062 static int __init perf_event_sysfs_init(void)
12067 mutex_lock(&pmus_lock);
12069 ret = bus_register(&pmu_bus);
12073 list_for_each_entry(pmu, &pmus, entry) {
12074 if (!pmu->name || pmu->type < 0)
12077 ret = pmu_dev_alloc(pmu);
12078 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12080 pmu_bus_running = 1;
12084 mutex_unlock(&pmus_lock);
12088 device_initcall(perf_event_sysfs_init);
12090 #ifdef CONFIG_CGROUP_PERF
12091 static struct cgroup_subsys_state *
12092 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
12094 struct perf_cgroup *jc;
12096 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
12098 return ERR_PTR(-ENOMEM);
12100 jc->info = alloc_percpu(struct perf_cgroup_info);
12103 return ERR_PTR(-ENOMEM);
12109 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
12111 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
12113 free_percpu(jc->info);
12117 static int __perf_cgroup_move(void *info)
12119 struct task_struct *task = info;
12121 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
12126 static void perf_cgroup_attach(struct cgroup_taskset *tset)
12128 struct task_struct *task;
12129 struct cgroup_subsys_state *css;
12131 cgroup_taskset_for_each(task, css, tset)
12132 task_function_call(task, __perf_cgroup_move, task);
12135 struct cgroup_subsys perf_event_cgrp_subsys = {
12136 .css_alloc = perf_cgroup_css_alloc,
12137 .css_free = perf_cgroup_css_free,
12138 .attach = perf_cgroup_attach,
12140 * Implicitly enable on dfl hierarchy so that perf events can
12141 * always be filtered by cgroup2 path as long as perf_event
12142 * controller is not mounted on a legacy hierarchy.
12144 .implicit_on_dfl = true,
12147 #endif /* CONFIG_CGROUP_PERF */