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>
52 #include <linux/min_heap.h>
56 #include <asm/irq_regs.h>
58 typedef int (*remote_function_f)(void *);
60 struct remote_function_call {
61 struct task_struct *p;
62 remote_function_f func;
67 static void remote_function(void *data)
69 struct remote_function_call *tfc = data;
70 struct task_struct *p = tfc->p;
74 if (task_cpu(p) != smp_processor_id())
78 * Now that we're on right CPU with IRQs disabled, we can test
79 * if we hit the right task without races.
82 tfc->ret = -ESRCH; /* No such (running) process */
87 tfc->ret = tfc->func(tfc->info);
91 * task_function_call - call a function on the cpu on which a task runs
92 * @p: the task to evaluate
93 * @func: the function to be called
94 * @info: the function call argument
96 * Calls the function @func when the task is currently running. This might
97 * be on the current CPU, which just calls the function directly
99 * returns: @func return value, or
100 * -ESRCH - when the process isn't running
101 * -EAGAIN - when the process moved away
104 task_function_call(struct task_struct *p, remote_function_f func, void *info)
106 struct remote_function_call data = {
115 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
118 } while (ret == -EAGAIN);
124 * cpu_function_call - call a function on the cpu
125 * @func: the function to be called
126 * @info: the function call argument
128 * Calls the function @func on the remote cpu.
130 * returns: @func return value or -ENXIO when the cpu is offline
132 static int cpu_function_call(int cpu, remote_function_f func, void *info)
134 struct remote_function_call data = {
138 .ret = -ENXIO, /* No such CPU */
141 smp_call_function_single(cpu, remote_function, &data, 1);
146 static inline struct perf_cpu_context *
147 __get_cpu_context(struct perf_event_context *ctx)
149 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
152 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
153 struct perf_event_context *ctx)
155 raw_spin_lock(&cpuctx->ctx.lock);
157 raw_spin_lock(&ctx->lock);
160 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
161 struct perf_event_context *ctx)
164 raw_spin_unlock(&ctx->lock);
165 raw_spin_unlock(&cpuctx->ctx.lock);
168 #define TASK_TOMBSTONE ((void *)-1L)
170 static bool is_kernel_event(struct perf_event *event)
172 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
176 * On task ctx scheduling...
178 * When !ctx->nr_events a task context will not be scheduled. This means
179 * we can disable the scheduler hooks (for performance) without leaving
180 * pending task ctx state.
182 * This however results in two special cases:
184 * - removing the last event from a task ctx; this is relatively straight
185 * forward and is done in __perf_remove_from_context.
187 * - adding the first event to a task ctx; this is tricky because we cannot
188 * rely on ctx->is_active and therefore cannot use event_function_call().
189 * See perf_install_in_context().
191 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
194 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
195 struct perf_event_context *, void *);
197 struct event_function_struct {
198 struct perf_event *event;
203 static int event_function(void *info)
205 struct event_function_struct *efs = info;
206 struct perf_event *event = efs->event;
207 struct perf_event_context *ctx = event->ctx;
208 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
209 struct perf_event_context *task_ctx = cpuctx->task_ctx;
212 lockdep_assert_irqs_disabled();
214 perf_ctx_lock(cpuctx, task_ctx);
216 * Since we do the IPI call without holding ctx->lock things can have
217 * changed, double check we hit the task we set out to hit.
220 if (ctx->task != current) {
226 * We only use event_function_call() on established contexts,
227 * and event_function() is only ever called when active (or
228 * rather, we'll have bailed in task_function_call() or the
229 * above ctx->task != current test), therefore we must have
230 * ctx->is_active here.
232 WARN_ON_ONCE(!ctx->is_active);
234 * And since we have ctx->is_active, cpuctx->task_ctx must
237 WARN_ON_ONCE(task_ctx != ctx);
239 WARN_ON_ONCE(&cpuctx->ctx != ctx);
242 efs->func(event, cpuctx, ctx, efs->data);
244 perf_ctx_unlock(cpuctx, task_ctx);
249 static void event_function_call(struct perf_event *event, event_f func, void *data)
251 struct perf_event_context *ctx = event->ctx;
252 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
253 struct event_function_struct efs = {
259 if (!event->parent) {
261 * If this is a !child event, we must hold ctx::mutex to
262 * stabilize the the event->ctx relation. See
263 * perf_event_ctx_lock().
265 lockdep_assert_held(&ctx->mutex);
269 cpu_function_call(event->cpu, event_function, &efs);
273 if (task == TASK_TOMBSTONE)
277 if (!task_function_call(task, event_function, &efs))
280 raw_spin_lock_irq(&ctx->lock);
282 * Reload the task pointer, it might have been changed by
283 * a concurrent perf_event_context_sched_out().
286 if (task == TASK_TOMBSTONE) {
287 raw_spin_unlock_irq(&ctx->lock);
290 if (ctx->is_active) {
291 raw_spin_unlock_irq(&ctx->lock);
294 func(event, NULL, ctx, data);
295 raw_spin_unlock_irq(&ctx->lock);
299 * Similar to event_function_call() + event_function(), but hard assumes IRQs
300 * are already disabled and we're on the right CPU.
302 static void event_function_local(struct perf_event *event, event_f func, void *data)
304 struct perf_event_context *ctx = event->ctx;
305 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
306 struct task_struct *task = READ_ONCE(ctx->task);
307 struct perf_event_context *task_ctx = NULL;
309 lockdep_assert_irqs_disabled();
312 if (task == TASK_TOMBSTONE)
318 perf_ctx_lock(cpuctx, task_ctx);
321 if (task == TASK_TOMBSTONE)
326 * We must be either inactive or active and the right task,
327 * otherwise we're screwed, since we cannot IPI to somewhere
330 if (ctx->is_active) {
331 if (WARN_ON_ONCE(task != current))
334 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
338 WARN_ON_ONCE(&cpuctx->ctx != ctx);
341 func(event, cpuctx, ctx, data);
343 perf_ctx_unlock(cpuctx, task_ctx);
346 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
347 PERF_FLAG_FD_OUTPUT |\
348 PERF_FLAG_PID_CGROUP |\
349 PERF_FLAG_FD_CLOEXEC)
352 * branch priv levels that need permission checks
354 #define PERF_SAMPLE_BRANCH_PERM_PLM \
355 (PERF_SAMPLE_BRANCH_KERNEL |\
356 PERF_SAMPLE_BRANCH_HV)
359 EVENT_FLEXIBLE = 0x1,
362 /* see ctx_resched() for details */
364 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
368 * perf_sched_events : >0 events exist
369 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
372 static void perf_sched_delayed(struct work_struct *work);
373 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
374 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
375 static DEFINE_MUTEX(perf_sched_mutex);
376 static atomic_t perf_sched_count;
378 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
379 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
380 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
382 static atomic_t nr_mmap_events __read_mostly;
383 static atomic_t nr_comm_events __read_mostly;
384 static atomic_t nr_namespaces_events __read_mostly;
385 static atomic_t nr_task_events __read_mostly;
386 static atomic_t nr_freq_events __read_mostly;
387 static atomic_t nr_switch_events __read_mostly;
388 static atomic_t nr_ksymbol_events __read_mostly;
389 static atomic_t nr_bpf_events __read_mostly;
390 static atomic_t nr_cgroup_events __read_mostly;
392 static LIST_HEAD(pmus);
393 static DEFINE_MUTEX(pmus_lock);
394 static struct srcu_struct pmus_srcu;
395 static cpumask_var_t perf_online_mask;
398 * perf event paranoia level:
399 * -1 - not paranoid at all
400 * 0 - disallow raw tracepoint access for unpriv
401 * 1 - disallow cpu events for unpriv
402 * 2 - disallow kernel profiling for unpriv
404 int sysctl_perf_event_paranoid __read_mostly = 2;
406 /* Minimum for 512 kiB + 1 user control page */
407 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
410 * max perf event sample rate
412 #define DEFAULT_MAX_SAMPLE_RATE 100000
413 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
414 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
416 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
418 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
419 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
421 static int perf_sample_allowed_ns __read_mostly =
422 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
424 static void update_perf_cpu_limits(void)
426 u64 tmp = perf_sample_period_ns;
428 tmp *= sysctl_perf_cpu_time_max_percent;
429 tmp = div_u64(tmp, 100);
433 WRITE_ONCE(perf_sample_allowed_ns, tmp);
436 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
438 int perf_proc_update_handler(struct ctl_table *table, int write,
439 void __user *buffer, size_t *lenp,
443 int perf_cpu = sysctl_perf_cpu_time_max_percent;
445 * If throttling is disabled don't allow the write:
447 if (write && (perf_cpu == 100 || perf_cpu == 0))
450 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
454 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
455 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
456 update_perf_cpu_limits();
461 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
463 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
464 void __user *buffer, size_t *lenp,
467 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
472 if (sysctl_perf_cpu_time_max_percent == 100 ||
473 sysctl_perf_cpu_time_max_percent == 0) {
475 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
476 WRITE_ONCE(perf_sample_allowed_ns, 0);
478 update_perf_cpu_limits();
485 * perf samples are done in some very critical code paths (NMIs).
486 * If they take too much CPU time, the system can lock up and not
487 * get any real work done. This will drop the sample rate when
488 * we detect that events are taking too long.
490 #define NR_ACCUMULATED_SAMPLES 128
491 static DEFINE_PER_CPU(u64, running_sample_length);
493 static u64 __report_avg;
494 static u64 __report_allowed;
496 static void perf_duration_warn(struct irq_work *w)
498 printk_ratelimited(KERN_INFO
499 "perf: interrupt took too long (%lld > %lld), lowering "
500 "kernel.perf_event_max_sample_rate to %d\n",
501 __report_avg, __report_allowed,
502 sysctl_perf_event_sample_rate);
505 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
507 void perf_sample_event_took(u64 sample_len_ns)
509 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
517 /* Decay the counter by 1 average sample. */
518 running_len = __this_cpu_read(running_sample_length);
519 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
520 running_len += sample_len_ns;
521 __this_cpu_write(running_sample_length, running_len);
524 * Note: this will be biased artifically low until we have
525 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
526 * from having to maintain a count.
528 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
529 if (avg_len <= max_len)
532 __report_avg = avg_len;
533 __report_allowed = max_len;
536 * Compute a throttle threshold 25% below the current duration.
538 avg_len += avg_len / 4;
539 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
545 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
546 WRITE_ONCE(max_samples_per_tick, max);
548 sysctl_perf_event_sample_rate = max * HZ;
549 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
551 if (!irq_work_queue(&perf_duration_work)) {
552 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
553 "kernel.perf_event_max_sample_rate to %d\n",
554 __report_avg, __report_allowed,
555 sysctl_perf_event_sample_rate);
559 static atomic64_t perf_event_id;
561 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
562 enum event_type_t event_type);
564 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
565 enum event_type_t event_type,
566 struct task_struct *task);
568 static void update_context_time(struct perf_event_context *ctx);
569 static u64 perf_event_time(struct perf_event *event);
571 void __weak perf_event_print_debug(void) { }
573 extern __weak const char *perf_pmu_name(void)
578 static inline u64 perf_clock(void)
580 return local_clock();
583 static inline u64 perf_event_clock(struct perf_event *event)
585 return event->clock();
589 * State based event timekeeping...
591 * The basic idea is to use event->state to determine which (if any) time
592 * fields to increment with the current delta. This means we only need to
593 * update timestamps when we change state or when they are explicitly requested
596 * Event groups make things a little more complicated, but not terribly so. The
597 * rules for a group are that if the group leader is OFF the entire group is
598 * OFF, irrespecive of what the group member states are. This results in
599 * __perf_effective_state().
601 * A futher ramification is that when a group leader flips between OFF and
602 * !OFF, we need to update all group member times.
605 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
606 * need to make sure the relevant context time is updated before we try and
607 * update our timestamps.
610 static __always_inline enum perf_event_state
611 __perf_effective_state(struct perf_event *event)
613 struct perf_event *leader = event->group_leader;
615 if (leader->state <= PERF_EVENT_STATE_OFF)
616 return leader->state;
621 static __always_inline void
622 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
624 enum perf_event_state state = __perf_effective_state(event);
625 u64 delta = now - event->tstamp;
627 *enabled = event->total_time_enabled;
628 if (state >= PERF_EVENT_STATE_INACTIVE)
631 *running = event->total_time_running;
632 if (state >= PERF_EVENT_STATE_ACTIVE)
636 static void perf_event_update_time(struct perf_event *event)
638 u64 now = perf_event_time(event);
640 __perf_update_times(event, now, &event->total_time_enabled,
641 &event->total_time_running);
645 static void perf_event_update_sibling_time(struct perf_event *leader)
647 struct perf_event *sibling;
649 for_each_sibling_event(sibling, leader)
650 perf_event_update_time(sibling);
654 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
656 if (event->state == state)
659 perf_event_update_time(event);
661 * If a group leader gets enabled/disabled all its siblings
664 if ((event->state < 0) ^ (state < 0))
665 perf_event_update_sibling_time(event);
667 WRITE_ONCE(event->state, state);
670 #ifdef CONFIG_CGROUP_PERF
673 perf_cgroup_match(struct perf_event *event)
675 struct perf_event_context *ctx = event->ctx;
676 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
678 /* @event doesn't care about cgroup */
682 /* wants specific cgroup scope but @cpuctx isn't associated with any */
687 * Cgroup scoping is recursive. An event enabled for a cgroup is
688 * also enabled for all its descendant cgroups. If @cpuctx's
689 * cgroup is a descendant of @event's (the test covers identity
690 * case), it's a match.
692 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
693 event->cgrp->css.cgroup);
696 static inline void perf_detach_cgroup(struct perf_event *event)
698 css_put(&event->cgrp->css);
702 static inline int is_cgroup_event(struct perf_event *event)
704 return event->cgrp != NULL;
707 static inline u64 perf_cgroup_event_time(struct perf_event *event)
709 struct perf_cgroup_info *t;
711 t = per_cpu_ptr(event->cgrp->info, event->cpu);
715 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
717 struct perf_cgroup_info *info;
722 info = this_cpu_ptr(cgrp->info);
724 info->time += now - info->timestamp;
725 info->timestamp = now;
728 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
730 struct perf_cgroup *cgrp = cpuctx->cgrp;
731 struct cgroup_subsys_state *css;
734 for (css = &cgrp->css; css; css = css->parent) {
735 cgrp = container_of(css, struct perf_cgroup, css);
736 __update_cgrp_time(cgrp);
741 static inline void update_cgrp_time_from_event(struct perf_event *event)
743 struct perf_cgroup *cgrp;
746 * ensure we access cgroup data only when needed and
747 * when we know the cgroup is pinned (css_get)
749 if (!is_cgroup_event(event))
752 cgrp = perf_cgroup_from_task(current, event->ctx);
754 * Do not update time when cgroup is not active
756 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
757 __update_cgrp_time(event->cgrp);
761 perf_cgroup_set_timestamp(struct task_struct *task,
762 struct perf_event_context *ctx)
764 struct perf_cgroup *cgrp;
765 struct perf_cgroup_info *info;
766 struct cgroup_subsys_state *css;
769 * ctx->lock held by caller
770 * ensure we do not access cgroup data
771 * unless we have the cgroup pinned (css_get)
773 if (!task || !ctx->nr_cgroups)
776 cgrp = perf_cgroup_from_task(task, ctx);
778 for (css = &cgrp->css; css; css = css->parent) {
779 cgrp = container_of(css, struct perf_cgroup, css);
780 info = this_cpu_ptr(cgrp->info);
781 info->timestamp = ctx->timestamp;
785 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
787 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
788 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
791 * reschedule events based on the cgroup constraint of task.
793 * mode SWOUT : schedule out everything
794 * mode SWIN : schedule in based on cgroup for next
796 static void perf_cgroup_switch(struct task_struct *task, int mode)
798 struct perf_cpu_context *cpuctx;
799 struct list_head *list;
803 * Disable interrupts and preemption to avoid this CPU's
804 * cgrp_cpuctx_entry to change under us.
806 local_irq_save(flags);
808 list = this_cpu_ptr(&cgrp_cpuctx_list);
809 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
810 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
812 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
813 perf_pmu_disable(cpuctx->ctx.pmu);
815 if (mode & PERF_CGROUP_SWOUT) {
816 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
818 * must not be done before ctxswout due
819 * to event_filter_match() in event_sched_out()
824 if (mode & PERF_CGROUP_SWIN) {
825 WARN_ON_ONCE(cpuctx->cgrp);
827 * set cgrp before ctxsw in to allow
828 * event_filter_match() to not have to pass
830 * we pass the cpuctx->ctx to perf_cgroup_from_task()
831 * because cgorup events are only per-cpu
833 cpuctx->cgrp = perf_cgroup_from_task(task,
835 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
837 perf_pmu_enable(cpuctx->ctx.pmu);
838 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
841 local_irq_restore(flags);
844 static inline void perf_cgroup_sched_out(struct task_struct *task,
845 struct task_struct *next)
847 struct perf_cgroup *cgrp1;
848 struct perf_cgroup *cgrp2 = NULL;
852 * we come here when we know perf_cgroup_events > 0
853 * we do not need to pass the ctx here because we know
854 * we are holding the rcu lock
856 cgrp1 = perf_cgroup_from_task(task, NULL);
857 cgrp2 = perf_cgroup_from_task(next, NULL);
860 * only schedule out current cgroup events if we know
861 * that we are switching to a different cgroup. Otherwise,
862 * do no touch the cgroup events.
865 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
870 static inline void perf_cgroup_sched_in(struct task_struct *prev,
871 struct task_struct *task)
873 struct perf_cgroup *cgrp1;
874 struct perf_cgroup *cgrp2 = NULL;
878 * we come here when we know perf_cgroup_events > 0
879 * we do not need to pass the ctx here because we know
880 * we are holding the rcu lock
882 cgrp1 = perf_cgroup_from_task(task, NULL);
883 cgrp2 = perf_cgroup_from_task(prev, NULL);
886 * only need to schedule in cgroup events if we are changing
887 * cgroup during ctxsw. Cgroup events were not scheduled
888 * out of ctxsw out if that was not the case.
891 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
896 static int perf_cgroup_ensure_storage(struct perf_event *event,
897 struct cgroup_subsys_state *css)
899 struct perf_cpu_context *cpuctx;
900 struct perf_event **storage;
901 int cpu, heap_size, ret = 0;
904 * Allow storage to have sufficent space for an iterator for each
905 * possibly nested cgroup plus an iterator for events with no cgroup.
907 for (heap_size = 1; css; css = css->parent)
910 for_each_possible_cpu(cpu) {
911 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
912 if (heap_size <= cpuctx->heap_size)
915 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
916 GFP_KERNEL, cpu_to_node(cpu));
922 raw_spin_lock_irq(&cpuctx->ctx.lock);
923 if (cpuctx->heap_size < heap_size) {
924 swap(cpuctx->heap, storage);
925 if (storage == cpuctx->heap_default)
927 cpuctx->heap_size = heap_size;
929 raw_spin_unlock_irq(&cpuctx->ctx.lock);
937 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
938 struct perf_event_attr *attr,
939 struct perf_event *group_leader)
941 struct perf_cgroup *cgrp;
942 struct cgroup_subsys_state *css;
943 struct fd f = fdget(fd);
949 css = css_tryget_online_from_dir(f.file->f_path.dentry,
950 &perf_event_cgrp_subsys);
956 ret = perf_cgroup_ensure_storage(event, css);
960 cgrp = container_of(css, struct perf_cgroup, css);
964 * all events in a group must monitor
965 * the same cgroup because a task belongs
966 * to only one perf cgroup at a time
968 if (group_leader && group_leader->cgrp != cgrp) {
969 perf_detach_cgroup(event);
978 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
980 struct perf_cgroup_info *t;
981 t = per_cpu_ptr(event->cgrp->info, event->cpu);
982 event->shadow_ctx_time = now - t->timestamp;
986 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
987 * cleared when last cgroup event is removed.
990 list_update_cgroup_event(struct perf_event *event,
991 struct perf_event_context *ctx, bool add)
993 struct perf_cpu_context *cpuctx;
994 struct list_head *cpuctx_entry;
996 if (!is_cgroup_event(event))
1000 * Because cgroup events are always per-cpu events,
1001 * @ctx == &cpuctx->ctx.
1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1006 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1007 * matching the event's cgroup, we must do this for every new event,
1008 * because if the first would mismatch, the second would not try again
1009 * and we would leave cpuctx->cgrp unset.
1011 if (add && !cpuctx->cgrp) {
1012 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1014 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1015 cpuctx->cgrp = cgrp;
1018 if (add && ctx->nr_cgroups++)
1020 else if (!add && --ctx->nr_cgroups)
1023 /* no cgroup running */
1025 cpuctx->cgrp = NULL;
1027 cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
1029 list_add(cpuctx_entry,
1030 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1032 list_del(cpuctx_entry);
1035 #else /* !CONFIG_CGROUP_PERF */
1038 perf_cgroup_match(struct perf_event *event)
1043 static inline void perf_detach_cgroup(struct perf_event *event)
1046 static inline int is_cgroup_event(struct perf_event *event)
1051 static inline void update_cgrp_time_from_event(struct perf_event *event)
1055 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1059 static inline void perf_cgroup_sched_out(struct task_struct *task,
1060 struct task_struct *next)
1064 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1065 struct task_struct *task)
1069 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1070 struct perf_event_attr *attr,
1071 struct perf_event *group_leader)
1077 perf_cgroup_set_timestamp(struct task_struct *task,
1078 struct perf_event_context *ctx)
1083 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1088 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1092 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1098 list_update_cgroup_event(struct perf_event *event,
1099 struct perf_event_context *ctx, bool add)
1106 * set default to be dependent on timer tick just
1107 * like original code
1109 #define PERF_CPU_HRTIMER (1000 / HZ)
1111 * function must be called with interrupts disabled
1113 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1115 struct perf_cpu_context *cpuctx;
1118 lockdep_assert_irqs_disabled();
1120 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1121 rotations = perf_rotate_context(cpuctx);
1123 raw_spin_lock(&cpuctx->hrtimer_lock);
1125 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1127 cpuctx->hrtimer_active = 0;
1128 raw_spin_unlock(&cpuctx->hrtimer_lock);
1130 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1133 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1135 struct hrtimer *timer = &cpuctx->hrtimer;
1136 struct pmu *pmu = cpuctx->ctx.pmu;
1139 /* no multiplexing needed for SW PMU */
1140 if (pmu->task_ctx_nr == perf_sw_context)
1144 * check default is sane, if not set then force to
1145 * default interval (1/tick)
1147 interval = pmu->hrtimer_interval_ms;
1149 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1151 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1153 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1154 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1155 timer->function = perf_mux_hrtimer_handler;
1158 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1160 struct hrtimer *timer = &cpuctx->hrtimer;
1161 struct pmu *pmu = cpuctx->ctx.pmu;
1162 unsigned long flags;
1164 /* not for SW PMU */
1165 if (pmu->task_ctx_nr == perf_sw_context)
1168 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1169 if (!cpuctx->hrtimer_active) {
1170 cpuctx->hrtimer_active = 1;
1171 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1172 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1174 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1179 void perf_pmu_disable(struct pmu *pmu)
1181 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1183 pmu->pmu_disable(pmu);
1186 void perf_pmu_enable(struct pmu *pmu)
1188 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1190 pmu->pmu_enable(pmu);
1193 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1196 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1197 * perf_event_task_tick() are fully serialized because they're strictly cpu
1198 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1199 * disabled, while perf_event_task_tick is called from IRQ context.
1201 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1203 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1205 lockdep_assert_irqs_disabled();
1207 WARN_ON(!list_empty(&ctx->active_ctx_list));
1209 list_add(&ctx->active_ctx_list, head);
1212 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1214 lockdep_assert_irqs_disabled();
1216 WARN_ON(list_empty(&ctx->active_ctx_list));
1218 list_del_init(&ctx->active_ctx_list);
1221 static void get_ctx(struct perf_event_context *ctx)
1223 refcount_inc(&ctx->refcount);
1226 static void free_ctx(struct rcu_head *head)
1228 struct perf_event_context *ctx;
1230 ctx = container_of(head, struct perf_event_context, rcu_head);
1231 kfree(ctx->task_ctx_data);
1235 static void put_ctx(struct perf_event_context *ctx)
1237 if (refcount_dec_and_test(&ctx->refcount)) {
1238 if (ctx->parent_ctx)
1239 put_ctx(ctx->parent_ctx);
1240 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1241 put_task_struct(ctx->task);
1242 call_rcu(&ctx->rcu_head, free_ctx);
1247 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1248 * perf_pmu_migrate_context() we need some magic.
1250 * Those places that change perf_event::ctx will hold both
1251 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1253 * Lock ordering is by mutex address. There are two other sites where
1254 * perf_event_context::mutex nests and those are:
1256 * - perf_event_exit_task_context() [ child , 0 ]
1257 * perf_event_exit_event()
1258 * put_event() [ parent, 1 ]
1260 * - perf_event_init_context() [ parent, 0 ]
1261 * inherit_task_group()
1264 * perf_event_alloc()
1266 * perf_try_init_event() [ child , 1 ]
1268 * While it appears there is an obvious deadlock here -- the parent and child
1269 * nesting levels are inverted between the two. This is in fact safe because
1270 * life-time rules separate them. That is an exiting task cannot fork, and a
1271 * spawning task cannot (yet) exit.
1273 * But remember that that these are parent<->child context relations, and
1274 * migration does not affect children, therefore these two orderings should not
1277 * The change in perf_event::ctx does not affect children (as claimed above)
1278 * because the sys_perf_event_open() case will install a new event and break
1279 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1280 * concerned with cpuctx and that doesn't have children.
1282 * The places that change perf_event::ctx will issue:
1284 * perf_remove_from_context();
1285 * synchronize_rcu();
1286 * perf_install_in_context();
1288 * to affect the change. The remove_from_context() + synchronize_rcu() should
1289 * quiesce the event, after which we can install it in the new location. This
1290 * means that only external vectors (perf_fops, prctl) can perturb the event
1291 * while in transit. Therefore all such accessors should also acquire
1292 * perf_event_context::mutex to serialize against this.
1294 * However; because event->ctx can change while we're waiting to acquire
1295 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1300 * task_struct::perf_event_mutex
1301 * perf_event_context::mutex
1302 * perf_event::child_mutex;
1303 * perf_event_context::lock
1304 * perf_event::mmap_mutex
1306 * perf_addr_filters_head::lock
1310 * cpuctx->mutex / perf_event_context::mutex
1312 static struct perf_event_context *
1313 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1315 struct perf_event_context *ctx;
1319 ctx = READ_ONCE(event->ctx);
1320 if (!refcount_inc_not_zero(&ctx->refcount)) {
1326 mutex_lock_nested(&ctx->mutex, nesting);
1327 if (event->ctx != ctx) {
1328 mutex_unlock(&ctx->mutex);
1336 static inline struct perf_event_context *
1337 perf_event_ctx_lock(struct perf_event *event)
1339 return perf_event_ctx_lock_nested(event, 0);
1342 static void perf_event_ctx_unlock(struct perf_event *event,
1343 struct perf_event_context *ctx)
1345 mutex_unlock(&ctx->mutex);
1350 * This must be done under the ctx->lock, such as to serialize against
1351 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1352 * calling scheduler related locks and ctx->lock nests inside those.
1354 static __must_check struct perf_event_context *
1355 unclone_ctx(struct perf_event_context *ctx)
1357 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1359 lockdep_assert_held(&ctx->lock);
1362 ctx->parent_ctx = NULL;
1368 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1373 * only top level events have the pid namespace they were created in
1376 event = event->parent;
1378 nr = __task_pid_nr_ns(p, type, event->ns);
1379 /* avoid -1 if it is idle thread or runs in another ns */
1380 if (!nr && !pid_alive(p))
1385 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1387 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1390 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1392 return perf_event_pid_type(event, p, PIDTYPE_PID);
1396 * If we inherit events we want to return the parent event id
1399 static u64 primary_event_id(struct perf_event *event)
1404 id = event->parent->id;
1410 * Get the perf_event_context for a task and lock it.
1412 * This has to cope with with the fact that until it is locked,
1413 * the context could get moved to another task.
1415 static struct perf_event_context *
1416 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1418 struct perf_event_context *ctx;
1422 * One of the few rules of preemptible RCU is that one cannot do
1423 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1424 * part of the read side critical section was irqs-enabled -- see
1425 * rcu_read_unlock_special().
1427 * Since ctx->lock nests under rq->lock we must ensure the entire read
1428 * side critical section has interrupts disabled.
1430 local_irq_save(*flags);
1432 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1435 * If this context is a clone of another, it might
1436 * get swapped for another underneath us by
1437 * perf_event_task_sched_out, though the
1438 * rcu_read_lock() protects us from any context
1439 * getting freed. Lock the context and check if it
1440 * got swapped before we could get the lock, and retry
1441 * if so. If we locked the right context, then it
1442 * can't get swapped on us any more.
1444 raw_spin_lock(&ctx->lock);
1445 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1446 raw_spin_unlock(&ctx->lock);
1448 local_irq_restore(*flags);
1452 if (ctx->task == TASK_TOMBSTONE ||
1453 !refcount_inc_not_zero(&ctx->refcount)) {
1454 raw_spin_unlock(&ctx->lock);
1457 WARN_ON_ONCE(ctx->task != task);
1462 local_irq_restore(*flags);
1467 * Get the context for a task and increment its pin_count so it
1468 * can't get swapped to another task. This also increments its
1469 * reference count so that the context can't get freed.
1471 static struct perf_event_context *
1472 perf_pin_task_context(struct task_struct *task, int ctxn)
1474 struct perf_event_context *ctx;
1475 unsigned long flags;
1477 ctx = perf_lock_task_context(task, ctxn, &flags);
1480 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1485 static void perf_unpin_context(struct perf_event_context *ctx)
1487 unsigned long flags;
1489 raw_spin_lock_irqsave(&ctx->lock, flags);
1491 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1495 * Update the record of the current time in a context.
1497 static void update_context_time(struct perf_event_context *ctx)
1499 u64 now = perf_clock();
1501 ctx->time += now - ctx->timestamp;
1502 ctx->timestamp = now;
1505 static u64 perf_event_time(struct perf_event *event)
1507 struct perf_event_context *ctx = event->ctx;
1509 if (is_cgroup_event(event))
1510 return perf_cgroup_event_time(event);
1512 return ctx ? ctx->time : 0;
1515 static enum event_type_t get_event_type(struct perf_event *event)
1517 struct perf_event_context *ctx = event->ctx;
1518 enum event_type_t event_type;
1520 lockdep_assert_held(&ctx->lock);
1523 * It's 'group type', really, because if our group leader is
1524 * pinned, so are we.
1526 if (event->group_leader != event)
1527 event = event->group_leader;
1529 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1531 event_type |= EVENT_CPU;
1537 * Helper function to initialize event group nodes.
1539 static void init_event_group(struct perf_event *event)
1541 RB_CLEAR_NODE(&event->group_node);
1542 event->group_index = 0;
1546 * Extract pinned or flexible groups from the context
1547 * based on event attrs bits.
1549 static struct perf_event_groups *
1550 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1552 if (event->attr.pinned)
1553 return &ctx->pinned_groups;
1555 return &ctx->flexible_groups;
1559 * Helper function to initializes perf_event_group trees.
1561 static void perf_event_groups_init(struct perf_event_groups *groups)
1563 groups->tree = RB_ROOT;
1568 * Compare function for event groups;
1570 * Implements complex key that first sorts by CPU and then by virtual index
1571 * which provides ordering when rotating groups for the same CPU.
1574 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1576 if (left->cpu < right->cpu)
1578 if (left->cpu > right->cpu)
1581 #ifdef CONFIG_CGROUP_PERF
1582 if (left->cgrp != right->cgrp) {
1583 if (!left->cgrp || !left->cgrp->css.cgroup) {
1585 * Left has no cgroup but right does, no cgroups come
1590 if (!right->cgrp || !right->cgrp->css.cgroup) {
1592 * Right has no cgroup but left does, no cgroups come
1597 /* Two dissimilar cgroups, order by id. */
1598 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1605 if (left->group_index < right->group_index)
1607 if (left->group_index > right->group_index)
1614 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1615 * key (see perf_event_groups_less). This places it last inside the CPU
1619 perf_event_groups_insert(struct perf_event_groups *groups,
1620 struct perf_event *event)
1622 struct perf_event *node_event;
1623 struct rb_node *parent;
1624 struct rb_node **node;
1626 event->group_index = ++groups->index;
1628 node = &groups->tree.rb_node;
1633 node_event = container_of(*node, struct perf_event, group_node);
1635 if (perf_event_groups_less(event, node_event))
1636 node = &parent->rb_left;
1638 node = &parent->rb_right;
1641 rb_link_node(&event->group_node, parent, node);
1642 rb_insert_color(&event->group_node, &groups->tree);
1646 * Helper function to insert event into the pinned or flexible groups.
1649 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1651 struct perf_event_groups *groups;
1653 groups = get_event_groups(event, ctx);
1654 perf_event_groups_insert(groups, event);
1658 * Delete a group from a tree.
1661 perf_event_groups_delete(struct perf_event_groups *groups,
1662 struct perf_event *event)
1664 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1665 RB_EMPTY_ROOT(&groups->tree));
1667 rb_erase(&event->group_node, &groups->tree);
1668 init_event_group(event);
1672 * Helper function to delete event from its groups.
1675 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1677 struct perf_event_groups *groups;
1679 groups = get_event_groups(event, ctx);
1680 perf_event_groups_delete(groups, event);
1684 * Get the leftmost event in the cpu/cgroup subtree.
1686 static struct perf_event *
1687 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1688 struct cgroup *cgrp)
1690 struct perf_event *node_event = NULL, *match = NULL;
1691 struct rb_node *node = groups->tree.rb_node;
1692 #ifdef CONFIG_CGROUP_PERF
1693 u64 node_cgrp_id, cgrp_id = 0;
1696 cgrp_id = cgrp->kn->id;
1700 node_event = container_of(node, struct perf_event, group_node);
1702 if (cpu < node_event->cpu) {
1703 node = node->rb_left;
1706 if (cpu > node_event->cpu) {
1707 node = node->rb_right;
1710 #ifdef CONFIG_CGROUP_PERF
1712 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1713 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1715 if (cgrp_id < node_cgrp_id) {
1716 node = node->rb_left;
1719 if (cgrp_id > node_cgrp_id) {
1720 node = node->rb_right;
1725 node = node->rb_left;
1732 * Like rb_entry_next_safe() for the @cpu subtree.
1734 static struct perf_event *
1735 perf_event_groups_next(struct perf_event *event)
1737 struct perf_event *next;
1738 #ifdef CONFIG_CGROUP_PERF
1739 u64 curr_cgrp_id = 0;
1740 u64 next_cgrp_id = 0;
1743 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1744 if (next == NULL || next->cpu != event->cpu)
1747 #ifdef CONFIG_CGROUP_PERF
1748 if (event->cgrp && event->cgrp->css.cgroup)
1749 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1751 if (next->cgrp && next->cgrp->css.cgroup)
1752 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1754 if (curr_cgrp_id != next_cgrp_id)
1761 * Iterate through the whole groups tree.
1763 #define perf_event_groups_for_each(event, groups) \
1764 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1765 typeof(*event), group_node); event; \
1766 event = rb_entry_safe(rb_next(&event->group_node), \
1767 typeof(*event), group_node))
1770 * Add an event from the lists for its context.
1771 * Must be called with ctx->mutex and ctx->lock held.
1774 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1776 lockdep_assert_held(&ctx->lock);
1778 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1779 event->attach_state |= PERF_ATTACH_CONTEXT;
1781 event->tstamp = perf_event_time(event);
1784 * If we're a stand alone event or group leader, we go to the context
1785 * list, group events are kept attached to the group so that
1786 * perf_group_detach can, at all times, locate all siblings.
1788 if (event->group_leader == event) {
1789 event->group_caps = event->event_caps;
1790 add_event_to_groups(event, ctx);
1793 list_update_cgroup_event(event, ctx, true);
1795 list_add_rcu(&event->event_entry, &ctx->event_list);
1797 if (event->attr.inherit_stat)
1804 * Initialize event state based on the perf_event_attr::disabled.
1806 static inline void perf_event__state_init(struct perf_event *event)
1808 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1809 PERF_EVENT_STATE_INACTIVE;
1812 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1814 int entry = sizeof(u64); /* value */
1818 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1819 size += sizeof(u64);
1821 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1822 size += sizeof(u64);
1824 if (event->attr.read_format & PERF_FORMAT_ID)
1825 entry += sizeof(u64);
1827 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1829 size += sizeof(u64);
1833 event->read_size = size;
1836 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1838 struct perf_sample_data *data;
1841 if (sample_type & PERF_SAMPLE_IP)
1842 size += sizeof(data->ip);
1844 if (sample_type & PERF_SAMPLE_ADDR)
1845 size += sizeof(data->addr);
1847 if (sample_type & PERF_SAMPLE_PERIOD)
1848 size += sizeof(data->period);
1850 if (sample_type & PERF_SAMPLE_WEIGHT)
1851 size += sizeof(data->weight);
1853 if (sample_type & PERF_SAMPLE_READ)
1854 size += event->read_size;
1856 if (sample_type & PERF_SAMPLE_DATA_SRC)
1857 size += sizeof(data->data_src.val);
1859 if (sample_type & PERF_SAMPLE_TRANSACTION)
1860 size += sizeof(data->txn);
1862 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1863 size += sizeof(data->phys_addr);
1865 if (sample_type & PERF_SAMPLE_CGROUP)
1866 size += sizeof(data->cgroup);
1868 event->header_size = size;
1872 * Called at perf_event creation and when events are attached/detached from a
1875 static void perf_event__header_size(struct perf_event *event)
1877 __perf_event_read_size(event,
1878 event->group_leader->nr_siblings);
1879 __perf_event_header_size(event, event->attr.sample_type);
1882 static void perf_event__id_header_size(struct perf_event *event)
1884 struct perf_sample_data *data;
1885 u64 sample_type = event->attr.sample_type;
1888 if (sample_type & PERF_SAMPLE_TID)
1889 size += sizeof(data->tid_entry);
1891 if (sample_type & PERF_SAMPLE_TIME)
1892 size += sizeof(data->time);
1894 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1895 size += sizeof(data->id);
1897 if (sample_type & PERF_SAMPLE_ID)
1898 size += sizeof(data->id);
1900 if (sample_type & PERF_SAMPLE_STREAM_ID)
1901 size += sizeof(data->stream_id);
1903 if (sample_type & PERF_SAMPLE_CPU)
1904 size += sizeof(data->cpu_entry);
1906 event->id_header_size = size;
1909 static bool perf_event_validate_size(struct perf_event *event)
1912 * The values computed here will be over-written when we actually
1915 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1916 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1917 perf_event__id_header_size(event);
1920 * Sum the lot; should not exceed the 64k limit we have on records.
1921 * Conservative limit to allow for callchains and other variable fields.
1923 if (event->read_size + event->header_size +
1924 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1930 static void perf_group_attach(struct perf_event *event)
1932 struct perf_event *group_leader = event->group_leader, *pos;
1934 lockdep_assert_held(&event->ctx->lock);
1937 * We can have double attach due to group movement in perf_event_open.
1939 if (event->attach_state & PERF_ATTACH_GROUP)
1942 event->attach_state |= PERF_ATTACH_GROUP;
1944 if (group_leader == event)
1947 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1949 group_leader->group_caps &= event->event_caps;
1951 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1952 group_leader->nr_siblings++;
1954 perf_event__header_size(group_leader);
1956 for_each_sibling_event(pos, group_leader)
1957 perf_event__header_size(pos);
1961 * Remove an event from the lists for its context.
1962 * Must be called with ctx->mutex and ctx->lock held.
1965 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1967 WARN_ON_ONCE(event->ctx != ctx);
1968 lockdep_assert_held(&ctx->lock);
1971 * We can have double detach due to exit/hot-unplug + close.
1973 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1976 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1978 list_update_cgroup_event(event, ctx, false);
1981 if (event->attr.inherit_stat)
1984 list_del_rcu(&event->event_entry);
1986 if (event->group_leader == event)
1987 del_event_from_groups(event, ctx);
1990 * If event was in error state, then keep it
1991 * that way, otherwise bogus counts will be
1992 * returned on read(). The only way to get out
1993 * of error state is by explicit re-enabling
1996 if (event->state > PERF_EVENT_STATE_OFF)
1997 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2003 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2005 if (!has_aux(aux_event))
2008 if (!event->pmu->aux_output_match)
2011 return event->pmu->aux_output_match(aux_event);
2014 static void put_event(struct perf_event *event);
2015 static void event_sched_out(struct perf_event *event,
2016 struct perf_cpu_context *cpuctx,
2017 struct perf_event_context *ctx);
2019 static void perf_put_aux_event(struct perf_event *event)
2021 struct perf_event_context *ctx = event->ctx;
2022 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2023 struct perf_event *iter;
2026 * If event uses aux_event tear down the link
2028 if (event->aux_event) {
2029 iter = event->aux_event;
2030 event->aux_event = NULL;
2036 * If the event is an aux_event, tear down all links to
2037 * it from other events.
2039 for_each_sibling_event(iter, event->group_leader) {
2040 if (iter->aux_event != event)
2043 iter->aux_event = NULL;
2047 * If it's ACTIVE, schedule it out and put it into ERROR
2048 * state so that we don't try to schedule it again. Note
2049 * that perf_event_enable() will clear the ERROR status.
2051 event_sched_out(iter, cpuctx, ctx);
2052 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2056 static bool perf_need_aux_event(struct perf_event *event)
2058 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2061 static int perf_get_aux_event(struct perf_event *event,
2062 struct perf_event *group_leader)
2065 * Our group leader must be an aux event if we want to be
2066 * an aux_output. This way, the aux event will precede its
2067 * aux_output events in the group, and therefore will always
2074 * aux_output and aux_sample_size are mutually exclusive.
2076 if (event->attr.aux_output && event->attr.aux_sample_size)
2079 if (event->attr.aux_output &&
2080 !perf_aux_output_match(event, group_leader))
2083 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2086 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2090 * Link aux_outputs to their aux event; this is undone in
2091 * perf_group_detach() by perf_put_aux_event(). When the
2092 * group in torn down, the aux_output events loose their
2093 * link to the aux_event and can't schedule any more.
2095 event->aux_event = group_leader;
2100 static inline struct list_head *get_event_list(struct perf_event *event)
2102 struct perf_event_context *ctx = event->ctx;
2103 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2106 static void perf_group_detach(struct perf_event *event)
2108 struct perf_event *sibling, *tmp;
2109 struct perf_event_context *ctx = event->ctx;
2111 lockdep_assert_held(&ctx->lock);
2114 * We can have double detach due to exit/hot-unplug + close.
2116 if (!(event->attach_state & PERF_ATTACH_GROUP))
2119 event->attach_state &= ~PERF_ATTACH_GROUP;
2121 perf_put_aux_event(event);
2124 * If this is a sibling, remove it from its group.
2126 if (event->group_leader != event) {
2127 list_del_init(&event->sibling_list);
2128 event->group_leader->nr_siblings--;
2133 * If this was a group event with sibling events then
2134 * upgrade the siblings to singleton events by adding them
2135 * to whatever list we are on.
2137 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2139 sibling->group_leader = sibling;
2140 list_del_init(&sibling->sibling_list);
2142 /* Inherit group flags from the previous leader */
2143 sibling->group_caps = event->group_caps;
2145 if (!RB_EMPTY_NODE(&event->group_node)) {
2146 add_event_to_groups(sibling, event->ctx);
2148 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2149 list_add_tail(&sibling->active_list, get_event_list(sibling));
2152 WARN_ON_ONCE(sibling->ctx != event->ctx);
2156 perf_event__header_size(event->group_leader);
2158 for_each_sibling_event(tmp, event->group_leader)
2159 perf_event__header_size(tmp);
2162 static bool is_orphaned_event(struct perf_event *event)
2164 return event->state == PERF_EVENT_STATE_DEAD;
2167 static inline int __pmu_filter_match(struct perf_event *event)
2169 struct pmu *pmu = event->pmu;
2170 return pmu->filter_match ? pmu->filter_match(event) : 1;
2174 * Check whether we should attempt to schedule an event group based on
2175 * PMU-specific filtering. An event group can consist of HW and SW events,
2176 * potentially with a SW leader, so we must check all the filters, to
2177 * determine whether a group is schedulable:
2179 static inline int pmu_filter_match(struct perf_event *event)
2181 struct perf_event *sibling;
2183 if (!__pmu_filter_match(event))
2186 for_each_sibling_event(sibling, event) {
2187 if (!__pmu_filter_match(sibling))
2195 event_filter_match(struct perf_event *event)
2197 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2198 perf_cgroup_match(event) && pmu_filter_match(event);
2202 event_sched_out(struct perf_event *event,
2203 struct perf_cpu_context *cpuctx,
2204 struct perf_event_context *ctx)
2206 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2208 WARN_ON_ONCE(event->ctx != ctx);
2209 lockdep_assert_held(&ctx->lock);
2211 if (event->state != PERF_EVENT_STATE_ACTIVE)
2215 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2216 * we can schedule events _OUT_ individually through things like
2217 * __perf_remove_from_context().
2219 list_del_init(&event->active_list);
2221 perf_pmu_disable(event->pmu);
2223 event->pmu->del(event, 0);
2226 if (READ_ONCE(event->pending_disable) >= 0) {
2227 WRITE_ONCE(event->pending_disable, -1);
2228 state = PERF_EVENT_STATE_OFF;
2230 perf_event_set_state(event, state);
2232 if (!is_software_event(event))
2233 cpuctx->active_oncpu--;
2234 if (!--ctx->nr_active)
2235 perf_event_ctx_deactivate(ctx);
2236 if (event->attr.freq && event->attr.sample_freq)
2238 if (event->attr.exclusive || !cpuctx->active_oncpu)
2239 cpuctx->exclusive = 0;
2241 perf_pmu_enable(event->pmu);
2245 group_sched_out(struct perf_event *group_event,
2246 struct perf_cpu_context *cpuctx,
2247 struct perf_event_context *ctx)
2249 struct perf_event *event;
2251 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2254 perf_pmu_disable(ctx->pmu);
2256 event_sched_out(group_event, cpuctx, ctx);
2259 * Schedule out siblings (if any):
2261 for_each_sibling_event(event, group_event)
2262 event_sched_out(event, cpuctx, ctx);
2264 perf_pmu_enable(ctx->pmu);
2266 if (group_event->attr.exclusive)
2267 cpuctx->exclusive = 0;
2270 #define DETACH_GROUP 0x01UL
2273 * Cross CPU call to remove a performance event
2275 * We disable the event on the hardware level first. After that we
2276 * remove it from the context list.
2279 __perf_remove_from_context(struct perf_event *event,
2280 struct perf_cpu_context *cpuctx,
2281 struct perf_event_context *ctx,
2284 unsigned long flags = (unsigned long)info;
2286 if (ctx->is_active & EVENT_TIME) {
2287 update_context_time(ctx);
2288 update_cgrp_time_from_cpuctx(cpuctx);
2291 event_sched_out(event, cpuctx, ctx);
2292 if (flags & DETACH_GROUP)
2293 perf_group_detach(event);
2294 list_del_event(event, ctx);
2296 if (!ctx->nr_events && ctx->is_active) {
2298 ctx->rotate_necessary = 0;
2300 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2301 cpuctx->task_ctx = NULL;
2307 * Remove the event from a task's (or a CPU's) list of events.
2309 * If event->ctx is a cloned context, callers must make sure that
2310 * every task struct that event->ctx->task could possibly point to
2311 * remains valid. This is OK when called from perf_release since
2312 * that only calls us on the top-level context, which can't be a clone.
2313 * When called from perf_event_exit_task, it's OK because the
2314 * context has been detached from its task.
2316 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2318 struct perf_event_context *ctx = event->ctx;
2320 lockdep_assert_held(&ctx->mutex);
2322 event_function_call(event, __perf_remove_from_context, (void *)flags);
2325 * The above event_function_call() can NO-OP when it hits
2326 * TASK_TOMBSTONE. In that case we must already have been detached
2327 * from the context (by perf_event_exit_event()) but the grouping
2328 * might still be in-tact.
2330 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2331 if ((flags & DETACH_GROUP) &&
2332 (event->attach_state & PERF_ATTACH_GROUP)) {
2334 * Since in that case we cannot possibly be scheduled, simply
2337 raw_spin_lock_irq(&ctx->lock);
2338 perf_group_detach(event);
2339 raw_spin_unlock_irq(&ctx->lock);
2344 * Cross CPU call to disable a performance event
2346 static void __perf_event_disable(struct perf_event *event,
2347 struct perf_cpu_context *cpuctx,
2348 struct perf_event_context *ctx,
2351 if (event->state < PERF_EVENT_STATE_INACTIVE)
2354 if (ctx->is_active & EVENT_TIME) {
2355 update_context_time(ctx);
2356 update_cgrp_time_from_event(event);
2359 if (event == event->group_leader)
2360 group_sched_out(event, cpuctx, ctx);
2362 event_sched_out(event, cpuctx, ctx);
2364 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2370 * If event->ctx is a cloned context, callers must make sure that
2371 * every task struct that event->ctx->task could possibly point to
2372 * remains valid. This condition is satisfied when called through
2373 * perf_event_for_each_child or perf_event_for_each because they
2374 * hold the top-level event's child_mutex, so any descendant that
2375 * goes to exit will block in perf_event_exit_event().
2377 * When called from perf_pending_event it's OK because event->ctx
2378 * is the current context on this CPU and preemption is disabled,
2379 * hence we can't get into perf_event_task_sched_out for this context.
2381 static void _perf_event_disable(struct perf_event *event)
2383 struct perf_event_context *ctx = event->ctx;
2385 raw_spin_lock_irq(&ctx->lock);
2386 if (event->state <= PERF_EVENT_STATE_OFF) {
2387 raw_spin_unlock_irq(&ctx->lock);
2390 raw_spin_unlock_irq(&ctx->lock);
2392 event_function_call(event, __perf_event_disable, NULL);
2395 void perf_event_disable_local(struct perf_event *event)
2397 event_function_local(event, __perf_event_disable, NULL);
2401 * Strictly speaking kernel users cannot create groups and therefore this
2402 * interface does not need the perf_event_ctx_lock() magic.
2404 void perf_event_disable(struct perf_event *event)
2406 struct perf_event_context *ctx;
2408 ctx = perf_event_ctx_lock(event);
2409 _perf_event_disable(event);
2410 perf_event_ctx_unlock(event, ctx);
2412 EXPORT_SYMBOL_GPL(perf_event_disable);
2414 void perf_event_disable_inatomic(struct perf_event *event)
2416 WRITE_ONCE(event->pending_disable, smp_processor_id());
2417 /* can fail, see perf_pending_event_disable() */
2418 irq_work_queue(&event->pending);
2421 static void perf_set_shadow_time(struct perf_event *event,
2422 struct perf_event_context *ctx)
2425 * use the correct time source for the time snapshot
2427 * We could get by without this by leveraging the
2428 * fact that to get to this function, the caller
2429 * has most likely already called update_context_time()
2430 * and update_cgrp_time_xx() and thus both timestamp
2431 * are identical (or very close). Given that tstamp is,
2432 * already adjusted for cgroup, we could say that:
2433 * tstamp - ctx->timestamp
2435 * tstamp - cgrp->timestamp.
2437 * Then, in perf_output_read(), the calculation would
2438 * work with no changes because:
2439 * - event is guaranteed scheduled in
2440 * - no scheduled out in between
2441 * - thus the timestamp would be the same
2443 * But this is a bit hairy.
2445 * So instead, we have an explicit cgroup call to remain
2446 * within the time time source all along. We believe it
2447 * is cleaner and simpler to understand.
2449 if (is_cgroup_event(event))
2450 perf_cgroup_set_shadow_time(event, event->tstamp);
2452 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2455 #define MAX_INTERRUPTS (~0ULL)
2457 static void perf_log_throttle(struct perf_event *event, int enable);
2458 static void perf_log_itrace_start(struct perf_event *event);
2461 event_sched_in(struct perf_event *event,
2462 struct perf_cpu_context *cpuctx,
2463 struct perf_event_context *ctx)
2467 WARN_ON_ONCE(event->ctx != ctx);
2469 lockdep_assert_held(&ctx->lock);
2471 if (event->state <= PERF_EVENT_STATE_OFF)
2474 WRITE_ONCE(event->oncpu, smp_processor_id());
2476 * Order event::oncpu write to happen before the ACTIVE state is
2477 * visible. This allows perf_event_{stop,read}() to observe the correct
2478 * ->oncpu if it sees ACTIVE.
2481 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2484 * Unthrottle events, since we scheduled we might have missed several
2485 * ticks already, also for a heavily scheduling task there is little
2486 * guarantee it'll get a tick in a timely manner.
2488 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2489 perf_log_throttle(event, 1);
2490 event->hw.interrupts = 0;
2493 perf_pmu_disable(event->pmu);
2495 perf_set_shadow_time(event, ctx);
2497 perf_log_itrace_start(event);
2499 if (event->pmu->add(event, PERF_EF_START)) {
2500 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2506 if (!is_software_event(event))
2507 cpuctx->active_oncpu++;
2508 if (!ctx->nr_active++)
2509 perf_event_ctx_activate(ctx);
2510 if (event->attr.freq && event->attr.sample_freq)
2513 if (event->attr.exclusive)
2514 cpuctx->exclusive = 1;
2517 perf_pmu_enable(event->pmu);
2523 group_sched_in(struct perf_event *group_event,
2524 struct perf_cpu_context *cpuctx,
2525 struct perf_event_context *ctx)
2527 struct perf_event *event, *partial_group = NULL;
2528 struct pmu *pmu = ctx->pmu;
2530 if (group_event->state == PERF_EVENT_STATE_OFF)
2533 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2535 if (event_sched_in(group_event, cpuctx, ctx)) {
2536 pmu->cancel_txn(pmu);
2537 perf_mux_hrtimer_restart(cpuctx);
2542 * Schedule in siblings as one group (if any):
2544 for_each_sibling_event(event, group_event) {
2545 if (event_sched_in(event, cpuctx, ctx)) {
2546 partial_group = event;
2551 if (!pmu->commit_txn(pmu))
2556 * Groups can be scheduled in as one unit only, so undo any
2557 * partial group before returning:
2558 * The events up to the failed event are scheduled out normally.
2560 for_each_sibling_event(event, group_event) {
2561 if (event == partial_group)
2564 event_sched_out(event, cpuctx, ctx);
2566 event_sched_out(group_event, cpuctx, ctx);
2568 pmu->cancel_txn(pmu);
2570 perf_mux_hrtimer_restart(cpuctx);
2576 * Work out whether we can put this event group on the CPU now.
2578 static int group_can_go_on(struct perf_event *event,
2579 struct perf_cpu_context *cpuctx,
2583 * Groups consisting entirely of software events can always go on.
2585 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2588 * If an exclusive group is already on, no other hardware
2591 if (cpuctx->exclusive)
2594 * If this group is exclusive and there are already
2595 * events on the CPU, it can't go on.
2597 if (event->attr.exclusive && cpuctx->active_oncpu)
2600 * Otherwise, try to add it if all previous groups were able
2606 static void add_event_to_ctx(struct perf_event *event,
2607 struct perf_event_context *ctx)
2609 list_add_event(event, ctx);
2610 perf_group_attach(event);
2613 static void ctx_sched_out(struct perf_event_context *ctx,
2614 struct perf_cpu_context *cpuctx,
2615 enum event_type_t event_type);
2617 ctx_sched_in(struct perf_event_context *ctx,
2618 struct perf_cpu_context *cpuctx,
2619 enum event_type_t event_type,
2620 struct task_struct *task);
2622 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2623 struct perf_event_context *ctx,
2624 enum event_type_t event_type)
2626 if (!cpuctx->task_ctx)
2629 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2632 ctx_sched_out(ctx, cpuctx, event_type);
2635 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2636 struct perf_event_context *ctx,
2637 struct task_struct *task)
2639 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2641 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2642 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2644 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2648 * We want to maintain the following priority of scheduling:
2649 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2650 * - task pinned (EVENT_PINNED)
2651 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2652 * - task flexible (EVENT_FLEXIBLE).
2654 * In order to avoid unscheduling and scheduling back in everything every
2655 * time an event is added, only do it for the groups of equal priority and
2658 * This can be called after a batch operation on task events, in which case
2659 * event_type is a bit mask of the types of events involved. For CPU events,
2660 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2662 static void ctx_resched(struct perf_cpu_context *cpuctx,
2663 struct perf_event_context *task_ctx,
2664 enum event_type_t event_type)
2666 enum event_type_t ctx_event_type;
2667 bool cpu_event = !!(event_type & EVENT_CPU);
2670 * If pinned groups are involved, flexible groups also need to be
2673 if (event_type & EVENT_PINNED)
2674 event_type |= EVENT_FLEXIBLE;
2676 ctx_event_type = event_type & EVENT_ALL;
2678 perf_pmu_disable(cpuctx->ctx.pmu);
2680 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2683 * Decide which cpu ctx groups to schedule out based on the types
2684 * of events that caused rescheduling:
2685 * - EVENT_CPU: schedule out corresponding groups;
2686 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2687 * - otherwise, do nothing more.
2690 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2691 else if (ctx_event_type & EVENT_PINNED)
2692 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2694 perf_event_sched_in(cpuctx, task_ctx, current);
2695 perf_pmu_enable(cpuctx->ctx.pmu);
2698 void perf_pmu_resched(struct pmu *pmu)
2700 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2701 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2703 perf_ctx_lock(cpuctx, task_ctx);
2704 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2705 perf_ctx_unlock(cpuctx, task_ctx);
2709 * Cross CPU call to install and enable a performance event
2711 * Very similar to remote_function() + event_function() but cannot assume that
2712 * things like ctx->is_active and cpuctx->task_ctx are set.
2714 static int __perf_install_in_context(void *info)
2716 struct perf_event *event = info;
2717 struct perf_event_context *ctx = event->ctx;
2718 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2719 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2720 bool reprogram = true;
2723 raw_spin_lock(&cpuctx->ctx.lock);
2725 raw_spin_lock(&ctx->lock);
2728 reprogram = (ctx->task == current);
2731 * If the task is running, it must be running on this CPU,
2732 * otherwise we cannot reprogram things.
2734 * If its not running, we don't care, ctx->lock will
2735 * serialize against it becoming runnable.
2737 if (task_curr(ctx->task) && !reprogram) {
2742 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2743 } else if (task_ctx) {
2744 raw_spin_lock(&task_ctx->lock);
2747 #ifdef CONFIG_CGROUP_PERF
2748 if (is_cgroup_event(event)) {
2750 * If the current cgroup doesn't match the event's
2751 * cgroup, we should not try to schedule it.
2753 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2754 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2755 event->cgrp->css.cgroup);
2760 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2761 add_event_to_ctx(event, ctx);
2762 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2764 add_event_to_ctx(event, ctx);
2768 perf_ctx_unlock(cpuctx, task_ctx);
2773 static bool exclusive_event_installable(struct perf_event *event,
2774 struct perf_event_context *ctx);
2777 * Attach a performance event to a context.
2779 * Very similar to event_function_call, see comment there.
2782 perf_install_in_context(struct perf_event_context *ctx,
2783 struct perf_event *event,
2786 struct task_struct *task = READ_ONCE(ctx->task);
2788 lockdep_assert_held(&ctx->mutex);
2790 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2792 if (event->cpu != -1)
2796 * Ensures that if we can observe event->ctx, both the event and ctx
2797 * will be 'complete'. See perf_iterate_sb_cpu().
2799 smp_store_release(&event->ctx, ctx);
2802 * perf_event_attr::disabled events will not run and can be initialized
2803 * without IPI. Except when this is the first event for the context, in
2804 * that case we need the magic of the IPI to set ctx->is_active.
2806 * The IOC_ENABLE that is sure to follow the creation of a disabled
2807 * event will issue the IPI and reprogram the hardware.
2809 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2810 raw_spin_lock_irq(&ctx->lock);
2811 if (ctx->task == TASK_TOMBSTONE) {
2812 raw_spin_unlock_irq(&ctx->lock);
2815 add_event_to_ctx(event, ctx);
2816 raw_spin_unlock_irq(&ctx->lock);
2821 cpu_function_call(cpu, __perf_install_in_context, event);
2826 * Should not happen, we validate the ctx is still alive before calling.
2828 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2832 * Installing events is tricky because we cannot rely on ctx->is_active
2833 * to be set in case this is the nr_events 0 -> 1 transition.
2835 * Instead we use task_curr(), which tells us if the task is running.
2836 * However, since we use task_curr() outside of rq::lock, we can race
2837 * against the actual state. This means the result can be wrong.
2839 * If we get a false positive, we retry, this is harmless.
2841 * If we get a false negative, things are complicated. If we are after
2842 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2843 * value must be correct. If we're before, it doesn't matter since
2844 * perf_event_context_sched_in() will program the counter.
2846 * However, this hinges on the remote context switch having observed
2847 * our task->perf_event_ctxp[] store, such that it will in fact take
2848 * ctx::lock in perf_event_context_sched_in().
2850 * We do this by task_function_call(), if the IPI fails to hit the task
2851 * we know any future context switch of task must see the
2852 * perf_event_ctpx[] store.
2856 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2857 * task_cpu() load, such that if the IPI then does not find the task
2858 * running, a future context switch of that task must observe the
2863 if (!task_function_call(task, __perf_install_in_context, event))
2866 raw_spin_lock_irq(&ctx->lock);
2868 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2870 * Cannot happen because we already checked above (which also
2871 * cannot happen), and we hold ctx->mutex, which serializes us
2872 * against perf_event_exit_task_context().
2874 raw_spin_unlock_irq(&ctx->lock);
2878 * If the task is not running, ctx->lock will avoid it becoming so,
2879 * thus we can safely install the event.
2881 if (task_curr(task)) {
2882 raw_spin_unlock_irq(&ctx->lock);
2885 add_event_to_ctx(event, ctx);
2886 raw_spin_unlock_irq(&ctx->lock);
2890 * Cross CPU call to enable a performance event
2892 static void __perf_event_enable(struct perf_event *event,
2893 struct perf_cpu_context *cpuctx,
2894 struct perf_event_context *ctx,
2897 struct perf_event *leader = event->group_leader;
2898 struct perf_event_context *task_ctx;
2900 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2901 event->state <= PERF_EVENT_STATE_ERROR)
2905 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2907 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2909 if (!ctx->is_active)
2912 if (!event_filter_match(event)) {
2913 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2918 * If the event is in a group and isn't the group leader,
2919 * then don't put it on unless the group is on.
2921 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2922 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2926 task_ctx = cpuctx->task_ctx;
2928 WARN_ON_ONCE(task_ctx != ctx);
2930 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2936 * If event->ctx is a cloned context, callers must make sure that
2937 * every task struct that event->ctx->task could possibly point to
2938 * remains valid. This condition is satisfied when called through
2939 * perf_event_for_each_child or perf_event_for_each as described
2940 * for perf_event_disable.
2942 static void _perf_event_enable(struct perf_event *event)
2944 struct perf_event_context *ctx = event->ctx;
2946 raw_spin_lock_irq(&ctx->lock);
2947 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2948 event->state < PERF_EVENT_STATE_ERROR) {
2949 raw_spin_unlock_irq(&ctx->lock);
2954 * If the event is in error state, clear that first.
2956 * That way, if we see the event in error state below, we know that it
2957 * has gone back into error state, as distinct from the task having
2958 * been scheduled away before the cross-call arrived.
2960 if (event->state == PERF_EVENT_STATE_ERROR)
2961 event->state = PERF_EVENT_STATE_OFF;
2962 raw_spin_unlock_irq(&ctx->lock);
2964 event_function_call(event, __perf_event_enable, NULL);
2968 * See perf_event_disable();
2970 void perf_event_enable(struct perf_event *event)
2972 struct perf_event_context *ctx;
2974 ctx = perf_event_ctx_lock(event);
2975 _perf_event_enable(event);
2976 perf_event_ctx_unlock(event, ctx);
2978 EXPORT_SYMBOL_GPL(perf_event_enable);
2980 struct stop_event_data {
2981 struct perf_event *event;
2982 unsigned int restart;
2985 static int __perf_event_stop(void *info)
2987 struct stop_event_data *sd = info;
2988 struct perf_event *event = sd->event;
2990 /* if it's already INACTIVE, do nothing */
2991 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2994 /* matches smp_wmb() in event_sched_in() */
2998 * There is a window with interrupts enabled before we get here,
2999 * so we need to check again lest we try to stop another CPU's event.
3001 if (READ_ONCE(event->oncpu) != smp_processor_id())
3004 event->pmu->stop(event, PERF_EF_UPDATE);
3007 * May race with the actual stop (through perf_pmu_output_stop()),
3008 * but it is only used for events with AUX ring buffer, and such
3009 * events will refuse to restart because of rb::aux_mmap_count==0,
3010 * see comments in perf_aux_output_begin().
3012 * Since this is happening on an event-local CPU, no trace is lost
3016 event->pmu->start(event, 0);
3021 static int perf_event_stop(struct perf_event *event, int restart)
3023 struct stop_event_data sd = {
3030 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3033 /* matches smp_wmb() in event_sched_in() */
3037 * We only want to restart ACTIVE events, so if the event goes
3038 * inactive here (event->oncpu==-1), there's nothing more to do;
3039 * fall through with ret==-ENXIO.
3041 ret = cpu_function_call(READ_ONCE(event->oncpu),
3042 __perf_event_stop, &sd);
3043 } while (ret == -EAGAIN);
3049 * In order to contain the amount of racy and tricky in the address filter
3050 * configuration management, it is a two part process:
3052 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3053 * we update the addresses of corresponding vmas in
3054 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3055 * (p2) when an event is scheduled in (pmu::add), it calls
3056 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3057 * if the generation has changed since the previous call.
3059 * If (p1) happens while the event is active, we restart it to force (p2).
3061 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3062 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3064 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3065 * registered mapping, called for every new mmap(), with mm::mmap_sem down
3067 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3070 void perf_event_addr_filters_sync(struct perf_event *event)
3072 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3074 if (!has_addr_filter(event))
3077 raw_spin_lock(&ifh->lock);
3078 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3079 event->pmu->addr_filters_sync(event);
3080 event->hw.addr_filters_gen = event->addr_filters_gen;
3082 raw_spin_unlock(&ifh->lock);
3084 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3086 static int _perf_event_refresh(struct perf_event *event, int refresh)
3089 * not supported on inherited events
3091 if (event->attr.inherit || !is_sampling_event(event))
3094 atomic_add(refresh, &event->event_limit);
3095 _perf_event_enable(event);
3101 * See perf_event_disable()
3103 int perf_event_refresh(struct perf_event *event, int refresh)
3105 struct perf_event_context *ctx;
3108 ctx = perf_event_ctx_lock(event);
3109 ret = _perf_event_refresh(event, refresh);
3110 perf_event_ctx_unlock(event, ctx);
3114 EXPORT_SYMBOL_GPL(perf_event_refresh);
3116 static int perf_event_modify_breakpoint(struct perf_event *bp,
3117 struct perf_event_attr *attr)
3121 _perf_event_disable(bp);
3123 err = modify_user_hw_breakpoint_check(bp, attr, true);
3125 if (!bp->attr.disabled)
3126 _perf_event_enable(bp);
3131 static int perf_event_modify_attr(struct perf_event *event,
3132 struct perf_event_attr *attr)
3134 if (event->attr.type != attr->type)
3137 switch (event->attr.type) {
3138 case PERF_TYPE_BREAKPOINT:
3139 return perf_event_modify_breakpoint(event, attr);
3141 /* Place holder for future additions. */
3146 static void ctx_sched_out(struct perf_event_context *ctx,
3147 struct perf_cpu_context *cpuctx,
3148 enum event_type_t event_type)
3150 struct perf_event *event, *tmp;
3151 int is_active = ctx->is_active;
3153 lockdep_assert_held(&ctx->lock);
3155 if (likely(!ctx->nr_events)) {
3157 * See __perf_remove_from_context().
3159 WARN_ON_ONCE(ctx->is_active);
3161 WARN_ON_ONCE(cpuctx->task_ctx);
3165 ctx->is_active &= ~event_type;
3166 if (!(ctx->is_active & EVENT_ALL))
3170 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3171 if (!ctx->is_active)
3172 cpuctx->task_ctx = NULL;
3176 * Always update time if it was set; not only when it changes.
3177 * Otherwise we can 'forget' to update time for any but the last
3178 * context we sched out. For example:
3180 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3181 * ctx_sched_out(.event_type = EVENT_PINNED)
3183 * would only update time for the pinned events.
3185 if (is_active & EVENT_TIME) {
3186 /* update (and stop) ctx time */
3187 update_context_time(ctx);
3188 update_cgrp_time_from_cpuctx(cpuctx);
3191 is_active ^= ctx->is_active; /* changed bits */
3193 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3196 perf_pmu_disable(ctx->pmu);
3197 if (is_active & EVENT_PINNED) {
3198 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3199 group_sched_out(event, cpuctx, ctx);
3202 if (is_active & EVENT_FLEXIBLE) {
3203 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3204 group_sched_out(event, cpuctx, ctx);
3207 * Since we cleared EVENT_FLEXIBLE, also clear
3208 * rotate_necessary, is will be reset by
3209 * ctx_flexible_sched_in() when needed.
3211 ctx->rotate_necessary = 0;
3213 perf_pmu_enable(ctx->pmu);
3217 * Test whether two contexts are equivalent, i.e. whether they have both been
3218 * cloned from the same version of the same context.
3220 * Equivalence is measured using a generation number in the context that is
3221 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3222 * and list_del_event().
3224 static int context_equiv(struct perf_event_context *ctx1,
3225 struct perf_event_context *ctx2)
3227 lockdep_assert_held(&ctx1->lock);
3228 lockdep_assert_held(&ctx2->lock);
3230 /* Pinning disables the swap optimization */
3231 if (ctx1->pin_count || ctx2->pin_count)
3234 /* If ctx1 is the parent of ctx2 */
3235 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3238 /* If ctx2 is the parent of ctx1 */
3239 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3243 * If ctx1 and ctx2 have the same parent; we flatten the parent
3244 * hierarchy, see perf_event_init_context().
3246 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3247 ctx1->parent_gen == ctx2->parent_gen)
3254 static void __perf_event_sync_stat(struct perf_event *event,
3255 struct perf_event *next_event)
3259 if (!event->attr.inherit_stat)
3263 * Update the event value, we cannot use perf_event_read()
3264 * because we're in the middle of a context switch and have IRQs
3265 * disabled, which upsets smp_call_function_single(), however
3266 * we know the event must be on the current CPU, therefore we
3267 * don't need to use it.
3269 if (event->state == PERF_EVENT_STATE_ACTIVE)
3270 event->pmu->read(event);
3272 perf_event_update_time(event);
3275 * In order to keep per-task stats reliable we need to flip the event
3276 * values when we flip the contexts.
3278 value = local64_read(&next_event->count);
3279 value = local64_xchg(&event->count, value);
3280 local64_set(&next_event->count, value);
3282 swap(event->total_time_enabled, next_event->total_time_enabled);
3283 swap(event->total_time_running, next_event->total_time_running);
3286 * Since we swizzled the values, update the user visible data too.
3288 perf_event_update_userpage(event);
3289 perf_event_update_userpage(next_event);
3292 static void perf_event_sync_stat(struct perf_event_context *ctx,
3293 struct perf_event_context *next_ctx)
3295 struct perf_event *event, *next_event;
3300 update_context_time(ctx);
3302 event = list_first_entry(&ctx->event_list,
3303 struct perf_event, event_entry);
3305 next_event = list_first_entry(&next_ctx->event_list,
3306 struct perf_event, event_entry);
3308 while (&event->event_entry != &ctx->event_list &&
3309 &next_event->event_entry != &next_ctx->event_list) {
3311 __perf_event_sync_stat(event, next_event);
3313 event = list_next_entry(event, event_entry);
3314 next_event = list_next_entry(next_event, event_entry);
3318 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3319 struct task_struct *next)
3321 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3322 struct perf_event_context *next_ctx;
3323 struct perf_event_context *parent, *next_parent;
3324 struct perf_cpu_context *cpuctx;
3330 cpuctx = __get_cpu_context(ctx);
3331 if (!cpuctx->task_ctx)
3335 next_ctx = next->perf_event_ctxp[ctxn];
3339 parent = rcu_dereference(ctx->parent_ctx);
3340 next_parent = rcu_dereference(next_ctx->parent_ctx);
3342 /* If neither context have a parent context; they cannot be clones. */
3343 if (!parent && !next_parent)
3346 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3348 * Looks like the two contexts are clones, so we might be
3349 * able to optimize the context switch. We lock both
3350 * contexts and check that they are clones under the
3351 * lock (including re-checking that neither has been
3352 * uncloned in the meantime). It doesn't matter which
3353 * order we take the locks because no other cpu could
3354 * be trying to lock both of these tasks.
3356 raw_spin_lock(&ctx->lock);
3357 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3358 if (context_equiv(ctx, next_ctx)) {
3359 struct pmu *pmu = ctx->pmu;
3361 WRITE_ONCE(ctx->task, next);
3362 WRITE_ONCE(next_ctx->task, task);
3365 * PMU specific parts of task perf context can require
3366 * additional synchronization. As an example of such
3367 * synchronization see implementation details of Intel
3368 * LBR call stack data profiling;
3370 if (pmu->swap_task_ctx)
3371 pmu->swap_task_ctx(ctx, next_ctx);
3373 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3376 * RCU_INIT_POINTER here is safe because we've not
3377 * modified the ctx and the above modification of
3378 * ctx->task and ctx->task_ctx_data are immaterial
3379 * since those values are always verified under
3380 * ctx->lock which we're now holding.
3382 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3383 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3387 perf_event_sync_stat(ctx, next_ctx);
3389 raw_spin_unlock(&next_ctx->lock);
3390 raw_spin_unlock(&ctx->lock);
3396 raw_spin_lock(&ctx->lock);
3397 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3398 raw_spin_unlock(&ctx->lock);
3402 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3404 void perf_sched_cb_dec(struct pmu *pmu)
3406 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3408 this_cpu_dec(perf_sched_cb_usages);
3410 if (!--cpuctx->sched_cb_usage)
3411 list_del(&cpuctx->sched_cb_entry);
3415 void perf_sched_cb_inc(struct pmu *pmu)
3417 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3419 if (!cpuctx->sched_cb_usage++)
3420 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3422 this_cpu_inc(perf_sched_cb_usages);
3426 * This function provides the context switch callback to the lower code
3427 * layer. It is invoked ONLY when the context switch callback is enabled.
3429 * This callback is relevant even to per-cpu events; for example multi event
3430 * PEBS requires this to provide PID/TID information. This requires we flush
3431 * all queued PEBS records before we context switch to a new task.
3433 static void perf_pmu_sched_task(struct task_struct *prev,
3434 struct task_struct *next,
3437 struct perf_cpu_context *cpuctx;
3443 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3444 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3446 if (WARN_ON_ONCE(!pmu->sched_task))
3449 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3450 perf_pmu_disable(pmu);
3452 pmu->sched_task(cpuctx->task_ctx, sched_in);
3454 perf_pmu_enable(pmu);
3455 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3459 static void perf_event_switch(struct task_struct *task,
3460 struct task_struct *next_prev, bool sched_in);
3462 #define for_each_task_context_nr(ctxn) \
3463 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3466 * Called from scheduler to remove the events of the current task,
3467 * with interrupts disabled.
3469 * We stop each event and update the event value in event->count.
3471 * This does not protect us against NMI, but disable()
3472 * sets the disabled bit in the control field of event _before_
3473 * accessing the event control register. If a NMI hits, then it will
3474 * not restart the event.
3476 void __perf_event_task_sched_out(struct task_struct *task,
3477 struct task_struct *next)
3481 if (__this_cpu_read(perf_sched_cb_usages))
3482 perf_pmu_sched_task(task, next, false);
3484 if (atomic_read(&nr_switch_events))
3485 perf_event_switch(task, next, false);
3487 for_each_task_context_nr(ctxn)
3488 perf_event_context_sched_out(task, ctxn, next);
3491 * if cgroup events exist on this CPU, then we need
3492 * to check if we have to switch out PMU state.
3493 * cgroup event are system-wide mode only
3495 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3496 perf_cgroup_sched_out(task, next);
3500 * Called with IRQs disabled
3502 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3503 enum event_type_t event_type)
3505 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3508 static bool perf_less_group_idx(const void *l, const void *r)
3510 const struct perf_event *le = l, *re = r;
3512 return le->group_index < re->group_index;
3515 static void swap_ptr(void *l, void *r)
3517 void **lp = l, **rp = r;
3522 static const struct min_heap_callbacks perf_min_heap = {
3523 .elem_size = sizeof(struct perf_event *),
3524 .less = perf_less_group_idx,
3528 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3530 struct perf_event **itrs = heap->data;
3533 itrs[heap->nr] = event;
3538 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3539 struct perf_event_groups *groups, int cpu,
3540 int (*func)(struct perf_event *, void *),
3543 #ifdef CONFIG_CGROUP_PERF
3544 struct cgroup_subsys_state *css = NULL;
3546 /* Space for per CPU and/or any CPU event iterators. */
3547 struct perf_event *itrs[2];
3548 struct min_heap event_heap;
3549 struct perf_event **evt;
3553 event_heap = (struct min_heap){
3554 .data = cpuctx->heap,
3556 .size = cpuctx->heap_size,
3559 lockdep_assert_held(&cpuctx->ctx.lock);
3561 #ifdef CONFIG_CGROUP_PERF
3563 css = &cpuctx->cgrp->css;
3566 event_heap = (struct min_heap){
3569 .size = ARRAY_SIZE(itrs),
3571 /* Events not within a CPU context may be on any CPU. */
3572 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3574 evt = event_heap.data;
3576 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3578 #ifdef CONFIG_CGROUP_PERF
3579 for (; css; css = css->parent)
3580 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3583 min_heapify_all(&event_heap, &perf_min_heap);
3585 while (event_heap.nr) {
3586 ret = func(*evt, data);
3590 *evt = perf_event_groups_next(*evt);
3592 min_heapify(&event_heap, 0, &perf_min_heap);
3594 min_heap_pop(&event_heap, &perf_min_heap);
3600 static int merge_sched_in(struct perf_event *event, void *data)
3602 struct perf_event_context *ctx = event->ctx;
3603 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3604 int *can_add_hw = data;
3606 if (event->state <= PERF_EVENT_STATE_OFF)
3609 if (!event_filter_match(event))
3612 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3613 if (!group_sched_in(event, cpuctx, ctx))
3614 list_add_tail(&event->active_list, get_event_list(event));
3617 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3618 if (event->attr.pinned)
3619 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3622 ctx->rotate_necessary = 1;
3629 ctx_pinned_sched_in(struct perf_event_context *ctx,
3630 struct perf_cpu_context *cpuctx)
3634 if (ctx != &cpuctx->ctx)
3637 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3639 merge_sched_in, &can_add_hw);
3643 ctx_flexible_sched_in(struct perf_event_context *ctx,
3644 struct perf_cpu_context *cpuctx)
3648 if (ctx != &cpuctx->ctx)
3651 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3653 merge_sched_in, &can_add_hw);
3657 ctx_sched_in(struct perf_event_context *ctx,
3658 struct perf_cpu_context *cpuctx,
3659 enum event_type_t event_type,
3660 struct task_struct *task)
3662 int is_active = ctx->is_active;
3665 lockdep_assert_held(&ctx->lock);
3667 if (likely(!ctx->nr_events))
3670 ctx->is_active |= (event_type | EVENT_TIME);
3673 cpuctx->task_ctx = ctx;
3675 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3678 is_active ^= ctx->is_active; /* changed bits */
3680 if (is_active & EVENT_TIME) {
3681 /* start ctx time */
3683 ctx->timestamp = now;
3684 perf_cgroup_set_timestamp(task, ctx);
3688 * First go through the list and put on any pinned groups
3689 * in order to give them the best chance of going on.
3691 if (is_active & EVENT_PINNED)
3692 ctx_pinned_sched_in(ctx, cpuctx);
3694 /* Then walk through the lower prio flexible groups */
3695 if (is_active & EVENT_FLEXIBLE)
3696 ctx_flexible_sched_in(ctx, cpuctx);
3699 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3700 enum event_type_t event_type,
3701 struct task_struct *task)
3703 struct perf_event_context *ctx = &cpuctx->ctx;
3705 ctx_sched_in(ctx, cpuctx, event_type, task);
3708 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3709 struct task_struct *task)
3711 struct perf_cpu_context *cpuctx;
3713 cpuctx = __get_cpu_context(ctx);
3714 if (cpuctx->task_ctx == ctx)
3717 perf_ctx_lock(cpuctx, ctx);
3719 * We must check ctx->nr_events while holding ctx->lock, such
3720 * that we serialize against perf_install_in_context().
3722 if (!ctx->nr_events)
3725 perf_pmu_disable(ctx->pmu);
3727 * We want to keep the following priority order:
3728 * cpu pinned (that don't need to move), task pinned,
3729 * cpu flexible, task flexible.
3731 * However, if task's ctx is not carrying any pinned
3732 * events, no need to flip the cpuctx's events around.
3734 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3735 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3736 perf_event_sched_in(cpuctx, ctx, task);
3737 perf_pmu_enable(ctx->pmu);
3740 perf_ctx_unlock(cpuctx, ctx);
3744 * Called from scheduler to add the events of the current task
3745 * with interrupts disabled.
3747 * We restore the event value and then enable it.
3749 * This does not protect us against NMI, but enable()
3750 * sets the enabled bit in the control field of event _before_
3751 * accessing the event control register. If a NMI hits, then it will
3752 * keep the event running.
3754 void __perf_event_task_sched_in(struct task_struct *prev,
3755 struct task_struct *task)
3757 struct perf_event_context *ctx;
3761 * If cgroup events exist on this CPU, then we need to check if we have
3762 * to switch in PMU state; cgroup event are system-wide mode only.
3764 * Since cgroup events are CPU events, we must schedule these in before
3765 * we schedule in the task events.
3767 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3768 perf_cgroup_sched_in(prev, task);
3770 for_each_task_context_nr(ctxn) {
3771 ctx = task->perf_event_ctxp[ctxn];
3775 perf_event_context_sched_in(ctx, task);
3778 if (atomic_read(&nr_switch_events))
3779 perf_event_switch(task, prev, true);
3781 if (__this_cpu_read(perf_sched_cb_usages))
3782 perf_pmu_sched_task(prev, task, true);
3785 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3787 u64 frequency = event->attr.sample_freq;
3788 u64 sec = NSEC_PER_SEC;
3789 u64 divisor, dividend;
3791 int count_fls, nsec_fls, frequency_fls, sec_fls;
3793 count_fls = fls64(count);
3794 nsec_fls = fls64(nsec);
3795 frequency_fls = fls64(frequency);
3799 * We got @count in @nsec, with a target of sample_freq HZ
3800 * the target period becomes:
3803 * period = -------------------
3804 * @nsec * sample_freq
3809 * Reduce accuracy by one bit such that @a and @b converge
3810 * to a similar magnitude.
3812 #define REDUCE_FLS(a, b) \
3814 if (a##_fls > b##_fls) { \
3824 * Reduce accuracy until either term fits in a u64, then proceed with
3825 * the other, so that finally we can do a u64/u64 division.
3827 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3828 REDUCE_FLS(nsec, frequency);
3829 REDUCE_FLS(sec, count);
3832 if (count_fls + sec_fls > 64) {
3833 divisor = nsec * frequency;
3835 while (count_fls + sec_fls > 64) {
3836 REDUCE_FLS(count, sec);
3840 dividend = count * sec;
3842 dividend = count * sec;
3844 while (nsec_fls + frequency_fls > 64) {
3845 REDUCE_FLS(nsec, frequency);
3849 divisor = nsec * frequency;
3855 return div64_u64(dividend, divisor);
3858 static DEFINE_PER_CPU(int, perf_throttled_count);
3859 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3861 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3863 struct hw_perf_event *hwc = &event->hw;
3864 s64 period, sample_period;
3867 period = perf_calculate_period(event, nsec, count);
3869 delta = (s64)(period - hwc->sample_period);
3870 delta = (delta + 7) / 8; /* low pass filter */
3872 sample_period = hwc->sample_period + delta;
3877 hwc->sample_period = sample_period;
3879 if (local64_read(&hwc->period_left) > 8*sample_period) {
3881 event->pmu->stop(event, PERF_EF_UPDATE);
3883 local64_set(&hwc->period_left, 0);
3886 event->pmu->start(event, PERF_EF_RELOAD);
3891 * combine freq adjustment with unthrottling to avoid two passes over the
3892 * events. At the same time, make sure, having freq events does not change
3893 * the rate of unthrottling as that would introduce bias.
3895 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3898 struct perf_event *event;
3899 struct hw_perf_event *hwc;
3900 u64 now, period = TICK_NSEC;
3904 * only need to iterate over all events iff:
3905 * - context have events in frequency mode (needs freq adjust)
3906 * - there are events to unthrottle on this cpu
3908 if (!(ctx->nr_freq || needs_unthr))
3911 raw_spin_lock(&ctx->lock);
3912 perf_pmu_disable(ctx->pmu);
3914 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3915 if (event->state != PERF_EVENT_STATE_ACTIVE)
3918 if (!event_filter_match(event))
3921 perf_pmu_disable(event->pmu);
3925 if (hwc->interrupts == MAX_INTERRUPTS) {
3926 hwc->interrupts = 0;
3927 perf_log_throttle(event, 1);
3928 event->pmu->start(event, 0);
3931 if (!event->attr.freq || !event->attr.sample_freq)
3935 * stop the event and update event->count
3937 event->pmu->stop(event, PERF_EF_UPDATE);
3939 now = local64_read(&event->count);
3940 delta = now - hwc->freq_count_stamp;
3941 hwc->freq_count_stamp = now;
3945 * reload only if value has changed
3946 * we have stopped the event so tell that
3947 * to perf_adjust_period() to avoid stopping it
3951 perf_adjust_period(event, period, delta, false);
3953 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3955 perf_pmu_enable(event->pmu);
3958 perf_pmu_enable(ctx->pmu);
3959 raw_spin_unlock(&ctx->lock);
3963 * Move @event to the tail of the @ctx's elegible events.
3965 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
3968 * Rotate the first entry last of non-pinned groups. Rotation might be
3969 * disabled by the inheritance code.
3971 if (ctx->rotate_disable)
3974 perf_event_groups_delete(&ctx->flexible_groups, event);
3975 perf_event_groups_insert(&ctx->flexible_groups, event);
3978 /* pick an event from the flexible_groups to rotate */
3979 static inline struct perf_event *
3980 ctx_event_to_rotate(struct perf_event_context *ctx)
3982 struct perf_event *event;
3984 /* pick the first active flexible event */
3985 event = list_first_entry_or_null(&ctx->flexible_active,
3986 struct perf_event, active_list);
3988 /* if no active flexible event, pick the first event */
3990 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
3991 typeof(*event), group_node);
3995 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
3996 * finds there are unschedulable events, it will set it again.
3998 ctx->rotate_necessary = 0;
4003 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4005 struct perf_event *cpu_event = NULL, *task_event = NULL;
4006 struct perf_event_context *task_ctx = NULL;
4007 int cpu_rotate, task_rotate;
4010 * Since we run this from IRQ context, nobody can install new
4011 * events, thus the event count values are stable.
4014 cpu_rotate = cpuctx->ctx.rotate_necessary;
4015 task_ctx = cpuctx->task_ctx;
4016 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4018 if (!(cpu_rotate || task_rotate))
4021 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4022 perf_pmu_disable(cpuctx->ctx.pmu);
4025 task_event = ctx_event_to_rotate(task_ctx);
4027 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4030 * As per the order given at ctx_resched() first 'pop' task flexible
4031 * and then, if needed CPU flexible.
4033 if (task_event || (task_ctx && cpu_event))
4034 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4036 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4039 rotate_ctx(task_ctx, task_event);
4041 rotate_ctx(&cpuctx->ctx, cpu_event);
4043 perf_event_sched_in(cpuctx, task_ctx, current);
4045 perf_pmu_enable(cpuctx->ctx.pmu);
4046 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4051 void perf_event_task_tick(void)
4053 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4054 struct perf_event_context *ctx, *tmp;
4057 lockdep_assert_irqs_disabled();
4059 __this_cpu_inc(perf_throttled_seq);
4060 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4061 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4063 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4064 perf_adjust_freq_unthr_context(ctx, throttled);
4067 static int event_enable_on_exec(struct perf_event *event,
4068 struct perf_event_context *ctx)
4070 if (!event->attr.enable_on_exec)
4073 event->attr.enable_on_exec = 0;
4074 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4077 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4083 * Enable all of a task's events that have been marked enable-on-exec.
4084 * This expects task == current.
4086 static void perf_event_enable_on_exec(int ctxn)
4088 struct perf_event_context *ctx, *clone_ctx = NULL;
4089 enum event_type_t event_type = 0;
4090 struct perf_cpu_context *cpuctx;
4091 struct perf_event *event;
4092 unsigned long flags;
4095 local_irq_save(flags);
4096 ctx = current->perf_event_ctxp[ctxn];
4097 if (!ctx || !ctx->nr_events)
4100 cpuctx = __get_cpu_context(ctx);
4101 perf_ctx_lock(cpuctx, ctx);
4102 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4103 list_for_each_entry(event, &ctx->event_list, event_entry) {
4104 enabled |= event_enable_on_exec(event, ctx);
4105 event_type |= get_event_type(event);
4109 * Unclone and reschedule this context if we enabled any event.
4112 clone_ctx = unclone_ctx(ctx);
4113 ctx_resched(cpuctx, ctx, event_type);
4115 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4117 perf_ctx_unlock(cpuctx, ctx);
4120 local_irq_restore(flags);
4126 struct perf_read_data {
4127 struct perf_event *event;
4132 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4134 u16 local_pkg, event_pkg;
4136 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4137 int local_cpu = smp_processor_id();
4139 event_pkg = topology_physical_package_id(event_cpu);
4140 local_pkg = topology_physical_package_id(local_cpu);
4142 if (event_pkg == local_pkg)
4150 * Cross CPU call to read the hardware event
4152 static void __perf_event_read(void *info)
4154 struct perf_read_data *data = info;
4155 struct perf_event *sub, *event = data->event;
4156 struct perf_event_context *ctx = event->ctx;
4157 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4158 struct pmu *pmu = event->pmu;
4161 * If this is a task context, we need to check whether it is
4162 * the current task context of this cpu. If not it has been
4163 * scheduled out before the smp call arrived. In that case
4164 * event->count would have been updated to a recent sample
4165 * when the event was scheduled out.
4167 if (ctx->task && cpuctx->task_ctx != ctx)
4170 raw_spin_lock(&ctx->lock);
4171 if (ctx->is_active & EVENT_TIME) {
4172 update_context_time(ctx);
4173 update_cgrp_time_from_event(event);
4176 perf_event_update_time(event);
4178 perf_event_update_sibling_time(event);
4180 if (event->state != PERF_EVENT_STATE_ACTIVE)
4189 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4193 for_each_sibling_event(sub, event) {
4194 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4196 * Use sibling's PMU rather than @event's since
4197 * sibling could be on different (eg: software) PMU.
4199 sub->pmu->read(sub);
4203 data->ret = pmu->commit_txn(pmu);
4206 raw_spin_unlock(&ctx->lock);
4209 static inline u64 perf_event_count(struct perf_event *event)
4211 return local64_read(&event->count) + atomic64_read(&event->child_count);
4215 * NMI-safe method to read a local event, that is an event that
4217 * - either for the current task, or for this CPU
4218 * - does not have inherit set, for inherited task events
4219 * will not be local and we cannot read them atomically
4220 * - must not have a pmu::count method
4222 int perf_event_read_local(struct perf_event *event, u64 *value,
4223 u64 *enabled, u64 *running)
4225 unsigned long flags;
4229 * Disabling interrupts avoids all counter scheduling (context
4230 * switches, timer based rotation and IPIs).
4232 local_irq_save(flags);
4235 * It must not be an event with inherit set, we cannot read
4236 * all child counters from atomic context.
4238 if (event->attr.inherit) {
4243 /* If this is a per-task event, it must be for current */
4244 if ((event->attach_state & PERF_ATTACH_TASK) &&
4245 event->hw.target != current) {
4250 /* If this is a per-CPU event, it must be for this CPU */
4251 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4252 event->cpu != smp_processor_id()) {
4257 /* If this is a pinned event it must be running on this CPU */
4258 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4264 * If the event is currently on this CPU, its either a per-task event,
4265 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4268 if (event->oncpu == smp_processor_id())
4269 event->pmu->read(event);
4271 *value = local64_read(&event->count);
4272 if (enabled || running) {
4273 u64 now = event->shadow_ctx_time + perf_clock();
4274 u64 __enabled, __running;
4276 __perf_update_times(event, now, &__enabled, &__running);
4278 *enabled = __enabled;
4280 *running = __running;
4283 local_irq_restore(flags);
4288 static int perf_event_read(struct perf_event *event, bool group)
4290 enum perf_event_state state = READ_ONCE(event->state);
4291 int event_cpu, ret = 0;
4294 * If event is enabled and currently active on a CPU, update the
4295 * value in the event structure:
4298 if (state == PERF_EVENT_STATE_ACTIVE) {
4299 struct perf_read_data data;
4302 * Orders the ->state and ->oncpu loads such that if we see
4303 * ACTIVE we must also see the right ->oncpu.
4305 * Matches the smp_wmb() from event_sched_in().
4309 event_cpu = READ_ONCE(event->oncpu);
4310 if ((unsigned)event_cpu >= nr_cpu_ids)
4313 data = (struct perf_read_data){
4320 event_cpu = __perf_event_read_cpu(event, event_cpu);
4323 * Purposely ignore the smp_call_function_single() return
4326 * If event_cpu isn't a valid CPU it means the event got
4327 * scheduled out and that will have updated the event count.
4329 * Therefore, either way, we'll have an up-to-date event count
4332 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4336 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4337 struct perf_event_context *ctx = event->ctx;
4338 unsigned long flags;
4340 raw_spin_lock_irqsave(&ctx->lock, flags);
4341 state = event->state;
4342 if (state != PERF_EVENT_STATE_INACTIVE) {
4343 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4348 * May read while context is not active (e.g., thread is
4349 * blocked), in that case we cannot update context time
4351 if (ctx->is_active & EVENT_TIME) {
4352 update_context_time(ctx);
4353 update_cgrp_time_from_event(event);
4356 perf_event_update_time(event);
4358 perf_event_update_sibling_time(event);
4359 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4366 * Initialize the perf_event context in a task_struct:
4368 static void __perf_event_init_context(struct perf_event_context *ctx)
4370 raw_spin_lock_init(&ctx->lock);
4371 mutex_init(&ctx->mutex);
4372 INIT_LIST_HEAD(&ctx->active_ctx_list);
4373 perf_event_groups_init(&ctx->pinned_groups);
4374 perf_event_groups_init(&ctx->flexible_groups);
4375 INIT_LIST_HEAD(&ctx->event_list);
4376 INIT_LIST_HEAD(&ctx->pinned_active);
4377 INIT_LIST_HEAD(&ctx->flexible_active);
4378 refcount_set(&ctx->refcount, 1);
4381 static struct perf_event_context *
4382 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4384 struct perf_event_context *ctx;
4386 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4390 __perf_event_init_context(ctx);
4392 ctx->task = get_task_struct(task);
4398 static struct task_struct *
4399 find_lively_task_by_vpid(pid_t vpid)
4401 struct task_struct *task;
4407 task = find_task_by_vpid(vpid);
4409 get_task_struct(task);
4413 return ERR_PTR(-ESRCH);
4419 * Returns a matching context with refcount and pincount.
4421 static struct perf_event_context *
4422 find_get_context(struct pmu *pmu, struct task_struct *task,
4423 struct perf_event *event)
4425 struct perf_event_context *ctx, *clone_ctx = NULL;
4426 struct perf_cpu_context *cpuctx;
4427 void *task_ctx_data = NULL;
4428 unsigned long flags;
4430 int cpu = event->cpu;
4433 /* Must be root to operate on a CPU event: */
4434 err = perf_allow_cpu(&event->attr);
4436 return ERR_PTR(err);
4438 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4447 ctxn = pmu->task_ctx_nr;
4451 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4452 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
4453 if (!task_ctx_data) {
4460 ctx = perf_lock_task_context(task, ctxn, &flags);
4462 clone_ctx = unclone_ctx(ctx);
4465 if (task_ctx_data && !ctx->task_ctx_data) {
4466 ctx->task_ctx_data = task_ctx_data;
4467 task_ctx_data = NULL;
4469 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4474 ctx = alloc_perf_context(pmu, task);
4479 if (task_ctx_data) {
4480 ctx->task_ctx_data = task_ctx_data;
4481 task_ctx_data = NULL;
4485 mutex_lock(&task->perf_event_mutex);
4487 * If it has already passed perf_event_exit_task().
4488 * we must see PF_EXITING, it takes this mutex too.
4490 if (task->flags & PF_EXITING)
4492 else if (task->perf_event_ctxp[ctxn])
4497 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4499 mutex_unlock(&task->perf_event_mutex);
4501 if (unlikely(err)) {
4510 kfree(task_ctx_data);
4514 kfree(task_ctx_data);
4515 return ERR_PTR(err);
4518 static void perf_event_free_filter(struct perf_event *event);
4519 static void perf_event_free_bpf_prog(struct perf_event *event);
4521 static void free_event_rcu(struct rcu_head *head)
4523 struct perf_event *event;
4525 event = container_of(head, struct perf_event, rcu_head);
4527 put_pid_ns(event->ns);
4528 perf_event_free_filter(event);
4532 static void ring_buffer_attach(struct perf_event *event,
4533 struct perf_buffer *rb);
4535 static void detach_sb_event(struct perf_event *event)
4537 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4539 raw_spin_lock(&pel->lock);
4540 list_del_rcu(&event->sb_list);
4541 raw_spin_unlock(&pel->lock);
4544 static bool is_sb_event(struct perf_event *event)
4546 struct perf_event_attr *attr = &event->attr;
4551 if (event->attach_state & PERF_ATTACH_TASK)
4554 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4555 attr->comm || attr->comm_exec ||
4556 attr->task || attr->ksymbol ||
4557 attr->context_switch ||
4563 static void unaccount_pmu_sb_event(struct perf_event *event)
4565 if (is_sb_event(event))
4566 detach_sb_event(event);
4569 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4574 if (is_cgroup_event(event))
4575 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4578 #ifdef CONFIG_NO_HZ_FULL
4579 static DEFINE_SPINLOCK(nr_freq_lock);
4582 static void unaccount_freq_event_nohz(void)
4584 #ifdef CONFIG_NO_HZ_FULL
4585 spin_lock(&nr_freq_lock);
4586 if (atomic_dec_and_test(&nr_freq_events))
4587 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4588 spin_unlock(&nr_freq_lock);
4592 static void unaccount_freq_event(void)
4594 if (tick_nohz_full_enabled())
4595 unaccount_freq_event_nohz();
4597 atomic_dec(&nr_freq_events);
4600 static void unaccount_event(struct perf_event *event)
4607 if (event->attach_state & PERF_ATTACH_TASK)
4609 if (event->attr.mmap || event->attr.mmap_data)
4610 atomic_dec(&nr_mmap_events);
4611 if (event->attr.comm)
4612 atomic_dec(&nr_comm_events);
4613 if (event->attr.namespaces)
4614 atomic_dec(&nr_namespaces_events);
4615 if (event->attr.cgroup)
4616 atomic_dec(&nr_cgroup_events);
4617 if (event->attr.task)
4618 atomic_dec(&nr_task_events);
4619 if (event->attr.freq)
4620 unaccount_freq_event();
4621 if (event->attr.context_switch) {
4623 atomic_dec(&nr_switch_events);
4625 if (is_cgroup_event(event))
4627 if (has_branch_stack(event))
4629 if (event->attr.ksymbol)
4630 atomic_dec(&nr_ksymbol_events);
4631 if (event->attr.bpf_event)
4632 atomic_dec(&nr_bpf_events);
4635 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4636 schedule_delayed_work(&perf_sched_work, HZ);
4639 unaccount_event_cpu(event, event->cpu);
4641 unaccount_pmu_sb_event(event);
4644 static void perf_sched_delayed(struct work_struct *work)
4646 mutex_lock(&perf_sched_mutex);
4647 if (atomic_dec_and_test(&perf_sched_count))
4648 static_branch_disable(&perf_sched_events);
4649 mutex_unlock(&perf_sched_mutex);
4653 * The following implement mutual exclusion of events on "exclusive" pmus
4654 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4655 * at a time, so we disallow creating events that might conflict, namely:
4657 * 1) cpu-wide events in the presence of per-task events,
4658 * 2) per-task events in the presence of cpu-wide events,
4659 * 3) two matching events on the same context.
4661 * The former two cases are handled in the allocation path (perf_event_alloc(),
4662 * _free_event()), the latter -- before the first perf_install_in_context().
4664 static int exclusive_event_init(struct perf_event *event)
4666 struct pmu *pmu = event->pmu;
4668 if (!is_exclusive_pmu(pmu))
4672 * Prevent co-existence of per-task and cpu-wide events on the
4673 * same exclusive pmu.
4675 * Negative pmu::exclusive_cnt means there are cpu-wide
4676 * events on this "exclusive" pmu, positive means there are
4679 * Since this is called in perf_event_alloc() path, event::ctx
4680 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4681 * to mean "per-task event", because unlike other attach states it
4682 * never gets cleared.
4684 if (event->attach_state & PERF_ATTACH_TASK) {
4685 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4688 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4695 static void exclusive_event_destroy(struct perf_event *event)
4697 struct pmu *pmu = event->pmu;
4699 if (!is_exclusive_pmu(pmu))
4702 /* see comment in exclusive_event_init() */
4703 if (event->attach_state & PERF_ATTACH_TASK)
4704 atomic_dec(&pmu->exclusive_cnt);
4706 atomic_inc(&pmu->exclusive_cnt);
4709 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4711 if ((e1->pmu == e2->pmu) &&
4712 (e1->cpu == e2->cpu ||
4719 static bool exclusive_event_installable(struct perf_event *event,
4720 struct perf_event_context *ctx)
4722 struct perf_event *iter_event;
4723 struct pmu *pmu = event->pmu;
4725 lockdep_assert_held(&ctx->mutex);
4727 if (!is_exclusive_pmu(pmu))
4730 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4731 if (exclusive_event_match(iter_event, event))
4738 static void perf_addr_filters_splice(struct perf_event *event,
4739 struct list_head *head);
4741 static void _free_event(struct perf_event *event)
4743 irq_work_sync(&event->pending);
4745 unaccount_event(event);
4747 security_perf_event_free(event);
4751 * Can happen when we close an event with re-directed output.
4753 * Since we have a 0 refcount, perf_mmap_close() will skip
4754 * over us; possibly making our ring_buffer_put() the last.
4756 mutex_lock(&event->mmap_mutex);
4757 ring_buffer_attach(event, NULL);
4758 mutex_unlock(&event->mmap_mutex);
4761 if (is_cgroup_event(event))
4762 perf_detach_cgroup(event);
4764 if (!event->parent) {
4765 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4766 put_callchain_buffers();
4769 perf_event_free_bpf_prog(event);
4770 perf_addr_filters_splice(event, NULL);
4771 kfree(event->addr_filter_ranges);
4774 event->destroy(event);
4777 * Must be after ->destroy(), due to uprobe_perf_close() using
4780 if (event->hw.target)
4781 put_task_struct(event->hw.target);
4784 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4785 * all task references must be cleaned up.
4788 put_ctx(event->ctx);
4790 exclusive_event_destroy(event);
4791 module_put(event->pmu->module);
4793 call_rcu(&event->rcu_head, free_event_rcu);
4797 * Used to free events which have a known refcount of 1, such as in error paths
4798 * where the event isn't exposed yet and inherited events.
4800 static void free_event(struct perf_event *event)
4802 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4803 "unexpected event refcount: %ld; ptr=%p\n",
4804 atomic_long_read(&event->refcount), event)) {
4805 /* leak to avoid use-after-free */
4813 * Remove user event from the owner task.
4815 static void perf_remove_from_owner(struct perf_event *event)
4817 struct task_struct *owner;
4821 * Matches the smp_store_release() in perf_event_exit_task(). If we
4822 * observe !owner it means the list deletion is complete and we can
4823 * indeed free this event, otherwise we need to serialize on
4824 * owner->perf_event_mutex.
4826 owner = READ_ONCE(event->owner);
4829 * Since delayed_put_task_struct() also drops the last
4830 * task reference we can safely take a new reference
4831 * while holding the rcu_read_lock().
4833 get_task_struct(owner);
4839 * If we're here through perf_event_exit_task() we're already
4840 * holding ctx->mutex which would be an inversion wrt. the
4841 * normal lock order.
4843 * However we can safely take this lock because its the child
4846 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4849 * We have to re-check the event->owner field, if it is cleared
4850 * we raced with perf_event_exit_task(), acquiring the mutex
4851 * ensured they're done, and we can proceed with freeing the
4855 list_del_init(&event->owner_entry);
4856 smp_store_release(&event->owner, NULL);
4858 mutex_unlock(&owner->perf_event_mutex);
4859 put_task_struct(owner);
4863 static void put_event(struct perf_event *event)
4865 if (!atomic_long_dec_and_test(&event->refcount))
4872 * Kill an event dead; while event:refcount will preserve the event
4873 * object, it will not preserve its functionality. Once the last 'user'
4874 * gives up the object, we'll destroy the thing.
4876 int perf_event_release_kernel(struct perf_event *event)
4878 struct perf_event_context *ctx = event->ctx;
4879 struct perf_event *child, *tmp;
4880 LIST_HEAD(free_list);
4883 * If we got here through err_file: fput(event_file); we will not have
4884 * attached to a context yet.
4887 WARN_ON_ONCE(event->attach_state &
4888 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4892 if (!is_kernel_event(event))
4893 perf_remove_from_owner(event);
4895 ctx = perf_event_ctx_lock(event);
4896 WARN_ON_ONCE(ctx->parent_ctx);
4897 perf_remove_from_context(event, DETACH_GROUP);
4899 raw_spin_lock_irq(&ctx->lock);
4901 * Mark this event as STATE_DEAD, there is no external reference to it
4904 * Anybody acquiring event->child_mutex after the below loop _must_
4905 * also see this, most importantly inherit_event() which will avoid
4906 * placing more children on the list.
4908 * Thus this guarantees that we will in fact observe and kill _ALL_
4911 event->state = PERF_EVENT_STATE_DEAD;
4912 raw_spin_unlock_irq(&ctx->lock);
4914 perf_event_ctx_unlock(event, ctx);
4917 mutex_lock(&event->child_mutex);
4918 list_for_each_entry(child, &event->child_list, child_list) {
4921 * Cannot change, child events are not migrated, see the
4922 * comment with perf_event_ctx_lock_nested().
4924 ctx = READ_ONCE(child->ctx);
4926 * Since child_mutex nests inside ctx::mutex, we must jump
4927 * through hoops. We start by grabbing a reference on the ctx.
4929 * Since the event cannot get freed while we hold the
4930 * child_mutex, the context must also exist and have a !0
4936 * Now that we have a ctx ref, we can drop child_mutex, and
4937 * acquire ctx::mutex without fear of it going away. Then we
4938 * can re-acquire child_mutex.
4940 mutex_unlock(&event->child_mutex);
4941 mutex_lock(&ctx->mutex);
4942 mutex_lock(&event->child_mutex);
4945 * Now that we hold ctx::mutex and child_mutex, revalidate our
4946 * state, if child is still the first entry, it didn't get freed
4947 * and we can continue doing so.
4949 tmp = list_first_entry_or_null(&event->child_list,
4950 struct perf_event, child_list);
4952 perf_remove_from_context(child, DETACH_GROUP);
4953 list_move(&child->child_list, &free_list);
4955 * This matches the refcount bump in inherit_event();
4956 * this can't be the last reference.
4961 mutex_unlock(&event->child_mutex);
4962 mutex_unlock(&ctx->mutex);
4966 mutex_unlock(&event->child_mutex);
4968 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
4969 void *var = &child->ctx->refcount;
4971 list_del(&child->child_list);
4975 * Wake any perf_event_free_task() waiting for this event to be
4978 smp_mb(); /* pairs with wait_var_event() */
4983 put_event(event); /* Must be the 'last' reference */
4986 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4989 * Called when the last reference to the file is gone.
4991 static int perf_release(struct inode *inode, struct file *file)
4993 perf_event_release_kernel(file->private_data);
4997 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4999 struct perf_event *child;
5005 mutex_lock(&event->child_mutex);
5007 (void)perf_event_read(event, false);
5008 total += perf_event_count(event);
5010 *enabled += event->total_time_enabled +
5011 atomic64_read(&event->child_total_time_enabled);
5012 *running += event->total_time_running +
5013 atomic64_read(&event->child_total_time_running);
5015 list_for_each_entry(child, &event->child_list, child_list) {
5016 (void)perf_event_read(child, false);
5017 total += perf_event_count(child);
5018 *enabled += child->total_time_enabled;
5019 *running += child->total_time_running;
5021 mutex_unlock(&event->child_mutex);
5026 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5028 struct perf_event_context *ctx;
5031 ctx = perf_event_ctx_lock(event);
5032 count = __perf_event_read_value(event, enabled, running);
5033 perf_event_ctx_unlock(event, ctx);
5037 EXPORT_SYMBOL_GPL(perf_event_read_value);
5039 static int __perf_read_group_add(struct perf_event *leader,
5040 u64 read_format, u64 *values)
5042 struct perf_event_context *ctx = leader->ctx;
5043 struct perf_event *sub;
5044 unsigned long flags;
5045 int n = 1; /* skip @nr */
5048 ret = perf_event_read(leader, true);
5052 raw_spin_lock_irqsave(&ctx->lock, flags);
5055 * Since we co-schedule groups, {enabled,running} times of siblings
5056 * will be identical to those of the leader, so we only publish one
5059 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5060 values[n++] += leader->total_time_enabled +
5061 atomic64_read(&leader->child_total_time_enabled);
5064 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5065 values[n++] += leader->total_time_running +
5066 atomic64_read(&leader->child_total_time_running);
5070 * Write {count,id} tuples for every sibling.
5072 values[n++] += perf_event_count(leader);
5073 if (read_format & PERF_FORMAT_ID)
5074 values[n++] = primary_event_id(leader);
5076 for_each_sibling_event(sub, leader) {
5077 values[n++] += perf_event_count(sub);
5078 if (read_format & PERF_FORMAT_ID)
5079 values[n++] = primary_event_id(sub);
5082 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5086 static int perf_read_group(struct perf_event *event,
5087 u64 read_format, char __user *buf)
5089 struct perf_event *leader = event->group_leader, *child;
5090 struct perf_event_context *ctx = leader->ctx;
5094 lockdep_assert_held(&ctx->mutex);
5096 values = kzalloc(event->read_size, GFP_KERNEL);
5100 values[0] = 1 + leader->nr_siblings;
5103 * By locking the child_mutex of the leader we effectively
5104 * lock the child list of all siblings.. XXX explain how.
5106 mutex_lock(&leader->child_mutex);
5108 ret = __perf_read_group_add(leader, read_format, values);
5112 list_for_each_entry(child, &leader->child_list, child_list) {
5113 ret = __perf_read_group_add(child, read_format, values);
5118 mutex_unlock(&leader->child_mutex);
5120 ret = event->read_size;
5121 if (copy_to_user(buf, values, event->read_size))
5126 mutex_unlock(&leader->child_mutex);
5132 static int perf_read_one(struct perf_event *event,
5133 u64 read_format, char __user *buf)
5135 u64 enabled, running;
5139 values[n++] = __perf_event_read_value(event, &enabled, &running);
5140 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5141 values[n++] = enabled;
5142 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5143 values[n++] = running;
5144 if (read_format & PERF_FORMAT_ID)
5145 values[n++] = primary_event_id(event);
5147 if (copy_to_user(buf, values, n * sizeof(u64)))
5150 return n * sizeof(u64);
5153 static bool is_event_hup(struct perf_event *event)
5157 if (event->state > PERF_EVENT_STATE_EXIT)
5160 mutex_lock(&event->child_mutex);
5161 no_children = list_empty(&event->child_list);
5162 mutex_unlock(&event->child_mutex);
5167 * Read the performance event - simple non blocking version for now
5170 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5172 u64 read_format = event->attr.read_format;
5176 * Return end-of-file for a read on an event that is in
5177 * error state (i.e. because it was pinned but it couldn't be
5178 * scheduled on to the CPU at some point).
5180 if (event->state == PERF_EVENT_STATE_ERROR)
5183 if (count < event->read_size)
5186 WARN_ON_ONCE(event->ctx->parent_ctx);
5187 if (read_format & PERF_FORMAT_GROUP)
5188 ret = perf_read_group(event, read_format, buf);
5190 ret = perf_read_one(event, read_format, buf);
5196 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5198 struct perf_event *event = file->private_data;
5199 struct perf_event_context *ctx;
5202 ret = security_perf_event_read(event);
5206 ctx = perf_event_ctx_lock(event);
5207 ret = __perf_read(event, buf, count);
5208 perf_event_ctx_unlock(event, ctx);
5213 static __poll_t perf_poll(struct file *file, poll_table *wait)
5215 struct perf_event *event = file->private_data;
5216 struct perf_buffer *rb;
5217 __poll_t events = EPOLLHUP;
5219 poll_wait(file, &event->waitq, wait);
5221 if (is_event_hup(event))
5225 * Pin the event->rb by taking event->mmap_mutex; otherwise
5226 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5228 mutex_lock(&event->mmap_mutex);
5231 events = atomic_xchg(&rb->poll, 0);
5232 mutex_unlock(&event->mmap_mutex);
5236 static void _perf_event_reset(struct perf_event *event)
5238 (void)perf_event_read(event, false);
5239 local64_set(&event->count, 0);
5240 perf_event_update_userpage(event);
5243 /* Assume it's not an event with inherit set. */
5244 u64 perf_event_pause(struct perf_event *event, bool reset)
5246 struct perf_event_context *ctx;
5249 ctx = perf_event_ctx_lock(event);
5250 WARN_ON_ONCE(event->attr.inherit);
5251 _perf_event_disable(event);
5252 count = local64_read(&event->count);
5254 local64_set(&event->count, 0);
5255 perf_event_ctx_unlock(event, ctx);
5259 EXPORT_SYMBOL_GPL(perf_event_pause);
5262 * Holding the top-level event's child_mutex means that any
5263 * descendant process that has inherited this event will block
5264 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5265 * task existence requirements of perf_event_enable/disable.
5267 static void perf_event_for_each_child(struct perf_event *event,
5268 void (*func)(struct perf_event *))
5270 struct perf_event *child;
5272 WARN_ON_ONCE(event->ctx->parent_ctx);
5274 mutex_lock(&event->child_mutex);
5276 list_for_each_entry(child, &event->child_list, child_list)
5278 mutex_unlock(&event->child_mutex);
5281 static void perf_event_for_each(struct perf_event *event,
5282 void (*func)(struct perf_event *))
5284 struct perf_event_context *ctx = event->ctx;
5285 struct perf_event *sibling;
5287 lockdep_assert_held(&ctx->mutex);
5289 event = event->group_leader;
5291 perf_event_for_each_child(event, func);
5292 for_each_sibling_event(sibling, event)
5293 perf_event_for_each_child(sibling, func);
5296 static void __perf_event_period(struct perf_event *event,
5297 struct perf_cpu_context *cpuctx,
5298 struct perf_event_context *ctx,
5301 u64 value = *((u64 *)info);
5304 if (event->attr.freq) {
5305 event->attr.sample_freq = value;
5307 event->attr.sample_period = value;
5308 event->hw.sample_period = value;
5311 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5313 perf_pmu_disable(ctx->pmu);
5315 * We could be throttled; unthrottle now to avoid the tick
5316 * trying to unthrottle while we already re-started the event.
5318 if (event->hw.interrupts == MAX_INTERRUPTS) {
5319 event->hw.interrupts = 0;
5320 perf_log_throttle(event, 1);
5322 event->pmu->stop(event, PERF_EF_UPDATE);
5325 local64_set(&event->hw.period_left, 0);
5328 event->pmu->start(event, PERF_EF_RELOAD);
5329 perf_pmu_enable(ctx->pmu);
5333 static int perf_event_check_period(struct perf_event *event, u64 value)
5335 return event->pmu->check_period(event, value);
5338 static int _perf_event_period(struct perf_event *event, u64 value)
5340 if (!is_sampling_event(event))
5346 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5349 if (perf_event_check_period(event, value))
5352 if (!event->attr.freq && (value & (1ULL << 63)))
5355 event_function_call(event, __perf_event_period, &value);
5360 int perf_event_period(struct perf_event *event, u64 value)
5362 struct perf_event_context *ctx;
5365 ctx = perf_event_ctx_lock(event);
5366 ret = _perf_event_period(event, value);
5367 perf_event_ctx_unlock(event, ctx);
5371 EXPORT_SYMBOL_GPL(perf_event_period);
5373 static const struct file_operations perf_fops;
5375 static inline int perf_fget_light(int fd, struct fd *p)
5377 struct fd f = fdget(fd);
5381 if (f.file->f_op != &perf_fops) {
5389 static int perf_event_set_output(struct perf_event *event,
5390 struct perf_event *output_event);
5391 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5392 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5393 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5394 struct perf_event_attr *attr);
5396 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5398 void (*func)(struct perf_event *);
5402 case PERF_EVENT_IOC_ENABLE:
5403 func = _perf_event_enable;
5405 case PERF_EVENT_IOC_DISABLE:
5406 func = _perf_event_disable;
5408 case PERF_EVENT_IOC_RESET:
5409 func = _perf_event_reset;
5412 case PERF_EVENT_IOC_REFRESH:
5413 return _perf_event_refresh(event, arg);
5415 case PERF_EVENT_IOC_PERIOD:
5419 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5422 return _perf_event_period(event, value);
5424 case PERF_EVENT_IOC_ID:
5426 u64 id = primary_event_id(event);
5428 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5433 case PERF_EVENT_IOC_SET_OUTPUT:
5437 struct perf_event *output_event;
5439 ret = perf_fget_light(arg, &output);
5442 output_event = output.file->private_data;
5443 ret = perf_event_set_output(event, output_event);
5446 ret = perf_event_set_output(event, NULL);
5451 case PERF_EVENT_IOC_SET_FILTER:
5452 return perf_event_set_filter(event, (void __user *)arg);
5454 case PERF_EVENT_IOC_SET_BPF:
5455 return perf_event_set_bpf_prog(event, arg);
5457 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5458 struct perf_buffer *rb;
5461 rb = rcu_dereference(event->rb);
5462 if (!rb || !rb->nr_pages) {
5466 rb_toggle_paused(rb, !!arg);
5471 case PERF_EVENT_IOC_QUERY_BPF:
5472 return perf_event_query_prog_array(event, (void __user *)arg);
5474 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5475 struct perf_event_attr new_attr;
5476 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5482 return perf_event_modify_attr(event, &new_attr);
5488 if (flags & PERF_IOC_FLAG_GROUP)
5489 perf_event_for_each(event, func);
5491 perf_event_for_each_child(event, func);
5496 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5498 struct perf_event *event = file->private_data;
5499 struct perf_event_context *ctx;
5502 /* Treat ioctl like writes as it is likely a mutating operation. */
5503 ret = security_perf_event_write(event);
5507 ctx = perf_event_ctx_lock(event);
5508 ret = _perf_ioctl(event, cmd, arg);
5509 perf_event_ctx_unlock(event, ctx);
5514 #ifdef CONFIG_COMPAT
5515 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5518 switch (_IOC_NR(cmd)) {
5519 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5520 case _IOC_NR(PERF_EVENT_IOC_ID):
5521 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5522 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5523 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5524 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5525 cmd &= ~IOCSIZE_MASK;
5526 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5530 return perf_ioctl(file, cmd, arg);
5533 # define perf_compat_ioctl NULL
5536 int perf_event_task_enable(void)
5538 struct perf_event_context *ctx;
5539 struct perf_event *event;
5541 mutex_lock(¤t->perf_event_mutex);
5542 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5543 ctx = perf_event_ctx_lock(event);
5544 perf_event_for_each_child(event, _perf_event_enable);
5545 perf_event_ctx_unlock(event, ctx);
5547 mutex_unlock(¤t->perf_event_mutex);
5552 int perf_event_task_disable(void)
5554 struct perf_event_context *ctx;
5555 struct perf_event *event;
5557 mutex_lock(¤t->perf_event_mutex);
5558 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5559 ctx = perf_event_ctx_lock(event);
5560 perf_event_for_each_child(event, _perf_event_disable);
5561 perf_event_ctx_unlock(event, ctx);
5563 mutex_unlock(¤t->perf_event_mutex);
5568 static int perf_event_index(struct perf_event *event)
5570 if (event->hw.state & PERF_HES_STOPPED)
5573 if (event->state != PERF_EVENT_STATE_ACTIVE)
5576 return event->pmu->event_idx(event);
5579 static void calc_timer_values(struct perf_event *event,
5586 *now = perf_clock();
5587 ctx_time = event->shadow_ctx_time + *now;
5588 __perf_update_times(event, ctx_time, enabled, running);
5591 static void perf_event_init_userpage(struct perf_event *event)
5593 struct perf_event_mmap_page *userpg;
5594 struct perf_buffer *rb;
5597 rb = rcu_dereference(event->rb);
5601 userpg = rb->user_page;
5603 /* Allow new userspace to detect that bit 0 is deprecated */
5604 userpg->cap_bit0_is_deprecated = 1;
5605 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5606 userpg->data_offset = PAGE_SIZE;
5607 userpg->data_size = perf_data_size(rb);
5613 void __weak arch_perf_update_userpage(
5614 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5619 * Callers need to ensure there can be no nesting of this function, otherwise
5620 * the seqlock logic goes bad. We can not serialize this because the arch
5621 * code calls this from NMI context.
5623 void perf_event_update_userpage(struct perf_event *event)
5625 struct perf_event_mmap_page *userpg;
5626 struct perf_buffer *rb;
5627 u64 enabled, running, now;
5630 rb = rcu_dereference(event->rb);
5635 * compute total_time_enabled, total_time_running
5636 * based on snapshot values taken when the event
5637 * was last scheduled in.
5639 * we cannot simply called update_context_time()
5640 * because of locking issue as we can be called in
5643 calc_timer_values(event, &now, &enabled, &running);
5645 userpg = rb->user_page;
5647 * Disable preemption to guarantee consistent time stamps are stored to
5653 userpg->index = perf_event_index(event);
5654 userpg->offset = perf_event_count(event);
5656 userpg->offset -= local64_read(&event->hw.prev_count);
5658 userpg->time_enabled = enabled +
5659 atomic64_read(&event->child_total_time_enabled);
5661 userpg->time_running = running +
5662 atomic64_read(&event->child_total_time_running);
5664 arch_perf_update_userpage(event, userpg, now);
5672 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5674 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5676 struct perf_event *event = vmf->vma->vm_file->private_data;
5677 struct perf_buffer *rb;
5678 vm_fault_t ret = VM_FAULT_SIGBUS;
5680 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5681 if (vmf->pgoff == 0)
5687 rb = rcu_dereference(event->rb);
5691 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5694 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5698 get_page(vmf->page);
5699 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5700 vmf->page->index = vmf->pgoff;
5709 static void ring_buffer_attach(struct perf_event *event,
5710 struct perf_buffer *rb)
5712 struct perf_buffer *old_rb = NULL;
5713 unsigned long flags;
5717 * Should be impossible, we set this when removing
5718 * event->rb_entry and wait/clear when adding event->rb_entry.
5720 WARN_ON_ONCE(event->rcu_pending);
5723 spin_lock_irqsave(&old_rb->event_lock, flags);
5724 list_del_rcu(&event->rb_entry);
5725 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5727 event->rcu_batches = get_state_synchronize_rcu();
5728 event->rcu_pending = 1;
5732 if (event->rcu_pending) {
5733 cond_synchronize_rcu(event->rcu_batches);
5734 event->rcu_pending = 0;
5737 spin_lock_irqsave(&rb->event_lock, flags);
5738 list_add_rcu(&event->rb_entry, &rb->event_list);
5739 spin_unlock_irqrestore(&rb->event_lock, flags);
5743 * Avoid racing with perf_mmap_close(AUX): stop the event
5744 * before swizzling the event::rb pointer; if it's getting
5745 * unmapped, its aux_mmap_count will be 0 and it won't
5746 * restart. See the comment in __perf_pmu_output_stop().
5748 * Data will inevitably be lost when set_output is done in
5749 * mid-air, but then again, whoever does it like this is
5750 * not in for the data anyway.
5753 perf_event_stop(event, 0);
5755 rcu_assign_pointer(event->rb, rb);
5758 ring_buffer_put(old_rb);
5760 * Since we detached before setting the new rb, so that we
5761 * could attach the new rb, we could have missed a wakeup.
5764 wake_up_all(&event->waitq);
5768 static void ring_buffer_wakeup(struct perf_event *event)
5770 struct perf_buffer *rb;
5773 rb = rcu_dereference(event->rb);
5775 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5776 wake_up_all(&event->waitq);
5781 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5783 struct perf_buffer *rb;
5786 rb = rcu_dereference(event->rb);
5788 if (!refcount_inc_not_zero(&rb->refcount))
5796 void ring_buffer_put(struct perf_buffer *rb)
5798 if (!refcount_dec_and_test(&rb->refcount))
5801 WARN_ON_ONCE(!list_empty(&rb->event_list));
5803 call_rcu(&rb->rcu_head, rb_free_rcu);
5806 static void perf_mmap_open(struct vm_area_struct *vma)
5808 struct perf_event *event = vma->vm_file->private_data;
5810 atomic_inc(&event->mmap_count);
5811 atomic_inc(&event->rb->mmap_count);
5814 atomic_inc(&event->rb->aux_mmap_count);
5816 if (event->pmu->event_mapped)
5817 event->pmu->event_mapped(event, vma->vm_mm);
5820 static void perf_pmu_output_stop(struct perf_event *event);
5823 * A buffer can be mmap()ed multiple times; either directly through the same
5824 * event, or through other events by use of perf_event_set_output().
5826 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5827 * the buffer here, where we still have a VM context. This means we need
5828 * to detach all events redirecting to us.
5830 static void perf_mmap_close(struct vm_area_struct *vma)
5832 struct perf_event *event = vma->vm_file->private_data;
5834 struct perf_buffer *rb = ring_buffer_get(event);
5835 struct user_struct *mmap_user = rb->mmap_user;
5836 int mmap_locked = rb->mmap_locked;
5837 unsigned long size = perf_data_size(rb);
5839 if (event->pmu->event_unmapped)
5840 event->pmu->event_unmapped(event, vma->vm_mm);
5843 * rb->aux_mmap_count will always drop before rb->mmap_count and
5844 * event->mmap_count, so it is ok to use event->mmap_mutex to
5845 * serialize with perf_mmap here.
5847 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5848 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5850 * Stop all AUX events that are writing to this buffer,
5851 * so that we can free its AUX pages and corresponding PMU
5852 * data. Note that after rb::aux_mmap_count dropped to zero,
5853 * they won't start any more (see perf_aux_output_begin()).
5855 perf_pmu_output_stop(event);
5857 /* now it's safe to free the pages */
5858 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5859 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5861 /* this has to be the last one */
5863 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5865 mutex_unlock(&event->mmap_mutex);
5868 atomic_dec(&rb->mmap_count);
5870 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5873 ring_buffer_attach(event, NULL);
5874 mutex_unlock(&event->mmap_mutex);
5876 /* If there's still other mmap()s of this buffer, we're done. */
5877 if (atomic_read(&rb->mmap_count))
5881 * No other mmap()s, detach from all other events that might redirect
5882 * into the now unreachable buffer. Somewhat complicated by the
5883 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5887 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5888 if (!atomic_long_inc_not_zero(&event->refcount)) {
5890 * This event is en-route to free_event() which will
5891 * detach it and remove it from the list.
5897 mutex_lock(&event->mmap_mutex);
5899 * Check we didn't race with perf_event_set_output() which can
5900 * swizzle the rb from under us while we were waiting to
5901 * acquire mmap_mutex.
5903 * If we find a different rb; ignore this event, a next
5904 * iteration will no longer find it on the list. We have to
5905 * still restart the iteration to make sure we're not now
5906 * iterating the wrong list.
5908 if (event->rb == rb)
5909 ring_buffer_attach(event, NULL);
5911 mutex_unlock(&event->mmap_mutex);
5915 * Restart the iteration; either we're on the wrong list or
5916 * destroyed its integrity by doing a deletion.
5923 * It could be there's still a few 0-ref events on the list; they'll
5924 * get cleaned up by free_event() -- they'll also still have their
5925 * ref on the rb and will free it whenever they are done with it.
5927 * Aside from that, this buffer is 'fully' detached and unmapped,
5928 * undo the VM accounting.
5931 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5932 &mmap_user->locked_vm);
5933 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5934 free_uid(mmap_user);
5937 ring_buffer_put(rb); /* could be last */
5940 static const struct vm_operations_struct perf_mmap_vmops = {
5941 .open = perf_mmap_open,
5942 .close = perf_mmap_close, /* non mergeable */
5943 .fault = perf_mmap_fault,
5944 .page_mkwrite = perf_mmap_fault,
5947 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5949 struct perf_event *event = file->private_data;
5950 unsigned long user_locked, user_lock_limit;
5951 struct user_struct *user = current_user();
5952 struct perf_buffer *rb = NULL;
5953 unsigned long locked, lock_limit;
5954 unsigned long vma_size;
5955 unsigned long nr_pages;
5956 long user_extra = 0, extra = 0;
5957 int ret = 0, flags = 0;
5960 * Don't allow mmap() of inherited per-task counters. This would
5961 * create a performance issue due to all children writing to the
5964 if (event->cpu == -1 && event->attr.inherit)
5967 if (!(vma->vm_flags & VM_SHARED))
5970 ret = security_perf_event_read(event);
5974 vma_size = vma->vm_end - vma->vm_start;
5976 if (vma->vm_pgoff == 0) {
5977 nr_pages = (vma_size / PAGE_SIZE) - 1;
5980 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5981 * mapped, all subsequent mappings should have the same size
5982 * and offset. Must be above the normal perf buffer.
5984 u64 aux_offset, aux_size;
5989 nr_pages = vma_size / PAGE_SIZE;
5991 mutex_lock(&event->mmap_mutex);
5998 aux_offset = READ_ONCE(rb->user_page->aux_offset);
5999 aux_size = READ_ONCE(rb->user_page->aux_size);
6001 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6004 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6007 /* already mapped with a different offset */
6008 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6011 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6014 /* already mapped with a different size */
6015 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6018 if (!is_power_of_2(nr_pages))
6021 if (!atomic_inc_not_zero(&rb->mmap_count))
6024 if (rb_has_aux(rb)) {
6025 atomic_inc(&rb->aux_mmap_count);
6030 atomic_set(&rb->aux_mmap_count, 1);
6031 user_extra = nr_pages;
6037 * If we have rb pages ensure they're a power-of-two number, so we
6038 * can do bitmasks instead of modulo.
6040 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6043 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6046 WARN_ON_ONCE(event->ctx->parent_ctx);
6048 mutex_lock(&event->mmap_mutex);
6050 if (event->rb->nr_pages != nr_pages) {
6055 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6057 * Raced against perf_mmap_close() through
6058 * perf_event_set_output(). Try again, hope for better
6061 mutex_unlock(&event->mmap_mutex);
6068 user_extra = nr_pages + 1;
6071 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6074 * Increase the limit linearly with more CPUs:
6076 user_lock_limit *= num_online_cpus();
6078 user_locked = atomic_long_read(&user->locked_vm);
6081 * sysctl_perf_event_mlock may have changed, so that
6082 * user->locked_vm > user_lock_limit
6084 if (user_locked > user_lock_limit)
6085 user_locked = user_lock_limit;
6086 user_locked += user_extra;
6088 if (user_locked > user_lock_limit) {
6090 * charge locked_vm until it hits user_lock_limit;
6091 * charge the rest from pinned_vm
6093 extra = user_locked - user_lock_limit;
6094 user_extra -= extra;
6097 lock_limit = rlimit(RLIMIT_MEMLOCK);
6098 lock_limit >>= PAGE_SHIFT;
6099 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6101 if ((locked > lock_limit) && perf_is_paranoid() &&
6102 !capable(CAP_IPC_LOCK)) {
6107 WARN_ON(!rb && event->rb);
6109 if (vma->vm_flags & VM_WRITE)
6110 flags |= RING_BUFFER_WRITABLE;
6113 rb = rb_alloc(nr_pages,
6114 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6122 atomic_set(&rb->mmap_count, 1);
6123 rb->mmap_user = get_current_user();
6124 rb->mmap_locked = extra;
6126 ring_buffer_attach(event, rb);
6128 perf_event_init_userpage(event);
6129 perf_event_update_userpage(event);
6131 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6132 event->attr.aux_watermark, flags);
6134 rb->aux_mmap_locked = extra;
6139 atomic_long_add(user_extra, &user->locked_vm);
6140 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6142 atomic_inc(&event->mmap_count);
6144 atomic_dec(&rb->mmap_count);
6147 mutex_unlock(&event->mmap_mutex);
6150 * Since pinned accounting is per vm we cannot allow fork() to copy our
6153 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6154 vma->vm_ops = &perf_mmap_vmops;
6156 if (event->pmu->event_mapped)
6157 event->pmu->event_mapped(event, vma->vm_mm);
6162 static int perf_fasync(int fd, struct file *filp, int on)
6164 struct inode *inode = file_inode(filp);
6165 struct perf_event *event = filp->private_data;
6169 retval = fasync_helper(fd, filp, on, &event->fasync);
6170 inode_unlock(inode);
6178 static const struct file_operations perf_fops = {
6179 .llseek = no_llseek,
6180 .release = perf_release,
6183 .unlocked_ioctl = perf_ioctl,
6184 .compat_ioctl = perf_compat_ioctl,
6186 .fasync = perf_fasync,
6192 * If there's data, ensure we set the poll() state and publish everything
6193 * to user-space before waking everybody up.
6196 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6198 /* only the parent has fasync state */
6200 event = event->parent;
6201 return &event->fasync;
6204 void perf_event_wakeup(struct perf_event *event)
6206 ring_buffer_wakeup(event);
6208 if (event->pending_kill) {
6209 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6210 event->pending_kill = 0;
6214 static void perf_pending_event_disable(struct perf_event *event)
6216 int cpu = READ_ONCE(event->pending_disable);
6221 if (cpu == smp_processor_id()) {
6222 WRITE_ONCE(event->pending_disable, -1);
6223 perf_event_disable_local(event);
6230 * perf_event_disable_inatomic()
6231 * @pending_disable = CPU-A;
6235 * @pending_disable = -1;
6238 * perf_event_disable_inatomic()
6239 * @pending_disable = CPU-B;
6240 * irq_work_queue(); // FAILS
6243 * perf_pending_event()
6245 * But the event runs on CPU-B and wants disabling there.
6247 irq_work_queue_on(&event->pending, cpu);
6250 static void perf_pending_event(struct irq_work *entry)
6252 struct perf_event *event = container_of(entry, struct perf_event, pending);
6255 rctx = perf_swevent_get_recursion_context();
6257 * If we 'fail' here, that's OK, it means recursion is already disabled
6258 * and we won't recurse 'further'.
6261 perf_pending_event_disable(event);
6263 if (event->pending_wakeup) {
6264 event->pending_wakeup = 0;
6265 perf_event_wakeup(event);
6269 perf_swevent_put_recursion_context(rctx);
6273 * We assume there is only KVM supporting the callbacks.
6274 * Later on, we might change it to a list if there is
6275 * another virtualization implementation supporting the callbacks.
6277 struct perf_guest_info_callbacks *perf_guest_cbs;
6279 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6281 perf_guest_cbs = cbs;
6284 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6286 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6288 perf_guest_cbs = NULL;
6291 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6294 perf_output_sample_regs(struct perf_output_handle *handle,
6295 struct pt_regs *regs, u64 mask)
6298 DECLARE_BITMAP(_mask, 64);
6300 bitmap_from_u64(_mask, mask);
6301 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6304 val = perf_reg_value(regs, bit);
6305 perf_output_put(handle, val);
6309 static void perf_sample_regs_user(struct perf_regs *regs_user,
6310 struct pt_regs *regs,
6311 struct pt_regs *regs_user_copy)
6313 if (user_mode(regs)) {
6314 regs_user->abi = perf_reg_abi(current);
6315 regs_user->regs = regs;
6316 } else if (!(current->flags & PF_KTHREAD)) {
6317 perf_get_regs_user(regs_user, regs, regs_user_copy);
6319 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6320 regs_user->regs = NULL;
6324 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6325 struct pt_regs *regs)
6327 regs_intr->regs = regs;
6328 regs_intr->abi = perf_reg_abi(current);
6333 * Get remaining task size from user stack pointer.
6335 * It'd be better to take stack vma map and limit this more
6336 * precisely, but there's no way to get it safely under interrupt,
6337 * so using TASK_SIZE as limit.
6339 static u64 perf_ustack_task_size(struct pt_regs *regs)
6341 unsigned long addr = perf_user_stack_pointer(regs);
6343 if (!addr || addr >= TASK_SIZE)
6346 return TASK_SIZE - addr;
6350 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6351 struct pt_regs *regs)
6355 /* No regs, no stack pointer, no dump. */
6360 * Check if we fit in with the requested stack size into the:
6362 * If we don't, we limit the size to the TASK_SIZE.
6364 * - remaining sample size
6365 * If we don't, we customize the stack size to
6366 * fit in to the remaining sample size.
6369 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6370 stack_size = min(stack_size, (u16) task_size);
6372 /* Current header size plus static size and dynamic size. */
6373 header_size += 2 * sizeof(u64);
6375 /* Do we fit in with the current stack dump size? */
6376 if ((u16) (header_size + stack_size) < header_size) {
6378 * If we overflow the maximum size for the sample,
6379 * we customize the stack dump size to fit in.
6381 stack_size = USHRT_MAX - header_size - sizeof(u64);
6382 stack_size = round_up(stack_size, sizeof(u64));
6389 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6390 struct pt_regs *regs)
6392 /* Case of a kernel thread, nothing to dump */
6395 perf_output_put(handle, size);
6405 * - the size requested by user or the best one we can fit
6406 * in to the sample max size
6408 * - user stack dump data
6410 * - the actual dumped size
6414 perf_output_put(handle, dump_size);
6417 sp = perf_user_stack_pointer(regs);
6420 rem = __output_copy_user(handle, (void *) sp, dump_size);
6422 dyn_size = dump_size - rem;
6424 perf_output_skip(handle, rem);
6427 perf_output_put(handle, dyn_size);
6431 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6432 struct perf_sample_data *data,
6435 struct perf_event *sampler = event->aux_event;
6436 struct perf_buffer *rb;
6443 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6446 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6449 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6454 * If this is an NMI hit inside sampling code, don't take
6455 * the sample. See also perf_aux_sample_output().
6457 if (READ_ONCE(rb->aux_in_sampling)) {
6460 size = min_t(size_t, size, perf_aux_size(rb));
6461 data->aux_size = ALIGN(size, sizeof(u64));
6463 ring_buffer_put(rb);
6466 return data->aux_size;
6469 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6470 struct perf_event *event,
6471 struct perf_output_handle *handle,
6474 unsigned long flags;
6478 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6479 * paths. If we start calling them in NMI context, they may race with
6480 * the IRQ ones, that is, for example, re-starting an event that's just
6481 * been stopped, which is why we're using a separate callback that
6482 * doesn't change the event state.
6484 * IRQs need to be disabled to prevent IPIs from racing with us.
6486 local_irq_save(flags);
6488 * Guard against NMI hits inside the critical section;
6489 * see also perf_prepare_sample_aux().
6491 WRITE_ONCE(rb->aux_in_sampling, 1);
6494 ret = event->pmu->snapshot_aux(event, handle, size);
6497 WRITE_ONCE(rb->aux_in_sampling, 0);
6498 local_irq_restore(flags);
6503 static void perf_aux_sample_output(struct perf_event *event,
6504 struct perf_output_handle *handle,
6505 struct perf_sample_data *data)
6507 struct perf_event *sampler = event->aux_event;
6508 struct perf_buffer *rb;
6512 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6515 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6519 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6522 * An error here means that perf_output_copy() failed (returned a
6523 * non-zero surplus that it didn't copy), which in its current
6524 * enlightened implementation is not possible. If that changes, we'd
6527 if (WARN_ON_ONCE(size < 0))
6531 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6532 * perf_prepare_sample_aux(), so should not be more than that.
6534 pad = data->aux_size - size;
6535 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6540 perf_output_copy(handle, &zero, pad);
6544 ring_buffer_put(rb);
6547 static void __perf_event_header__init_id(struct perf_event_header *header,
6548 struct perf_sample_data *data,
6549 struct perf_event *event)
6551 u64 sample_type = event->attr.sample_type;
6553 data->type = sample_type;
6554 header->size += event->id_header_size;
6556 if (sample_type & PERF_SAMPLE_TID) {
6557 /* namespace issues */
6558 data->tid_entry.pid = perf_event_pid(event, current);
6559 data->tid_entry.tid = perf_event_tid(event, current);
6562 if (sample_type & PERF_SAMPLE_TIME)
6563 data->time = perf_event_clock(event);
6565 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6566 data->id = primary_event_id(event);
6568 if (sample_type & PERF_SAMPLE_STREAM_ID)
6569 data->stream_id = event->id;
6571 if (sample_type & PERF_SAMPLE_CPU) {
6572 data->cpu_entry.cpu = raw_smp_processor_id();
6573 data->cpu_entry.reserved = 0;
6577 void perf_event_header__init_id(struct perf_event_header *header,
6578 struct perf_sample_data *data,
6579 struct perf_event *event)
6581 if (event->attr.sample_id_all)
6582 __perf_event_header__init_id(header, data, event);
6585 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6586 struct perf_sample_data *data)
6588 u64 sample_type = data->type;
6590 if (sample_type & PERF_SAMPLE_TID)
6591 perf_output_put(handle, data->tid_entry);
6593 if (sample_type & PERF_SAMPLE_TIME)
6594 perf_output_put(handle, data->time);
6596 if (sample_type & PERF_SAMPLE_ID)
6597 perf_output_put(handle, data->id);
6599 if (sample_type & PERF_SAMPLE_STREAM_ID)
6600 perf_output_put(handle, data->stream_id);
6602 if (sample_type & PERF_SAMPLE_CPU)
6603 perf_output_put(handle, data->cpu_entry);
6605 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6606 perf_output_put(handle, data->id);
6609 void perf_event__output_id_sample(struct perf_event *event,
6610 struct perf_output_handle *handle,
6611 struct perf_sample_data *sample)
6613 if (event->attr.sample_id_all)
6614 __perf_event__output_id_sample(handle, sample);
6617 static void perf_output_read_one(struct perf_output_handle *handle,
6618 struct perf_event *event,
6619 u64 enabled, u64 running)
6621 u64 read_format = event->attr.read_format;
6625 values[n++] = perf_event_count(event);
6626 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6627 values[n++] = enabled +
6628 atomic64_read(&event->child_total_time_enabled);
6630 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6631 values[n++] = running +
6632 atomic64_read(&event->child_total_time_running);
6634 if (read_format & PERF_FORMAT_ID)
6635 values[n++] = primary_event_id(event);
6637 __output_copy(handle, values, n * sizeof(u64));
6640 static void perf_output_read_group(struct perf_output_handle *handle,
6641 struct perf_event *event,
6642 u64 enabled, u64 running)
6644 struct perf_event *leader = event->group_leader, *sub;
6645 u64 read_format = event->attr.read_format;
6649 values[n++] = 1 + leader->nr_siblings;
6651 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6652 values[n++] = enabled;
6654 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6655 values[n++] = running;
6657 if ((leader != event) &&
6658 (leader->state == PERF_EVENT_STATE_ACTIVE))
6659 leader->pmu->read(leader);
6661 values[n++] = perf_event_count(leader);
6662 if (read_format & PERF_FORMAT_ID)
6663 values[n++] = primary_event_id(leader);
6665 __output_copy(handle, values, n * sizeof(u64));
6667 for_each_sibling_event(sub, leader) {
6670 if ((sub != event) &&
6671 (sub->state == PERF_EVENT_STATE_ACTIVE))
6672 sub->pmu->read(sub);
6674 values[n++] = perf_event_count(sub);
6675 if (read_format & PERF_FORMAT_ID)
6676 values[n++] = primary_event_id(sub);
6678 __output_copy(handle, values, n * sizeof(u64));
6682 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6683 PERF_FORMAT_TOTAL_TIME_RUNNING)
6686 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6688 * The problem is that its both hard and excessively expensive to iterate the
6689 * child list, not to mention that its impossible to IPI the children running
6690 * on another CPU, from interrupt/NMI context.
6692 static void perf_output_read(struct perf_output_handle *handle,
6693 struct perf_event *event)
6695 u64 enabled = 0, running = 0, now;
6696 u64 read_format = event->attr.read_format;
6699 * compute total_time_enabled, total_time_running
6700 * based on snapshot values taken when the event
6701 * was last scheduled in.
6703 * we cannot simply called update_context_time()
6704 * because of locking issue as we are called in
6707 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6708 calc_timer_values(event, &now, &enabled, &running);
6710 if (event->attr.read_format & PERF_FORMAT_GROUP)
6711 perf_output_read_group(handle, event, enabled, running);
6713 perf_output_read_one(handle, event, enabled, running);
6716 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6718 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6721 void perf_output_sample(struct perf_output_handle *handle,
6722 struct perf_event_header *header,
6723 struct perf_sample_data *data,
6724 struct perf_event *event)
6726 u64 sample_type = data->type;
6728 perf_output_put(handle, *header);
6730 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6731 perf_output_put(handle, data->id);
6733 if (sample_type & PERF_SAMPLE_IP)
6734 perf_output_put(handle, data->ip);
6736 if (sample_type & PERF_SAMPLE_TID)
6737 perf_output_put(handle, data->tid_entry);
6739 if (sample_type & PERF_SAMPLE_TIME)
6740 perf_output_put(handle, data->time);
6742 if (sample_type & PERF_SAMPLE_ADDR)
6743 perf_output_put(handle, data->addr);
6745 if (sample_type & PERF_SAMPLE_ID)
6746 perf_output_put(handle, data->id);
6748 if (sample_type & PERF_SAMPLE_STREAM_ID)
6749 perf_output_put(handle, data->stream_id);
6751 if (sample_type & PERF_SAMPLE_CPU)
6752 perf_output_put(handle, data->cpu_entry);
6754 if (sample_type & PERF_SAMPLE_PERIOD)
6755 perf_output_put(handle, data->period);
6757 if (sample_type & PERF_SAMPLE_READ)
6758 perf_output_read(handle, event);
6760 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6763 size += data->callchain->nr;
6764 size *= sizeof(u64);
6765 __output_copy(handle, data->callchain, size);
6768 if (sample_type & PERF_SAMPLE_RAW) {
6769 struct perf_raw_record *raw = data->raw;
6772 struct perf_raw_frag *frag = &raw->frag;
6774 perf_output_put(handle, raw->size);
6777 __output_custom(handle, frag->copy,
6778 frag->data, frag->size);
6780 __output_copy(handle, frag->data,
6783 if (perf_raw_frag_last(frag))
6788 __output_skip(handle, NULL, frag->pad);
6794 .size = sizeof(u32),
6797 perf_output_put(handle, raw);
6801 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6802 if (data->br_stack) {
6805 size = data->br_stack->nr
6806 * sizeof(struct perf_branch_entry);
6808 perf_output_put(handle, data->br_stack->nr);
6809 if (perf_sample_save_hw_index(event))
6810 perf_output_put(handle, data->br_stack->hw_idx);
6811 perf_output_copy(handle, data->br_stack->entries, size);
6814 * we always store at least the value of nr
6817 perf_output_put(handle, nr);
6821 if (sample_type & PERF_SAMPLE_REGS_USER) {
6822 u64 abi = data->regs_user.abi;
6825 * If there are no regs to dump, notice it through
6826 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6828 perf_output_put(handle, abi);
6831 u64 mask = event->attr.sample_regs_user;
6832 perf_output_sample_regs(handle,
6833 data->regs_user.regs,
6838 if (sample_type & PERF_SAMPLE_STACK_USER) {
6839 perf_output_sample_ustack(handle,
6840 data->stack_user_size,
6841 data->regs_user.regs);
6844 if (sample_type & PERF_SAMPLE_WEIGHT)
6845 perf_output_put(handle, data->weight);
6847 if (sample_type & PERF_SAMPLE_DATA_SRC)
6848 perf_output_put(handle, data->data_src.val);
6850 if (sample_type & PERF_SAMPLE_TRANSACTION)
6851 perf_output_put(handle, data->txn);
6853 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6854 u64 abi = data->regs_intr.abi;
6856 * If there are no regs to dump, notice it through
6857 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6859 perf_output_put(handle, abi);
6862 u64 mask = event->attr.sample_regs_intr;
6864 perf_output_sample_regs(handle,
6865 data->regs_intr.regs,
6870 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6871 perf_output_put(handle, data->phys_addr);
6873 if (sample_type & PERF_SAMPLE_CGROUP)
6874 perf_output_put(handle, data->cgroup);
6876 if (sample_type & PERF_SAMPLE_AUX) {
6877 perf_output_put(handle, data->aux_size);
6880 perf_aux_sample_output(event, handle, data);
6883 if (!event->attr.watermark) {
6884 int wakeup_events = event->attr.wakeup_events;
6886 if (wakeup_events) {
6887 struct perf_buffer *rb = handle->rb;
6888 int events = local_inc_return(&rb->events);
6890 if (events >= wakeup_events) {
6891 local_sub(wakeup_events, &rb->events);
6892 local_inc(&rb->wakeup);
6898 static u64 perf_virt_to_phys(u64 virt)
6901 struct page *p = NULL;
6906 if (virt >= TASK_SIZE) {
6907 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6908 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6909 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6910 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6913 * Walking the pages tables for user address.
6914 * Interrupts are disabled, so it prevents any tear down
6915 * of the page tables.
6916 * Try IRQ-safe __get_user_pages_fast first.
6917 * If failed, leave phys_addr as 0.
6919 if ((current->mm != NULL) &&
6920 (__get_user_pages_fast(virt, 1, 0, &p) == 1))
6921 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6930 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6932 struct perf_callchain_entry *
6933 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6935 bool kernel = !event->attr.exclude_callchain_kernel;
6936 bool user = !event->attr.exclude_callchain_user;
6937 /* Disallow cross-task user callchains. */
6938 bool crosstask = event->ctx->task && event->ctx->task != current;
6939 const u32 max_stack = event->attr.sample_max_stack;
6940 struct perf_callchain_entry *callchain;
6942 if (!kernel && !user)
6943 return &__empty_callchain;
6945 callchain = get_perf_callchain(regs, 0, kernel, user,
6946 max_stack, crosstask, true);
6947 return callchain ?: &__empty_callchain;
6950 void perf_prepare_sample(struct perf_event_header *header,
6951 struct perf_sample_data *data,
6952 struct perf_event *event,
6953 struct pt_regs *regs)
6955 u64 sample_type = event->attr.sample_type;
6957 header->type = PERF_RECORD_SAMPLE;
6958 header->size = sizeof(*header) + event->header_size;
6961 header->misc |= perf_misc_flags(regs);
6963 __perf_event_header__init_id(header, data, event);
6965 if (sample_type & PERF_SAMPLE_IP)
6966 data->ip = perf_instruction_pointer(regs);
6968 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6971 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
6972 data->callchain = perf_callchain(event, regs);
6974 size += data->callchain->nr;
6976 header->size += size * sizeof(u64);
6979 if (sample_type & PERF_SAMPLE_RAW) {
6980 struct perf_raw_record *raw = data->raw;
6984 struct perf_raw_frag *frag = &raw->frag;
6989 if (perf_raw_frag_last(frag))
6994 size = round_up(sum + sizeof(u32), sizeof(u64));
6995 raw->size = size - sizeof(u32);
6996 frag->pad = raw->size - sum;
7001 header->size += size;
7004 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7005 int size = sizeof(u64); /* nr */
7006 if (data->br_stack) {
7007 if (perf_sample_save_hw_index(event))
7008 size += sizeof(u64);
7010 size += data->br_stack->nr
7011 * sizeof(struct perf_branch_entry);
7013 header->size += size;
7016 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7017 perf_sample_regs_user(&data->regs_user, regs,
7018 &data->regs_user_copy);
7020 if (sample_type & PERF_SAMPLE_REGS_USER) {
7021 /* regs dump ABI info */
7022 int size = sizeof(u64);
7024 if (data->regs_user.regs) {
7025 u64 mask = event->attr.sample_regs_user;
7026 size += hweight64(mask) * sizeof(u64);
7029 header->size += size;
7032 if (sample_type & PERF_SAMPLE_STACK_USER) {
7034 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7035 * processed as the last one or have additional check added
7036 * in case new sample type is added, because we could eat
7037 * up the rest of the sample size.
7039 u16 stack_size = event->attr.sample_stack_user;
7040 u16 size = sizeof(u64);
7042 stack_size = perf_sample_ustack_size(stack_size, header->size,
7043 data->regs_user.regs);
7046 * If there is something to dump, add space for the dump
7047 * itself and for the field that tells the dynamic size,
7048 * which is how many have been actually dumped.
7051 size += sizeof(u64) + stack_size;
7053 data->stack_user_size = stack_size;
7054 header->size += size;
7057 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7058 /* regs dump ABI info */
7059 int size = sizeof(u64);
7061 perf_sample_regs_intr(&data->regs_intr, regs);
7063 if (data->regs_intr.regs) {
7064 u64 mask = event->attr.sample_regs_intr;
7066 size += hweight64(mask) * sizeof(u64);
7069 header->size += size;
7072 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7073 data->phys_addr = perf_virt_to_phys(data->addr);
7075 #ifdef CONFIG_CGROUP_PERF
7076 if (sample_type & PERF_SAMPLE_CGROUP) {
7077 struct cgroup *cgrp;
7079 /* protected by RCU */
7080 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7081 data->cgroup = cgroup_id(cgrp);
7085 if (sample_type & PERF_SAMPLE_AUX) {
7088 header->size += sizeof(u64); /* size */
7091 * Given the 16bit nature of header::size, an AUX sample can
7092 * easily overflow it, what with all the preceding sample bits.
7093 * Make sure this doesn't happen by using up to U16_MAX bytes
7094 * per sample in total (rounded down to 8 byte boundary).
7096 size = min_t(size_t, U16_MAX - header->size,
7097 event->attr.aux_sample_size);
7098 size = rounddown(size, 8);
7099 size = perf_prepare_sample_aux(event, data, size);
7101 WARN_ON_ONCE(size + header->size > U16_MAX);
7102 header->size += size;
7105 * If you're adding more sample types here, you likely need to do
7106 * something about the overflowing header::size, like repurpose the
7107 * lowest 3 bits of size, which should be always zero at the moment.
7108 * This raises a more important question, do we really need 512k sized
7109 * samples and why, so good argumentation is in order for whatever you
7112 WARN_ON_ONCE(header->size & 7);
7115 static __always_inline int
7116 __perf_event_output(struct perf_event *event,
7117 struct perf_sample_data *data,
7118 struct pt_regs *regs,
7119 int (*output_begin)(struct perf_output_handle *,
7120 struct perf_event *,
7123 struct perf_output_handle handle;
7124 struct perf_event_header header;
7127 /* protect the callchain buffers */
7130 perf_prepare_sample(&header, data, event, regs);
7132 err = output_begin(&handle, event, header.size);
7136 perf_output_sample(&handle, &header, data, event);
7138 perf_output_end(&handle);
7146 perf_event_output_forward(struct perf_event *event,
7147 struct perf_sample_data *data,
7148 struct pt_regs *regs)
7150 __perf_event_output(event, data, regs, perf_output_begin_forward);
7154 perf_event_output_backward(struct perf_event *event,
7155 struct perf_sample_data *data,
7156 struct pt_regs *regs)
7158 __perf_event_output(event, data, regs, perf_output_begin_backward);
7162 perf_event_output(struct perf_event *event,
7163 struct perf_sample_data *data,
7164 struct pt_regs *regs)
7166 return __perf_event_output(event, data, regs, perf_output_begin);
7173 struct perf_read_event {
7174 struct perf_event_header header;
7181 perf_event_read_event(struct perf_event *event,
7182 struct task_struct *task)
7184 struct perf_output_handle handle;
7185 struct perf_sample_data sample;
7186 struct perf_read_event read_event = {
7188 .type = PERF_RECORD_READ,
7190 .size = sizeof(read_event) + event->read_size,
7192 .pid = perf_event_pid(event, task),
7193 .tid = perf_event_tid(event, task),
7197 perf_event_header__init_id(&read_event.header, &sample, event);
7198 ret = perf_output_begin(&handle, event, read_event.header.size);
7202 perf_output_put(&handle, read_event);
7203 perf_output_read(&handle, event);
7204 perf_event__output_id_sample(event, &handle, &sample);
7206 perf_output_end(&handle);
7209 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7212 perf_iterate_ctx(struct perf_event_context *ctx,
7213 perf_iterate_f output,
7214 void *data, bool all)
7216 struct perf_event *event;
7218 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7220 if (event->state < PERF_EVENT_STATE_INACTIVE)
7222 if (!event_filter_match(event))
7226 output(event, data);
7230 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7232 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7233 struct perf_event *event;
7235 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7237 * Skip events that are not fully formed yet; ensure that
7238 * if we observe event->ctx, both event and ctx will be
7239 * complete enough. See perf_install_in_context().
7241 if (!smp_load_acquire(&event->ctx))
7244 if (event->state < PERF_EVENT_STATE_INACTIVE)
7246 if (!event_filter_match(event))
7248 output(event, data);
7253 * Iterate all events that need to receive side-band events.
7255 * For new callers; ensure that account_pmu_sb_event() includes
7256 * your event, otherwise it might not get delivered.
7259 perf_iterate_sb(perf_iterate_f output, void *data,
7260 struct perf_event_context *task_ctx)
7262 struct perf_event_context *ctx;
7269 * If we have task_ctx != NULL we only notify the task context itself.
7270 * The task_ctx is set only for EXIT events before releasing task
7274 perf_iterate_ctx(task_ctx, output, data, false);
7278 perf_iterate_sb_cpu(output, data);
7280 for_each_task_context_nr(ctxn) {
7281 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7283 perf_iterate_ctx(ctx, output, data, false);
7291 * Clear all file-based filters at exec, they'll have to be
7292 * re-instated when/if these objects are mmapped again.
7294 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7296 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7297 struct perf_addr_filter *filter;
7298 unsigned int restart = 0, count = 0;
7299 unsigned long flags;
7301 if (!has_addr_filter(event))
7304 raw_spin_lock_irqsave(&ifh->lock, flags);
7305 list_for_each_entry(filter, &ifh->list, entry) {
7306 if (filter->path.dentry) {
7307 event->addr_filter_ranges[count].start = 0;
7308 event->addr_filter_ranges[count].size = 0;
7316 event->addr_filters_gen++;
7317 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7320 perf_event_stop(event, 1);
7323 void perf_event_exec(void)
7325 struct perf_event_context *ctx;
7329 for_each_task_context_nr(ctxn) {
7330 ctx = current->perf_event_ctxp[ctxn];
7334 perf_event_enable_on_exec(ctxn);
7336 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7342 struct remote_output {
7343 struct perf_buffer *rb;
7347 static void __perf_event_output_stop(struct perf_event *event, void *data)
7349 struct perf_event *parent = event->parent;
7350 struct remote_output *ro = data;
7351 struct perf_buffer *rb = ro->rb;
7352 struct stop_event_data sd = {
7356 if (!has_aux(event))
7363 * In case of inheritance, it will be the parent that links to the
7364 * ring-buffer, but it will be the child that's actually using it.
7366 * We are using event::rb to determine if the event should be stopped,
7367 * however this may race with ring_buffer_attach() (through set_output),
7368 * which will make us skip the event that actually needs to be stopped.
7369 * So ring_buffer_attach() has to stop an aux event before re-assigning
7372 if (rcu_dereference(parent->rb) == rb)
7373 ro->err = __perf_event_stop(&sd);
7376 static int __perf_pmu_output_stop(void *info)
7378 struct perf_event *event = info;
7379 struct pmu *pmu = event->ctx->pmu;
7380 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7381 struct remote_output ro = {
7386 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7387 if (cpuctx->task_ctx)
7388 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7395 static void perf_pmu_output_stop(struct perf_event *event)
7397 struct perf_event *iter;
7402 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7404 * For per-CPU events, we need to make sure that neither they
7405 * nor their children are running; for cpu==-1 events it's
7406 * sufficient to stop the event itself if it's active, since
7407 * it can't have children.
7411 cpu = READ_ONCE(iter->oncpu);
7416 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7417 if (err == -EAGAIN) {
7426 * task tracking -- fork/exit
7428 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7431 struct perf_task_event {
7432 struct task_struct *task;
7433 struct perf_event_context *task_ctx;
7436 struct perf_event_header header;
7446 static int perf_event_task_match(struct perf_event *event)
7448 return event->attr.comm || event->attr.mmap ||
7449 event->attr.mmap2 || event->attr.mmap_data ||
7453 static void perf_event_task_output(struct perf_event *event,
7456 struct perf_task_event *task_event = data;
7457 struct perf_output_handle handle;
7458 struct perf_sample_data sample;
7459 struct task_struct *task = task_event->task;
7460 int ret, size = task_event->event_id.header.size;
7462 if (!perf_event_task_match(event))
7465 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7467 ret = perf_output_begin(&handle, event,
7468 task_event->event_id.header.size);
7472 task_event->event_id.pid = perf_event_pid(event, task);
7473 task_event->event_id.ppid = perf_event_pid(event, current);
7475 task_event->event_id.tid = perf_event_tid(event, task);
7476 task_event->event_id.ptid = perf_event_tid(event, current);
7478 task_event->event_id.time = perf_event_clock(event);
7480 perf_output_put(&handle, task_event->event_id);
7482 perf_event__output_id_sample(event, &handle, &sample);
7484 perf_output_end(&handle);
7486 task_event->event_id.header.size = size;
7489 static void perf_event_task(struct task_struct *task,
7490 struct perf_event_context *task_ctx,
7493 struct perf_task_event task_event;
7495 if (!atomic_read(&nr_comm_events) &&
7496 !atomic_read(&nr_mmap_events) &&
7497 !atomic_read(&nr_task_events))
7500 task_event = (struct perf_task_event){
7502 .task_ctx = task_ctx,
7505 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7507 .size = sizeof(task_event.event_id),
7517 perf_iterate_sb(perf_event_task_output,
7522 void perf_event_fork(struct task_struct *task)
7524 perf_event_task(task, NULL, 1);
7525 perf_event_namespaces(task);
7532 struct perf_comm_event {
7533 struct task_struct *task;
7538 struct perf_event_header header;
7545 static int perf_event_comm_match(struct perf_event *event)
7547 return event->attr.comm;
7550 static void perf_event_comm_output(struct perf_event *event,
7553 struct perf_comm_event *comm_event = data;
7554 struct perf_output_handle handle;
7555 struct perf_sample_data sample;
7556 int size = comm_event->event_id.header.size;
7559 if (!perf_event_comm_match(event))
7562 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7563 ret = perf_output_begin(&handle, event,
7564 comm_event->event_id.header.size);
7569 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7570 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7572 perf_output_put(&handle, comm_event->event_id);
7573 __output_copy(&handle, comm_event->comm,
7574 comm_event->comm_size);
7576 perf_event__output_id_sample(event, &handle, &sample);
7578 perf_output_end(&handle);
7580 comm_event->event_id.header.size = size;
7583 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7585 char comm[TASK_COMM_LEN];
7588 memset(comm, 0, sizeof(comm));
7589 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7590 size = ALIGN(strlen(comm)+1, sizeof(u64));
7592 comm_event->comm = comm;
7593 comm_event->comm_size = size;
7595 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7597 perf_iterate_sb(perf_event_comm_output,
7602 void perf_event_comm(struct task_struct *task, bool exec)
7604 struct perf_comm_event comm_event;
7606 if (!atomic_read(&nr_comm_events))
7609 comm_event = (struct perf_comm_event){
7615 .type = PERF_RECORD_COMM,
7616 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7624 perf_event_comm_event(&comm_event);
7628 * namespaces tracking
7631 struct perf_namespaces_event {
7632 struct task_struct *task;
7635 struct perf_event_header header;
7640 struct perf_ns_link_info link_info[NR_NAMESPACES];
7644 static int perf_event_namespaces_match(struct perf_event *event)
7646 return event->attr.namespaces;
7649 static void perf_event_namespaces_output(struct perf_event *event,
7652 struct perf_namespaces_event *namespaces_event = data;
7653 struct perf_output_handle handle;
7654 struct perf_sample_data sample;
7655 u16 header_size = namespaces_event->event_id.header.size;
7658 if (!perf_event_namespaces_match(event))
7661 perf_event_header__init_id(&namespaces_event->event_id.header,
7663 ret = perf_output_begin(&handle, event,
7664 namespaces_event->event_id.header.size);
7668 namespaces_event->event_id.pid = perf_event_pid(event,
7669 namespaces_event->task);
7670 namespaces_event->event_id.tid = perf_event_tid(event,
7671 namespaces_event->task);
7673 perf_output_put(&handle, namespaces_event->event_id);
7675 perf_event__output_id_sample(event, &handle, &sample);
7677 perf_output_end(&handle);
7679 namespaces_event->event_id.header.size = header_size;
7682 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7683 struct task_struct *task,
7684 const struct proc_ns_operations *ns_ops)
7686 struct path ns_path;
7687 struct inode *ns_inode;
7690 error = ns_get_path(&ns_path, task, ns_ops);
7692 ns_inode = ns_path.dentry->d_inode;
7693 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7694 ns_link_info->ino = ns_inode->i_ino;
7699 void perf_event_namespaces(struct task_struct *task)
7701 struct perf_namespaces_event namespaces_event;
7702 struct perf_ns_link_info *ns_link_info;
7704 if (!atomic_read(&nr_namespaces_events))
7707 namespaces_event = (struct perf_namespaces_event){
7711 .type = PERF_RECORD_NAMESPACES,
7713 .size = sizeof(namespaces_event.event_id),
7717 .nr_namespaces = NR_NAMESPACES,
7718 /* .link_info[NR_NAMESPACES] */
7722 ns_link_info = namespaces_event.event_id.link_info;
7724 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7725 task, &mntns_operations);
7727 #ifdef CONFIG_USER_NS
7728 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7729 task, &userns_operations);
7731 #ifdef CONFIG_NET_NS
7732 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7733 task, &netns_operations);
7735 #ifdef CONFIG_UTS_NS
7736 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7737 task, &utsns_operations);
7739 #ifdef CONFIG_IPC_NS
7740 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7741 task, &ipcns_operations);
7743 #ifdef CONFIG_PID_NS
7744 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7745 task, &pidns_operations);
7747 #ifdef CONFIG_CGROUPS
7748 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7749 task, &cgroupns_operations);
7752 perf_iterate_sb(perf_event_namespaces_output,
7760 #ifdef CONFIG_CGROUP_PERF
7762 struct perf_cgroup_event {
7766 struct perf_event_header header;
7772 static int perf_event_cgroup_match(struct perf_event *event)
7774 return event->attr.cgroup;
7777 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7779 struct perf_cgroup_event *cgroup_event = data;
7780 struct perf_output_handle handle;
7781 struct perf_sample_data sample;
7782 u16 header_size = cgroup_event->event_id.header.size;
7785 if (!perf_event_cgroup_match(event))
7788 perf_event_header__init_id(&cgroup_event->event_id.header,
7790 ret = perf_output_begin(&handle, event,
7791 cgroup_event->event_id.header.size);
7795 perf_output_put(&handle, cgroup_event->event_id);
7796 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7798 perf_event__output_id_sample(event, &handle, &sample);
7800 perf_output_end(&handle);
7802 cgroup_event->event_id.header.size = header_size;
7805 static void perf_event_cgroup(struct cgroup *cgrp)
7807 struct perf_cgroup_event cgroup_event;
7808 char path_enomem[16] = "//enomem";
7812 if (!atomic_read(&nr_cgroup_events))
7815 cgroup_event = (struct perf_cgroup_event){
7818 .type = PERF_RECORD_CGROUP,
7820 .size = sizeof(cgroup_event.event_id),
7822 .id = cgroup_id(cgrp),
7826 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7827 if (pathname == NULL) {
7828 cgroup_event.path = path_enomem;
7830 /* just to be sure to have enough space for alignment */
7831 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7832 cgroup_event.path = pathname;
7836 * Since our buffer works in 8 byte units we need to align our string
7837 * size to a multiple of 8. However, we must guarantee the tail end is
7838 * zero'd out to avoid leaking random bits to userspace.
7840 size = strlen(cgroup_event.path) + 1;
7841 while (!IS_ALIGNED(size, sizeof(u64)))
7842 cgroup_event.path[size++] = '\0';
7844 cgroup_event.event_id.header.size += size;
7845 cgroup_event.path_size = size;
7847 perf_iterate_sb(perf_event_cgroup_output,
7860 struct perf_mmap_event {
7861 struct vm_area_struct *vma;
7863 const char *file_name;
7871 struct perf_event_header header;
7881 static int perf_event_mmap_match(struct perf_event *event,
7884 struct perf_mmap_event *mmap_event = data;
7885 struct vm_area_struct *vma = mmap_event->vma;
7886 int executable = vma->vm_flags & VM_EXEC;
7888 return (!executable && event->attr.mmap_data) ||
7889 (executable && (event->attr.mmap || event->attr.mmap2));
7892 static void perf_event_mmap_output(struct perf_event *event,
7895 struct perf_mmap_event *mmap_event = data;
7896 struct perf_output_handle handle;
7897 struct perf_sample_data sample;
7898 int size = mmap_event->event_id.header.size;
7899 u32 type = mmap_event->event_id.header.type;
7902 if (!perf_event_mmap_match(event, data))
7905 if (event->attr.mmap2) {
7906 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7907 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7908 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7909 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7910 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7911 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7912 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7915 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7916 ret = perf_output_begin(&handle, event,
7917 mmap_event->event_id.header.size);
7921 mmap_event->event_id.pid = perf_event_pid(event, current);
7922 mmap_event->event_id.tid = perf_event_tid(event, current);
7924 perf_output_put(&handle, mmap_event->event_id);
7926 if (event->attr.mmap2) {
7927 perf_output_put(&handle, mmap_event->maj);
7928 perf_output_put(&handle, mmap_event->min);
7929 perf_output_put(&handle, mmap_event->ino);
7930 perf_output_put(&handle, mmap_event->ino_generation);
7931 perf_output_put(&handle, mmap_event->prot);
7932 perf_output_put(&handle, mmap_event->flags);
7935 __output_copy(&handle, mmap_event->file_name,
7936 mmap_event->file_size);
7938 perf_event__output_id_sample(event, &handle, &sample);
7940 perf_output_end(&handle);
7942 mmap_event->event_id.header.size = size;
7943 mmap_event->event_id.header.type = type;
7946 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7948 struct vm_area_struct *vma = mmap_event->vma;
7949 struct file *file = vma->vm_file;
7950 int maj = 0, min = 0;
7951 u64 ino = 0, gen = 0;
7952 u32 prot = 0, flags = 0;
7958 if (vma->vm_flags & VM_READ)
7960 if (vma->vm_flags & VM_WRITE)
7962 if (vma->vm_flags & VM_EXEC)
7965 if (vma->vm_flags & VM_MAYSHARE)
7968 flags = MAP_PRIVATE;
7970 if (vma->vm_flags & VM_DENYWRITE)
7971 flags |= MAP_DENYWRITE;
7972 if (vma->vm_flags & VM_MAYEXEC)
7973 flags |= MAP_EXECUTABLE;
7974 if (vma->vm_flags & VM_LOCKED)
7975 flags |= MAP_LOCKED;
7976 if (vma->vm_flags & VM_HUGETLB)
7977 flags |= MAP_HUGETLB;
7980 struct inode *inode;
7983 buf = kmalloc(PATH_MAX, GFP_KERNEL);
7989 * d_path() works from the end of the rb backwards, so we
7990 * need to add enough zero bytes after the string to handle
7991 * the 64bit alignment we do later.
7993 name = file_path(file, buf, PATH_MAX - sizeof(u64));
7998 inode = file_inode(vma->vm_file);
7999 dev = inode->i_sb->s_dev;
8001 gen = inode->i_generation;
8007 if (vma->vm_ops && vma->vm_ops->name) {
8008 name = (char *) vma->vm_ops->name(vma);
8013 name = (char *)arch_vma_name(vma);
8017 if (vma->vm_start <= vma->vm_mm->start_brk &&
8018 vma->vm_end >= vma->vm_mm->brk) {
8022 if (vma->vm_start <= vma->vm_mm->start_stack &&
8023 vma->vm_end >= vma->vm_mm->start_stack) {
8033 strlcpy(tmp, name, sizeof(tmp));
8037 * Since our buffer works in 8 byte units we need to align our string
8038 * size to a multiple of 8. However, we must guarantee the tail end is
8039 * zero'd out to avoid leaking random bits to userspace.
8041 size = strlen(name)+1;
8042 while (!IS_ALIGNED(size, sizeof(u64)))
8043 name[size++] = '\0';
8045 mmap_event->file_name = name;
8046 mmap_event->file_size = size;
8047 mmap_event->maj = maj;
8048 mmap_event->min = min;
8049 mmap_event->ino = ino;
8050 mmap_event->ino_generation = gen;
8051 mmap_event->prot = prot;
8052 mmap_event->flags = flags;
8054 if (!(vma->vm_flags & VM_EXEC))
8055 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8057 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8059 perf_iterate_sb(perf_event_mmap_output,
8067 * Check whether inode and address range match filter criteria.
8069 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8070 struct file *file, unsigned long offset,
8073 /* d_inode(NULL) won't be equal to any mapped user-space file */
8074 if (!filter->path.dentry)
8077 if (d_inode(filter->path.dentry) != file_inode(file))
8080 if (filter->offset > offset + size)
8083 if (filter->offset + filter->size < offset)
8089 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8090 struct vm_area_struct *vma,
8091 struct perf_addr_filter_range *fr)
8093 unsigned long vma_size = vma->vm_end - vma->vm_start;
8094 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8095 struct file *file = vma->vm_file;
8097 if (!perf_addr_filter_match(filter, file, off, vma_size))
8100 if (filter->offset < off) {
8101 fr->start = vma->vm_start;
8102 fr->size = min(vma_size, filter->size - (off - filter->offset));
8104 fr->start = vma->vm_start + filter->offset - off;
8105 fr->size = min(vma->vm_end - fr->start, filter->size);
8111 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8113 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8114 struct vm_area_struct *vma = data;
8115 struct perf_addr_filter *filter;
8116 unsigned int restart = 0, count = 0;
8117 unsigned long flags;
8119 if (!has_addr_filter(event))
8125 raw_spin_lock_irqsave(&ifh->lock, flags);
8126 list_for_each_entry(filter, &ifh->list, entry) {
8127 if (perf_addr_filter_vma_adjust(filter, vma,
8128 &event->addr_filter_ranges[count]))
8135 event->addr_filters_gen++;
8136 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8139 perf_event_stop(event, 1);
8143 * Adjust all task's events' filters to the new vma
8145 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8147 struct perf_event_context *ctx;
8151 * Data tracing isn't supported yet and as such there is no need
8152 * to keep track of anything that isn't related to executable code:
8154 if (!(vma->vm_flags & VM_EXEC))
8158 for_each_task_context_nr(ctxn) {
8159 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8163 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8168 void perf_event_mmap(struct vm_area_struct *vma)
8170 struct perf_mmap_event mmap_event;
8172 if (!atomic_read(&nr_mmap_events))
8175 mmap_event = (struct perf_mmap_event){
8181 .type = PERF_RECORD_MMAP,
8182 .misc = PERF_RECORD_MISC_USER,
8187 .start = vma->vm_start,
8188 .len = vma->vm_end - vma->vm_start,
8189 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8191 /* .maj (attr_mmap2 only) */
8192 /* .min (attr_mmap2 only) */
8193 /* .ino (attr_mmap2 only) */
8194 /* .ino_generation (attr_mmap2 only) */
8195 /* .prot (attr_mmap2 only) */
8196 /* .flags (attr_mmap2 only) */
8199 perf_addr_filters_adjust(vma);
8200 perf_event_mmap_event(&mmap_event);
8203 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8204 unsigned long size, u64 flags)
8206 struct perf_output_handle handle;
8207 struct perf_sample_data sample;
8208 struct perf_aux_event {
8209 struct perf_event_header header;
8215 .type = PERF_RECORD_AUX,
8217 .size = sizeof(rec),
8225 perf_event_header__init_id(&rec.header, &sample, event);
8226 ret = perf_output_begin(&handle, event, rec.header.size);
8231 perf_output_put(&handle, rec);
8232 perf_event__output_id_sample(event, &handle, &sample);
8234 perf_output_end(&handle);
8238 * Lost/dropped samples logging
8240 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8242 struct perf_output_handle handle;
8243 struct perf_sample_data sample;
8247 struct perf_event_header header;
8249 } lost_samples_event = {
8251 .type = PERF_RECORD_LOST_SAMPLES,
8253 .size = sizeof(lost_samples_event),
8258 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8260 ret = perf_output_begin(&handle, event,
8261 lost_samples_event.header.size);
8265 perf_output_put(&handle, lost_samples_event);
8266 perf_event__output_id_sample(event, &handle, &sample);
8267 perf_output_end(&handle);
8271 * context_switch tracking
8274 struct perf_switch_event {
8275 struct task_struct *task;
8276 struct task_struct *next_prev;
8279 struct perf_event_header header;
8285 static int perf_event_switch_match(struct perf_event *event)
8287 return event->attr.context_switch;
8290 static void perf_event_switch_output(struct perf_event *event, void *data)
8292 struct perf_switch_event *se = data;
8293 struct perf_output_handle handle;
8294 struct perf_sample_data sample;
8297 if (!perf_event_switch_match(event))
8300 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8301 if (event->ctx->task) {
8302 se->event_id.header.type = PERF_RECORD_SWITCH;
8303 se->event_id.header.size = sizeof(se->event_id.header);
8305 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8306 se->event_id.header.size = sizeof(se->event_id);
8307 se->event_id.next_prev_pid =
8308 perf_event_pid(event, se->next_prev);
8309 se->event_id.next_prev_tid =
8310 perf_event_tid(event, se->next_prev);
8313 perf_event_header__init_id(&se->event_id.header, &sample, event);
8315 ret = perf_output_begin(&handle, event, se->event_id.header.size);
8319 if (event->ctx->task)
8320 perf_output_put(&handle, se->event_id.header);
8322 perf_output_put(&handle, se->event_id);
8324 perf_event__output_id_sample(event, &handle, &sample);
8326 perf_output_end(&handle);
8329 static void perf_event_switch(struct task_struct *task,
8330 struct task_struct *next_prev, bool sched_in)
8332 struct perf_switch_event switch_event;
8334 /* N.B. caller checks nr_switch_events != 0 */
8336 switch_event = (struct perf_switch_event){
8338 .next_prev = next_prev,
8342 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8345 /* .next_prev_pid */
8346 /* .next_prev_tid */
8350 if (!sched_in && task->state == TASK_RUNNING)
8351 switch_event.event_id.header.misc |=
8352 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8354 perf_iterate_sb(perf_event_switch_output,
8360 * IRQ throttle logging
8363 static void perf_log_throttle(struct perf_event *event, int enable)
8365 struct perf_output_handle handle;
8366 struct perf_sample_data sample;
8370 struct perf_event_header header;
8374 } throttle_event = {
8376 .type = PERF_RECORD_THROTTLE,
8378 .size = sizeof(throttle_event),
8380 .time = perf_event_clock(event),
8381 .id = primary_event_id(event),
8382 .stream_id = event->id,
8386 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8388 perf_event_header__init_id(&throttle_event.header, &sample, event);
8390 ret = perf_output_begin(&handle, event,
8391 throttle_event.header.size);
8395 perf_output_put(&handle, throttle_event);
8396 perf_event__output_id_sample(event, &handle, &sample);
8397 perf_output_end(&handle);
8401 * ksymbol register/unregister tracking
8404 struct perf_ksymbol_event {
8408 struct perf_event_header header;
8416 static int perf_event_ksymbol_match(struct perf_event *event)
8418 return event->attr.ksymbol;
8421 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8423 struct perf_ksymbol_event *ksymbol_event = data;
8424 struct perf_output_handle handle;
8425 struct perf_sample_data sample;
8428 if (!perf_event_ksymbol_match(event))
8431 perf_event_header__init_id(&ksymbol_event->event_id.header,
8433 ret = perf_output_begin(&handle, event,
8434 ksymbol_event->event_id.header.size);
8438 perf_output_put(&handle, ksymbol_event->event_id);
8439 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8440 perf_event__output_id_sample(event, &handle, &sample);
8442 perf_output_end(&handle);
8445 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8448 struct perf_ksymbol_event ksymbol_event;
8449 char name[KSYM_NAME_LEN];
8453 if (!atomic_read(&nr_ksymbol_events))
8456 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8457 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8460 strlcpy(name, sym, KSYM_NAME_LEN);
8461 name_len = strlen(name) + 1;
8462 while (!IS_ALIGNED(name_len, sizeof(u64)))
8463 name[name_len++] = '\0';
8464 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8467 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8469 ksymbol_event = (struct perf_ksymbol_event){
8471 .name_len = name_len,
8474 .type = PERF_RECORD_KSYMBOL,
8475 .size = sizeof(ksymbol_event.event_id) +
8480 .ksym_type = ksym_type,
8485 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8488 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8492 * bpf program load/unload tracking
8495 struct perf_bpf_event {
8496 struct bpf_prog *prog;
8498 struct perf_event_header header;
8502 u8 tag[BPF_TAG_SIZE];
8506 static int perf_event_bpf_match(struct perf_event *event)
8508 return event->attr.bpf_event;
8511 static void perf_event_bpf_output(struct perf_event *event, void *data)
8513 struct perf_bpf_event *bpf_event = data;
8514 struct perf_output_handle handle;
8515 struct perf_sample_data sample;
8518 if (!perf_event_bpf_match(event))
8521 perf_event_header__init_id(&bpf_event->event_id.header,
8523 ret = perf_output_begin(&handle, event,
8524 bpf_event->event_id.header.size);
8528 perf_output_put(&handle, bpf_event->event_id);
8529 perf_event__output_id_sample(event, &handle, &sample);
8531 perf_output_end(&handle);
8534 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8535 enum perf_bpf_event_type type)
8537 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8540 if (prog->aux->func_cnt == 0) {
8541 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8542 (u64)(unsigned long)prog->bpf_func,
8543 prog->jited_len, unregister,
8544 prog->aux->ksym.name);
8546 for (i = 0; i < prog->aux->func_cnt; i++) {
8547 struct bpf_prog *subprog = prog->aux->func[i];
8550 PERF_RECORD_KSYMBOL_TYPE_BPF,
8551 (u64)(unsigned long)subprog->bpf_func,
8552 subprog->jited_len, unregister,
8553 prog->aux->ksym.name);
8558 void perf_event_bpf_event(struct bpf_prog *prog,
8559 enum perf_bpf_event_type type,
8562 struct perf_bpf_event bpf_event;
8564 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8565 type >= PERF_BPF_EVENT_MAX)
8569 case PERF_BPF_EVENT_PROG_LOAD:
8570 case PERF_BPF_EVENT_PROG_UNLOAD:
8571 if (atomic_read(&nr_ksymbol_events))
8572 perf_event_bpf_emit_ksymbols(prog, type);
8578 if (!atomic_read(&nr_bpf_events))
8581 bpf_event = (struct perf_bpf_event){
8585 .type = PERF_RECORD_BPF_EVENT,
8586 .size = sizeof(bpf_event.event_id),
8590 .id = prog->aux->id,
8594 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8596 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8597 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8600 void perf_event_itrace_started(struct perf_event *event)
8602 event->attach_state |= PERF_ATTACH_ITRACE;
8605 static void perf_log_itrace_start(struct perf_event *event)
8607 struct perf_output_handle handle;
8608 struct perf_sample_data sample;
8609 struct perf_aux_event {
8610 struct perf_event_header header;
8617 event = event->parent;
8619 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8620 event->attach_state & PERF_ATTACH_ITRACE)
8623 rec.header.type = PERF_RECORD_ITRACE_START;
8624 rec.header.misc = 0;
8625 rec.header.size = sizeof(rec);
8626 rec.pid = perf_event_pid(event, current);
8627 rec.tid = perf_event_tid(event, current);
8629 perf_event_header__init_id(&rec.header, &sample, event);
8630 ret = perf_output_begin(&handle, event, rec.header.size);
8635 perf_output_put(&handle, rec);
8636 perf_event__output_id_sample(event, &handle, &sample);
8638 perf_output_end(&handle);
8642 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8644 struct hw_perf_event *hwc = &event->hw;
8648 seq = __this_cpu_read(perf_throttled_seq);
8649 if (seq != hwc->interrupts_seq) {
8650 hwc->interrupts_seq = seq;
8651 hwc->interrupts = 1;
8654 if (unlikely(throttle
8655 && hwc->interrupts >= max_samples_per_tick)) {
8656 __this_cpu_inc(perf_throttled_count);
8657 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8658 hwc->interrupts = MAX_INTERRUPTS;
8659 perf_log_throttle(event, 0);
8664 if (event->attr.freq) {
8665 u64 now = perf_clock();
8666 s64 delta = now - hwc->freq_time_stamp;
8668 hwc->freq_time_stamp = now;
8670 if (delta > 0 && delta < 2*TICK_NSEC)
8671 perf_adjust_period(event, delta, hwc->last_period, true);
8677 int perf_event_account_interrupt(struct perf_event *event)
8679 return __perf_event_account_interrupt(event, 1);
8683 * Generic event overflow handling, sampling.
8686 static int __perf_event_overflow(struct perf_event *event,
8687 int throttle, struct perf_sample_data *data,
8688 struct pt_regs *regs)
8690 int events = atomic_read(&event->event_limit);
8694 * Non-sampling counters might still use the PMI to fold short
8695 * hardware counters, ignore those.
8697 if (unlikely(!is_sampling_event(event)))
8700 ret = __perf_event_account_interrupt(event, throttle);
8703 * XXX event_limit might not quite work as expected on inherited
8707 event->pending_kill = POLL_IN;
8708 if (events && atomic_dec_and_test(&event->event_limit)) {
8710 event->pending_kill = POLL_HUP;
8712 perf_event_disable_inatomic(event);
8715 READ_ONCE(event->overflow_handler)(event, data, regs);
8717 if (*perf_event_fasync(event) && event->pending_kill) {
8718 event->pending_wakeup = 1;
8719 irq_work_queue(&event->pending);
8725 int perf_event_overflow(struct perf_event *event,
8726 struct perf_sample_data *data,
8727 struct pt_regs *regs)
8729 return __perf_event_overflow(event, 1, data, regs);
8733 * Generic software event infrastructure
8736 struct swevent_htable {
8737 struct swevent_hlist *swevent_hlist;
8738 struct mutex hlist_mutex;
8741 /* Recursion avoidance in each contexts */
8742 int recursion[PERF_NR_CONTEXTS];
8745 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8748 * We directly increment event->count and keep a second value in
8749 * event->hw.period_left to count intervals. This period event
8750 * is kept in the range [-sample_period, 0] so that we can use the
8754 u64 perf_swevent_set_period(struct perf_event *event)
8756 struct hw_perf_event *hwc = &event->hw;
8757 u64 period = hwc->last_period;
8761 hwc->last_period = hwc->sample_period;
8764 old = val = local64_read(&hwc->period_left);
8768 nr = div64_u64(period + val, period);
8769 offset = nr * period;
8771 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8777 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8778 struct perf_sample_data *data,
8779 struct pt_regs *regs)
8781 struct hw_perf_event *hwc = &event->hw;
8785 overflow = perf_swevent_set_period(event);
8787 if (hwc->interrupts == MAX_INTERRUPTS)
8790 for (; overflow; overflow--) {
8791 if (__perf_event_overflow(event, throttle,
8794 * We inhibit the overflow from happening when
8795 * hwc->interrupts == MAX_INTERRUPTS.
8803 static void perf_swevent_event(struct perf_event *event, u64 nr,
8804 struct perf_sample_data *data,
8805 struct pt_regs *regs)
8807 struct hw_perf_event *hwc = &event->hw;
8809 local64_add(nr, &event->count);
8814 if (!is_sampling_event(event))
8817 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8819 return perf_swevent_overflow(event, 1, data, regs);
8821 data->period = event->hw.last_period;
8823 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8824 return perf_swevent_overflow(event, 1, data, regs);
8826 if (local64_add_negative(nr, &hwc->period_left))
8829 perf_swevent_overflow(event, 0, data, regs);
8832 static int perf_exclude_event(struct perf_event *event,
8833 struct pt_regs *regs)
8835 if (event->hw.state & PERF_HES_STOPPED)
8839 if (event->attr.exclude_user && user_mode(regs))
8842 if (event->attr.exclude_kernel && !user_mode(regs))
8849 static int perf_swevent_match(struct perf_event *event,
8850 enum perf_type_id type,
8852 struct perf_sample_data *data,
8853 struct pt_regs *regs)
8855 if (event->attr.type != type)
8858 if (event->attr.config != event_id)
8861 if (perf_exclude_event(event, regs))
8867 static inline u64 swevent_hash(u64 type, u32 event_id)
8869 u64 val = event_id | (type << 32);
8871 return hash_64(val, SWEVENT_HLIST_BITS);
8874 static inline struct hlist_head *
8875 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
8877 u64 hash = swevent_hash(type, event_id);
8879 return &hlist->heads[hash];
8882 /* For the read side: events when they trigger */
8883 static inline struct hlist_head *
8884 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
8886 struct swevent_hlist *hlist;
8888 hlist = rcu_dereference(swhash->swevent_hlist);
8892 return __find_swevent_head(hlist, type, event_id);
8895 /* For the event head insertion and removal in the hlist */
8896 static inline struct hlist_head *
8897 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
8899 struct swevent_hlist *hlist;
8900 u32 event_id = event->attr.config;
8901 u64 type = event->attr.type;
8904 * Event scheduling is always serialized against hlist allocation
8905 * and release. Which makes the protected version suitable here.
8906 * The context lock guarantees that.
8908 hlist = rcu_dereference_protected(swhash->swevent_hlist,
8909 lockdep_is_held(&event->ctx->lock));
8913 return __find_swevent_head(hlist, type, event_id);
8916 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
8918 struct perf_sample_data *data,
8919 struct pt_regs *regs)
8921 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8922 struct perf_event *event;
8923 struct hlist_head *head;
8926 head = find_swevent_head_rcu(swhash, type, event_id);
8930 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8931 if (perf_swevent_match(event, type, event_id, data, regs))
8932 perf_swevent_event(event, nr, data, regs);
8938 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
8940 int perf_swevent_get_recursion_context(void)
8942 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8944 return get_recursion_context(swhash->recursion);
8946 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
8948 void perf_swevent_put_recursion_context(int rctx)
8950 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8952 put_recursion_context(swhash->recursion, rctx);
8955 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8957 struct perf_sample_data data;
8959 if (WARN_ON_ONCE(!regs))
8962 perf_sample_data_init(&data, addr, 0);
8963 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
8966 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8970 preempt_disable_notrace();
8971 rctx = perf_swevent_get_recursion_context();
8972 if (unlikely(rctx < 0))
8975 ___perf_sw_event(event_id, nr, regs, addr);
8977 perf_swevent_put_recursion_context(rctx);
8979 preempt_enable_notrace();
8982 static void perf_swevent_read(struct perf_event *event)
8986 static int perf_swevent_add(struct perf_event *event, int flags)
8988 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8989 struct hw_perf_event *hwc = &event->hw;
8990 struct hlist_head *head;
8992 if (is_sampling_event(event)) {
8993 hwc->last_period = hwc->sample_period;
8994 perf_swevent_set_period(event);
8997 hwc->state = !(flags & PERF_EF_START);
8999 head = find_swevent_head(swhash, event);
9000 if (WARN_ON_ONCE(!head))
9003 hlist_add_head_rcu(&event->hlist_entry, head);
9004 perf_event_update_userpage(event);
9009 static void perf_swevent_del(struct perf_event *event, int flags)
9011 hlist_del_rcu(&event->hlist_entry);
9014 static void perf_swevent_start(struct perf_event *event, int flags)
9016 event->hw.state = 0;
9019 static void perf_swevent_stop(struct perf_event *event, int flags)
9021 event->hw.state = PERF_HES_STOPPED;
9024 /* Deref the hlist from the update side */
9025 static inline struct swevent_hlist *
9026 swevent_hlist_deref(struct swevent_htable *swhash)
9028 return rcu_dereference_protected(swhash->swevent_hlist,
9029 lockdep_is_held(&swhash->hlist_mutex));
9032 static void swevent_hlist_release(struct swevent_htable *swhash)
9034 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9039 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9040 kfree_rcu(hlist, rcu_head);
9043 static void swevent_hlist_put_cpu(int cpu)
9045 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9047 mutex_lock(&swhash->hlist_mutex);
9049 if (!--swhash->hlist_refcount)
9050 swevent_hlist_release(swhash);
9052 mutex_unlock(&swhash->hlist_mutex);
9055 static void swevent_hlist_put(void)
9059 for_each_possible_cpu(cpu)
9060 swevent_hlist_put_cpu(cpu);
9063 static int swevent_hlist_get_cpu(int cpu)
9065 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9068 mutex_lock(&swhash->hlist_mutex);
9069 if (!swevent_hlist_deref(swhash) &&
9070 cpumask_test_cpu(cpu, perf_online_mask)) {
9071 struct swevent_hlist *hlist;
9073 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9078 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9080 swhash->hlist_refcount++;
9082 mutex_unlock(&swhash->hlist_mutex);
9087 static int swevent_hlist_get(void)
9089 int err, cpu, failed_cpu;
9091 mutex_lock(&pmus_lock);
9092 for_each_possible_cpu(cpu) {
9093 err = swevent_hlist_get_cpu(cpu);
9099 mutex_unlock(&pmus_lock);
9102 for_each_possible_cpu(cpu) {
9103 if (cpu == failed_cpu)
9105 swevent_hlist_put_cpu(cpu);
9107 mutex_unlock(&pmus_lock);
9111 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9113 static void sw_perf_event_destroy(struct perf_event *event)
9115 u64 event_id = event->attr.config;
9117 WARN_ON(event->parent);
9119 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9120 swevent_hlist_put();
9123 static int perf_swevent_init(struct perf_event *event)
9125 u64 event_id = event->attr.config;
9127 if (event->attr.type != PERF_TYPE_SOFTWARE)
9131 * no branch sampling for software events
9133 if (has_branch_stack(event))
9137 case PERF_COUNT_SW_CPU_CLOCK:
9138 case PERF_COUNT_SW_TASK_CLOCK:
9145 if (event_id >= PERF_COUNT_SW_MAX)
9148 if (!event->parent) {
9151 err = swevent_hlist_get();
9155 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9156 event->destroy = sw_perf_event_destroy;
9162 static struct pmu perf_swevent = {
9163 .task_ctx_nr = perf_sw_context,
9165 .capabilities = PERF_PMU_CAP_NO_NMI,
9167 .event_init = perf_swevent_init,
9168 .add = perf_swevent_add,
9169 .del = perf_swevent_del,
9170 .start = perf_swevent_start,
9171 .stop = perf_swevent_stop,
9172 .read = perf_swevent_read,
9175 #ifdef CONFIG_EVENT_TRACING
9177 static int perf_tp_filter_match(struct perf_event *event,
9178 struct perf_sample_data *data)
9180 void *record = data->raw->frag.data;
9182 /* only top level events have filters set */
9184 event = event->parent;
9186 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9191 static int perf_tp_event_match(struct perf_event *event,
9192 struct perf_sample_data *data,
9193 struct pt_regs *regs)
9195 if (event->hw.state & PERF_HES_STOPPED)
9198 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9200 if (event->attr.exclude_kernel && !user_mode(regs))
9203 if (!perf_tp_filter_match(event, data))
9209 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9210 struct trace_event_call *call, u64 count,
9211 struct pt_regs *regs, struct hlist_head *head,
9212 struct task_struct *task)
9214 if (bpf_prog_array_valid(call)) {
9215 *(struct pt_regs **)raw_data = regs;
9216 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9217 perf_swevent_put_recursion_context(rctx);
9221 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9224 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9226 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9227 struct pt_regs *regs, struct hlist_head *head, int rctx,
9228 struct task_struct *task)
9230 struct perf_sample_data data;
9231 struct perf_event *event;
9233 struct perf_raw_record raw = {
9240 perf_sample_data_init(&data, 0, 0);
9243 perf_trace_buf_update(record, event_type);
9245 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9246 if (perf_tp_event_match(event, &data, regs))
9247 perf_swevent_event(event, count, &data, regs);
9251 * If we got specified a target task, also iterate its context and
9252 * deliver this event there too.
9254 if (task && task != current) {
9255 struct perf_event_context *ctx;
9256 struct trace_entry *entry = record;
9259 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9263 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9264 if (event->cpu != smp_processor_id())
9266 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9268 if (event->attr.config != entry->type)
9270 if (perf_tp_event_match(event, &data, regs))
9271 perf_swevent_event(event, count, &data, regs);
9277 perf_swevent_put_recursion_context(rctx);
9279 EXPORT_SYMBOL_GPL(perf_tp_event);
9281 static void tp_perf_event_destroy(struct perf_event *event)
9283 perf_trace_destroy(event);
9286 static int perf_tp_event_init(struct perf_event *event)
9290 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9294 * no branch sampling for tracepoint events
9296 if (has_branch_stack(event))
9299 err = perf_trace_init(event);
9303 event->destroy = tp_perf_event_destroy;
9308 static struct pmu perf_tracepoint = {
9309 .task_ctx_nr = perf_sw_context,
9311 .event_init = perf_tp_event_init,
9312 .add = perf_trace_add,
9313 .del = perf_trace_del,
9314 .start = perf_swevent_start,
9315 .stop = perf_swevent_stop,
9316 .read = perf_swevent_read,
9319 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9321 * Flags in config, used by dynamic PMU kprobe and uprobe
9322 * The flags should match following PMU_FORMAT_ATTR().
9324 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9325 * if not set, create kprobe/uprobe
9327 * The following values specify a reference counter (or semaphore in the
9328 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9329 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9331 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9332 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9334 enum perf_probe_config {
9335 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9336 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9337 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9340 PMU_FORMAT_ATTR(retprobe, "config:0");
9343 #ifdef CONFIG_KPROBE_EVENTS
9344 static struct attribute *kprobe_attrs[] = {
9345 &format_attr_retprobe.attr,
9349 static struct attribute_group kprobe_format_group = {
9351 .attrs = kprobe_attrs,
9354 static const struct attribute_group *kprobe_attr_groups[] = {
9355 &kprobe_format_group,
9359 static int perf_kprobe_event_init(struct perf_event *event);
9360 static struct pmu perf_kprobe = {
9361 .task_ctx_nr = perf_sw_context,
9362 .event_init = perf_kprobe_event_init,
9363 .add = perf_trace_add,
9364 .del = perf_trace_del,
9365 .start = perf_swevent_start,
9366 .stop = perf_swevent_stop,
9367 .read = perf_swevent_read,
9368 .attr_groups = kprobe_attr_groups,
9371 static int perf_kprobe_event_init(struct perf_event *event)
9376 if (event->attr.type != perf_kprobe.type)
9379 if (!capable(CAP_SYS_ADMIN))
9383 * no branch sampling for probe events
9385 if (has_branch_stack(event))
9388 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9389 err = perf_kprobe_init(event, is_retprobe);
9393 event->destroy = perf_kprobe_destroy;
9397 #endif /* CONFIG_KPROBE_EVENTS */
9399 #ifdef CONFIG_UPROBE_EVENTS
9400 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9402 static struct attribute *uprobe_attrs[] = {
9403 &format_attr_retprobe.attr,
9404 &format_attr_ref_ctr_offset.attr,
9408 static struct attribute_group uprobe_format_group = {
9410 .attrs = uprobe_attrs,
9413 static const struct attribute_group *uprobe_attr_groups[] = {
9414 &uprobe_format_group,
9418 static int perf_uprobe_event_init(struct perf_event *event);
9419 static struct pmu perf_uprobe = {
9420 .task_ctx_nr = perf_sw_context,
9421 .event_init = perf_uprobe_event_init,
9422 .add = perf_trace_add,
9423 .del = perf_trace_del,
9424 .start = perf_swevent_start,
9425 .stop = perf_swevent_stop,
9426 .read = perf_swevent_read,
9427 .attr_groups = uprobe_attr_groups,
9430 static int perf_uprobe_event_init(struct perf_event *event)
9433 unsigned long ref_ctr_offset;
9436 if (event->attr.type != perf_uprobe.type)
9439 if (!capable(CAP_SYS_ADMIN))
9443 * no branch sampling for probe events
9445 if (has_branch_stack(event))
9448 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9449 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9450 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9454 event->destroy = perf_uprobe_destroy;
9458 #endif /* CONFIG_UPROBE_EVENTS */
9460 static inline void perf_tp_register(void)
9462 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9463 #ifdef CONFIG_KPROBE_EVENTS
9464 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9466 #ifdef CONFIG_UPROBE_EVENTS
9467 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9471 static void perf_event_free_filter(struct perf_event *event)
9473 ftrace_profile_free_filter(event);
9476 #ifdef CONFIG_BPF_SYSCALL
9477 static void bpf_overflow_handler(struct perf_event *event,
9478 struct perf_sample_data *data,
9479 struct pt_regs *regs)
9481 struct bpf_perf_event_data_kern ctx = {
9487 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9488 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9491 ret = BPF_PROG_RUN(event->prog, &ctx);
9494 __this_cpu_dec(bpf_prog_active);
9498 event->orig_overflow_handler(event, data, regs);
9501 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9503 struct bpf_prog *prog;
9505 if (event->overflow_handler_context)
9506 /* hw breakpoint or kernel counter */
9512 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9514 return PTR_ERR(prog);
9517 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9518 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9522 static void perf_event_free_bpf_handler(struct perf_event *event)
9524 struct bpf_prog *prog = event->prog;
9529 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9534 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9538 static void perf_event_free_bpf_handler(struct perf_event *event)
9544 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9545 * with perf_event_open()
9547 static inline bool perf_event_is_tracing(struct perf_event *event)
9549 if (event->pmu == &perf_tracepoint)
9551 #ifdef CONFIG_KPROBE_EVENTS
9552 if (event->pmu == &perf_kprobe)
9555 #ifdef CONFIG_UPROBE_EVENTS
9556 if (event->pmu == &perf_uprobe)
9562 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9564 bool is_kprobe, is_tracepoint, is_syscall_tp;
9565 struct bpf_prog *prog;
9568 if (!perf_event_is_tracing(event))
9569 return perf_event_set_bpf_handler(event, prog_fd);
9571 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9572 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9573 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9574 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9575 /* bpf programs can only be attached to u/kprobe or tracepoint */
9578 prog = bpf_prog_get(prog_fd);
9580 return PTR_ERR(prog);
9582 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9583 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9584 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9585 /* valid fd, but invalid bpf program type */
9590 /* Kprobe override only works for kprobes, not uprobes. */
9591 if (prog->kprobe_override &&
9592 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9597 if (is_tracepoint || is_syscall_tp) {
9598 int off = trace_event_get_offsets(event->tp_event);
9600 if (prog->aux->max_ctx_offset > off) {
9606 ret = perf_event_attach_bpf_prog(event, prog);
9612 static void perf_event_free_bpf_prog(struct perf_event *event)
9614 if (!perf_event_is_tracing(event)) {
9615 perf_event_free_bpf_handler(event);
9618 perf_event_detach_bpf_prog(event);
9623 static inline void perf_tp_register(void)
9627 static void perf_event_free_filter(struct perf_event *event)
9631 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9636 static void perf_event_free_bpf_prog(struct perf_event *event)
9639 #endif /* CONFIG_EVENT_TRACING */
9641 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9642 void perf_bp_event(struct perf_event *bp, void *data)
9644 struct perf_sample_data sample;
9645 struct pt_regs *regs = data;
9647 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9649 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9650 perf_swevent_event(bp, 1, &sample, regs);
9655 * Allocate a new address filter
9657 static struct perf_addr_filter *
9658 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9660 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9661 struct perf_addr_filter *filter;
9663 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9667 INIT_LIST_HEAD(&filter->entry);
9668 list_add_tail(&filter->entry, filters);
9673 static void free_filters_list(struct list_head *filters)
9675 struct perf_addr_filter *filter, *iter;
9677 list_for_each_entry_safe(filter, iter, filters, entry) {
9678 path_put(&filter->path);
9679 list_del(&filter->entry);
9685 * Free existing address filters and optionally install new ones
9687 static void perf_addr_filters_splice(struct perf_event *event,
9688 struct list_head *head)
9690 unsigned long flags;
9693 if (!has_addr_filter(event))
9696 /* don't bother with children, they don't have their own filters */
9700 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9702 list_splice_init(&event->addr_filters.list, &list);
9704 list_splice(head, &event->addr_filters.list);
9706 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9708 free_filters_list(&list);
9712 * Scan through mm's vmas and see if one of them matches the
9713 * @filter; if so, adjust filter's address range.
9714 * Called with mm::mmap_sem down for reading.
9716 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9717 struct mm_struct *mm,
9718 struct perf_addr_filter_range *fr)
9720 struct vm_area_struct *vma;
9722 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9726 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9732 * Update event's address range filters based on the
9733 * task's existing mappings, if any.
9735 static void perf_event_addr_filters_apply(struct perf_event *event)
9737 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9738 struct task_struct *task = READ_ONCE(event->ctx->task);
9739 struct perf_addr_filter *filter;
9740 struct mm_struct *mm = NULL;
9741 unsigned int count = 0;
9742 unsigned long flags;
9745 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9746 * will stop on the parent's child_mutex that our caller is also holding
9748 if (task == TASK_TOMBSTONE)
9751 if (ifh->nr_file_filters) {
9752 mm = get_task_mm(event->ctx->task);
9756 down_read(&mm->mmap_sem);
9759 raw_spin_lock_irqsave(&ifh->lock, flags);
9760 list_for_each_entry(filter, &ifh->list, entry) {
9761 if (filter->path.dentry) {
9763 * Adjust base offset if the filter is associated to a
9764 * binary that needs to be mapped:
9766 event->addr_filter_ranges[count].start = 0;
9767 event->addr_filter_ranges[count].size = 0;
9769 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9771 event->addr_filter_ranges[count].start = filter->offset;
9772 event->addr_filter_ranges[count].size = filter->size;
9778 event->addr_filters_gen++;
9779 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9781 if (ifh->nr_file_filters) {
9782 up_read(&mm->mmap_sem);
9788 perf_event_stop(event, 1);
9792 * Address range filtering: limiting the data to certain
9793 * instruction address ranges. Filters are ioctl()ed to us from
9794 * userspace as ascii strings.
9796 * Filter string format:
9799 * where ACTION is one of the
9800 * * "filter": limit the trace to this region
9801 * * "start": start tracing from this address
9802 * * "stop": stop tracing at this address/region;
9804 * * for kernel addresses: <start address>[/<size>]
9805 * * for object files: <start address>[/<size>]@</path/to/object/file>
9807 * if <size> is not specified or is zero, the range is treated as a single
9808 * address; not valid for ACTION=="filter".
9822 IF_STATE_ACTION = 0,
9827 static const match_table_t if_tokens = {
9828 { IF_ACT_FILTER, "filter" },
9829 { IF_ACT_START, "start" },
9830 { IF_ACT_STOP, "stop" },
9831 { IF_SRC_FILE, "%u/%u@%s" },
9832 { IF_SRC_KERNEL, "%u/%u" },
9833 { IF_SRC_FILEADDR, "%u@%s" },
9834 { IF_SRC_KERNELADDR, "%u" },
9835 { IF_ACT_NONE, NULL },
9839 * Address filter string parser
9842 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9843 struct list_head *filters)
9845 struct perf_addr_filter *filter = NULL;
9846 char *start, *orig, *filename = NULL;
9847 substring_t args[MAX_OPT_ARGS];
9848 int state = IF_STATE_ACTION, token;
9849 unsigned int kernel = 0;
9852 orig = fstr = kstrdup(fstr, GFP_KERNEL);
9856 while ((start = strsep(&fstr, " ,\n")) != NULL) {
9857 static const enum perf_addr_filter_action_t actions[] = {
9858 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
9859 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
9860 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
9867 /* filter definition begins */
9868 if (state == IF_STATE_ACTION) {
9869 filter = perf_addr_filter_new(event, filters);
9874 token = match_token(start, if_tokens, args);
9879 if (state != IF_STATE_ACTION)
9882 filter->action = actions[token];
9883 state = IF_STATE_SOURCE;
9886 case IF_SRC_KERNELADDR:
9891 case IF_SRC_FILEADDR:
9893 if (state != IF_STATE_SOURCE)
9897 ret = kstrtoul(args[0].from, 0, &filter->offset);
9901 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
9903 ret = kstrtoul(args[1].from, 0, &filter->size);
9908 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
9909 int fpos = token == IF_SRC_FILE ? 2 : 1;
9911 filename = match_strdup(&args[fpos]);
9918 state = IF_STATE_END;
9926 * Filter definition is fully parsed, validate and install it.
9927 * Make sure that it doesn't contradict itself or the event's
9930 if (state == IF_STATE_END) {
9932 if (kernel && event->attr.exclude_kernel)
9936 * ACTION "filter" must have a non-zero length region
9939 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
9948 * For now, we only support file-based filters
9949 * in per-task events; doing so for CPU-wide
9950 * events requires additional context switching
9951 * trickery, since same object code will be
9952 * mapped at different virtual addresses in
9953 * different processes.
9956 if (!event->ctx->task)
9957 goto fail_free_name;
9959 /* look up the path and grab its inode */
9960 ret = kern_path(filename, LOOKUP_FOLLOW,
9963 goto fail_free_name;
9969 if (!filter->path.dentry ||
9970 !S_ISREG(d_inode(filter->path.dentry)
9974 event->addr_filters.nr_file_filters++;
9977 /* ready to consume more filters */
9978 state = IF_STATE_ACTION;
9983 if (state != IF_STATE_ACTION)
9993 free_filters_list(filters);
10000 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10002 LIST_HEAD(filters);
10006 * Since this is called in perf_ioctl() path, we're already holding
10009 lockdep_assert_held(&event->ctx->mutex);
10011 if (WARN_ON_ONCE(event->parent))
10014 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10016 goto fail_clear_files;
10018 ret = event->pmu->addr_filters_validate(&filters);
10020 goto fail_free_filters;
10022 /* remove existing filters, if any */
10023 perf_addr_filters_splice(event, &filters);
10025 /* install new filters */
10026 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10031 free_filters_list(&filters);
10034 event->addr_filters.nr_file_filters = 0;
10039 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10044 filter_str = strndup_user(arg, PAGE_SIZE);
10045 if (IS_ERR(filter_str))
10046 return PTR_ERR(filter_str);
10048 #ifdef CONFIG_EVENT_TRACING
10049 if (perf_event_is_tracing(event)) {
10050 struct perf_event_context *ctx = event->ctx;
10053 * Beware, here be dragons!!
10055 * the tracepoint muck will deadlock against ctx->mutex, but
10056 * the tracepoint stuff does not actually need it. So
10057 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10058 * already have a reference on ctx.
10060 * This can result in event getting moved to a different ctx,
10061 * but that does not affect the tracepoint state.
10063 mutex_unlock(&ctx->mutex);
10064 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10065 mutex_lock(&ctx->mutex);
10068 if (has_addr_filter(event))
10069 ret = perf_event_set_addr_filter(event, filter_str);
10076 * hrtimer based swevent callback
10079 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10081 enum hrtimer_restart ret = HRTIMER_RESTART;
10082 struct perf_sample_data data;
10083 struct pt_regs *regs;
10084 struct perf_event *event;
10087 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10089 if (event->state != PERF_EVENT_STATE_ACTIVE)
10090 return HRTIMER_NORESTART;
10092 event->pmu->read(event);
10094 perf_sample_data_init(&data, 0, event->hw.last_period);
10095 regs = get_irq_regs();
10097 if (regs && !perf_exclude_event(event, regs)) {
10098 if (!(event->attr.exclude_idle && is_idle_task(current)))
10099 if (__perf_event_overflow(event, 1, &data, regs))
10100 ret = HRTIMER_NORESTART;
10103 period = max_t(u64, 10000, event->hw.sample_period);
10104 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10109 static void perf_swevent_start_hrtimer(struct perf_event *event)
10111 struct hw_perf_event *hwc = &event->hw;
10114 if (!is_sampling_event(event))
10117 period = local64_read(&hwc->period_left);
10122 local64_set(&hwc->period_left, 0);
10124 period = max_t(u64, 10000, hwc->sample_period);
10126 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10127 HRTIMER_MODE_REL_PINNED_HARD);
10130 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10132 struct hw_perf_event *hwc = &event->hw;
10134 if (is_sampling_event(event)) {
10135 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10136 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10138 hrtimer_cancel(&hwc->hrtimer);
10142 static void perf_swevent_init_hrtimer(struct perf_event *event)
10144 struct hw_perf_event *hwc = &event->hw;
10146 if (!is_sampling_event(event))
10149 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10150 hwc->hrtimer.function = perf_swevent_hrtimer;
10153 * Since hrtimers have a fixed rate, we can do a static freq->period
10154 * mapping and avoid the whole period adjust feedback stuff.
10156 if (event->attr.freq) {
10157 long freq = event->attr.sample_freq;
10159 event->attr.sample_period = NSEC_PER_SEC / freq;
10160 hwc->sample_period = event->attr.sample_period;
10161 local64_set(&hwc->period_left, hwc->sample_period);
10162 hwc->last_period = hwc->sample_period;
10163 event->attr.freq = 0;
10168 * Software event: cpu wall time clock
10171 static void cpu_clock_event_update(struct perf_event *event)
10176 now = local_clock();
10177 prev = local64_xchg(&event->hw.prev_count, now);
10178 local64_add(now - prev, &event->count);
10181 static void cpu_clock_event_start(struct perf_event *event, int flags)
10183 local64_set(&event->hw.prev_count, local_clock());
10184 perf_swevent_start_hrtimer(event);
10187 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10189 perf_swevent_cancel_hrtimer(event);
10190 cpu_clock_event_update(event);
10193 static int cpu_clock_event_add(struct perf_event *event, int flags)
10195 if (flags & PERF_EF_START)
10196 cpu_clock_event_start(event, flags);
10197 perf_event_update_userpage(event);
10202 static void cpu_clock_event_del(struct perf_event *event, int flags)
10204 cpu_clock_event_stop(event, flags);
10207 static void cpu_clock_event_read(struct perf_event *event)
10209 cpu_clock_event_update(event);
10212 static int cpu_clock_event_init(struct perf_event *event)
10214 if (event->attr.type != PERF_TYPE_SOFTWARE)
10217 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10221 * no branch sampling for software events
10223 if (has_branch_stack(event))
10224 return -EOPNOTSUPP;
10226 perf_swevent_init_hrtimer(event);
10231 static struct pmu perf_cpu_clock = {
10232 .task_ctx_nr = perf_sw_context,
10234 .capabilities = PERF_PMU_CAP_NO_NMI,
10236 .event_init = cpu_clock_event_init,
10237 .add = cpu_clock_event_add,
10238 .del = cpu_clock_event_del,
10239 .start = cpu_clock_event_start,
10240 .stop = cpu_clock_event_stop,
10241 .read = cpu_clock_event_read,
10245 * Software event: task time clock
10248 static void task_clock_event_update(struct perf_event *event, u64 now)
10253 prev = local64_xchg(&event->hw.prev_count, now);
10254 delta = now - prev;
10255 local64_add(delta, &event->count);
10258 static void task_clock_event_start(struct perf_event *event, int flags)
10260 local64_set(&event->hw.prev_count, event->ctx->time);
10261 perf_swevent_start_hrtimer(event);
10264 static void task_clock_event_stop(struct perf_event *event, int flags)
10266 perf_swevent_cancel_hrtimer(event);
10267 task_clock_event_update(event, event->ctx->time);
10270 static int task_clock_event_add(struct perf_event *event, int flags)
10272 if (flags & PERF_EF_START)
10273 task_clock_event_start(event, flags);
10274 perf_event_update_userpage(event);
10279 static void task_clock_event_del(struct perf_event *event, int flags)
10281 task_clock_event_stop(event, PERF_EF_UPDATE);
10284 static void task_clock_event_read(struct perf_event *event)
10286 u64 now = perf_clock();
10287 u64 delta = now - event->ctx->timestamp;
10288 u64 time = event->ctx->time + delta;
10290 task_clock_event_update(event, time);
10293 static int task_clock_event_init(struct perf_event *event)
10295 if (event->attr.type != PERF_TYPE_SOFTWARE)
10298 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10302 * no branch sampling for software events
10304 if (has_branch_stack(event))
10305 return -EOPNOTSUPP;
10307 perf_swevent_init_hrtimer(event);
10312 static struct pmu perf_task_clock = {
10313 .task_ctx_nr = perf_sw_context,
10315 .capabilities = PERF_PMU_CAP_NO_NMI,
10317 .event_init = task_clock_event_init,
10318 .add = task_clock_event_add,
10319 .del = task_clock_event_del,
10320 .start = task_clock_event_start,
10321 .stop = task_clock_event_stop,
10322 .read = task_clock_event_read,
10325 static void perf_pmu_nop_void(struct pmu *pmu)
10329 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10333 static int perf_pmu_nop_int(struct pmu *pmu)
10338 static int perf_event_nop_int(struct perf_event *event, u64 value)
10343 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10345 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10347 __this_cpu_write(nop_txn_flags, flags);
10349 if (flags & ~PERF_PMU_TXN_ADD)
10352 perf_pmu_disable(pmu);
10355 static int perf_pmu_commit_txn(struct pmu *pmu)
10357 unsigned int flags = __this_cpu_read(nop_txn_flags);
10359 __this_cpu_write(nop_txn_flags, 0);
10361 if (flags & ~PERF_PMU_TXN_ADD)
10364 perf_pmu_enable(pmu);
10368 static void perf_pmu_cancel_txn(struct pmu *pmu)
10370 unsigned int flags = __this_cpu_read(nop_txn_flags);
10372 __this_cpu_write(nop_txn_flags, 0);
10374 if (flags & ~PERF_PMU_TXN_ADD)
10377 perf_pmu_enable(pmu);
10380 static int perf_event_idx_default(struct perf_event *event)
10386 * Ensures all contexts with the same task_ctx_nr have the same
10387 * pmu_cpu_context too.
10389 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10396 list_for_each_entry(pmu, &pmus, entry) {
10397 if (pmu->task_ctx_nr == ctxn)
10398 return pmu->pmu_cpu_context;
10404 static void free_pmu_context(struct pmu *pmu)
10407 * Static contexts such as perf_sw_context have a global lifetime
10408 * and may be shared between different PMUs. Avoid freeing them
10409 * when a single PMU is going away.
10411 if (pmu->task_ctx_nr > perf_invalid_context)
10414 free_percpu(pmu->pmu_cpu_context);
10418 * Let userspace know that this PMU supports address range filtering:
10420 static ssize_t nr_addr_filters_show(struct device *dev,
10421 struct device_attribute *attr,
10424 struct pmu *pmu = dev_get_drvdata(dev);
10426 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10428 DEVICE_ATTR_RO(nr_addr_filters);
10430 static struct idr pmu_idr;
10433 type_show(struct device *dev, struct device_attribute *attr, char *page)
10435 struct pmu *pmu = dev_get_drvdata(dev);
10437 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10439 static DEVICE_ATTR_RO(type);
10442 perf_event_mux_interval_ms_show(struct device *dev,
10443 struct device_attribute *attr,
10446 struct pmu *pmu = dev_get_drvdata(dev);
10448 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10451 static DEFINE_MUTEX(mux_interval_mutex);
10454 perf_event_mux_interval_ms_store(struct device *dev,
10455 struct device_attribute *attr,
10456 const char *buf, size_t count)
10458 struct pmu *pmu = dev_get_drvdata(dev);
10459 int timer, cpu, ret;
10461 ret = kstrtoint(buf, 0, &timer);
10468 /* same value, noting to do */
10469 if (timer == pmu->hrtimer_interval_ms)
10472 mutex_lock(&mux_interval_mutex);
10473 pmu->hrtimer_interval_ms = timer;
10475 /* update all cpuctx for this PMU */
10477 for_each_online_cpu(cpu) {
10478 struct perf_cpu_context *cpuctx;
10479 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10480 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10482 cpu_function_call(cpu,
10483 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10485 cpus_read_unlock();
10486 mutex_unlock(&mux_interval_mutex);
10490 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10492 static struct attribute *pmu_dev_attrs[] = {
10493 &dev_attr_type.attr,
10494 &dev_attr_perf_event_mux_interval_ms.attr,
10497 ATTRIBUTE_GROUPS(pmu_dev);
10499 static int pmu_bus_running;
10500 static struct bus_type pmu_bus = {
10501 .name = "event_source",
10502 .dev_groups = pmu_dev_groups,
10505 static void pmu_dev_release(struct device *dev)
10510 static int pmu_dev_alloc(struct pmu *pmu)
10514 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10518 pmu->dev->groups = pmu->attr_groups;
10519 device_initialize(pmu->dev);
10520 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10524 dev_set_drvdata(pmu->dev, pmu);
10525 pmu->dev->bus = &pmu_bus;
10526 pmu->dev->release = pmu_dev_release;
10527 ret = device_add(pmu->dev);
10531 /* For PMUs with address filters, throw in an extra attribute: */
10532 if (pmu->nr_addr_filters)
10533 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10538 if (pmu->attr_update)
10539 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10548 device_del(pmu->dev);
10551 put_device(pmu->dev);
10555 static struct lock_class_key cpuctx_mutex;
10556 static struct lock_class_key cpuctx_lock;
10558 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10560 int cpu, ret, max = PERF_TYPE_MAX;
10562 mutex_lock(&pmus_lock);
10564 pmu->pmu_disable_count = alloc_percpu(int);
10565 if (!pmu->pmu_disable_count)
10573 if (type != PERF_TYPE_SOFTWARE) {
10577 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10581 WARN_ON(type >= 0 && ret != type);
10587 if (pmu_bus_running) {
10588 ret = pmu_dev_alloc(pmu);
10594 if (pmu->task_ctx_nr == perf_hw_context) {
10595 static int hw_context_taken = 0;
10598 * Other than systems with heterogeneous CPUs, it never makes
10599 * sense for two PMUs to share perf_hw_context. PMUs which are
10600 * uncore must use perf_invalid_context.
10602 if (WARN_ON_ONCE(hw_context_taken &&
10603 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10604 pmu->task_ctx_nr = perf_invalid_context;
10606 hw_context_taken = 1;
10609 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10610 if (pmu->pmu_cpu_context)
10611 goto got_cpu_context;
10614 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10615 if (!pmu->pmu_cpu_context)
10618 for_each_possible_cpu(cpu) {
10619 struct perf_cpu_context *cpuctx;
10621 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10622 __perf_event_init_context(&cpuctx->ctx);
10623 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10624 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10625 cpuctx->ctx.pmu = pmu;
10626 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10628 __perf_mux_hrtimer_init(cpuctx, cpu);
10630 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10631 cpuctx->heap = cpuctx->heap_default;
10635 if (!pmu->start_txn) {
10636 if (pmu->pmu_enable) {
10638 * If we have pmu_enable/pmu_disable calls, install
10639 * transaction stubs that use that to try and batch
10640 * hardware accesses.
10642 pmu->start_txn = perf_pmu_start_txn;
10643 pmu->commit_txn = perf_pmu_commit_txn;
10644 pmu->cancel_txn = perf_pmu_cancel_txn;
10646 pmu->start_txn = perf_pmu_nop_txn;
10647 pmu->commit_txn = perf_pmu_nop_int;
10648 pmu->cancel_txn = perf_pmu_nop_void;
10652 if (!pmu->pmu_enable) {
10653 pmu->pmu_enable = perf_pmu_nop_void;
10654 pmu->pmu_disable = perf_pmu_nop_void;
10657 if (!pmu->check_period)
10658 pmu->check_period = perf_event_nop_int;
10660 if (!pmu->event_idx)
10661 pmu->event_idx = perf_event_idx_default;
10664 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10665 * since these cannot be in the IDR. This way the linear search
10666 * is fast, provided a valid software event is provided.
10668 if (type == PERF_TYPE_SOFTWARE || !name)
10669 list_add_rcu(&pmu->entry, &pmus);
10671 list_add_tail_rcu(&pmu->entry, &pmus);
10673 atomic_set(&pmu->exclusive_cnt, 0);
10676 mutex_unlock(&pmus_lock);
10681 device_del(pmu->dev);
10682 put_device(pmu->dev);
10685 if (pmu->type != PERF_TYPE_SOFTWARE)
10686 idr_remove(&pmu_idr, pmu->type);
10689 free_percpu(pmu->pmu_disable_count);
10692 EXPORT_SYMBOL_GPL(perf_pmu_register);
10694 void perf_pmu_unregister(struct pmu *pmu)
10696 mutex_lock(&pmus_lock);
10697 list_del_rcu(&pmu->entry);
10700 * We dereference the pmu list under both SRCU and regular RCU, so
10701 * synchronize against both of those.
10703 synchronize_srcu(&pmus_srcu);
10706 free_percpu(pmu->pmu_disable_count);
10707 if (pmu->type != PERF_TYPE_SOFTWARE)
10708 idr_remove(&pmu_idr, pmu->type);
10709 if (pmu_bus_running) {
10710 if (pmu->nr_addr_filters)
10711 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10712 device_del(pmu->dev);
10713 put_device(pmu->dev);
10715 free_pmu_context(pmu);
10716 mutex_unlock(&pmus_lock);
10718 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10720 static inline bool has_extended_regs(struct perf_event *event)
10722 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10723 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10726 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10728 struct perf_event_context *ctx = NULL;
10731 if (!try_module_get(pmu->module))
10735 * A number of pmu->event_init() methods iterate the sibling_list to,
10736 * for example, validate if the group fits on the PMU. Therefore,
10737 * if this is a sibling event, acquire the ctx->mutex to protect
10738 * the sibling_list.
10740 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10742 * This ctx->mutex can nest when we're called through
10743 * inheritance. See the perf_event_ctx_lock_nested() comment.
10745 ctx = perf_event_ctx_lock_nested(event->group_leader,
10746 SINGLE_DEPTH_NESTING);
10751 ret = pmu->event_init(event);
10754 perf_event_ctx_unlock(event->group_leader, ctx);
10757 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10758 has_extended_regs(event))
10761 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10762 event_has_any_exclude_flag(event))
10765 if (ret && event->destroy)
10766 event->destroy(event);
10770 module_put(pmu->module);
10775 static struct pmu *perf_init_event(struct perf_event *event)
10777 int idx, type, ret;
10780 idx = srcu_read_lock(&pmus_srcu);
10782 /* Try parent's PMU first: */
10783 if (event->parent && event->parent->pmu) {
10784 pmu = event->parent->pmu;
10785 ret = perf_try_init_event(pmu, event);
10791 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
10792 * are often aliases for PERF_TYPE_RAW.
10794 type = event->attr.type;
10795 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
10796 type = PERF_TYPE_RAW;
10800 pmu = idr_find(&pmu_idr, type);
10803 ret = perf_try_init_event(pmu, event);
10804 if (ret == -ENOENT && event->attr.type != type) {
10805 type = event->attr.type;
10810 pmu = ERR_PTR(ret);
10815 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
10816 ret = perf_try_init_event(pmu, event);
10820 if (ret != -ENOENT) {
10821 pmu = ERR_PTR(ret);
10825 pmu = ERR_PTR(-ENOENT);
10827 srcu_read_unlock(&pmus_srcu, idx);
10832 static void attach_sb_event(struct perf_event *event)
10834 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10836 raw_spin_lock(&pel->lock);
10837 list_add_rcu(&event->sb_list, &pel->list);
10838 raw_spin_unlock(&pel->lock);
10842 * We keep a list of all !task (and therefore per-cpu) events
10843 * that need to receive side-band records.
10845 * This avoids having to scan all the various PMU per-cpu contexts
10846 * looking for them.
10848 static void account_pmu_sb_event(struct perf_event *event)
10850 if (is_sb_event(event))
10851 attach_sb_event(event);
10854 static void account_event_cpu(struct perf_event *event, int cpu)
10859 if (is_cgroup_event(event))
10860 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
10863 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
10864 static void account_freq_event_nohz(void)
10866 #ifdef CONFIG_NO_HZ_FULL
10867 /* Lock so we don't race with concurrent unaccount */
10868 spin_lock(&nr_freq_lock);
10869 if (atomic_inc_return(&nr_freq_events) == 1)
10870 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
10871 spin_unlock(&nr_freq_lock);
10875 static void account_freq_event(void)
10877 if (tick_nohz_full_enabled())
10878 account_freq_event_nohz();
10880 atomic_inc(&nr_freq_events);
10884 static void account_event(struct perf_event *event)
10891 if (event->attach_state & PERF_ATTACH_TASK)
10893 if (event->attr.mmap || event->attr.mmap_data)
10894 atomic_inc(&nr_mmap_events);
10895 if (event->attr.comm)
10896 atomic_inc(&nr_comm_events);
10897 if (event->attr.namespaces)
10898 atomic_inc(&nr_namespaces_events);
10899 if (event->attr.cgroup)
10900 atomic_inc(&nr_cgroup_events);
10901 if (event->attr.task)
10902 atomic_inc(&nr_task_events);
10903 if (event->attr.freq)
10904 account_freq_event();
10905 if (event->attr.context_switch) {
10906 atomic_inc(&nr_switch_events);
10909 if (has_branch_stack(event))
10911 if (is_cgroup_event(event))
10913 if (event->attr.ksymbol)
10914 atomic_inc(&nr_ksymbol_events);
10915 if (event->attr.bpf_event)
10916 atomic_inc(&nr_bpf_events);
10920 * We need the mutex here because static_branch_enable()
10921 * must complete *before* the perf_sched_count increment
10924 if (atomic_inc_not_zero(&perf_sched_count))
10927 mutex_lock(&perf_sched_mutex);
10928 if (!atomic_read(&perf_sched_count)) {
10929 static_branch_enable(&perf_sched_events);
10931 * Guarantee that all CPUs observe they key change and
10932 * call the perf scheduling hooks before proceeding to
10933 * install events that need them.
10938 * Now that we have waited for the sync_sched(), allow further
10939 * increments to by-pass the mutex.
10941 atomic_inc(&perf_sched_count);
10942 mutex_unlock(&perf_sched_mutex);
10946 account_event_cpu(event, event->cpu);
10948 account_pmu_sb_event(event);
10952 * Allocate and initialize an event structure
10954 static struct perf_event *
10955 perf_event_alloc(struct perf_event_attr *attr, int cpu,
10956 struct task_struct *task,
10957 struct perf_event *group_leader,
10958 struct perf_event *parent_event,
10959 perf_overflow_handler_t overflow_handler,
10960 void *context, int cgroup_fd)
10963 struct perf_event *event;
10964 struct hw_perf_event *hwc;
10965 long err = -EINVAL;
10967 if ((unsigned)cpu >= nr_cpu_ids) {
10968 if (!task || cpu != -1)
10969 return ERR_PTR(-EINVAL);
10972 event = kzalloc(sizeof(*event), GFP_KERNEL);
10974 return ERR_PTR(-ENOMEM);
10977 * Single events are their own group leaders, with an
10978 * empty sibling list:
10981 group_leader = event;
10983 mutex_init(&event->child_mutex);
10984 INIT_LIST_HEAD(&event->child_list);
10986 INIT_LIST_HEAD(&event->event_entry);
10987 INIT_LIST_HEAD(&event->sibling_list);
10988 INIT_LIST_HEAD(&event->active_list);
10989 init_event_group(event);
10990 INIT_LIST_HEAD(&event->rb_entry);
10991 INIT_LIST_HEAD(&event->active_entry);
10992 INIT_LIST_HEAD(&event->addr_filters.list);
10993 INIT_HLIST_NODE(&event->hlist_entry);
10996 init_waitqueue_head(&event->waitq);
10997 event->pending_disable = -1;
10998 init_irq_work(&event->pending, perf_pending_event);
11000 mutex_init(&event->mmap_mutex);
11001 raw_spin_lock_init(&event->addr_filters.lock);
11003 atomic_long_set(&event->refcount, 1);
11005 event->attr = *attr;
11006 event->group_leader = group_leader;
11010 event->parent = parent_event;
11012 event->ns = get_pid_ns(task_active_pid_ns(current));
11013 event->id = atomic64_inc_return(&perf_event_id);
11015 event->state = PERF_EVENT_STATE_INACTIVE;
11018 event->attach_state = PERF_ATTACH_TASK;
11020 * XXX pmu::event_init needs to know what task to account to
11021 * and we cannot use the ctx information because we need the
11022 * pmu before we get a ctx.
11024 event->hw.target = get_task_struct(task);
11027 event->clock = &local_clock;
11029 event->clock = parent_event->clock;
11031 if (!overflow_handler && parent_event) {
11032 overflow_handler = parent_event->overflow_handler;
11033 context = parent_event->overflow_handler_context;
11034 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11035 if (overflow_handler == bpf_overflow_handler) {
11036 struct bpf_prog *prog = parent_event->prog;
11038 bpf_prog_inc(prog);
11039 event->prog = prog;
11040 event->orig_overflow_handler =
11041 parent_event->orig_overflow_handler;
11046 if (overflow_handler) {
11047 event->overflow_handler = overflow_handler;
11048 event->overflow_handler_context = context;
11049 } else if (is_write_backward(event)){
11050 event->overflow_handler = perf_event_output_backward;
11051 event->overflow_handler_context = NULL;
11053 event->overflow_handler = perf_event_output_forward;
11054 event->overflow_handler_context = NULL;
11057 perf_event__state_init(event);
11062 hwc->sample_period = attr->sample_period;
11063 if (attr->freq && attr->sample_freq)
11064 hwc->sample_period = 1;
11065 hwc->last_period = hwc->sample_period;
11067 local64_set(&hwc->period_left, hwc->sample_period);
11070 * We currently do not support PERF_SAMPLE_READ on inherited events.
11071 * See perf_output_read().
11073 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11076 if (!has_branch_stack(event))
11077 event->attr.branch_sample_type = 0;
11079 pmu = perf_init_event(event);
11081 err = PTR_ERR(pmu);
11086 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11087 * be different on other CPUs in the uncore mask.
11089 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11094 if (event->attr.aux_output &&
11095 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11100 if (cgroup_fd != -1) {
11101 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11106 err = exclusive_event_init(event);
11110 if (has_addr_filter(event)) {
11111 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11112 sizeof(struct perf_addr_filter_range),
11114 if (!event->addr_filter_ranges) {
11120 * Clone the parent's vma offsets: they are valid until exec()
11121 * even if the mm is not shared with the parent.
11123 if (event->parent) {
11124 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11126 raw_spin_lock_irq(&ifh->lock);
11127 memcpy(event->addr_filter_ranges,
11128 event->parent->addr_filter_ranges,
11129 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11130 raw_spin_unlock_irq(&ifh->lock);
11133 /* force hw sync on the address filters */
11134 event->addr_filters_gen = 1;
11137 if (!event->parent) {
11138 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11139 err = get_callchain_buffers(attr->sample_max_stack);
11141 goto err_addr_filters;
11145 err = security_perf_event_alloc(event);
11147 goto err_callchain_buffer;
11149 /* symmetric to unaccount_event() in _free_event() */
11150 account_event(event);
11154 err_callchain_buffer:
11155 if (!event->parent) {
11156 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11157 put_callchain_buffers();
11160 kfree(event->addr_filter_ranges);
11163 exclusive_event_destroy(event);
11166 if (is_cgroup_event(event))
11167 perf_detach_cgroup(event);
11168 if (event->destroy)
11169 event->destroy(event);
11170 module_put(pmu->module);
11173 put_pid_ns(event->ns);
11174 if (event->hw.target)
11175 put_task_struct(event->hw.target);
11178 return ERR_PTR(err);
11181 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11182 struct perf_event_attr *attr)
11187 /* Zero the full structure, so that a short copy will be nice. */
11188 memset(attr, 0, sizeof(*attr));
11190 ret = get_user(size, &uattr->size);
11194 /* ABI compatibility quirk: */
11196 size = PERF_ATTR_SIZE_VER0;
11197 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11200 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11209 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11212 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11215 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11218 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11219 u64 mask = attr->branch_sample_type;
11221 /* only using defined bits */
11222 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11225 /* at least one branch bit must be set */
11226 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11229 /* propagate priv level, when not set for branch */
11230 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11232 /* exclude_kernel checked on syscall entry */
11233 if (!attr->exclude_kernel)
11234 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11236 if (!attr->exclude_user)
11237 mask |= PERF_SAMPLE_BRANCH_USER;
11239 if (!attr->exclude_hv)
11240 mask |= PERF_SAMPLE_BRANCH_HV;
11242 * adjust user setting (for HW filter setup)
11244 attr->branch_sample_type = mask;
11246 /* privileged levels capture (kernel, hv): check permissions */
11247 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11248 ret = perf_allow_kernel(attr);
11254 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11255 ret = perf_reg_validate(attr->sample_regs_user);
11260 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11261 if (!arch_perf_have_user_stack_dump())
11265 * We have __u32 type for the size, but so far
11266 * we can only use __u16 as maximum due to the
11267 * __u16 sample size limit.
11269 if (attr->sample_stack_user >= USHRT_MAX)
11271 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11275 if (!attr->sample_max_stack)
11276 attr->sample_max_stack = sysctl_perf_event_max_stack;
11278 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11279 ret = perf_reg_validate(attr->sample_regs_intr);
11281 #ifndef CONFIG_CGROUP_PERF
11282 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11290 put_user(sizeof(*attr), &uattr->size);
11296 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11298 struct perf_buffer *rb = NULL;
11304 /* don't allow circular references */
11305 if (event == output_event)
11309 * Don't allow cross-cpu buffers
11311 if (output_event->cpu != event->cpu)
11315 * If its not a per-cpu rb, it must be the same task.
11317 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11321 * Mixing clocks in the same buffer is trouble you don't need.
11323 if (output_event->clock != event->clock)
11327 * Either writing ring buffer from beginning or from end.
11328 * Mixing is not allowed.
11330 if (is_write_backward(output_event) != is_write_backward(event))
11334 * If both events generate aux data, they must be on the same PMU
11336 if (has_aux(event) && has_aux(output_event) &&
11337 event->pmu != output_event->pmu)
11341 mutex_lock(&event->mmap_mutex);
11342 /* Can't redirect output if we've got an active mmap() */
11343 if (atomic_read(&event->mmap_count))
11346 if (output_event) {
11347 /* get the rb we want to redirect to */
11348 rb = ring_buffer_get(output_event);
11353 ring_buffer_attach(event, rb);
11357 mutex_unlock(&event->mmap_mutex);
11363 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11369 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11372 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11374 bool nmi_safe = false;
11377 case CLOCK_MONOTONIC:
11378 event->clock = &ktime_get_mono_fast_ns;
11382 case CLOCK_MONOTONIC_RAW:
11383 event->clock = &ktime_get_raw_fast_ns;
11387 case CLOCK_REALTIME:
11388 event->clock = &ktime_get_real_ns;
11391 case CLOCK_BOOTTIME:
11392 event->clock = &ktime_get_boottime_ns;
11396 event->clock = &ktime_get_clocktai_ns;
11403 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11410 * Variation on perf_event_ctx_lock_nested(), except we take two context
11413 static struct perf_event_context *
11414 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11415 struct perf_event_context *ctx)
11417 struct perf_event_context *gctx;
11421 gctx = READ_ONCE(group_leader->ctx);
11422 if (!refcount_inc_not_zero(&gctx->refcount)) {
11428 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11430 if (group_leader->ctx != gctx) {
11431 mutex_unlock(&ctx->mutex);
11432 mutex_unlock(&gctx->mutex);
11441 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11443 * @attr_uptr: event_id type attributes for monitoring/sampling
11446 * @group_fd: group leader event fd
11448 SYSCALL_DEFINE5(perf_event_open,
11449 struct perf_event_attr __user *, attr_uptr,
11450 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11452 struct perf_event *group_leader = NULL, *output_event = NULL;
11453 struct perf_event *event, *sibling;
11454 struct perf_event_attr attr;
11455 struct perf_event_context *ctx, *uninitialized_var(gctx);
11456 struct file *event_file = NULL;
11457 struct fd group = {NULL, 0};
11458 struct task_struct *task = NULL;
11461 int move_group = 0;
11463 int f_flags = O_RDWR;
11464 int cgroup_fd = -1;
11466 /* for future expandability... */
11467 if (flags & ~PERF_FLAG_ALL)
11470 /* Do we allow access to perf_event_open(2) ? */
11471 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11475 err = perf_copy_attr(attr_uptr, &attr);
11479 if (!attr.exclude_kernel) {
11480 err = perf_allow_kernel(&attr);
11485 if (attr.namespaces) {
11486 if (!capable(CAP_SYS_ADMIN))
11491 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11494 if (attr.sample_period & (1ULL << 63))
11498 /* Only privileged users can get physical addresses */
11499 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11500 err = perf_allow_kernel(&attr);
11505 err = security_locked_down(LOCKDOWN_PERF);
11506 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11507 /* REGS_INTR can leak data, lockdown must prevent this */
11513 * In cgroup mode, the pid argument is used to pass the fd
11514 * opened to the cgroup directory in cgroupfs. The cpu argument
11515 * designates the cpu on which to monitor threads from that
11518 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11521 if (flags & PERF_FLAG_FD_CLOEXEC)
11522 f_flags |= O_CLOEXEC;
11524 event_fd = get_unused_fd_flags(f_flags);
11528 if (group_fd != -1) {
11529 err = perf_fget_light(group_fd, &group);
11532 group_leader = group.file->private_data;
11533 if (flags & PERF_FLAG_FD_OUTPUT)
11534 output_event = group_leader;
11535 if (flags & PERF_FLAG_FD_NO_GROUP)
11536 group_leader = NULL;
11539 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11540 task = find_lively_task_by_vpid(pid);
11541 if (IS_ERR(task)) {
11542 err = PTR_ERR(task);
11547 if (task && group_leader &&
11548 group_leader->attr.inherit != attr.inherit) {
11554 err = mutex_lock_interruptible(&task->signal->exec_update_mutex);
11559 * Reuse ptrace permission checks for now.
11561 * We must hold exec_update_mutex across this and any potential
11562 * perf_install_in_context() call for this new event to
11563 * serialize against exec() altering our credentials (and the
11564 * perf_event_exit_task() that could imply).
11567 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11571 if (flags & PERF_FLAG_PID_CGROUP)
11574 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11575 NULL, NULL, cgroup_fd);
11576 if (IS_ERR(event)) {
11577 err = PTR_ERR(event);
11581 if (is_sampling_event(event)) {
11582 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11589 * Special case software events and allow them to be part of
11590 * any hardware group.
11594 if (attr.use_clockid) {
11595 err = perf_event_set_clock(event, attr.clockid);
11600 if (pmu->task_ctx_nr == perf_sw_context)
11601 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11603 if (group_leader) {
11604 if (is_software_event(event) &&
11605 !in_software_context(group_leader)) {
11607 * If the event is a sw event, but the group_leader
11608 * is on hw context.
11610 * Allow the addition of software events to hw
11611 * groups, this is safe because software events
11612 * never fail to schedule.
11614 pmu = group_leader->ctx->pmu;
11615 } else if (!is_software_event(event) &&
11616 is_software_event(group_leader) &&
11617 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11619 * In case the group is a pure software group, and we
11620 * try to add a hardware event, move the whole group to
11621 * the hardware context.
11628 * Get the target context (task or percpu):
11630 ctx = find_get_context(pmu, task, event);
11632 err = PTR_ERR(ctx);
11637 * Look up the group leader (we will attach this event to it):
11639 if (group_leader) {
11643 * Do not allow a recursive hierarchy (this new sibling
11644 * becoming part of another group-sibling):
11646 if (group_leader->group_leader != group_leader)
11649 /* All events in a group should have the same clock */
11650 if (group_leader->clock != event->clock)
11654 * Make sure we're both events for the same CPU;
11655 * grouping events for different CPUs is broken; since
11656 * you can never concurrently schedule them anyhow.
11658 if (group_leader->cpu != event->cpu)
11662 * Make sure we're both on the same task, or both
11665 if (group_leader->ctx->task != ctx->task)
11669 * Do not allow to attach to a group in a different task
11670 * or CPU context. If we're moving SW events, we'll fix
11671 * this up later, so allow that.
11673 if (!move_group && group_leader->ctx != ctx)
11677 * Only a group leader can be exclusive or pinned
11679 if (attr.exclusive || attr.pinned)
11683 if (output_event) {
11684 err = perf_event_set_output(event, output_event);
11689 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11691 if (IS_ERR(event_file)) {
11692 err = PTR_ERR(event_file);
11698 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11700 if (gctx->task == TASK_TOMBSTONE) {
11706 * Check if we raced against another sys_perf_event_open() call
11707 * moving the software group underneath us.
11709 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11711 * If someone moved the group out from under us, check
11712 * if this new event wound up on the same ctx, if so
11713 * its the regular !move_group case, otherwise fail.
11719 perf_event_ctx_unlock(group_leader, gctx);
11725 * Failure to create exclusive events returns -EBUSY.
11728 if (!exclusive_event_installable(group_leader, ctx))
11731 for_each_sibling_event(sibling, group_leader) {
11732 if (!exclusive_event_installable(sibling, ctx))
11736 mutex_lock(&ctx->mutex);
11739 if (ctx->task == TASK_TOMBSTONE) {
11744 if (!perf_event_validate_size(event)) {
11751 * Check if the @cpu we're creating an event for is online.
11753 * We use the perf_cpu_context::ctx::mutex to serialize against
11754 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11756 struct perf_cpu_context *cpuctx =
11757 container_of(ctx, struct perf_cpu_context, ctx);
11759 if (!cpuctx->online) {
11765 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
11771 * Must be under the same ctx::mutex as perf_install_in_context(),
11772 * because we need to serialize with concurrent event creation.
11774 if (!exclusive_event_installable(event, ctx)) {
11779 WARN_ON_ONCE(ctx->parent_ctx);
11782 * This is the point on no return; we cannot fail hereafter. This is
11783 * where we start modifying current state.
11788 * See perf_event_ctx_lock() for comments on the details
11789 * of swizzling perf_event::ctx.
11791 perf_remove_from_context(group_leader, 0);
11794 for_each_sibling_event(sibling, group_leader) {
11795 perf_remove_from_context(sibling, 0);
11800 * Wait for everybody to stop referencing the events through
11801 * the old lists, before installing it on new lists.
11806 * Install the group siblings before the group leader.
11808 * Because a group leader will try and install the entire group
11809 * (through the sibling list, which is still in-tact), we can
11810 * end up with siblings installed in the wrong context.
11812 * By installing siblings first we NO-OP because they're not
11813 * reachable through the group lists.
11815 for_each_sibling_event(sibling, group_leader) {
11816 perf_event__state_init(sibling);
11817 perf_install_in_context(ctx, sibling, sibling->cpu);
11822 * Removing from the context ends up with disabled
11823 * event. What we want here is event in the initial
11824 * startup state, ready to be add into new context.
11826 perf_event__state_init(group_leader);
11827 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11832 * Precalculate sample_data sizes; do while holding ctx::mutex such
11833 * that we're serialized against further additions and before
11834 * perf_install_in_context() which is the point the event is active and
11835 * can use these values.
11837 perf_event__header_size(event);
11838 perf_event__id_header_size(event);
11840 event->owner = current;
11842 perf_install_in_context(ctx, event, event->cpu);
11843 perf_unpin_context(ctx);
11846 perf_event_ctx_unlock(group_leader, gctx);
11847 mutex_unlock(&ctx->mutex);
11850 mutex_unlock(&task->signal->exec_update_mutex);
11851 put_task_struct(task);
11854 mutex_lock(¤t->perf_event_mutex);
11855 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
11856 mutex_unlock(¤t->perf_event_mutex);
11859 * Drop the reference on the group_event after placing the
11860 * new event on the sibling_list. This ensures destruction
11861 * of the group leader will find the pointer to itself in
11862 * perf_group_detach().
11865 fd_install(event_fd, event_file);
11870 perf_event_ctx_unlock(group_leader, gctx);
11871 mutex_unlock(&ctx->mutex);
11875 perf_unpin_context(ctx);
11879 * If event_file is set, the fput() above will have called ->release()
11880 * and that will take care of freeing the event.
11886 mutex_unlock(&task->signal->exec_update_mutex);
11889 put_task_struct(task);
11893 put_unused_fd(event_fd);
11898 * perf_event_create_kernel_counter
11900 * @attr: attributes of the counter to create
11901 * @cpu: cpu in which the counter is bound
11902 * @task: task to profile (NULL for percpu)
11904 struct perf_event *
11905 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
11906 struct task_struct *task,
11907 perf_overflow_handler_t overflow_handler,
11910 struct perf_event_context *ctx;
11911 struct perf_event *event;
11915 * Grouping is not supported for kernel events, neither is 'AUX',
11916 * make sure the caller's intentions are adjusted.
11918 if (attr->aux_output)
11919 return ERR_PTR(-EINVAL);
11921 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
11922 overflow_handler, context, -1);
11923 if (IS_ERR(event)) {
11924 err = PTR_ERR(event);
11928 /* Mark owner so we could distinguish it from user events. */
11929 event->owner = TASK_TOMBSTONE;
11932 * Get the target context (task or percpu):
11934 ctx = find_get_context(event->pmu, task, event);
11936 err = PTR_ERR(ctx);
11940 WARN_ON_ONCE(ctx->parent_ctx);
11941 mutex_lock(&ctx->mutex);
11942 if (ctx->task == TASK_TOMBSTONE) {
11949 * Check if the @cpu we're creating an event for is online.
11951 * We use the perf_cpu_context::ctx::mutex to serialize against
11952 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11954 struct perf_cpu_context *cpuctx =
11955 container_of(ctx, struct perf_cpu_context, ctx);
11956 if (!cpuctx->online) {
11962 if (!exclusive_event_installable(event, ctx)) {
11967 perf_install_in_context(ctx, event, event->cpu);
11968 perf_unpin_context(ctx);
11969 mutex_unlock(&ctx->mutex);
11974 mutex_unlock(&ctx->mutex);
11975 perf_unpin_context(ctx);
11980 return ERR_PTR(err);
11982 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
11984 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
11986 struct perf_event_context *src_ctx;
11987 struct perf_event_context *dst_ctx;
11988 struct perf_event *event, *tmp;
11991 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
11992 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
11995 * See perf_event_ctx_lock() for comments on the details
11996 * of swizzling perf_event::ctx.
11998 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
11999 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12001 perf_remove_from_context(event, 0);
12002 unaccount_event_cpu(event, src_cpu);
12004 list_add(&event->migrate_entry, &events);
12008 * Wait for the events to quiesce before re-instating them.
12013 * Re-instate events in 2 passes.
12015 * Skip over group leaders and only install siblings on this first
12016 * pass, siblings will not get enabled without a leader, however a
12017 * leader will enable its siblings, even if those are still on the old
12020 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12021 if (event->group_leader == event)
12024 list_del(&event->migrate_entry);
12025 if (event->state >= PERF_EVENT_STATE_OFF)
12026 event->state = PERF_EVENT_STATE_INACTIVE;
12027 account_event_cpu(event, dst_cpu);
12028 perf_install_in_context(dst_ctx, event, dst_cpu);
12033 * Once all the siblings are setup properly, install the group leaders
12036 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12037 list_del(&event->migrate_entry);
12038 if (event->state >= PERF_EVENT_STATE_OFF)
12039 event->state = PERF_EVENT_STATE_INACTIVE;
12040 account_event_cpu(event, dst_cpu);
12041 perf_install_in_context(dst_ctx, event, dst_cpu);
12044 mutex_unlock(&dst_ctx->mutex);
12045 mutex_unlock(&src_ctx->mutex);
12047 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12049 static void sync_child_event(struct perf_event *child_event,
12050 struct task_struct *child)
12052 struct perf_event *parent_event = child_event->parent;
12055 if (child_event->attr.inherit_stat)
12056 perf_event_read_event(child_event, child);
12058 child_val = perf_event_count(child_event);
12061 * Add back the child's count to the parent's count:
12063 atomic64_add(child_val, &parent_event->child_count);
12064 atomic64_add(child_event->total_time_enabled,
12065 &parent_event->child_total_time_enabled);
12066 atomic64_add(child_event->total_time_running,
12067 &parent_event->child_total_time_running);
12071 perf_event_exit_event(struct perf_event *child_event,
12072 struct perf_event_context *child_ctx,
12073 struct task_struct *child)
12075 struct perf_event *parent_event = child_event->parent;
12078 * Do not destroy the 'original' grouping; because of the context
12079 * switch optimization the original events could've ended up in a
12080 * random child task.
12082 * If we were to destroy the original group, all group related
12083 * operations would cease to function properly after this random
12086 * Do destroy all inherited groups, we don't care about those
12087 * and being thorough is better.
12089 raw_spin_lock_irq(&child_ctx->lock);
12090 WARN_ON_ONCE(child_ctx->is_active);
12093 perf_group_detach(child_event);
12094 list_del_event(child_event, child_ctx);
12095 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12096 raw_spin_unlock_irq(&child_ctx->lock);
12099 * Parent events are governed by their filedesc, retain them.
12101 if (!parent_event) {
12102 perf_event_wakeup(child_event);
12106 * Child events can be cleaned up.
12109 sync_child_event(child_event, child);
12112 * Remove this event from the parent's list
12114 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12115 mutex_lock(&parent_event->child_mutex);
12116 list_del_init(&child_event->child_list);
12117 mutex_unlock(&parent_event->child_mutex);
12120 * Kick perf_poll() for is_event_hup().
12122 perf_event_wakeup(parent_event);
12123 free_event(child_event);
12124 put_event(parent_event);
12127 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12129 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12130 struct perf_event *child_event, *next;
12132 WARN_ON_ONCE(child != current);
12134 child_ctx = perf_pin_task_context(child, ctxn);
12139 * In order to reduce the amount of tricky in ctx tear-down, we hold
12140 * ctx::mutex over the entire thing. This serializes against almost
12141 * everything that wants to access the ctx.
12143 * The exception is sys_perf_event_open() /
12144 * perf_event_create_kernel_count() which does find_get_context()
12145 * without ctx::mutex (it cannot because of the move_group double mutex
12146 * lock thing). See the comments in perf_install_in_context().
12148 mutex_lock(&child_ctx->mutex);
12151 * In a single ctx::lock section, de-schedule the events and detach the
12152 * context from the task such that we cannot ever get it scheduled back
12155 raw_spin_lock_irq(&child_ctx->lock);
12156 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12159 * Now that the context is inactive, destroy the task <-> ctx relation
12160 * and mark the context dead.
12162 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12163 put_ctx(child_ctx); /* cannot be last */
12164 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12165 put_task_struct(current); /* cannot be last */
12167 clone_ctx = unclone_ctx(child_ctx);
12168 raw_spin_unlock_irq(&child_ctx->lock);
12171 put_ctx(clone_ctx);
12174 * Report the task dead after unscheduling the events so that we
12175 * won't get any samples after PERF_RECORD_EXIT. We can however still
12176 * get a few PERF_RECORD_READ events.
12178 perf_event_task(child, child_ctx, 0);
12180 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12181 perf_event_exit_event(child_event, child_ctx, child);
12183 mutex_unlock(&child_ctx->mutex);
12185 put_ctx(child_ctx);
12189 * When a child task exits, feed back event values to parent events.
12191 * Can be called with exec_update_mutex held when called from
12192 * install_exec_creds().
12194 void perf_event_exit_task(struct task_struct *child)
12196 struct perf_event *event, *tmp;
12199 mutex_lock(&child->perf_event_mutex);
12200 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12202 list_del_init(&event->owner_entry);
12205 * Ensure the list deletion is visible before we clear
12206 * the owner, closes a race against perf_release() where
12207 * we need to serialize on the owner->perf_event_mutex.
12209 smp_store_release(&event->owner, NULL);
12211 mutex_unlock(&child->perf_event_mutex);
12213 for_each_task_context_nr(ctxn)
12214 perf_event_exit_task_context(child, ctxn);
12217 * The perf_event_exit_task_context calls perf_event_task
12218 * with child's task_ctx, which generates EXIT events for
12219 * child contexts and sets child->perf_event_ctxp[] to NULL.
12220 * At this point we need to send EXIT events to cpu contexts.
12222 perf_event_task(child, NULL, 0);
12225 static void perf_free_event(struct perf_event *event,
12226 struct perf_event_context *ctx)
12228 struct perf_event *parent = event->parent;
12230 if (WARN_ON_ONCE(!parent))
12233 mutex_lock(&parent->child_mutex);
12234 list_del_init(&event->child_list);
12235 mutex_unlock(&parent->child_mutex);
12239 raw_spin_lock_irq(&ctx->lock);
12240 perf_group_detach(event);
12241 list_del_event(event, ctx);
12242 raw_spin_unlock_irq(&ctx->lock);
12247 * Free a context as created by inheritance by perf_event_init_task() below,
12248 * used by fork() in case of fail.
12250 * Even though the task has never lived, the context and events have been
12251 * exposed through the child_list, so we must take care tearing it all down.
12253 void perf_event_free_task(struct task_struct *task)
12255 struct perf_event_context *ctx;
12256 struct perf_event *event, *tmp;
12259 for_each_task_context_nr(ctxn) {
12260 ctx = task->perf_event_ctxp[ctxn];
12264 mutex_lock(&ctx->mutex);
12265 raw_spin_lock_irq(&ctx->lock);
12267 * Destroy the task <-> ctx relation and mark the context dead.
12269 * This is important because even though the task hasn't been
12270 * exposed yet the context has been (through child_list).
12272 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12273 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12274 put_task_struct(task); /* cannot be last */
12275 raw_spin_unlock_irq(&ctx->lock);
12277 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12278 perf_free_event(event, ctx);
12280 mutex_unlock(&ctx->mutex);
12283 * perf_event_release_kernel() could've stolen some of our
12284 * child events and still have them on its free_list. In that
12285 * case we must wait for these events to have been freed (in
12286 * particular all their references to this task must've been
12289 * Without this copy_process() will unconditionally free this
12290 * task (irrespective of its reference count) and
12291 * _free_event()'s put_task_struct(event->hw.target) will be a
12294 * Wait for all events to drop their context reference.
12296 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12297 put_ctx(ctx); /* must be last */
12301 void perf_event_delayed_put(struct task_struct *task)
12305 for_each_task_context_nr(ctxn)
12306 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12309 struct file *perf_event_get(unsigned int fd)
12311 struct file *file = fget(fd);
12313 return ERR_PTR(-EBADF);
12315 if (file->f_op != &perf_fops) {
12317 return ERR_PTR(-EBADF);
12323 const struct perf_event *perf_get_event(struct file *file)
12325 if (file->f_op != &perf_fops)
12326 return ERR_PTR(-EINVAL);
12328 return file->private_data;
12331 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12334 return ERR_PTR(-EINVAL);
12336 return &event->attr;
12340 * Inherit an event from parent task to child task.
12343 * - valid pointer on success
12344 * - NULL for orphaned events
12345 * - IS_ERR() on error
12347 static struct perf_event *
12348 inherit_event(struct perf_event *parent_event,
12349 struct task_struct *parent,
12350 struct perf_event_context *parent_ctx,
12351 struct task_struct *child,
12352 struct perf_event *group_leader,
12353 struct perf_event_context *child_ctx)
12355 enum perf_event_state parent_state = parent_event->state;
12356 struct perf_event *child_event;
12357 unsigned long flags;
12360 * Instead of creating recursive hierarchies of events,
12361 * we link inherited events back to the original parent,
12362 * which has a filp for sure, which we use as the reference
12365 if (parent_event->parent)
12366 parent_event = parent_event->parent;
12368 child_event = perf_event_alloc(&parent_event->attr,
12371 group_leader, parent_event,
12373 if (IS_ERR(child_event))
12374 return child_event;
12377 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12378 !child_ctx->task_ctx_data) {
12379 struct pmu *pmu = child_event->pmu;
12381 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
12383 if (!child_ctx->task_ctx_data) {
12384 free_event(child_event);
12385 return ERR_PTR(-ENOMEM);
12390 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12391 * must be under the same lock in order to serialize against
12392 * perf_event_release_kernel(), such that either we must observe
12393 * is_orphaned_event() or they will observe us on the child_list.
12395 mutex_lock(&parent_event->child_mutex);
12396 if (is_orphaned_event(parent_event) ||
12397 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12398 mutex_unlock(&parent_event->child_mutex);
12399 /* task_ctx_data is freed with child_ctx */
12400 free_event(child_event);
12404 get_ctx(child_ctx);
12407 * Make the child state follow the state of the parent event,
12408 * not its attr.disabled bit. We hold the parent's mutex,
12409 * so we won't race with perf_event_{en, dis}able_family.
12411 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12412 child_event->state = PERF_EVENT_STATE_INACTIVE;
12414 child_event->state = PERF_EVENT_STATE_OFF;
12416 if (parent_event->attr.freq) {
12417 u64 sample_period = parent_event->hw.sample_period;
12418 struct hw_perf_event *hwc = &child_event->hw;
12420 hwc->sample_period = sample_period;
12421 hwc->last_period = sample_period;
12423 local64_set(&hwc->period_left, sample_period);
12426 child_event->ctx = child_ctx;
12427 child_event->overflow_handler = parent_event->overflow_handler;
12428 child_event->overflow_handler_context
12429 = parent_event->overflow_handler_context;
12432 * Precalculate sample_data sizes
12434 perf_event__header_size(child_event);
12435 perf_event__id_header_size(child_event);
12438 * Link it up in the child's context:
12440 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12441 add_event_to_ctx(child_event, child_ctx);
12442 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12445 * Link this into the parent event's child list
12447 list_add_tail(&child_event->child_list, &parent_event->child_list);
12448 mutex_unlock(&parent_event->child_mutex);
12450 return child_event;
12454 * Inherits an event group.
12456 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12457 * This matches with perf_event_release_kernel() removing all child events.
12463 static int inherit_group(struct perf_event *parent_event,
12464 struct task_struct *parent,
12465 struct perf_event_context *parent_ctx,
12466 struct task_struct *child,
12467 struct perf_event_context *child_ctx)
12469 struct perf_event *leader;
12470 struct perf_event *sub;
12471 struct perf_event *child_ctr;
12473 leader = inherit_event(parent_event, parent, parent_ctx,
12474 child, NULL, child_ctx);
12475 if (IS_ERR(leader))
12476 return PTR_ERR(leader);
12478 * @leader can be NULL here because of is_orphaned_event(). In this
12479 * case inherit_event() will create individual events, similar to what
12480 * perf_group_detach() would do anyway.
12482 for_each_sibling_event(sub, parent_event) {
12483 child_ctr = inherit_event(sub, parent, parent_ctx,
12484 child, leader, child_ctx);
12485 if (IS_ERR(child_ctr))
12486 return PTR_ERR(child_ctr);
12488 if (sub->aux_event == parent_event && child_ctr &&
12489 !perf_get_aux_event(child_ctr, leader))
12496 * Creates the child task context and tries to inherit the event-group.
12498 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12499 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12500 * consistent with perf_event_release_kernel() removing all child events.
12507 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12508 struct perf_event_context *parent_ctx,
12509 struct task_struct *child, int ctxn,
12510 int *inherited_all)
12513 struct perf_event_context *child_ctx;
12515 if (!event->attr.inherit) {
12516 *inherited_all = 0;
12520 child_ctx = child->perf_event_ctxp[ctxn];
12523 * This is executed from the parent task context, so
12524 * inherit events that have been marked for cloning.
12525 * First allocate and initialize a context for the
12528 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12532 child->perf_event_ctxp[ctxn] = child_ctx;
12535 ret = inherit_group(event, parent, parent_ctx,
12539 *inherited_all = 0;
12545 * Initialize the perf_event context in task_struct
12547 static int perf_event_init_context(struct task_struct *child, int ctxn)
12549 struct perf_event_context *child_ctx, *parent_ctx;
12550 struct perf_event_context *cloned_ctx;
12551 struct perf_event *event;
12552 struct task_struct *parent = current;
12553 int inherited_all = 1;
12554 unsigned long flags;
12557 if (likely(!parent->perf_event_ctxp[ctxn]))
12561 * If the parent's context is a clone, pin it so it won't get
12562 * swapped under us.
12564 parent_ctx = perf_pin_task_context(parent, ctxn);
12569 * No need to check if parent_ctx != NULL here; since we saw
12570 * it non-NULL earlier, the only reason for it to become NULL
12571 * is if we exit, and since we're currently in the middle of
12572 * a fork we can't be exiting at the same time.
12576 * Lock the parent list. No need to lock the child - not PID
12577 * hashed yet and not running, so nobody can access it.
12579 mutex_lock(&parent_ctx->mutex);
12582 * We dont have to disable NMIs - we are only looking at
12583 * the list, not manipulating it:
12585 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12586 ret = inherit_task_group(event, parent, parent_ctx,
12587 child, ctxn, &inherited_all);
12593 * We can't hold ctx->lock when iterating the ->flexible_group list due
12594 * to allocations, but we need to prevent rotation because
12595 * rotate_ctx() will change the list from interrupt context.
12597 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12598 parent_ctx->rotate_disable = 1;
12599 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12601 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12602 ret = inherit_task_group(event, parent, parent_ctx,
12603 child, ctxn, &inherited_all);
12608 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12609 parent_ctx->rotate_disable = 0;
12611 child_ctx = child->perf_event_ctxp[ctxn];
12613 if (child_ctx && inherited_all) {
12615 * Mark the child context as a clone of the parent
12616 * context, or of whatever the parent is a clone of.
12618 * Note that if the parent is a clone, the holding of
12619 * parent_ctx->lock avoids it from being uncloned.
12621 cloned_ctx = parent_ctx->parent_ctx;
12623 child_ctx->parent_ctx = cloned_ctx;
12624 child_ctx->parent_gen = parent_ctx->parent_gen;
12626 child_ctx->parent_ctx = parent_ctx;
12627 child_ctx->parent_gen = parent_ctx->generation;
12629 get_ctx(child_ctx->parent_ctx);
12632 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12634 mutex_unlock(&parent_ctx->mutex);
12636 perf_unpin_context(parent_ctx);
12637 put_ctx(parent_ctx);
12643 * Initialize the perf_event context in task_struct
12645 int perf_event_init_task(struct task_struct *child)
12649 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12650 mutex_init(&child->perf_event_mutex);
12651 INIT_LIST_HEAD(&child->perf_event_list);
12653 for_each_task_context_nr(ctxn) {
12654 ret = perf_event_init_context(child, ctxn);
12656 perf_event_free_task(child);
12664 static void __init perf_event_init_all_cpus(void)
12666 struct swevent_htable *swhash;
12669 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12671 for_each_possible_cpu(cpu) {
12672 swhash = &per_cpu(swevent_htable, cpu);
12673 mutex_init(&swhash->hlist_mutex);
12674 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12676 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12677 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12679 #ifdef CONFIG_CGROUP_PERF
12680 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12682 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
12686 static void perf_swevent_init_cpu(unsigned int cpu)
12688 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12690 mutex_lock(&swhash->hlist_mutex);
12691 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12692 struct swevent_hlist *hlist;
12694 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12696 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12698 mutex_unlock(&swhash->hlist_mutex);
12701 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12702 static void __perf_event_exit_context(void *__info)
12704 struct perf_event_context *ctx = __info;
12705 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12706 struct perf_event *event;
12708 raw_spin_lock(&ctx->lock);
12709 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12710 list_for_each_entry(event, &ctx->event_list, event_entry)
12711 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12712 raw_spin_unlock(&ctx->lock);
12715 static void perf_event_exit_cpu_context(int cpu)
12717 struct perf_cpu_context *cpuctx;
12718 struct perf_event_context *ctx;
12721 mutex_lock(&pmus_lock);
12722 list_for_each_entry(pmu, &pmus, entry) {
12723 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12724 ctx = &cpuctx->ctx;
12726 mutex_lock(&ctx->mutex);
12727 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12728 cpuctx->online = 0;
12729 mutex_unlock(&ctx->mutex);
12731 cpumask_clear_cpu(cpu, perf_online_mask);
12732 mutex_unlock(&pmus_lock);
12736 static void perf_event_exit_cpu_context(int cpu) { }
12740 int perf_event_init_cpu(unsigned int cpu)
12742 struct perf_cpu_context *cpuctx;
12743 struct perf_event_context *ctx;
12746 perf_swevent_init_cpu(cpu);
12748 mutex_lock(&pmus_lock);
12749 cpumask_set_cpu(cpu, perf_online_mask);
12750 list_for_each_entry(pmu, &pmus, entry) {
12751 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12752 ctx = &cpuctx->ctx;
12754 mutex_lock(&ctx->mutex);
12755 cpuctx->online = 1;
12756 mutex_unlock(&ctx->mutex);
12758 mutex_unlock(&pmus_lock);
12763 int perf_event_exit_cpu(unsigned int cpu)
12765 perf_event_exit_cpu_context(cpu);
12770 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12774 for_each_online_cpu(cpu)
12775 perf_event_exit_cpu(cpu);
12781 * Run the perf reboot notifier at the very last possible moment so that
12782 * the generic watchdog code runs as long as possible.
12784 static struct notifier_block perf_reboot_notifier = {
12785 .notifier_call = perf_reboot,
12786 .priority = INT_MIN,
12789 void __init perf_event_init(void)
12793 idr_init(&pmu_idr);
12795 perf_event_init_all_cpus();
12796 init_srcu_struct(&pmus_srcu);
12797 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12798 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12799 perf_pmu_register(&perf_task_clock, NULL, -1);
12800 perf_tp_register();
12801 perf_event_init_cpu(smp_processor_id());
12802 register_reboot_notifier(&perf_reboot_notifier);
12804 ret = init_hw_breakpoint();
12805 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12808 * Build time assertion that we keep the data_head at the intended
12809 * location. IOW, validation we got the __reserved[] size right.
12811 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12815 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12818 struct perf_pmu_events_attr *pmu_attr =
12819 container_of(attr, struct perf_pmu_events_attr, attr);
12821 if (pmu_attr->event_str)
12822 return sprintf(page, "%s\n", pmu_attr->event_str);
12826 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
12828 static int __init perf_event_sysfs_init(void)
12833 mutex_lock(&pmus_lock);
12835 ret = bus_register(&pmu_bus);
12839 list_for_each_entry(pmu, &pmus, entry) {
12840 if (!pmu->name || pmu->type < 0)
12843 ret = pmu_dev_alloc(pmu);
12844 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12846 pmu_bus_running = 1;
12850 mutex_unlock(&pmus_lock);
12854 device_initcall(perf_event_sysfs_init);
12856 #ifdef CONFIG_CGROUP_PERF
12857 static struct cgroup_subsys_state *
12858 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
12860 struct perf_cgroup *jc;
12862 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
12864 return ERR_PTR(-ENOMEM);
12866 jc->info = alloc_percpu(struct perf_cgroup_info);
12869 return ERR_PTR(-ENOMEM);
12875 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
12877 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
12879 free_percpu(jc->info);
12883 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
12885 perf_event_cgroup(css->cgroup);
12889 static int __perf_cgroup_move(void *info)
12891 struct task_struct *task = info;
12893 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
12898 static void perf_cgroup_attach(struct cgroup_taskset *tset)
12900 struct task_struct *task;
12901 struct cgroup_subsys_state *css;
12903 cgroup_taskset_for_each(task, css, tset)
12904 task_function_call(task, __perf_cgroup_move, task);
12907 struct cgroup_subsys perf_event_cgrp_subsys = {
12908 .css_alloc = perf_cgroup_css_alloc,
12909 .css_free = perf_cgroup_css_free,
12910 .css_online = perf_cgroup_css_online,
12911 .attach = perf_cgroup_attach,
12913 * Implicitly enable on dfl hierarchy so that perf events can
12914 * always be filtered by cgroup2 path as long as perf_event
12915 * controller is not mounted on a legacy hierarchy.
12917 .implicit_on_dfl = true,
12920 #endif /* CONFIG_CGROUP_PERF */