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/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
57 #include <asm/irq_regs.h>
59 typedef int (*remote_function_f)(void *);
61 struct remote_function_call {
62 struct task_struct *p;
63 remote_function_f func;
68 static void remote_function(void *data)
70 struct remote_function_call *tfc = data;
71 struct task_struct *p = tfc->p;
75 if (task_cpu(p) != smp_processor_id())
79 * Now that we're on right CPU with IRQs disabled, we can test
80 * if we hit the right task without races.
83 tfc->ret = -ESRCH; /* No such (running) process */
88 tfc->ret = tfc->func(tfc->info);
92 * task_function_call - call a function on the cpu on which a task runs
93 * @p: the task to evaluate
94 * @func: the function to be called
95 * @info: the function call argument
97 * Calls the function @func when the task is currently running. This might
98 * be on the current CPU, which just calls the function directly
100 * returns: @func return value, or
101 * -ESRCH - when the process isn't running
102 * -EAGAIN - when the process moved away
105 task_function_call(struct task_struct *p, remote_function_f func, void *info)
107 struct remote_function_call data = {
116 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
119 } while (ret == -EAGAIN);
125 * cpu_function_call - call a function on the cpu
126 * @func: the function to be called
127 * @info: the function call argument
129 * Calls the function @func on the remote cpu.
131 * returns: @func return value or -ENXIO when the cpu is offline
133 static int cpu_function_call(int cpu, remote_function_f func, void *info)
135 struct remote_function_call data = {
139 .ret = -ENXIO, /* No such CPU */
142 smp_call_function_single(cpu, remote_function, &data, 1);
147 static inline struct perf_cpu_context *
148 __get_cpu_context(struct perf_event_context *ctx)
150 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
153 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
154 struct perf_event_context *ctx)
156 raw_spin_lock(&cpuctx->ctx.lock);
158 raw_spin_lock(&ctx->lock);
161 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
162 struct perf_event_context *ctx)
165 raw_spin_unlock(&ctx->lock);
166 raw_spin_unlock(&cpuctx->ctx.lock);
169 #define TASK_TOMBSTONE ((void *)-1L)
171 static bool is_kernel_event(struct perf_event *event)
173 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
177 * On task ctx scheduling...
179 * When !ctx->nr_events a task context will not be scheduled. This means
180 * we can disable the scheduler hooks (for performance) without leaving
181 * pending task ctx state.
183 * This however results in two special cases:
185 * - removing the last event from a task ctx; this is relatively straight
186 * forward and is done in __perf_remove_from_context.
188 * - adding the first event to a task ctx; this is tricky because we cannot
189 * rely on ctx->is_active and therefore cannot use event_function_call().
190 * See perf_install_in_context().
192 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
195 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
196 struct perf_event_context *, void *);
198 struct event_function_struct {
199 struct perf_event *event;
204 static int event_function(void *info)
206 struct event_function_struct *efs = info;
207 struct perf_event *event = efs->event;
208 struct perf_event_context *ctx = event->ctx;
209 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
210 struct perf_event_context *task_ctx = cpuctx->task_ctx;
213 lockdep_assert_irqs_disabled();
215 perf_ctx_lock(cpuctx, task_ctx);
217 * Since we do the IPI call without holding ctx->lock things can have
218 * changed, double check we hit the task we set out to hit.
221 if (ctx->task != current) {
227 * We only use event_function_call() on established contexts,
228 * and event_function() is only ever called when active (or
229 * rather, we'll have bailed in task_function_call() or the
230 * above ctx->task != current test), therefore we must have
231 * ctx->is_active here.
233 WARN_ON_ONCE(!ctx->is_active);
235 * And since we have ctx->is_active, cpuctx->task_ctx must
238 WARN_ON_ONCE(task_ctx != ctx);
240 WARN_ON_ONCE(&cpuctx->ctx != ctx);
243 efs->func(event, cpuctx, ctx, efs->data);
245 perf_ctx_unlock(cpuctx, task_ctx);
250 static void event_function_call(struct perf_event *event, event_f func, void *data)
252 struct perf_event_context *ctx = event->ctx;
253 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
254 struct event_function_struct efs = {
260 if (!event->parent) {
262 * If this is a !child event, we must hold ctx::mutex to
263 * stabilize the the event->ctx relation. See
264 * perf_event_ctx_lock().
266 lockdep_assert_held(&ctx->mutex);
270 cpu_function_call(event->cpu, event_function, &efs);
274 if (task == TASK_TOMBSTONE)
278 if (!task_function_call(task, event_function, &efs))
281 raw_spin_lock_irq(&ctx->lock);
283 * Reload the task pointer, it might have been changed by
284 * a concurrent perf_event_context_sched_out().
287 if (task == TASK_TOMBSTONE) {
288 raw_spin_unlock_irq(&ctx->lock);
291 if (ctx->is_active) {
292 raw_spin_unlock_irq(&ctx->lock);
295 func(event, NULL, ctx, data);
296 raw_spin_unlock_irq(&ctx->lock);
300 * Similar to event_function_call() + event_function(), but hard assumes IRQs
301 * are already disabled and we're on the right CPU.
303 static void event_function_local(struct perf_event *event, event_f func, void *data)
305 struct perf_event_context *ctx = event->ctx;
306 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
307 struct task_struct *task = READ_ONCE(ctx->task);
308 struct perf_event_context *task_ctx = NULL;
310 lockdep_assert_irqs_disabled();
313 if (task == TASK_TOMBSTONE)
319 perf_ctx_lock(cpuctx, task_ctx);
322 if (task == TASK_TOMBSTONE)
327 * We must be either inactive or active and the right task,
328 * otherwise we're screwed, since we cannot IPI to somewhere
331 if (ctx->is_active) {
332 if (WARN_ON_ONCE(task != current))
335 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
339 WARN_ON_ONCE(&cpuctx->ctx != ctx);
342 func(event, cpuctx, ctx, data);
344 perf_ctx_unlock(cpuctx, task_ctx);
347 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
348 PERF_FLAG_FD_OUTPUT |\
349 PERF_FLAG_PID_CGROUP |\
350 PERF_FLAG_FD_CLOEXEC)
353 * branch priv levels that need permission checks
355 #define PERF_SAMPLE_BRANCH_PERM_PLM \
356 (PERF_SAMPLE_BRANCH_KERNEL |\
357 PERF_SAMPLE_BRANCH_HV)
360 EVENT_FLEXIBLE = 0x1,
363 /* see ctx_resched() for details */
365 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
369 * perf_sched_events : >0 events exist
370 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
373 static void perf_sched_delayed(struct work_struct *work);
374 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
375 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
376 static DEFINE_MUTEX(perf_sched_mutex);
377 static atomic_t perf_sched_count;
379 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
380 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
381 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
383 static atomic_t nr_mmap_events __read_mostly;
384 static atomic_t nr_comm_events __read_mostly;
385 static atomic_t nr_namespaces_events __read_mostly;
386 static atomic_t nr_task_events __read_mostly;
387 static atomic_t nr_freq_events __read_mostly;
388 static atomic_t nr_switch_events __read_mostly;
389 static atomic_t nr_ksymbol_events __read_mostly;
390 static atomic_t nr_bpf_events __read_mostly;
391 static atomic_t nr_cgroup_events __read_mostly;
393 static LIST_HEAD(pmus);
394 static DEFINE_MUTEX(pmus_lock);
395 static struct srcu_struct pmus_srcu;
396 static cpumask_var_t perf_online_mask;
399 * perf event paranoia level:
400 * -1 - not paranoid at all
401 * 0 - disallow raw tracepoint access for unpriv
402 * 1 - disallow cpu events for unpriv
403 * 2 - disallow kernel profiling for unpriv
405 int sysctl_perf_event_paranoid __read_mostly = 2;
407 /* Minimum for 512 kiB + 1 user control page */
408 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
411 * max perf event sample rate
413 #define DEFAULT_MAX_SAMPLE_RATE 100000
414 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
415 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
417 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
419 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
420 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
422 static int perf_sample_allowed_ns __read_mostly =
423 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
425 static void update_perf_cpu_limits(void)
427 u64 tmp = perf_sample_period_ns;
429 tmp *= sysctl_perf_cpu_time_max_percent;
430 tmp = div_u64(tmp, 100);
434 WRITE_ONCE(perf_sample_allowed_ns, tmp);
437 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
439 int perf_proc_update_handler(struct ctl_table *table, int write,
440 void *buffer, size_t *lenp, loff_t *ppos)
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 *buffer, size_t *lenp, loff_t *ppos)
466 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
471 if (sysctl_perf_cpu_time_max_percent == 100 ||
472 sysctl_perf_cpu_time_max_percent == 0) {
474 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
475 WRITE_ONCE(perf_sample_allowed_ns, 0);
477 update_perf_cpu_limits();
484 * perf samples are done in some very critical code paths (NMIs).
485 * If they take too much CPU time, the system can lock up and not
486 * get any real work done. This will drop the sample rate when
487 * we detect that events are taking too long.
489 #define NR_ACCUMULATED_SAMPLES 128
490 static DEFINE_PER_CPU(u64, running_sample_length);
492 static u64 __report_avg;
493 static u64 __report_allowed;
495 static void perf_duration_warn(struct irq_work *w)
497 printk_ratelimited(KERN_INFO
498 "perf: interrupt took too long (%lld > %lld), lowering "
499 "kernel.perf_event_max_sample_rate to %d\n",
500 __report_avg, __report_allowed,
501 sysctl_perf_event_sample_rate);
504 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
506 void perf_sample_event_took(u64 sample_len_ns)
508 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
516 /* Decay the counter by 1 average sample. */
517 running_len = __this_cpu_read(running_sample_length);
518 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
519 running_len += sample_len_ns;
520 __this_cpu_write(running_sample_length, running_len);
523 * Note: this will be biased artifically low until we have
524 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
525 * from having to maintain a count.
527 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
528 if (avg_len <= max_len)
531 __report_avg = avg_len;
532 __report_allowed = max_len;
535 * Compute a throttle threshold 25% below the current duration.
537 avg_len += avg_len / 4;
538 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
544 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
545 WRITE_ONCE(max_samples_per_tick, max);
547 sysctl_perf_event_sample_rate = max * HZ;
548 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
550 if (!irq_work_queue(&perf_duration_work)) {
551 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
552 "kernel.perf_event_max_sample_rate to %d\n",
553 __report_avg, __report_allowed,
554 sysctl_perf_event_sample_rate);
558 static atomic64_t perf_event_id;
560 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
561 enum event_type_t event_type);
563 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
564 enum event_type_t event_type,
565 struct task_struct *task);
567 static void update_context_time(struct perf_event_context *ctx);
568 static u64 perf_event_time(struct perf_event *event);
570 void __weak perf_event_print_debug(void) { }
572 extern __weak const char *perf_pmu_name(void)
577 static inline u64 perf_clock(void)
579 return local_clock();
582 static inline u64 perf_event_clock(struct perf_event *event)
584 return event->clock();
588 * State based event timekeeping...
590 * The basic idea is to use event->state to determine which (if any) time
591 * fields to increment with the current delta. This means we only need to
592 * update timestamps when we change state or when they are explicitly requested
595 * Event groups make things a little more complicated, but not terribly so. The
596 * rules for a group are that if the group leader is OFF the entire group is
597 * OFF, irrespecive of what the group member states are. This results in
598 * __perf_effective_state().
600 * A futher ramification is that when a group leader flips between OFF and
601 * !OFF, we need to update all group member times.
604 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
605 * need to make sure the relevant context time is updated before we try and
606 * update our timestamps.
609 static __always_inline enum perf_event_state
610 __perf_effective_state(struct perf_event *event)
612 struct perf_event *leader = event->group_leader;
614 if (leader->state <= PERF_EVENT_STATE_OFF)
615 return leader->state;
620 static __always_inline void
621 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
623 enum perf_event_state state = __perf_effective_state(event);
624 u64 delta = now - event->tstamp;
626 *enabled = event->total_time_enabled;
627 if (state >= PERF_EVENT_STATE_INACTIVE)
630 *running = event->total_time_running;
631 if (state >= PERF_EVENT_STATE_ACTIVE)
635 static void perf_event_update_time(struct perf_event *event)
637 u64 now = perf_event_time(event);
639 __perf_update_times(event, now, &event->total_time_enabled,
640 &event->total_time_running);
644 static void perf_event_update_sibling_time(struct perf_event *leader)
646 struct perf_event *sibling;
648 for_each_sibling_event(sibling, leader)
649 perf_event_update_time(sibling);
653 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
655 if (event->state == state)
658 perf_event_update_time(event);
660 * If a group leader gets enabled/disabled all its siblings
663 if ((event->state < 0) ^ (state < 0))
664 perf_event_update_sibling_time(event);
666 WRITE_ONCE(event->state, state);
669 #ifdef CONFIG_CGROUP_PERF
672 perf_cgroup_match(struct perf_event *event)
674 struct perf_event_context *ctx = event->ctx;
675 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
677 /* @event doesn't care about cgroup */
681 /* wants specific cgroup scope but @cpuctx isn't associated with any */
686 * Cgroup scoping is recursive. An event enabled for a cgroup is
687 * also enabled for all its descendant cgroups. If @cpuctx's
688 * cgroup is a descendant of @event's (the test covers identity
689 * case), it's a match.
691 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
692 event->cgrp->css.cgroup);
695 static inline void perf_detach_cgroup(struct perf_event *event)
697 css_put(&event->cgrp->css);
701 static inline int is_cgroup_event(struct perf_event *event)
703 return event->cgrp != NULL;
706 static inline u64 perf_cgroup_event_time(struct perf_event *event)
708 struct perf_cgroup_info *t;
710 t = per_cpu_ptr(event->cgrp->info, event->cpu);
714 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
716 struct perf_cgroup_info *info;
721 info = this_cpu_ptr(cgrp->info);
723 info->time += now - info->timestamp;
724 info->timestamp = now;
727 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
729 struct perf_cgroup *cgrp = cpuctx->cgrp;
730 struct cgroup_subsys_state *css;
733 for (css = &cgrp->css; css; css = css->parent) {
734 cgrp = container_of(css, struct perf_cgroup, css);
735 __update_cgrp_time(cgrp);
740 static inline void update_cgrp_time_from_event(struct perf_event *event)
742 struct perf_cgroup *cgrp;
745 * ensure we access cgroup data only when needed and
746 * when we know the cgroup is pinned (css_get)
748 if (!is_cgroup_event(event))
751 cgrp = perf_cgroup_from_task(current, event->ctx);
753 * Do not update time when cgroup is not active
755 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
756 __update_cgrp_time(event->cgrp);
760 perf_cgroup_set_timestamp(struct task_struct *task,
761 struct perf_event_context *ctx)
763 struct perf_cgroup *cgrp;
764 struct perf_cgroup_info *info;
765 struct cgroup_subsys_state *css;
768 * ctx->lock held by caller
769 * ensure we do not access cgroup data
770 * unless we have the cgroup pinned (css_get)
772 if (!task || !ctx->nr_cgroups)
775 cgrp = perf_cgroup_from_task(task, ctx);
777 for (css = &cgrp->css; css; css = css->parent) {
778 cgrp = container_of(css, struct perf_cgroup, css);
779 info = this_cpu_ptr(cgrp->info);
780 info->timestamp = ctx->timestamp;
784 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
786 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
787 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
790 * reschedule events based on the cgroup constraint of task.
792 * mode SWOUT : schedule out everything
793 * mode SWIN : schedule in based on cgroup for next
795 static void perf_cgroup_switch(struct task_struct *task, int mode)
797 struct perf_cpu_context *cpuctx;
798 struct list_head *list;
802 * Disable interrupts and preemption to avoid this CPU's
803 * cgrp_cpuctx_entry to change under us.
805 local_irq_save(flags);
807 list = this_cpu_ptr(&cgrp_cpuctx_list);
808 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
809 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
811 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
812 perf_pmu_disable(cpuctx->ctx.pmu);
814 if (mode & PERF_CGROUP_SWOUT) {
815 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
817 * must not be done before ctxswout due
818 * to event_filter_match() in event_sched_out()
823 if (mode & PERF_CGROUP_SWIN) {
824 WARN_ON_ONCE(cpuctx->cgrp);
826 * set cgrp before ctxsw in to allow
827 * event_filter_match() to not have to pass
829 * we pass the cpuctx->ctx to perf_cgroup_from_task()
830 * because cgorup events are only per-cpu
832 cpuctx->cgrp = perf_cgroup_from_task(task,
834 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
836 perf_pmu_enable(cpuctx->ctx.pmu);
837 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
840 local_irq_restore(flags);
843 static inline void perf_cgroup_sched_out(struct task_struct *task,
844 struct task_struct *next)
846 struct perf_cgroup *cgrp1;
847 struct perf_cgroup *cgrp2 = NULL;
851 * we come here when we know perf_cgroup_events > 0
852 * we do not need to pass the ctx here because we know
853 * we are holding the rcu lock
855 cgrp1 = perf_cgroup_from_task(task, NULL);
856 cgrp2 = perf_cgroup_from_task(next, NULL);
859 * only schedule out current cgroup events if we know
860 * that we are switching to a different cgroup. Otherwise,
861 * do no touch the cgroup events.
864 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
869 static inline void perf_cgroup_sched_in(struct task_struct *prev,
870 struct task_struct *task)
872 struct perf_cgroup *cgrp1;
873 struct perf_cgroup *cgrp2 = NULL;
877 * we come here when we know perf_cgroup_events > 0
878 * we do not need to pass the ctx here because we know
879 * we are holding the rcu lock
881 cgrp1 = perf_cgroup_from_task(task, NULL);
882 cgrp2 = perf_cgroup_from_task(prev, NULL);
885 * only need to schedule in cgroup events if we are changing
886 * cgroup during ctxsw. Cgroup events were not scheduled
887 * out of ctxsw out if that was not the case.
890 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
895 static int perf_cgroup_ensure_storage(struct perf_event *event,
896 struct cgroup_subsys_state *css)
898 struct perf_cpu_context *cpuctx;
899 struct perf_event **storage;
900 int cpu, heap_size, ret = 0;
903 * Allow storage to have sufficent space for an iterator for each
904 * possibly nested cgroup plus an iterator for events with no cgroup.
906 for (heap_size = 1; css; css = css->parent)
909 for_each_possible_cpu(cpu) {
910 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
911 if (heap_size <= cpuctx->heap_size)
914 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
915 GFP_KERNEL, cpu_to_node(cpu));
921 raw_spin_lock_irq(&cpuctx->ctx.lock);
922 if (cpuctx->heap_size < heap_size) {
923 swap(cpuctx->heap, storage);
924 if (storage == cpuctx->heap_default)
926 cpuctx->heap_size = heap_size;
928 raw_spin_unlock_irq(&cpuctx->ctx.lock);
936 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
937 struct perf_event_attr *attr,
938 struct perf_event *group_leader)
940 struct perf_cgroup *cgrp;
941 struct cgroup_subsys_state *css;
942 struct fd f = fdget(fd);
948 css = css_tryget_online_from_dir(f.file->f_path.dentry,
949 &perf_event_cgrp_subsys);
955 ret = perf_cgroup_ensure_storage(event, css);
959 cgrp = container_of(css, struct perf_cgroup, css);
963 * all events in a group must monitor
964 * the same cgroup because a task belongs
965 * to only one perf cgroup at a time
967 if (group_leader && group_leader->cgrp != cgrp) {
968 perf_detach_cgroup(event);
977 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
979 struct perf_cgroup_info *t;
980 t = per_cpu_ptr(event->cgrp->info, event->cpu);
981 event->shadow_ctx_time = now - t->timestamp;
985 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
987 struct perf_cpu_context *cpuctx;
989 if (!is_cgroup_event(event))
993 * Because cgroup events are always per-cpu events,
994 * @ctx == &cpuctx->ctx.
996 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
999 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1000 * matching the event's cgroup, we must do this for every new event,
1001 * because if the first would mismatch, the second would not try again
1002 * and we would leave cpuctx->cgrp unset.
1004 if (ctx->is_active && !cpuctx->cgrp) {
1005 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1007 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1008 cpuctx->cgrp = cgrp;
1011 if (ctx->nr_cgroups++)
1014 list_add(&cpuctx->cgrp_cpuctx_entry,
1015 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1019 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1021 struct perf_cpu_context *cpuctx;
1023 if (!is_cgroup_event(event))
1027 * Because cgroup events are always per-cpu events,
1028 * @ctx == &cpuctx->ctx.
1030 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1032 if (--ctx->nr_cgroups)
1035 if (ctx->is_active && cpuctx->cgrp)
1036 cpuctx->cgrp = NULL;
1038 list_del(&cpuctx->cgrp_cpuctx_entry);
1041 #else /* !CONFIG_CGROUP_PERF */
1044 perf_cgroup_match(struct perf_event *event)
1049 static inline void perf_detach_cgroup(struct perf_event *event)
1052 static inline int is_cgroup_event(struct perf_event *event)
1057 static inline void update_cgrp_time_from_event(struct perf_event *event)
1061 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1065 static inline void perf_cgroup_sched_out(struct task_struct *task,
1066 struct task_struct *next)
1070 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1071 struct task_struct *task)
1075 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1076 struct perf_event_attr *attr,
1077 struct perf_event *group_leader)
1083 perf_cgroup_set_timestamp(struct task_struct *task,
1084 struct perf_event_context *ctx)
1089 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1094 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1098 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1104 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1109 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1115 * set default to be dependent on timer tick just
1116 * like original code
1118 #define PERF_CPU_HRTIMER (1000 / HZ)
1120 * function must be called with interrupts disabled
1122 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1124 struct perf_cpu_context *cpuctx;
1127 lockdep_assert_irqs_disabled();
1129 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1130 rotations = perf_rotate_context(cpuctx);
1132 raw_spin_lock(&cpuctx->hrtimer_lock);
1134 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1136 cpuctx->hrtimer_active = 0;
1137 raw_spin_unlock(&cpuctx->hrtimer_lock);
1139 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1142 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1144 struct hrtimer *timer = &cpuctx->hrtimer;
1145 struct pmu *pmu = cpuctx->ctx.pmu;
1148 /* no multiplexing needed for SW PMU */
1149 if (pmu->task_ctx_nr == perf_sw_context)
1153 * check default is sane, if not set then force to
1154 * default interval (1/tick)
1156 interval = pmu->hrtimer_interval_ms;
1158 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1160 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1162 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1163 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1164 timer->function = perf_mux_hrtimer_handler;
1167 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1169 struct hrtimer *timer = &cpuctx->hrtimer;
1170 struct pmu *pmu = cpuctx->ctx.pmu;
1171 unsigned long flags;
1173 /* not for SW PMU */
1174 if (pmu->task_ctx_nr == perf_sw_context)
1177 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1178 if (!cpuctx->hrtimer_active) {
1179 cpuctx->hrtimer_active = 1;
1180 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1181 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1183 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1188 void perf_pmu_disable(struct pmu *pmu)
1190 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1192 pmu->pmu_disable(pmu);
1195 void perf_pmu_enable(struct pmu *pmu)
1197 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1199 pmu->pmu_enable(pmu);
1202 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1205 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1206 * perf_event_task_tick() are fully serialized because they're strictly cpu
1207 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1208 * disabled, while perf_event_task_tick is called from IRQ context.
1210 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1212 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1214 lockdep_assert_irqs_disabled();
1216 WARN_ON(!list_empty(&ctx->active_ctx_list));
1218 list_add(&ctx->active_ctx_list, head);
1221 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1223 lockdep_assert_irqs_disabled();
1225 WARN_ON(list_empty(&ctx->active_ctx_list));
1227 list_del_init(&ctx->active_ctx_list);
1230 static void get_ctx(struct perf_event_context *ctx)
1232 refcount_inc(&ctx->refcount);
1235 static void free_ctx(struct rcu_head *head)
1237 struct perf_event_context *ctx;
1239 ctx = container_of(head, struct perf_event_context, rcu_head);
1240 kfree(ctx->task_ctx_data);
1244 static void put_ctx(struct perf_event_context *ctx)
1246 if (refcount_dec_and_test(&ctx->refcount)) {
1247 if (ctx->parent_ctx)
1248 put_ctx(ctx->parent_ctx);
1249 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1250 put_task_struct(ctx->task);
1251 call_rcu(&ctx->rcu_head, free_ctx);
1256 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1257 * perf_pmu_migrate_context() we need some magic.
1259 * Those places that change perf_event::ctx will hold both
1260 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1262 * Lock ordering is by mutex address. There are two other sites where
1263 * perf_event_context::mutex nests and those are:
1265 * - perf_event_exit_task_context() [ child , 0 ]
1266 * perf_event_exit_event()
1267 * put_event() [ parent, 1 ]
1269 * - perf_event_init_context() [ parent, 0 ]
1270 * inherit_task_group()
1273 * perf_event_alloc()
1275 * perf_try_init_event() [ child , 1 ]
1277 * While it appears there is an obvious deadlock here -- the parent and child
1278 * nesting levels are inverted between the two. This is in fact safe because
1279 * life-time rules separate them. That is an exiting task cannot fork, and a
1280 * spawning task cannot (yet) exit.
1282 * But remember that that these are parent<->child context relations, and
1283 * migration does not affect children, therefore these two orderings should not
1286 * The change in perf_event::ctx does not affect children (as claimed above)
1287 * because the sys_perf_event_open() case will install a new event and break
1288 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1289 * concerned with cpuctx and that doesn't have children.
1291 * The places that change perf_event::ctx will issue:
1293 * perf_remove_from_context();
1294 * synchronize_rcu();
1295 * perf_install_in_context();
1297 * to affect the change. The remove_from_context() + synchronize_rcu() should
1298 * quiesce the event, after which we can install it in the new location. This
1299 * means that only external vectors (perf_fops, prctl) can perturb the event
1300 * while in transit. Therefore all such accessors should also acquire
1301 * perf_event_context::mutex to serialize against this.
1303 * However; because event->ctx can change while we're waiting to acquire
1304 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1309 * task_struct::perf_event_mutex
1310 * perf_event_context::mutex
1311 * perf_event::child_mutex;
1312 * perf_event_context::lock
1313 * perf_event::mmap_mutex
1315 * perf_addr_filters_head::lock
1319 * cpuctx->mutex / perf_event_context::mutex
1321 static struct perf_event_context *
1322 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1324 struct perf_event_context *ctx;
1328 ctx = READ_ONCE(event->ctx);
1329 if (!refcount_inc_not_zero(&ctx->refcount)) {
1335 mutex_lock_nested(&ctx->mutex, nesting);
1336 if (event->ctx != ctx) {
1337 mutex_unlock(&ctx->mutex);
1345 static inline struct perf_event_context *
1346 perf_event_ctx_lock(struct perf_event *event)
1348 return perf_event_ctx_lock_nested(event, 0);
1351 static void perf_event_ctx_unlock(struct perf_event *event,
1352 struct perf_event_context *ctx)
1354 mutex_unlock(&ctx->mutex);
1359 * This must be done under the ctx->lock, such as to serialize against
1360 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1361 * calling scheduler related locks and ctx->lock nests inside those.
1363 static __must_check struct perf_event_context *
1364 unclone_ctx(struct perf_event_context *ctx)
1366 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1368 lockdep_assert_held(&ctx->lock);
1371 ctx->parent_ctx = NULL;
1377 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1382 * only top level events have the pid namespace they were created in
1385 event = event->parent;
1387 nr = __task_pid_nr_ns(p, type, event->ns);
1388 /* avoid -1 if it is idle thread or runs in another ns */
1389 if (!nr && !pid_alive(p))
1394 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1396 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1399 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1401 return perf_event_pid_type(event, p, PIDTYPE_PID);
1405 * If we inherit events we want to return the parent event id
1408 static u64 primary_event_id(struct perf_event *event)
1413 id = event->parent->id;
1419 * Get the perf_event_context for a task and lock it.
1421 * This has to cope with with the fact that until it is locked,
1422 * the context could get moved to another task.
1424 static struct perf_event_context *
1425 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1427 struct perf_event_context *ctx;
1431 * One of the few rules of preemptible RCU is that one cannot do
1432 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1433 * part of the read side critical section was irqs-enabled -- see
1434 * rcu_read_unlock_special().
1436 * Since ctx->lock nests under rq->lock we must ensure the entire read
1437 * side critical section has interrupts disabled.
1439 local_irq_save(*flags);
1441 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1444 * If this context is a clone of another, it might
1445 * get swapped for another underneath us by
1446 * perf_event_task_sched_out, though the
1447 * rcu_read_lock() protects us from any context
1448 * getting freed. Lock the context and check if it
1449 * got swapped before we could get the lock, and retry
1450 * if so. If we locked the right context, then it
1451 * can't get swapped on us any more.
1453 raw_spin_lock(&ctx->lock);
1454 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1455 raw_spin_unlock(&ctx->lock);
1457 local_irq_restore(*flags);
1461 if (ctx->task == TASK_TOMBSTONE ||
1462 !refcount_inc_not_zero(&ctx->refcount)) {
1463 raw_spin_unlock(&ctx->lock);
1466 WARN_ON_ONCE(ctx->task != task);
1471 local_irq_restore(*flags);
1476 * Get the context for a task and increment its pin_count so it
1477 * can't get swapped to another task. This also increments its
1478 * reference count so that the context can't get freed.
1480 static struct perf_event_context *
1481 perf_pin_task_context(struct task_struct *task, int ctxn)
1483 struct perf_event_context *ctx;
1484 unsigned long flags;
1486 ctx = perf_lock_task_context(task, ctxn, &flags);
1489 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1494 static void perf_unpin_context(struct perf_event_context *ctx)
1496 unsigned long flags;
1498 raw_spin_lock_irqsave(&ctx->lock, flags);
1500 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1504 * Update the record of the current time in a context.
1506 static void update_context_time(struct perf_event_context *ctx)
1508 u64 now = perf_clock();
1510 ctx->time += now - ctx->timestamp;
1511 ctx->timestamp = now;
1514 static u64 perf_event_time(struct perf_event *event)
1516 struct perf_event_context *ctx = event->ctx;
1518 if (is_cgroup_event(event))
1519 return perf_cgroup_event_time(event);
1521 return ctx ? ctx->time : 0;
1524 static enum event_type_t get_event_type(struct perf_event *event)
1526 struct perf_event_context *ctx = event->ctx;
1527 enum event_type_t event_type;
1529 lockdep_assert_held(&ctx->lock);
1532 * It's 'group type', really, because if our group leader is
1533 * pinned, so are we.
1535 if (event->group_leader != event)
1536 event = event->group_leader;
1538 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1540 event_type |= EVENT_CPU;
1546 * Helper function to initialize event group nodes.
1548 static void init_event_group(struct perf_event *event)
1550 RB_CLEAR_NODE(&event->group_node);
1551 event->group_index = 0;
1555 * Extract pinned or flexible groups from the context
1556 * based on event attrs bits.
1558 static struct perf_event_groups *
1559 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1561 if (event->attr.pinned)
1562 return &ctx->pinned_groups;
1564 return &ctx->flexible_groups;
1568 * Helper function to initializes perf_event_group trees.
1570 static void perf_event_groups_init(struct perf_event_groups *groups)
1572 groups->tree = RB_ROOT;
1577 * Compare function for event groups;
1579 * Implements complex key that first sorts by CPU and then by virtual index
1580 * which provides ordering when rotating groups for the same CPU.
1583 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1585 if (left->cpu < right->cpu)
1587 if (left->cpu > right->cpu)
1590 #ifdef CONFIG_CGROUP_PERF
1591 if (left->cgrp != right->cgrp) {
1592 if (!left->cgrp || !left->cgrp->css.cgroup) {
1594 * Left has no cgroup but right does, no cgroups come
1599 if (!right->cgrp || !right->cgrp->css.cgroup) {
1601 * Right has no cgroup but left does, no cgroups come
1606 /* Two dissimilar cgroups, order by id. */
1607 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1614 if (left->group_index < right->group_index)
1616 if (left->group_index > right->group_index)
1623 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1624 * key (see perf_event_groups_less). This places it last inside the CPU
1628 perf_event_groups_insert(struct perf_event_groups *groups,
1629 struct perf_event *event)
1631 struct perf_event *node_event;
1632 struct rb_node *parent;
1633 struct rb_node **node;
1635 event->group_index = ++groups->index;
1637 node = &groups->tree.rb_node;
1642 node_event = container_of(*node, struct perf_event, group_node);
1644 if (perf_event_groups_less(event, node_event))
1645 node = &parent->rb_left;
1647 node = &parent->rb_right;
1650 rb_link_node(&event->group_node, parent, node);
1651 rb_insert_color(&event->group_node, &groups->tree);
1655 * Helper function to insert event into the pinned or flexible groups.
1658 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1660 struct perf_event_groups *groups;
1662 groups = get_event_groups(event, ctx);
1663 perf_event_groups_insert(groups, event);
1667 * Delete a group from a tree.
1670 perf_event_groups_delete(struct perf_event_groups *groups,
1671 struct perf_event *event)
1673 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1674 RB_EMPTY_ROOT(&groups->tree));
1676 rb_erase(&event->group_node, &groups->tree);
1677 init_event_group(event);
1681 * Helper function to delete event from its groups.
1684 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1686 struct perf_event_groups *groups;
1688 groups = get_event_groups(event, ctx);
1689 perf_event_groups_delete(groups, event);
1693 * Get the leftmost event in the cpu/cgroup subtree.
1695 static struct perf_event *
1696 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1697 struct cgroup *cgrp)
1699 struct perf_event *node_event = NULL, *match = NULL;
1700 struct rb_node *node = groups->tree.rb_node;
1701 #ifdef CONFIG_CGROUP_PERF
1702 u64 node_cgrp_id, cgrp_id = 0;
1705 cgrp_id = cgrp->kn->id;
1709 node_event = container_of(node, struct perf_event, group_node);
1711 if (cpu < node_event->cpu) {
1712 node = node->rb_left;
1715 if (cpu > node_event->cpu) {
1716 node = node->rb_right;
1719 #ifdef CONFIG_CGROUP_PERF
1721 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1722 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1724 if (cgrp_id < node_cgrp_id) {
1725 node = node->rb_left;
1728 if (cgrp_id > node_cgrp_id) {
1729 node = node->rb_right;
1734 node = node->rb_left;
1741 * Like rb_entry_next_safe() for the @cpu subtree.
1743 static struct perf_event *
1744 perf_event_groups_next(struct perf_event *event)
1746 struct perf_event *next;
1747 #ifdef CONFIG_CGROUP_PERF
1748 u64 curr_cgrp_id = 0;
1749 u64 next_cgrp_id = 0;
1752 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1753 if (next == NULL || next->cpu != event->cpu)
1756 #ifdef CONFIG_CGROUP_PERF
1757 if (event->cgrp && event->cgrp->css.cgroup)
1758 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1760 if (next->cgrp && next->cgrp->css.cgroup)
1761 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1763 if (curr_cgrp_id != next_cgrp_id)
1770 * Iterate through the whole groups tree.
1772 #define perf_event_groups_for_each(event, groups) \
1773 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1774 typeof(*event), group_node); event; \
1775 event = rb_entry_safe(rb_next(&event->group_node), \
1776 typeof(*event), group_node))
1779 * Add an event from the lists for its context.
1780 * Must be called with ctx->mutex and ctx->lock held.
1783 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1785 lockdep_assert_held(&ctx->lock);
1787 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1788 event->attach_state |= PERF_ATTACH_CONTEXT;
1790 event->tstamp = perf_event_time(event);
1793 * If we're a stand alone event or group leader, we go to the context
1794 * list, group events are kept attached to the group so that
1795 * perf_group_detach can, at all times, locate all siblings.
1797 if (event->group_leader == event) {
1798 event->group_caps = event->event_caps;
1799 add_event_to_groups(event, ctx);
1802 list_add_rcu(&event->event_entry, &ctx->event_list);
1804 if (event->attr.inherit_stat)
1807 if (event->state > PERF_EVENT_STATE_OFF)
1808 perf_cgroup_event_enable(event, ctx);
1814 * Initialize event state based on the perf_event_attr::disabled.
1816 static inline void perf_event__state_init(struct perf_event *event)
1818 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1819 PERF_EVENT_STATE_INACTIVE;
1822 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1824 int entry = sizeof(u64); /* value */
1828 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1829 size += sizeof(u64);
1831 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1832 size += sizeof(u64);
1834 if (event->attr.read_format & PERF_FORMAT_ID)
1835 entry += sizeof(u64);
1837 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1839 size += sizeof(u64);
1843 event->read_size = size;
1846 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1848 struct perf_sample_data *data;
1851 if (sample_type & PERF_SAMPLE_IP)
1852 size += sizeof(data->ip);
1854 if (sample_type & PERF_SAMPLE_ADDR)
1855 size += sizeof(data->addr);
1857 if (sample_type & PERF_SAMPLE_PERIOD)
1858 size += sizeof(data->period);
1860 if (sample_type & PERF_SAMPLE_WEIGHT)
1861 size += sizeof(data->weight);
1863 if (sample_type & PERF_SAMPLE_READ)
1864 size += event->read_size;
1866 if (sample_type & PERF_SAMPLE_DATA_SRC)
1867 size += sizeof(data->data_src.val);
1869 if (sample_type & PERF_SAMPLE_TRANSACTION)
1870 size += sizeof(data->txn);
1872 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1873 size += sizeof(data->phys_addr);
1875 if (sample_type & PERF_SAMPLE_CGROUP)
1876 size += sizeof(data->cgroup);
1878 event->header_size = size;
1882 * Called at perf_event creation and when events are attached/detached from a
1885 static void perf_event__header_size(struct perf_event *event)
1887 __perf_event_read_size(event,
1888 event->group_leader->nr_siblings);
1889 __perf_event_header_size(event, event->attr.sample_type);
1892 static void perf_event__id_header_size(struct perf_event *event)
1894 struct perf_sample_data *data;
1895 u64 sample_type = event->attr.sample_type;
1898 if (sample_type & PERF_SAMPLE_TID)
1899 size += sizeof(data->tid_entry);
1901 if (sample_type & PERF_SAMPLE_TIME)
1902 size += sizeof(data->time);
1904 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1905 size += sizeof(data->id);
1907 if (sample_type & PERF_SAMPLE_ID)
1908 size += sizeof(data->id);
1910 if (sample_type & PERF_SAMPLE_STREAM_ID)
1911 size += sizeof(data->stream_id);
1913 if (sample_type & PERF_SAMPLE_CPU)
1914 size += sizeof(data->cpu_entry);
1916 event->id_header_size = size;
1919 static bool perf_event_validate_size(struct perf_event *event)
1922 * The values computed here will be over-written when we actually
1925 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1926 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1927 perf_event__id_header_size(event);
1930 * Sum the lot; should not exceed the 64k limit we have on records.
1931 * Conservative limit to allow for callchains and other variable fields.
1933 if (event->read_size + event->header_size +
1934 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1940 static void perf_group_attach(struct perf_event *event)
1942 struct perf_event *group_leader = event->group_leader, *pos;
1944 lockdep_assert_held(&event->ctx->lock);
1947 * We can have double attach due to group movement in perf_event_open.
1949 if (event->attach_state & PERF_ATTACH_GROUP)
1952 event->attach_state |= PERF_ATTACH_GROUP;
1954 if (group_leader == event)
1957 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1959 group_leader->group_caps &= event->event_caps;
1961 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1962 group_leader->nr_siblings++;
1964 perf_event__header_size(group_leader);
1966 for_each_sibling_event(pos, group_leader)
1967 perf_event__header_size(pos);
1971 * Remove an event from the lists for its context.
1972 * Must be called with ctx->mutex and ctx->lock held.
1975 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1977 WARN_ON_ONCE(event->ctx != ctx);
1978 lockdep_assert_held(&ctx->lock);
1981 * We can have double detach due to exit/hot-unplug + close.
1983 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1986 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1989 if (event->attr.inherit_stat)
1992 list_del_rcu(&event->event_entry);
1994 if (event->group_leader == event)
1995 del_event_from_groups(event, ctx);
1998 * If event was in error state, then keep it
1999 * that way, otherwise bogus counts will be
2000 * returned on read(). The only way to get out
2001 * of error state is by explicit re-enabling
2004 if (event->state > PERF_EVENT_STATE_OFF) {
2005 perf_cgroup_event_disable(event, ctx);
2006 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2013 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2015 if (!has_aux(aux_event))
2018 if (!event->pmu->aux_output_match)
2021 return event->pmu->aux_output_match(aux_event);
2024 static void put_event(struct perf_event *event);
2025 static void event_sched_out(struct perf_event *event,
2026 struct perf_cpu_context *cpuctx,
2027 struct perf_event_context *ctx);
2029 static void perf_put_aux_event(struct perf_event *event)
2031 struct perf_event_context *ctx = event->ctx;
2032 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2033 struct perf_event *iter;
2036 * If event uses aux_event tear down the link
2038 if (event->aux_event) {
2039 iter = event->aux_event;
2040 event->aux_event = NULL;
2046 * If the event is an aux_event, tear down all links to
2047 * it from other events.
2049 for_each_sibling_event(iter, event->group_leader) {
2050 if (iter->aux_event != event)
2053 iter->aux_event = NULL;
2057 * If it's ACTIVE, schedule it out and put it into ERROR
2058 * state so that we don't try to schedule it again. Note
2059 * that perf_event_enable() will clear the ERROR status.
2061 event_sched_out(iter, cpuctx, ctx);
2062 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2066 static bool perf_need_aux_event(struct perf_event *event)
2068 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2071 static int perf_get_aux_event(struct perf_event *event,
2072 struct perf_event *group_leader)
2075 * Our group leader must be an aux event if we want to be
2076 * an aux_output. This way, the aux event will precede its
2077 * aux_output events in the group, and therefore will always
2084 * aux_output and aux_sample_size are mutually exclusive.
2086 if (event->attr.aux_output && event->attr.aux_sample_size)
2089 if (event->attr.aux_output &&
2090 !perf_aux_output_match(event, group_leader))
2093 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2096 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2100 * Link aux_outputs to their aux event; this is undone in
2101 * perf_group_detach() by perf_put_aux_event(). When the
2102 * group in torn down, the aux_output events loose their
2103 * link to the aux_event and can't schedule any more.
2105 event->aux_event = group_leader;
2110 static inline struct list_head *get_event_list(struct perf_event *event)
2112 struct perf_event_context *ctx = event->ctx;
2113 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2116 static void perf_group_detach(struct perf_event *event)
2118 struct perf_event *sibling, *tmp;
2119 struct perf_event_context *ctx = event->ctx;
2121 lockdep_assert_held(&ctx->lock);
2124 * We can have double detach due to exit/hot-unplug + close.
2126 if (!(event->attach_state & PERF_ATTACH_GROUP))
2129 event->attach_state &= ~PERF_ATTACH_GROUP;
2131 perf_put_aux_event(event);
2134 * If this is a sibling, remove it from its group.
2136 if (event->group_leader != event) {
2137 list_del_init(&event->sibling_list);
2138 event->group_leader->nr_siblings--;
2143 * If this was a group event with sibling events then
2144 * upgrade the siblings to singleton events by adding them
2145 * to whatever list we are on.
2147 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2149 sibling->group_leader = sibling;
2150 list_del_init(&sibling->sibling_list);
2152 /* Inherit group flags from the previous leader */
2153 sibling->group_caps = event->group_caps;
2155 if (!RB_EMPTY_NODE(&event->group_node)) {
2156 add_event_to_groups(sibling, event->ctx);
2158 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2159 list_add_tail(&sibling->active_list, get_event_list(sibling));
2162 WARN_ON_ONCE(sibling->ctx != event->ctx);
2166 perf_event__header_size(event->group_leader);
2168 for_each_sibling_event(tmp, event->group_leader)
2169 perf_event__header_size(tmp);
2172 static bool is_orphaned_event(struct perf_event *event)
2174 return event->state == PERF_EVENT_STATE_DEAD;
2177 static inline int __pmu_filter_match(struct perf_event *event)
2179 struct pmu *pmu = event->pmu;
2180 return pmu->filter_match ? pmu->filter_match(event) : 1;
2184 * Check whether we should attempt to schedule an event group based on
2185 * PMU-specific filtering. An event group can consist of HW and SW events,
2186 * potentially with a SW leader, so we must check all the filters, to
2187 * determine whether a group is schedulable:
2189 static inline int pmu_filter_match(struct perf_event *event)
2191 struct perf_event *sibling;
2193 if (!__pmu_filter_match(event))
2196 for_each_sibling_event(sibling, event) {
2197 if (!__pmu_filter_match(sibling))
2205 event_filter_match(struct perf_event *event)
2207 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2208 perf_cgroup_match(event) && pmu_filter_match(event);
2212 event_sched_out(struct perf_event *event,
2213 struct perf_cpu_context *cpuctx,
2214 struct perf_event_context *ctx)
2216 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2218 WARN_ON_ONCE(event->ctx != ctx);
2219 lockdep_assert_held(&ctx->lock);
2221 if (event->state != PERF_EVENT_STATE_ACTIVE)
2225 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2226 * we can schedule events _OUT_ individually through things like
2227 * __perf_remove_from_context().
2229 list_del_init(&event->active_list);
2231 perf_pmu_disable(event->pmu);
2233 event->pmu->del(event, 0);
2236 if (READ_ONCE(event->pending_disable) >= 0) {
2237 WRITE_ONCE(event->pending_disable, -1);
2238 perf_cgroup_event_disable(event, ctx);
2239 state = PERF_EVENT_STATE_OFF;
2241 perf_event_set_state(event, state);
2243 if (!is_software_event(event))
2244 cpuctx->active_oncpu--;
2245 if (!--ctx->nr_active)
2246 perf_event_ctx_deactivate(ctx);
2247 if (event->attr.freq && event->attr.sample_freq)
2249 if (event->attr.exclusive || !cpuctx->active_oncpu)
2250 cpuctx->exclusive = 0;
2252 perf_pmu_enable(event->pmu);
2256 group_sched_out(struct perf_event *group_event,
2257 struct perf_cpu_context *cpuctx,
2258 struct perf_event_context *ctx)
2260 struct perf_event *event;
2262 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2265 perf_pmu_disable(ctx->pmu);
2267 event_sched_out(group_event, cpuctx, ctx);
2270 * Schedule out siblings (if any):
2272 for_each_sibling_event(event, group_event)
2273 event_sched_out(event, cpuctx, ctx);
2275 perf_pmu_enable(ctx->pmu);
2277 if (group_event->attr.exclusive)
2278 cpuctx->exclusive = 0;
2281 #define DETACH_GROUP 0x01UL
2284 * Cross CPU call to remove a performance event
2286 * We disable the event on the hardware level first. After that we
2287 * remove it from the context list.
2290 __perf_remove_from_context(struct perf_event *event,
2291 struct perf_cpu_context *cpuctx,
2292 struct perf_event_context *ctx,
2295 unsigned long flags = (unsigned long)info;
2297 if (ctx->is_active & EVENT_TIME) {
2298 update_context_time(ctx);
2299 update_cgrp_time_from_cpuctx(cpuctx);
2302 event_sched_out(event, cpuctx, ctx);
2303 if (flags & DETACH_GROUP)
2304 perf_group_detach(event);
2305 list_del_event(event, ctx);
2307 if (!ctx->nr_events && ctx->is_active) {
2309 ctx->rotate_necessary = 0;
2311 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2312 cpuctx->task_ctx = NULL;
2318 * Remove the event from a task's (or a CPU's) list of events.
2320 * If event->ctx is a cloned context, callers must make sure that
2321 * every task struct that event->ctx->task could possibly point to
2322 * remains valid. This is OK when called from perf_release since
2323 * that only calls us on the top-level context, which can't be a clone.
2324 * When called from perf_event_exit_task, it's OK because the
2325 * context has been detached from its task.
2327 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2329 struct perf_event_context *ctx = event->ctx;
2331 lockdep_assert_held(&ctx->mutex);
2333 event_function_call(event, __perf_remove_from_context, (void *)flags);
2336 * The above event_function_call() can NO-OP when it hits
2337 * TASK_TOMBSTONE. In that case we must already have been detached
2338 * from the context (by perf_event_exit_event()) but the grouping
2339 * might still be in-tact.
2341 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2342 if ((flags & DETACH_GROUP) &&
2343 (event->attach_state & PERF_ATTACH_GROUP)) {
2345 * Since in that case we cannot possibly be scheduled, simply
2348 raw_spin_lock_irq(&ctx->lock);
2349 perf_group_detach(event);
2350 raw_spin_unlock_irq(&ctx->lock);
2355 * Cross CPU call to disable a performance event
2357 static void __perf_event_disable(struct perf_event *event,
2358 struct perf_cpu_context *cpuctx,
2359 struct perf_event_context *ctx,
2362 if (event->state < PERF_EVENT_STATE_INACTIVE)
2365 if (ctx->is_active & EVENT_TIME) {
2366 update_context_time(ctx);
2367 update_cgrp_time_from_event(event);
2370 if (event == event->group_leader)
2371 group_sched_out(event, cpuctx, ctx);
2373 event_sched_out(event, cpuctx, ctx);
2375 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2376 perf_cgroup_event_disable(event, ctx);
2382 * If event->ctx is a cloned context, callers must make sure that
2383 * every task struct that event->ctx->task could possibly point to
2384 * remains valid. This condition is satisfied when called through
2385 * perf_event_for_each_child or perf_event_for_each because they
2386 * hold the top-level event's child_mutex, so any descendant that
2387 * goes to exit will block in perf_event_exit_event().
2389 * When called from perf_pending_event it's OK because event->ctx
2390 * is the current context on this CPU and preemption is disabled,
2391 * hence we can't get into perf_event_task_sched_out for this context.
2393 static void _perf_event_disable(struct perf_event *event)
2395 struct perf_event_context *ctx = event->ctx;
2397 raw_spin_lock_irq(&ctx->lock);
2398 if (event->state <= PERF_EVENT_STATE_OFF) {
2399 raw_spin_unlock_irq(&ctx->lock);
2402 raw_spin_unlock_irq(&ctx->lock);
2404 event_function_call(event, __perf_event_disable, NULL);
2407 void perf_event_disable_local(struct perf_event *event)
2409 event_function_local(event, __perf_event_disable, NULL);
2413 * Strictly speaking kernel users cannot create groups and therefore this
2414 * interface does not need the perf_event_ctx_lock() magic.
2416 void perf_event_disable(struct perf_event *event)
2418 struct perf_event_context *ctx;
2420 ctx = perf_event_ctx_lock(event);
2421 _perf_event_disable(event);
2422 perf_event_ctx_unlock(event, ctx);
2424 EXPORT_SYMBOL_GPL(perf_event_disable);
2426 void perf_event_disable_inatomic(struct perf_event *event)
2428 WRITE_ONCE(event->pending_disable, smp_processor_id());
2429 /* can fail, see perf_pending_event_disable() */
2430 irq_work_queue(&event->pending);
2433 static void perf_set_shadow_time(struct perf_event *event,
2434 struct perf_event_context *ctx)
2437 * use the correct time source for the time snapshot
2439 * We could get by without this by leveraging the
2440 * fact that to get to this function, the caller
2441 * has most likely already called update_context_time()
2442 * and update_cgrp_time_xx() and thus both timestamp
2443 * are identical (or very close). Given that tstamp is,
2444 * already adjusted for cgroup, we could say that:
2445 * tstamp - ctx->timestamp
2447 * tstamp - cgrp->timestamp.
2449 * Then, in perf_output_read(), the calculation would
2450 * work with no changes because:
2451 * - event is guaranteed scheduled in
2452 * - no scheduled out in between
2453 * - thus the timestamp would be the same
2455 * But this is a bit hairy.
2457 * So instead, we have an explicit cgroup call to remain
2458 * within the time time source all along. We believe it
2459 * is cleaner and simpler to understand.
2461 if (is_cgroup_event(event))
2462 perf_cgroup_set_shadow_time(event, event->tstamp);
2464 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2467 #define MAX_INTERRUPTS (~0ULL)
2469 static void perf_log_throttle(struct perf_event *event, int enable);
2470 static void perf_log_itrace_start(struct perf_event *event);
2473 event_sched_in(struct perf_event *event,
2474 struct perf_cpu_context *cpuctx,
2475 struct perf_event_context *ctx)
2479 WARN_ON_ONCE(event->ctx != ctx);
2481 lockdep_assert_held(&ctx->lock);
2483 if (event->state <= PERF_EVENT_STATE_OFF)
2486 WRITE_ONCE(event->oncpu, smp_processor_id());
2488 * Order event::oncpu write to happen before the ACTIVE state is
2489 * visible. This allows perf_event_{stop,read}() to observe the correct
2490 * ->oncpu if it sees ACTIVE.
2493 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2496 * Unthrottle events, since we scheduled we might have missed several
2497 * ticks already, also for a heavily scheduling task there is little
2498 * guarantee it'll get a tick in a timely manner.
2500 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2501 perf_log_throttle(event, 1);
2502 event->hw.interrupts = 0;
2505 perf_pmu_disable(event->pmu);
2507 perf_set_shadow_time(event, ctx);
2509 perf_log_itrace_start(event);
2511 if (event->pmu->add(event, PERF_EF_START)) {
2512 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2518 if (!is_software_event(event))
2519 cpuctx->active_oncpu++;
2520 if (!ctx->nr_active++)
2521 perf_event_ctx_activate(ctx);
2522 if (event->attr.freq && event->attr.sample_freq)
2525 if (event->attr.exclusive)
2526 cpuctx->exclusive = 1;
2529 perf_pmu_enable(event->pmu);
2535 group_sched_in(struct perf_event *group_event,
2536 struct perf_cpu_context *cpuctx,
2537 struct perf_event_context *ctx)
2539 struct perf_event *event, *partial_group = NULL;
2540 struct pmu *pmu = ctx->pmu;
2542 if (group_event->state == PERF_EVENT_STATE_OFF)
2545 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2547 if (event_sched_in(group_event, cpuctx, ctx)) {
2548 pmu->cancel_txn(pmu);
2549 perf_mux_hrtimer_restart(cpuctx);
2554 * Schedule in siblings as one group (if any):
2556 for_each_sibling_event(event, group_event) {
2557 if (event_sched_in(event, cpuctx, ctx)) {
2558 partial_group = event;
2563 if (!pmu->commit_txn(pmu))
2568 * Groups can be scheduled in as one unit only, so undo any
2569 * partial group before returning:
2570 * The events up to the failed event are scheduled out normally.
2572 for_each_sibling_event(event, group_event) {
2573 if (event == partial_group)
2576 event_sched_out(event, cpuctx, ctx);
2578 event_sched_out(group_event, cpuctx, ctx);
2580 pmu->cancel_txn(pmu);
2582 perf_mux_hrtimer_restart(cpuctx);
2588 * Work out whether we can put this event group on the CPU now.
2590 static int group_can_go_on(struct perf_event *event,
2591 struct perf_cpu_context *cpuctx,
2595 * Groups consisting entirely of software events can always go on.
2597 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2600 * If an exclusive group is already on, no other hardware
2603 if (cpuctx->exclusive)
2606 * If this group is exclusive and there are already
2607 * events on the CPU, it can't go on.
2609 if (event->attr.exclusive && cpuctx->active_oncpu)
2612 * Otherwise, try to add it if all previous groups were able
2618 static void add_event_to_ctx(struct perf_event *event,
2619 struct perf_event_context *ctx)
2621 list_add_event(event, ctx);
2622 perf_group_attach(event);
2625 static void ctx_sched_out(struct perf_event_context *ctx,
2626 struct perf_cpu_context *cpuctx,
2627 enum event_type_t event_type);
2629 ctx_sched_in(struct perf_event_context *ctx,
2630 struct perf_cpu_context *cpuctx,
2631 enum event_type_t event_type,
2632 struct task_struct *task);
2634 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2635 struct perf_event_context *ctx,
2636 enum event_type_t event_type)
2638 if (!cpuctx->task_ctx)
2641 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2644 ctx_sched_out(ctx, cpuctx, event_type);
2647 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2648 struct perf_event_context *ctx,
2649 struct task_struct *task)
2651 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2653 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2654 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2656 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2660 * We want to maintain the following priority of scheduling:
2661 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2662 * - task pinned (EVENT_PINNED)
2663 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2664 * - task flexible (EVENT_FLEXIBLE).
2666 * In order to avoid unscheduling and scheduling back in everything every
2667 * time an event is added, only do it for the groups of equal priority and
2670 * This can be called after a batch operation on task events, in which case
2671 * event_type is a bit mask of the types of events involved. For CPU events,
2672 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2674 static void ctx_resched(struct perf_cpu_context *cpuctx,
2675 struct perf_event_context *task_ctx,
2676 enum event_type_t event_type)
2678 enum event_type_t ctx_event_type;
2679 bool cpu_event = !!(event_type & EVENT_CPU);
2682 * If pinned groups are involved, flexible groups also need to be
2685 if (event_type & EVENT_PINNED)
2686 event_type |= EVENT_FLEXIBLE;
2688 ctx_event_type = event_type & EVENT_ALL;
2690 perf_pmu_disable(cpuctx->ctx.pmu);
2692 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2695 * Decide which cpu ctx groups to schedule out based on the types
2696 * of events that caused rescheduling:
2697 * - EVENT_CPU: schedule out corresponding groups;
2698 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2699 * - otherwise, do nothing more.
2702 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2703 else if (ctx_event_type & EVENT_PINNED)
2704 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2706 perf_event_sched_in(cpuctx, task_ctx, current);
2707 perf_pmu_enable(cpuctx->ctx.pmu);
2710 void perf_pmu_resched(struct pmu *pmu)
2712 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2713 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2715 perf_ctx_lock(cpuctx, task_ctx);
2716 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2717 perf_ctx_unlock(cpuctx, task_ctx);
2721 * Cross CPU call to install and enable a performance event
2723 * Very similar to remote_function() + event_function() but cannot assume that
2724 * things like ctx->is_active and cpuctx->task_ctx are set.
2726 static int __perf_install_in_context(void *info)
2728 struct perf_event *event = info;
2729 struct perf_event_context *ctx = event->ctx;
2730 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2731 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2732 bool reprogram = true;
2735 raw_spin_lock(&cpuctx->ctx.lock);
2737 raw_spin_lock(&ctx->lock);
2740 reprogram = (ctx->task == current);
2743 * If the task is running, it must be running on this CPU,
2744 * otherwise we cannot reprogram things.
2746 * If its not running, we don't care, ctx->lock will
2747 * serialize against it becoming runnable.
2749 if (task_curr(ctx->task) && !reprogram) {
2754 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2755 } else if (task_ctx) {
2756 raw_spin_lock(&task_ctx->lock);
2759 #ifdef CONFIG_CGROUP_PERF
2760 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2762 * If the current cgroup doesn't match the event's
2763 * cgroup, we should not try to schedule it.
2765 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2766 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2767 event->cgrp->css.cgroup);
2772 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2773 add_event_to_ctx(event, ctx);
2774 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2776 add_event_to_ctx(event, ctx);
2780 perf_ctx_unlock(cpuctx, task_ctx);
2785 static bool exclusive_event_installable(struct perf_event *event,
2786 struct perf_event_context *ctx);
2789 * Attach a performance event to a context.
2791 * Very similar to event_function_call, see comment there.
2794 perf_install_in_context(struct perf_event_context *ctx,
2795 struct perf_event *event,
2798 struct task_struct *task = READ_ONCE(ctx->task);
2800 lockdep_assert_held(&ctx->mutex);
2802 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2804 if (event->cpu != -1)
2808 * Ensures that if we can observe event->ctx, both the event and ctx
2809 * will be 'complete'. See perf_iterate_sb_cpu().
2811 smp_store_release(&event->ctx, ctx);
2814 * perf_event_attr::disabled events will not run and can be initialized
2815 * without IPI. Except when this is the first event for the context, in
2816 * that case we need the magic of the IPI to set ctx->is_active.
2818 * The IOC_ENABLE that is sure to follow the creation of a disabled
2819 * event will issue the IPI and reprogram the hardware.
2821 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2822 raw_spin_lock_irq(&ctx->lock);
2823 if (ctx->task == TASK_TOMBSTONE) {
2824 raw_spin_unlock_irq(&ctx->lock);
2827 add_event_to_ctx(event, ctx);
2828 raw_spin_unlock_irq(&ctx->lock);
2833 cpu_function_call(cpu, __perf_install_in_context, event);
2838 * Should not happen, we validate the ctx is still alive before calling.
2840 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2844 * Installing events is tricky because we cannot rely on ctx->is_active
2845 * to be set in case this is the nr_events 0 -> 1 transition.
2847 * Instead we use task_curr(), which tells us if the task is running.
2848 * However, since we use task_curr() outside of rq::lock, we can race
2849 * against the actual state. This means the result can be wrong.
2851 * If we get a false positive, we retry, this is harmless.
2853 * If we get a false negative, things are complicated. If we are after
2854 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2855 * value must be correct. If we're before, it doesn't matter since
2856 * perf_event_context_sched_in() will program the counter.
2858 * However, this hinges on the remote context switch having observed
2859 * our task->perf_event_ctxp[] store, such that it will in fact take
2860 * ctx::lock in perf_event_context_sched_in().
2862 * We do this by task_function_call(), if the IPI fails to hit the task
2863 * we know any future context switch of task must see the
2864 * perf_event_ctpx[] store.
2868 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2869 * task_cpu() load, such that if the IPI then does not find the task
2870 * running, a future context switch of that task must observe the
2875 if (!task_function_call(task, __perf_install_in_context, event))
2878 raw_spin_lock_irq(&ctx->lock);
2880 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2882 * Cannot happen because we already checked above (which also
2883 * cannot happen), and we hold ctx->mutex, which serializes us
2884 * against perf_event_exit_task_context().
2886 raw_spin_unlock_irq(&ctx->lock);
2890 * If the task is not running, ctx->lock will avoid it becoming so,
2891 * thus we can safely install the event.
2893 if (task_curr(task)) {
2894 raw_spin_unlock_irq(&ctx->lock);
2897 add_event_to_ctx(event, ctx);
2898 raw_spin_unlock_irq(&ctx->lock);
2902 * Cross CPU call to enable a performance event
2904 static void __perf_event_enable(struct perf_event *event,
2905 struct perf_cpu_context *cpuctx,
2906 struct perf_event_context *ctx,
2909 struct perf_event *leader = event->group_leader;
2910 struct perf_event_context *task_ctx;
2912 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2913 event->state <= PERF_EVENT_STATE_ERROR)
2917 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2919 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2920 perf_cgroup_event_enable(event, ctx);
2922 if (!ctx->is_active)
2925 if (!event_filter_match(event)) {
2926 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2931 * If the event is in a group and isn't the group leader,
2932 * then don't put it on unless the group is on.
2934 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2935 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2939 task_ctx = cpuctx->task_ctx;
2941 WARN_ON_ONCE(task_ctx != ctx);
2943 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2949 * If event->ctx is a cloned context, callers must make sure that
2950 * every task struct that event->ctx->task could possibly point to
2951 * remains valid. This condition is satisfied when called through
2952 * perf_event_for_each_child or perf_event_for_each as described
2953 * for perf_event_disable.
2955 static void _perf_event_enable(struct perf_event *event)
2957 struct perf_event_context *ctx = event->ctx;
2959 raw_spin_lock_irq(&ctx->lock);
2960 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2961 event->state < PERF_EVENT_STATE_ERROR) {
2962 raw_spin_unlock_irq(&ctx->lock);
2967 * If the event is in error state, clear that first.
2969 * That way, if we see the event in error state below, we know that it
2970 * has gone back into error state, as distinct from the task having
2971 * been scheduled away before the cross-call arrived.
2973 if (event->state == PERF_EVENT_STATE_ERROR)
2974 event->state = PERF_EVENT_STATE_OFF;
2975 raw_spin_unlock_irq(&ctx->lock);
2977 event_function_call(event, __perf_event_enable, NULL);
2981 * See perf_event_disable();
2983 void perf_event_enable(struct perf_event *event)
2985 struct perf_event_context *ctx;
2987 ctx = perf_event_ctx_lock(event);
2988 _perf_event_enable(event);
2989 perf_event_ctx_unlock(event, ctx);
2991 EXPORT_SYMBOL_GPL(perf_event_enable);
2993 struct stop_event_data {
2994 struct perf_event *event;
2995 unsigned int restart;
2998 static int __perf_event_stop(void *info)
3000 struct stop_event_data *sd = info;
3001 struct perf_event *event = sd->event;
3003 /* if it's already INACTIVE, do nothing */
3004 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3007 /* matches smp_wmb() in event_sched_in() */
3011 * There is a window with interrupts enabled before we get here,
3012 * so we need to check again lest we try to stop another CPU's event.
3014 if (READ_ONCE(event->oncpu) != smp_processor_id())
3017 event->pmu->stop(event, PERF_EF_UPDATE);
3020 * May race with the actual stop (through perf_pmu_output_stop()),
3021 * but it is only used for events with AUX ring buffer, and such
3022 * events will refuse to restart because of rb::aux_mmap_count==0,
3023 * see comments in perf_aux_output_begin().
3025 * Since this is happening on an event-local CPU, no trace is lost
3029 event->pmu->start(event, 0);
3034 static int perf_event_stop(struct perf_event *event, int restart)
3036 struct stop_event_data sd = {
3043 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3046 /* matches smp_wmb() in event_sched_in() */
3050 * We only want to restart ACTIVE events, so if the event goes
3051 * inactive here (event->oncpu==-1), there's nothing more to do;
3052 * fall through with ret==-ENXIO.
3054 ret = cpu_function_call(READ_ONCE(event->oncpu),
3055 __perf_event_stop, &sd);
3056 } while (ret == -EAGAIN);
3062 * In order to contain the amount of racy and tricky in the address filter
3063 * configuration management, it is a two part process:
3065 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3066 * we update the addresses of corresponding vmas in
3067 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3068 * (p2) when an event is scheduled in (pmu::add), it calls
3069 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3070 * if the generation has changed since the previous call.
3072 * If (p1) happens while the event is active, we restart it to force (p2).
3074 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3075 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3077 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3078 * registered mapping, called for every new mmap(), with mm::mmap_sem down
3080 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3083 void perf_event_addr_filters_sync(struct perf_event *event)
3085 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3087 if (!has_addr_filter(event))
3090 raw_spin_lock(&ifh->lock);
3091 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3092 event->pmu->addr_filters_sync(event);
3093 event->hw.addr_filters_gen = event->addr_filters_gen;
3095 raw_spin_unlock(&ifh->lock);
3097 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3099 static int _perf_event_refresh(struct perf_event *event, int refresh)
3102 * not supported on inherited events
3104 if (event->attr.inherit || !is_sampling_event(event))
3107 atomic_add(refresh, &event->event_limit);
3108 _perf_event_enable(event);
3114 * See perf_event_disable()
3116 int perf_event_refresh(struct perf_event *event, int refresh)
3118 struct perf_event_context *ctx;
3121 ctx = perf_event_ctx_lock(event);
3122 ret = _perf_event_refresh(event, refresh);
3123 perf_event_ctx_unlock(event, ctx);
3127 EXPORT_SYMBOL_GPL(perf_event_refresh);
3129 static int perf_event_modify_breakpoint(struct perf_event *bp,
3130 struct perf_event_attr *attr)
3134 _perf_event_disable(bp);
3136 err = modify_user_hw_breakpoint_check(bp, attr, true);
3138 if (!bp->attr.disabled)
3139 _perf_event_enable(bp);
3144 static int perf_event_modify_attr(struct perf_event *event,
3145 struct perf_event_attr *attr)
3147 if (event->attr.type != attr->type)
3150 switch (event->attr.type) {
3151 case PERF_TYPE_BREAKPOINT:
3152 return perf_event_modify_breakpoint(event, attr);
3154 /* Place holder for future additions. */
3159 static void ctx_sched_out(struct perf_event_context *ctx,
3160 struct perf_cpu_context *cpuctx,
3161 enum event_type_t event_type)
3163 struct perf_event *event, *tmp;
3164 int is_active = ctx->is_active;
3166 lockdep_assert_held(&ctx->lock);
3168 if (likely(!ctx->nr_events)) {
3170 * See __perf_remove_from_context().
3172 WARN_ON_ONCE(ctx->is_active);
3174 WARN_ON_ONCE(cpuctx->task_ctx);
3178 ctx->is_active &= ~event_type;
3179 if (!(ctx->is_active & EVENT_ALL))
3183 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3184 if (!ctx->is_active)
3185 cpuctx->task_ctx = NULL;
3189 * Always update time if it was set; not only when it changes.
3190 * Otherwise we can 'forget' to update time for any but the last
3191 * context we sched out. For example:
3193 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3194 * ctx_sched_out(.event_type = EVENT_PINNED)
3196 * would only update time for the pinned events.
3198 if (is_active & EVENT_TIME) {
3199 /* update (and stop) ctx time */
3200 update_context_time(ctx);
3201 update_cgrp_time_from_cpuctx(cpuctx);
3204 is_active ^= ctx->is_active; /* changed bits */
3206 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3209 perf_pmu_disable(ctx->pmu);
3210 if (is_active & EVENT_PINNED) {
3211 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3212 group_sched_out(event, cpuctx, ctx);
3215 if (is_active & EVENT_FLEXIBLE) {
3216 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3217 group_sched_out(event, cpuctx, ctx);
3220 * Since we cleared EVENT_FLEXIBLE, also clear
3221 * rotate_necessary, is will be reset by
3222 * ctx_flexible_sched_in() when needed.
3224 ctx->rotate_necessary = 0;
3226 perf_pmu_enable(ctx->pmu);
3230 * Test whether two contexts are equivalent, i.e. whether they have both been
3231 * cloned from the same version of the same context.
3233 * Equivalence is measured using a generation number in the context that is
3234 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3235 * and list_del_event().
3237 static int context_equiv(struct perf_event_context *ctx1,
3238 struct perf_event_context *ctx2)
3240 lockdep_assert_held(&ctx1->lock);
3241 lockdep_assert_held(&ctx2->lock);
3243 /* Pinning disables the swap optimization */
3244 if (ctx1->pin_count || ctx2->pin_count)
3247 /* If ctx1 is the parent of ctx2 */
3248 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3251 /* If ctx2 is the parent of ctx1 */
3252 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3256 * If ctx1 and ctx2 have the same parent; we flatten the parent
3257 * hierarchy, see perf_event_init_context().
3259 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3260 ctx1->parent_gen == ctx2->parent_gen)
3267 static void __perf_event_sync_stat(struct perf_event *event,
3268 struct perf_event *next_event)
3272 if (!event->attr.inherit_stat)
3276 * Update the event value, we cannot use perf_event_read()
3277 * because we're in the middle of a context switch and have IRQs
3278 * disabled, which upsets smp_call_function_single(), however
3279 * we know the event must be on the current CPU, therefore we
3280 * don't need to use it.
3282 if (event->state == PERF_EVENT_STATE_ACTIVE)
3283 event->pmu->read(event);
3285 perf_event_update_time(event);
3288 * In order to keep per-task stats reliable we need to flip the event
3289 * values when we flip the contexts.
3291 value = local64_read(&next_event->count);
3292 value = local64_xchg(&event->count, value);
3293 local64_set(&next_event->count, value);
3295 swap(event->total_time_enabled, next_event->total_time_enabled);
3296 swap(event->total_time_running, next_event->total_time_running);
3299 * Since we swizzled the values, update the user visible data too.
3301 perf_event_update_userpage(event);
3302 perf_event_update_userpage(next_event);
3305 static void perf_event_sync_stat(struct perf_event_context *ctx,
3306 struct perf_event_context *next_ctx)
3308 struct perf_event *event, *next_event;
3313 update_context_time(ctx);
3315 event = list_first_entry(&ctx->event_list,
3316 struct perf_event, event_entry);
3318 next_event = list_first_entry(&next_ctx->event_list,
3319 struct perf_event, event_entry);
3321 while (&event->event_entry != &ctx->event_list &&
3322 &next_event->event_entry != &next_ctx->event_list) {
3324 __perf_event_sync_stat(event, next_event);
3326 event = list_next_entry(event, event_entry);
3327 next_event = list_next_entry(next_event, event_entry);
3331 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3332 struct task_struct *next)
3334 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3335 struct perf_event_context *next_ctx;
3336 struct perf_event_context *parent, *next_parent;
3337 struct perf_cpu_context *cpuctx;
3343 cpuctx = __get_cpu_context(ctx);
3344 if (!cpuctx->task_ctx)
3348 next_ctx = next->perf_event_ctxp[ctxn];
3352 parent = rcu_dereference(ctx->parent_ctx);
3353 next_parent = rcu_dereference(next_ctx->parent_ctx);
3355 /* If neither context have a parent context; they cannot be clones. */
3356 if (!parent && !next_parent)
3359 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3361 * Looks like the two contexts are clones, so we might be
3362 * able to optimize the context switch. We lock both
3363 * contexts and check that they are clones under the
3364 * lock (including re-checking that neither has been
3365 * uncloned in the meantime). It doesn't matter which
3366 * order we take the locks because no other cpu could
3367 * be trying to lock both of these tasks.
3369 raw_spin_lock(&ctx->lock);
3370 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3371 if (context_equiv(ctx, next_ctx)) {
3372 struct pmu *pmu = ctx->pmu;
3374 WRITE_ONCE(ctx->task, next);
3375 WRITE_ONCE(next_ctx->task, task);
3378 * PMU specific parts of task perf context can require
3379 * additional synchronization. As an example of such
3380 * synchronization see implementation details of Intel
3381 * LBR call stack data profiling;
3383 if (pmu->swap_task_ctx)
3384 pmu->swap_task_ctx(ctx, next_ctx);
3386 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3389 * RCU_INIT_POINTER here is safe because we've not
3390 * modified the ctx and the above modification of
3391 * ctx->task and ctx->task_ctx_data are immaterial
3392 * since those values are always verified under
3393 * ctx->lock which we're now holding.
3395 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3396 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3400 perf_event_sync_stat(ctx, next_ctx);
3402 raw_spin_unlock(&next_ctx->lock);
3403 raw_spin_unlock(&ctx->lock);
3409 raw_spin_lock(&ctx->lock);
3410 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3411 raw_spin_unlock(&ctx->lock);
3415 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3417 void perf_sched_cb_dec(struct pmu *pmu)
3419 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3421 this_cpu_dec(perf_sched_cb_usages);
3423 if (!--cpuctx->sched_cb_usage)
3424 list_del(&cpuctx->sched_cb_entry);
3428 void perf_sched_cb_inc(struct pmu *pmu)
3430 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3432 if (!cpuctx->sched_cb_usage++)
3433 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3435 this_cpu_inc(perf_sched_cb_usages);
3439 * This function provides the context switch callback to the lower code
3440 * layer. It is invoked ONLY when the context switch callback is enabled.
3442 * This callback is relevant even to per-cpu events; for example multi event
3443 * PEBS requires this to provide PID/TID information. This requires we flush
3444 * all queued PEBS records before we context switch to a new task.
3446 static void perf_pmu_sched_task(struct task_struct *prev,
3447 struct task_struct *next,
3450 struct perf_cpu_context *cpuctx;
3456 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3457 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3459 if (WARN_ON_ONCE(!pmu->sched_task))
3462 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3463 perf_pmu_disable(pmu);
3465 pmu->sched_task(cpuctx->task_ctx, sched_in);
3467 perf_pmu_enable(pmu);
3468 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3472 static void perf_event_switch(struct task_struct *task,
3473 struct task_struct *next_prev, bool sched_in);
3475 #define for_each_task_context_nr(ctxn) \
3476 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3479 * Called from scheduler to remove the events of the current task,
3480 * with interrupts disabled.
3482 * We stop each event and update the event value in event->count.
3484 * This does not protect us against NMI, but disable()
3485 * sets the disabled bit in the control field of event _before_
3486 * accessing the event control register. If a NMI hits, then it will
3487 * not restart the event.
3489 void __perf_event_task_sched_out(struct task_struct *task,
3490 struct task_struct *next)
3494 if (__this_cpu_read(perf_sched_cb_usages))
3495 perf_pmu_sched_task(task, next, false);
3497 if (atomic_read(&nr_switch_events))
3498 perf_event_switch(task, next, false);
3500 for_each_task_context_nr(ctxn)
3501 perf_event_context_sched_out(task, ctxn, next);
3504 * if cgroup events exist on this CPU, then we need
3505 * to check if we have to switch out PMU state.
3506 * cgroup event are system-wide mode only
3508 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3509 perf_cgroup_sched_out(task, next);
3513 * Called with IRQs disabled
3515 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3516 enum event_type_t event_type)
3518 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3521 static bool perf_less_group_idx(const void *l, const void *r)
3523 const struct perf_event *le = *(const struct perf_event **)l;
3524 const struct perf_event *re = *(const struct perf_event **)r;
3526 return le->group_index < re->group_index;
3529 static void swap_ptr(void *l, void *r)
3531 void **lp = l, **rp = r;
3536 static const struct min_heap_callbacks perf_min_heap = {
3537 .elem_size = sizeof(struct perf_event *),
3538 .less = perf_less_group_idx,
3542 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3544 struct perf_event **itrs = heap->data;
3547 itrs[heap->nr] = event;
3552 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3553 struct perf_event_groups *groups, int cpu,
3554 int (*func)(struct perf_event *, void *),
3557 #ifdef CONFIG_CGROUP_PERF
3558 struct cgroup_subsys_state *css = NULL;
3560 /* Space for per CPU and/or any CPU event iterators. */
3561 struct perf_event *itrs[2];
3562 struct min_heap event_heap;
3563 struct perf_event **evt;
3567 event_heap = (struct min_heap){
3568 .data = cpuctx->heap,
3570 .size = cpuctx->heap_size,
3573 lockdep_assert_held(&cpuctx->ctx.lock);
3575 #ifdef CONFIG_CGROUP_PERF
3577 css = &cpuctx->cgrp->css;
3580 event_heap = (struct min_heap){
3583 .size = ARRAY_SIZE(itrs),
3585 /* Events not within a CPU context may be on any CPU. */
3586 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3588 evt = event_heap.data;
3590 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3592 #ifdef CONFIG_CGROUP_PERF
3593 for (; css; css = css->parent)
3594 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3597 min_heapify_all(&event_heap, &perf_min_heap);
3599 while (event_heap.nr) {
3600 ret = func(*evt, data);
3604 *evt = perf_event_groups_next(*evt);
3606 min_heapify(&event_heap, 0, &perf_min_heap);
3608 min_heap_pop(&event_heap, &perf_min_heap);
3614 static int merge_sched_in(struct perf_event *event, void *data)
3616 struct perf_event_context *ctx = event->ctx;
3617 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3618 int *can_add_hw = data;
3620 if (event->state <= PERF_EVENT_STATE_OFF)
3623 if (!event_filter_match(event))
3626 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3627 if (!group_sched_in(event, cpuctx, ctx))
3628 list_add_tail(&event->active_list, get_event_list(event));
3631 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3632 if (event->attr.pinned) {
3633 perf_cgroup_event_disable(event, ctx);
3634 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3638 ctx->rotate_necessary = 1;
3645 ctx_pinned_sched_in(struct perf_event_context *ctx,
3646 struct perf_cpu_context *cpuctx)
3650 if (ctx != &cpuctx->ctx)
3653 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3655 merge_sched_in, &can_add_hw);
3659 ctx_flexible_sched_in(struct perf_event_context *ctx,
3660 struct perf_cpu_context *cpuctx)
3664 if (ctx != &cpuctx->ctx)
3667 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3669 merge_sched_in, &can_add_hw);
3673 ctx_sched_in(struct perf_event_context *ctx,
3674 struct perf_cpu_context *cpuctx,
3675 enum event_type_t event_type,
3676 struct task_struct *task)
3678 int is_active = ctx->is_active;
3681 lockdep_assert_held(&ctx->lock);
3683 if (likely(!ctx->nr_events))
3686 ctx->is_active |= (event_type | EVENT_TIME);
3689 cpuctx->task_ctx = ctx;
3691 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3694 is_active ^= ctx->is_active; /* changed bits */
3696 if (is_active & EVENT_TIME) {
3697 /* start ctx time */
3699 ctx->timestamp = now;
3700 perf_cgroup_set_timestamp(task, ctx);
3704 * First go through the list and put on any pinned groups
3705 * in order to give them the best chance of going on.
3707 if (is_active & EVENT_PINNED)
3708 ctx_pinned_sched_in(ctx, cpuctx);
3710 /* Then walk through the lower prio flexible groups */
3711 if (is_active & EVENT_FLEXIBLE)
3712 ctx_flexible_sched_in(ctx, cpuctx);
3715 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3716 enum event_type_t event_type,
3717 struct task_struct *task)
3719 struct perf_event_context *ctx = &cpuctx->ctx;
3721 ctx_sched_in(ctx, cpuctx, event_type, task);
3724 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3725 struct task_struct *task)
3727 struct perf_cpu_context *cpuctx;
3729 cpuctx = __get_cpu_context(ctx);
3730 if (cpuctx->task_ctx == ctx)
3733 perf_ctx_lock(cpuctx, ctx);
3735 * We must check ctx->nr_events while holding ctx->lock, such
3736 * that we serialize against perf_install_in_context().
3738 if (!ctx->nr_events)
3741 perf_pmu_disable(ctx->pmu);
3743 * We want to keep the following priority order:
3744 * cpu pinned (that don't need to move), task pinned,
3745 * cpu flexible, task flexible.
3747 * However, if task's ctx is not carrying any pinned
3748 * events, no need to flip the cpuctx's events around.
3750 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3751 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3752 perf_event_sched_in(cpuctx, ctx, task);
3753 perf_pmu_enable(ctx->pmu);
3756 perf_ctx_unlock(cpuctx, ctx);
3760 * Called from scheduler to add the events of the current task
3761 * with interrupts disabled.
3763 * We restore the event value and then enable it.
3765 * This does not protect us against NMI, but enable()
3766 * sets the enabled bit in the control field of event _before_
3767 * accessing the event control register. If a NMI hits, then it will
3768 * keep the event running.
3770 void __perf_event_task_sched_in(struct task_struct *prev,
3771 struct task_struct *task)
3773 struct perf_event_context *ctx;
3777 * If cgroup events exist on this CPU, then we need to check if we have
3778 * to switch in PMU state; cgroup event are system-wide mode only.
3780 * Since cgroup events are CPU events, we must schedule these in before
3781 * we schedule in the task events.
3783 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3784 perf_cgroup_sched_in(prev, task);
3786 for_each_task_context_nr(ctxn) {
3787 ctx = task->perf_event_ctxp[ctxn];
3791 perf_event_context_sched_in(ctx, task);
3794 if (atomic_read(&nr_switch_events))
3795 perf_event_switch(task, prev, true);
3797 if (__this_cpu_read(perf_sched_cb_usages))
3798 perf_pmu_sched_task(prev, task, true);
3801 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3803 u64 frequency = event->attr.sample_freq;
3804 u64 sec = NSEC_PER_SEC;
3805 u64 divisor, dividend;
3807 int count_fls, nsec_fls, frequency_fls, sec_fls;
3809 count_fls = fls64(count);
3810 nsec_fls = fls64(nsec);
3811 frequency_fls = fls64(frequency);
3815 * We got @count in @nsec, with a target of sample_freq HZ
3816 * the target period becomes:
3819 * period = -------------------
3820 * @nsec * sample_freq
3825 * Reduce accuracy by one bit such that @a and @b converge
3826 * to a similar magnitude.
3828 #define REDUCE_FLS(a, b) \
3830 if (a##_fls > b##_fls) { \
3840 * Reduce accuracy until either term fits in a u64, then proceed with
3841 * the other, so that finally we can do a u64/u64 division.
3843 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3844 REDUCE_FLS(nsec, frequency);
3845 REDUCE_FLS(sec, count);
3848 if (count_fls + sec_fls > 64) {
3849 divisor = nsec * frequency;
3851 while (count_fls + sec_fls > 64) {
3852 REDUCE_FLS(count, sec);
3856 dividend = count * sec;
3858 dividend = count * sec;
3860 while (nsec_fls + frequency_fls > 64) {
3861 REDUCE_FLS(nsec, frequency);
3865 divisor = nsec * frequency;
3871 return div64_u64(dividend, divisor);
3874 static DEFINE_PER_CPU(int, perf_throttled_count);
3875 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3877 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3879 struct hw_perf_event *hwc = &event->hw;
3880 s64 period, sample_period;
3883 period = perf_calculate_period(event, nsec, count);
3885 delta = (s64)(period - hwc->sample_period);
3886 delta = (delta + 7) / 8; /* low pass filter */
3888 sample_period = hwc->sample_period + delta;
3893 hwc->sample_period = sample_period;
3895 if (local64_read(&hwc->period_left) > 8*sample_period) {
3897 event->pmu->stop(event, PERF_EF_UPDATE);
3899 local64_set(&hwc->period_left, 0);
3902 event->pmu->start(event, PERF_EF_RELOAD);
3907 * combine freq adjustment with unthrottling to avoid two passes over the
3908 * events. At the same time, make sure, having freq events does not change
3909 * the rate of unthrottling as that would introduce bias.
3911 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3914 struct perf_event *event;
3915 struct hw_perf_event *hwc;
3916 u64 now, period = TICK_NSEC;
3920 * only need to iterate over all events iff:
3921 * - context have events in frequency mode (needs freq adjust)
3922 * - there are events to unthrottle on this cpu
3924 if (!(ctx->nr_freq || needs_unthr))
3927 raw_spin_lock(&ctx->lock);
3928 perf_pmu_disable(ctx->pmu);
3930 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3931 if (event->state != PERF_EVENT_STATE_ACTIVE)
3934 if (!event_filter_match(event))
3937 perf_pmu_disable(event->pmu);
3941 if (hwc->interrupts == MAX_INTERRUPTS) {
3942 hwc->interrupts = 0;
3943 perf_log_throttle(event, 1);
3944 event->pmu->start(event, 0);
3947 if (!event->attr.freq || !event->attr.sample_freq)
3951 * stop the event and update event->count
3953 event->pmu->stop(event, PERF_EF_UPDATE);
3955 now = local64_read(&event->count);
3956 delta = now - hwc->freq_count_stamp;
3957 hwc->freq_count_stamp = now;
3961 * reload only if value has changed
3962 * we have stopped the event so tell that
3963 * to perf_adjust_period() to avoid stopping it
3967 perf_adjust_period(event, period, delta, false);
3969 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3971 perf_pmu_enable(event->pmu);
3974 perf_pmu_enable(ctx->pmu);
3975 raw_spin_unlock(&ctx->lock);
3979 * Move @event to the tail of the @ctx's elegible events.
3981 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
3984 * Rotate the first entry last of non-pinned groups. Rotation might be
3985 * disabled by the inheritance code.
3987 if (ctx->rotate_disable)
3990 perf_event_groups_delete(&ctx->flexible_groups, event);
3991 perf_event_groups_insert(&ctx->flexible_groups, event);
3994 /* pick an event from the flexible_groups to rotate */
3995 static inline struct perf_event *
3996 ctx_event_to_rotate(struct perf_event_context *ctx)
3998 struct perf_event *event;
4000 /* pick the first active flexible event */
4001 event = list_first_entry_or_null(&ctx->flexible_active,
4002 struct perf_event, active_list);
4004 /* if no active flexible event, pick the first event */
4006 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4007 typeof(*event), group_node);
4011 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4012 * finds there are unschedulable events, it will set it again.
4014 ctx->rotate_necessary = 0;
4019 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4021 struct perf_event *cpu_event = NULL, *task_event = NULL;
4022 struct perf_event_context *task_ctx = NULL;
4023 int cpu_rotate, task_rotate;
4026 * Since we run this from IRQ context, nobody can install new
4027 * events, thus the event count values are stable.
4030 cpu_rotate = cpuctx->ctx.rotate_necessary;
4031 task_ctx = cpuctx->task_ctx;
4032 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4034 if (!(cpu_rotate || task_rotate))
4037 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4038 perf_pmu_disable(cpuctx->ctx.pmu);
4041 task_event = ctx_event_to_rotate(task_ctx);
4043 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4046 * As per the order given at ctx_resched() first 'pop' task flexible
4047 * and then, if needed CPU flexible.
4049 if (task_event || (task_ctx && cpu_event))
4050 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4052 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4055 rotate_ctx(task_ctx, task_event);
4057 rotate_ctx(&cpuctx->ctx, cpu_event);
4059 perf_event_sched_in(cpuctx, task_ctx, current);
4061 perf_pmu_enable(cpuctx->ctx.pmu);
4062 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4067 void perf_event_task_tick(void)
4069 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4070 struct perf_event_context *ctx, *tmp;
4073 lockdep_assert_irqs_disabled();
4075 __this_cpu_inc(perf_throttled_seq);
4076 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4077 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4079 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4080 perf_adjust_freq_unthr_context(ctx, throttled);
4083 static int event_enable_on_exec(struct perf_event *event,
4084 struct perf_event_context *ctx)
4086 if (!event->attr.enable_on_exec)
4089 event->attr.enable_on_exec = 0;
4090 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4093 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4099 * Enable all of a task's events that have been marked enable-on-exec.
4100 * This expects task == current.
4102 static void perf_event_enable_on_exec(int ctxn)
4104 struct perf_event_context *ctx, *clone_ctx = NULL;
4105 enum event_type_t event_type = 0;
4106 struct perf_cpu_context *cpuctx;
4107 struct perf_event *event;
4108 unsigned long flags;
4111 local_irq_save(flags);
4112 ctx = current->perf_event_ctxp[ctxn];
4113 if (!ctx || !ctx->nr_events)
4116 cpuctx = __get_cpu_context(ctx);
4117 perf_ctx_lock(cpuctx, ctx);
4118 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4119 list_for_each_entry(event, &ctx->event_list, event_entry) {
4120 enabled |= event_enable_on_exec(event, ctx);
4121 event_type |= get_event_type(event);
4125 * Unclone and reschedule this context if we enabled any event.
4128 clone_ctx = unclone_ctx(ctx);
4129 ctx_resched(cpuctx, ctx, event_type);
4131 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4133 perf_ctx_unlock(cpuctx, ctx);
4136 local_irq_restore(flags);
4142 struct perf_read_data {
4143 struct perf_event *event;
4148 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4150 u16 local_pkg, event_pkg;
4152 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4153 int local_cpu = smp_processor_id();
4155 event_pkg = topology_physical_package_id(event_cpu);
4156 local_pkg = topology_physical_package_id(local_cpu);
4158 if (event_pkg == local_pkg)
4166 * Cross CPU call to read the hardware event
4168 static void __perf_event_read(void *info)
4170 struct perf_read_data *data = info;
4171 struct perf_event *sub, *event = data->event;
4172 struct perf_event_context *ctx = event->ctx;
4173 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4174 struct pmu *pmu = event->pmu;
4177 * If this is a task context, we need to check whether it is
4178 * the current task context of this cpu. If not it has been
4179 * scheduled out before the smp call arrived. In that case
4180 * event->count would have been updated to a recent sample
4181 * when the event was scheduled out.
4183 if (ctx->task && cpuctx->task_ctx != ctx)
4186 raw_spin_lock(&ctx->lock);
4187 if (ctx->is_active & EVENT_TIME) {
4188 update_context_time(ctx);
4189 update_cgrp_time_from_event(event);
4192 perf_event_update_time(event);
4194 perf_event_update_sibling_time(event);
4196 if (event->state != PERF_EVENT_STATE_ACTIVE)
4205 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4209 for_each_sibling_event(sub, event) {
4210 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4212 * Use sibling's PMU rather than @event's since
4213 * sibling could be on different (eg: software) PMU.
4215 sub->pmu->read(sub);
4219 data->ret = pmu->commit_txn(pmu);
4222 raw_spin_unlock(&ctx->lock);
4225 static inline u64 perf_event_count(struct perf_event *event)
4227 return local64_read(&event->count) + atomic64_read(&event->child_count);
4231 * NMI-safe method to read a local event, that is an event that
4233 * - either for the current task, or for this CPU
4234 * - does not have inherit set, for inherited task events
4235 * will not be local and we cannot read them atomically
4236 * - must not have a pmu::count method
4238 int perf_event_read_local(struct perf_event *event, u64 *value,
4239 u64 *enabled, u64 *running)
4241 unsigned long flags;
4245 * Disabling interrupts avoids all counter scheduling (context
4246 * switches, timer based rotation and IPIs).
4248 local_irq_save(flags);
4251 * It must not be an event with inherit set, we cannot read
4252 * all child counters from atomic context.
4254 if (event->attr.inherit) {
4259 /* If this is a per-task event, it must be for current */
4260 if ((event->attach_state & PERF_ATTACH_TASK) &&
4261 event->hw.target != current) {
4266 /* If this is a per-CPU event, it must be for this CPU */
4267 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4268 event->cpu != smp_processor_id()) {
4273 /* If this is a pinned event it must be running on this CPU */
4274 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4280 * If the event is currently on this CPU, its either a per-task event,
4281 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4284 if (event->oncpu == smp_processor_id())
4285 event->pmu->read(event);
4287 *value = local64_read(&event->count);
4288 if (enabled || running) {
4289 u64 now = event->shadow_ctx_time + perf_clock();
4290 u64 __enabled, __running;
4292 __perf_update_times(event, now, &__enabled, &__running);
4294 *enabled = __enabled;
4296 *running = __running;
4299 local_irq_restore(flags);
4304 static int perf_event_read(struct perf_event *event, bool group)
4306 enum perf_event_state state = READ_ONCE(event->state);
4307 int event_cpu, ret = 0;
4310 * If event is enabled and currently active on a CPU, update the
4311 * value in the event structure:
4314 if (state == PERF_EVENT_STATE_ACTIVE) {
4315 struct perf_read_data data;
4318 * Orders the ->state and ->oncpu loads such that if we see
4319 * ACTIVE we must also see the right ->oncpu.
4321 * Matches the smp_wmb() from event_sched_in().
4325 event_cpu = READ_ONCE(event->oncpu);
4326 if ((unsigned)event_cpu >= nr_cpu_ids)
4329 data = (struct perf_read_data){
4336 event_cpu = __perf_event_read_cpu(event, event_cpu);
4339 * Purposely ignore the smp_call_function_single() return
4342 * If event_cpu isn't a valid CPU it means the event got
4343 * scheduled out and that will have updated the event count.
4345 * Therefore, either way, we'll have an up-to-date event count
4348 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4352 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4353 struct perf_event_context *ctx = event->ctx;
4354 unsigned long flags;
4356 raw_spin_lock_irqsave(&ctx->lock, flags);
4357 state = event->state;
4358 if (state != PERF_EVENT_STATE_INACTIVE) {
4359 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4364 * May read while context is not active (e.g., thread is
4365 * blocked), in that case we cannot update context time
4367 if (ctx->is_active & EVENT_TIME) {
4368 update_context_time(ctx);
4369 update_cgrp_time_from_event(event);
4372 perf_event_update_time(event);
4374 perf_event_update_sibling_time(event);
4375 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4382 * Initialize the perf_event context in a task_struct:
4384 static void __perf_event_init_context(struct perf_event_context *ctx)
4386 raw_spin_lock_init(&ctx->lock);
4387 mutex_init(&ctx->mutex);
4388 INIT_LIST_HEAD(&ctx->active_ctx_list);
4389 perf_event_groups_init(&ctx->pinned_groups);
4390 perf_event_groups_init(&ctx->flexible_groups);
4391 INIT_LIST_HEAD(&ctx->event_list);
4392 INIT_LIST_HEAD(&ctx->pinned_active);
4393 INIT_LIST_HEAD(&ctx->flexible_active);
4394 refcount_set(&ctx->refcount, 1);
4397 static struct perf_event_context *
4398 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4400 struct perf_event_context *ctx;
4402 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4406 __perf_event_init_context(ctx);
4408 ctx->task = get_task_struct(task);
4414 static struct task_struct *
4415 find_lively_task_by_vpid(pid_t vpid)
4417 struct task_struct *task;
4423 task = find_task_by_vpid(vpid);
4425 get_task_struct(task);
4429 return ERR_PTR(-ESRCH);
4435 * Returns a matching context with refcount and pincount.
4437 static struct perf_event_context *
4438 find_get_context(struct pmu *pmu, struct task_struct *task,
4439 struct perf_event *event)
4441 struct perf_event_context *ctx, *clone_ctx = NULL;
4442 struct perf_cpu_context *cpuctx;
4443 void *task_ctx_data = NULL;
4444 unsigned long flags;
4446 int cpu = event->cpu;
4449 /* Must be root to operate on a CPU event: */
4450 err = perf_allow_cpu(&event->attr);
4452 return ERR_PTR(err);
4454 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4463 ctxn = pmu->task_ctx_nr;
4467 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4468 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
4469 if (!task_ctx_data) {
4476 ctx = perf_lock_task_context(task, ctxn, &flags);
4478 clone_ctx = unclone_ctx(ctx);
4481 if (task_ctx_data && !ctx->task_ctx_data) {
4482 ctx->task_ctx_data = task_ctx_data;
4483 task_ctx_data = NULL;
4485 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4490 ctx = alloc_perf_context(pmu, task);
4495 if (task_ctx_data) {
4496 ctx->task_ctx_data = task_ctx_data;
4497 task_ctx_data = NULL;
4501 mutex_lock(&task->perf_event_mutex);
4503 * If it has already passed perf_event_exit_task().
4504 * we must see PF_EXITING, it takes this mutex too.
4506 if (task->flags & PF_EXITING)
4508 else if (task->perf_event_ctxp[ctxn])
4513 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4515 mutex_unlock(&task->perf_event_mutex);
4517 if (unlikely(err)) {
4526 kfree(task_ctx_data);
4530 kfree(task_ctx_data);
4531 return ERR_PTR(err);
4534 static void perf_event_free_filter(struct perf_event *event);
4535 static void perf_event_free_bpf_prog(struct perf_event *event);
4537 static void free_event_rcu(struct rcu_head *head)
4539 struct perf_event *event;
4541 event = container_of(head, struct perf_event, rcu_head);
4543 put_pid_ns(event->ns);
4544 perf_event_free_filter(event);
4548 static void ring_buffer_attach(struct perf_event *event,
4549 struct perf_buffer *rb);
4551 static void detach_sb_event(struct perf_event *event)
4553 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4555 raw_spin_lock(&pel->lock);
4556 list_del_rcu(&event->sb_list);
4557 raw_spin_unlock(&pel->lock);
4560 static bool is_sb_event(struct perf_event *event)
4562 struct perf_event_attr *attr = &event->attr;
4567 if (event->attach_state & PERF_ATTACH_TASK)
4570 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4571 attr->comm || attr->comm_exec ||
4572 attr->task || attr->ksymbol ||
4573 attr->context_switch ||
4579 static void unaccount_pmu_sb_event(struct perf_event *event)
4581 if (is_sb_event(event))
4582 detach_sb_event(event);
4585 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4590 if (is_cgroup_event(event))
4591 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4594 #ifdef CONFIG_NO_HZ_FULL
4595 static DEFINE_SPINLOCK(nr_freq_lock);
4598 static void unaccount_freq_event_nohz(void)
4600 #ifdef CONFIG_NO_HZ_FULL
4601 spin_lock(&nr_freq_lock);
4602 if (atomic_dec_and_test(&nr_freq_events))
4603 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4604 spin_unlock(&nr_freq_lock);
4608 static void unaccount_freq_event(void)
4610 if (tick_nohz_full_enabled())
4611 unaccount_freq_event_nohz();
4613 atomic_dec(&nr_freq_events);
4616 static void unaccount_event(struct perf_event *event)
4623 if (event->attach_state & PERF_ATTACH_TASK)
4625 if (event->attr.mmap || event->attr.mmap_data)
4626 atomic_dec(&nr_mmap_events);
4627 if (event->attr.comm)
4628 atomic_dec(&nr_comm_events);
4629 if (event->attr.namespaces)
4630 atomic_dec(&nr_namespaces_events);
4631 if (event->attr.cgroup)
4632 atomic_dec(&nr_cgroup_events);
4633 if (event->attr.task)
4634 atomic_dec(&nr_task_events);
4635 if (event->attr.freq)
4636 unaccount_freq_event();
4637 if (event->attr.context_switch) {
4639 atomic_dec(&nr_switch_events);
4641 if (is_cgroup_event(event))
4643 if (has_branch_stack(event))
4645 if (event->attr.ksymbol)
4646 atomic_dec(&nr_ksymbol_events);
4647 if (event->attr.bpf_event)
4648 atomic_dec(&nr_bpf_events);
4651 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4652 schedule_delayed_work(&perf_sched_work, HZ);
4655 unaccount_event_cpu(event, event->cpu);
4657 unaccount_pmu_sb_event(event);
4660 static void perf_sched_delayed(struct work_struct *work)
4662 mutex_lock(&perf_sched_mutex);
4663 if (atomic_dec_and_test(&perf_sched_count))
4664 static_branch_disable(&perf_sched_events);
4665 mutex_unlock(&perf_sched_mutex);
4669 * The following implement mutual exclusion of events on "exclusive" pmus
4670 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4671 * at a time, so we disallow creating events that might conflict, namely:
4673 * 1) cpu-wide events in the presence of per-task events,
4674 * 2) per-task events in the presence of cpu-wide events,
4675 * 3) two matching events on the same context.
4677 * The former two cases are handled in the allocation path (perf_event_alloc(),
4678 * _free_event()), the latter -- before the first perf_install_in_context().
4680 static int exclusive_event_init(struct perf_event *event)
4682 struct pmu *pmu = event->pmu;
4684 if (!is_exclusive_pmu(pmu))
4688 * Prevent co-existence of per-task and cpu-wide events on the
4689 * same exclusive pmu.
4691 * Negative pmu::exclusive_cnt means there are cpu-wide
4692 * events on this "exclusive" pmu, positive means there are
4695 * Since this is called in perf_event_alloc() path, event::ctx
4696 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4697 * to mean "per-task event", because unlike other attach states it
4698 * never gets cleared.
4700 if (event->attach_state & PERF_ATTACH_TASK) {
4701 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4704 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4711 static void exclusive_event_destroy(struct perf_event *event)
4713 struct pmu *pmu = event->pmu;
4715 if (!is_exclusive_pmu(pmu))
4718 /* see comment in exclusive_event_init() */
4719 if (event->attach_state & PERF_ATTACH_TASK)
4720 atomic_dec(&pmu->exclusive_cnt);
4722 atomic_inc(&pmu->exclusive_cnt);
4725 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4727 if ((e1->pmu == e2->pmu) &&
4728 (e1->cpu == e2->cpu ||
4735 static bool exclusive_event_installable(struct perf_event *event,
4736 struct perf_event_context *ctx)
4738 struct perf_event *iter_event;
4739 struct pmu *pmu = event->pmu;
4741 lockdep_assert_held(&ctx->mutex);
4743 if (!is_exclusive_pmu(pmu))
4746 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4747 if (exclusive_event_match(iter_event, event))
4754 static void perf_addr_filters_splice(struct perf_event *event,
4755 struct list_head *head);
4757 static void _free_event(struct perf_event *event)
4759 irq_work_sync(&event->pending);
4761 unaccount_event(event);
4763 security_perf_event_free(event);
4767 * Can happen when we close an event with re-directed output.
4769 * Since we have a 0 refcount, perf_mmap_close() will skip
4770 * over us; possibly making our ring_buffer_put() the last.
4772 mutex_lock(&event->mmap_mutex);
4773 ring_buffer_attach(event, NULL);
4774 mutex_unlock(&event->mmap_mutex);
4777 if (is_cgroup_event(event))
4778 perf_detach_cgroup(event);
4780 if (!event->parent) {
4781 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4782 put_callchain_buffers();
4785 perf_event_free_bpf_prog(event);
4786 perf_addr_filters_splice(event, NULL);
4787 kfree(event->addr_filter_ranges);
4790 event->destroy(event);
4793 * Must be after ->destroy(), due to uprobe_perf_close() using
4796 if (event->hw.target)
4797 put_task_struct(event->hw.target);
4800 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4801 * all task references must be cleaned up.
4804 put_ctx(event->ctx);
4806 exclusive_event_destroy(event);
4807 module_put(event->pmu->module);
4809 call_rcu(&event->rcu_head, free_event_rcu);
4813 * Used to free events which have a known refcount of 1, such as in error paths
4814 * where the event isn't exposed yet and inherited events.
4816 static void free_event(struct perf_event *event)
4818 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4819 "unexpected event refcount: %ld; ptr=%p\n",
4820 atomic_long_read(&event->refcount), event)) {
4821 /* leak to avoid use-after-free */
4829 * Remove user event from the owner task.
4831 static void perf_remove_from_owner(struct perf_event *event)
4833 struct task_struct *owner;
4837 * Matches the smp_store_release() in perf_event_exit_task(). If we
4838 * observe !owner it means the list deletion is complete and we can
4839 * indeed free this event, otherwise we need to serialize on
4840 * owner->perf_event_mutex.
4842 owner = READ_ONCE(event->owner);
4845 * Since delayed_put_task_struct() also drops the last
4846 * task reference we can safely take a new reference
4847 * while holding the rcu_read_lock().
4849 get_task_struct(owner);
4855 * If we're here through perf_event_exit_task() we're already
4856 * holding ctx->mutex which would be an inversion wrt. the
4857 * normal lock order.
4859 * However we can safely take this lock because its the child
4862 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4865 * We have to re-check the event->owner field, if it is cleared
4866 * we raced with perf_event_exit_task(), acquiring the mutex
4867 * ensured they're done, and we can proceed with freeing the
4871 list_del_init(&event->owner_entry);
4872 smp_store_release(&event->owner, NULL);
4874 mutex_unlock(&owner->perf_event_mutex);
4875 put_task_struct(owner);
4879 static void put_event(struct perf_event *event)
4881 if (!atomic_long_dec_and_test(&event->refcount))
4888 * Kill an event dead; while event:refcount will preserve the event
4889 * object, it will not preserve its functionality. Once the last 'user'
4890 * gives up the object, we'll destroy the thing.
4892 int perf_event_release_kernel(struct perf_event *event)
4894 struct perf_event_context *ctx = event->ctx;
4895 struct perf_event *child, *tmp;
4896 LIST_HEAD(free_list);
4899 * If we got here through err_file: fput(event_file); we will not have
4900 * attached to a context yet.
4903 WARN_ON_ONCE(event->attach_state &
4904 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4908 if (!is_kernel_event(event))
4909 perf_remove_from_owner(event);
4911 ctx = perf_event_ctx_lock(event);
4912 WARN_ON_ONCE(ctx->parent_ctx);
4913 perf_remove_from_context(event, DETACH_GROUP);
4915 raw_spin_lock_irq(&ctx->lock);
4917 * Mark this event as STATE_DEAD, there is no external reference to it
4920 * Anybody acquiring event->child_mutex after the below loop _must_
4921 * also see this, most importantly inherit_event() which will avoid
4922 * placing more children on the list.
4924 * Thus this guarantees that we will in fact observe and kill _ALL_
4927 event->state = PERF_EVENT_STATE_DEAD;
4928 raw_spin_unlock_irq(&ctx->lock);
4930 perf_event_ctx_unlock(event, ctx);
4933 mutex_lock(&event->child_mutex);
4934 list_for_each_entry(child, &event->child_list, child_list) {
4937 * Cannot change, child events are not migrated, see the
4938 * comment with perf_event_ctx_lock_nested().
4940 ctx = READ_ONCE(child->ctx);
4942 * Since child_mutex nests inside ctx::mutex, we must jump
4943 * through hoops. We start by grabbing a reference on the ctx.
4945 * Since the event cannot get freed while we hold the
4946 * child_mutex, the context must also exist and have a !0
4952 * Now that we have a ctx ref, we can drop child_mutex, and
4953 * acquire ctx::mutex without fear of it going away. Then we
4954 * can re-acquire child_mutex.
4956 mutex_unlock(&event->child_mutex);
4957 mutex_lock(&ctx->mutex);
4958 mutex_lock(&event->child_mutex);
4961 * Now that we hold ctx::mutex and child_mutex, revalidate our
4962 * state, if child is still the first entry, it didn't get freed
4963 * and we can continue doing so.
4965 tmp = list_first_entry_or_null(&event->child_list,
4966 struct perf_event, child_list);
4968 perf_remove_from_context(child, DETACH_GROUP);
4969 list_move(&child->child_list, &free_list);
4971 * This matches the refcount bump in inherit_event();
4972 * this can't be the last reference.
4977 mutex_unlock(&event->child_mutex);
4978 mutex_unlock(&ctx->mutex);
4982 mutex_unlock(&event->child_mutex);
4984 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
4985 void *var = &child->ctx->refcount;
4987 list_del(&child->child_list);
4991 * Wake any perf_event_free_task() waiting for this event to be
4994 smp_mb(); /* pairs with wait_var_event() */
4999 put_event(event); /* Must be the 'last' reference */
5002 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5005 * Called when the last reference to the file is gone.
5007 static int perf_release(struct inode *inode, struct file *file)
5009 perf_event_release_kernel(file->private_data);
5013 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5015 struct perf_event *child;
5021 mutex_lock(&event->child_mutex);
5023 (void)perf_event_read(event, false);
5024 total += perf_event_count(event);
5026 *enabled += event->total_time_enabled +
5027 atomic64_read(&event->child_total_time_enabled);
5028 *running += event->total_time_running +
5029 atomic64_read(&event->child_total_time_running);
5031 list_for_each_entry(child, &event->child_list, child_list) {
5032 (void)perf_event_read(child, false);
5033 total += perf_event_count(child);
5034 *enabled += child->total_time_enabled;
5035 *running += child->total_time_running;
5037 mutex_unlock(&event->child_mutex);
5042 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5044 struct perf_event_context *ctx;
5047 ctx = perf_event_ctx_lock(event);
5048 count = __perf_event_read_value(event, enabled, running);
5049 perf_event_ctx_unlock(event, ctx);
5053 EXPORT_SYMBOL_GPL(perf_event_read_value);
5055 static int __perf_read_group_add(struct perf_event *leader,
5056 u64 read_format, u64 *values)
5058 struct perf_event_context *ctx = leader->ctx;
5059 struct perf_event *sub;
5060 unsigned long flags;
5061 int n = 1; /* skip @nr */
5064 ret = perf_event_read(leader, true);
5068 raw_spin_lock_irqsave(&ctx->lock, flags);
5071 * Since we co-schedule groups, {enabled,running} times of siblings
5072 * will be identical to those of the leader, so we only publish one
5075 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5076 values[n++] += leader->total_time_enabled +
5077 atomic64_read(&leader->child_total_time_enabled);
5080 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5081 values[n++] += leader->total_time_running +
5082 atomic64_read(&leader->child_total_time_running);
5086 * Write {count,id} tuples for every sibling.
5088 values[n++] += perf_event_count(leader);
5089 if (read_format & PERF_FORMAT_ID)
5090 values[n++] = primary_event_id(leader);
5092 for_each_sibling_event(sub, leader) {
5093 values[n++] += perf_event_count(sub);
5094 if (read_format & PERF_FORMAT_ID)
5095 values[n++] = primary_event_id(sub);
5098 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5102 static int perf_read_group(struct perf_event *event,
5103 u64 read_format, char __user *buf)
5105 struct perf_event *leader = event->group_leader, *child;
5106 struct perf_event_context *ctx = leader->ctx;
5110 lockdep_assert_held(&ctx->mutex);
5112 values = kzalloc(event->read_size, GFP_KERNEL);
5116 values[0] = 1 + leader->nr_siblings;
5119 * By locking the child_mutex of the leader we effectively
5120 * lock the child list of all siblings.. XXX explain how.
5122 mutex_lock(&leader->child_mutex);
5124 ret = __perf_read_group_add(leader, read_format, values);
5128 list_for_each_entry(child, &leader->child_list, child_list) {
5129 ret = __perf_read_group_add(child, read_format, values);
5134 mutex_unlock(&leader->child_mutex);
5136 ret = event->read_size;
5137 if (copy_to_user(buf, values, event->read_size))
5142 mutex_unlock(&leader->child_mutex);
5148 static int perf_read_one(struct perf_event *event,
5149 u64 read_format, char __user *buf)
5151 u64 enabled, running;
5155 values[n++] = __perf_event_read_value(event, &enabled, &running);
5156 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5157 values[n++] = enabled;
5158 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5159 values[n++] = running;
5160 if (read_format & PERF_FORMAT_ID)
5161 values[n++] = primary_event_id(event);
5163 if (copy_to_user(buf, values, n * sizeof(u64)))
5166 return n * sizeof(u64);
5169 static bool is_event_hup(struct perf_event *event)
5173 if (event->state > PERF_EVENT_STATE_EXIT)
5176 mutex_lock(&event->child_mutex);
5177 no_children = list_empty(&event->child_list);
5178 mutex_unlock(&event->child_mutex);
5183 * Read the performance event - simple non blocking version for now
5186 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5188 u64 read_format = event->attr.read_format;
5192 * Return end-of-file for a read on an event that is in
5193 * error state (i.e. because it was pinned but it couldn't be
5194 * scheduled on to the CPU at some point).
5196 if (event->state == PERF_EVENT_STATE_ERROR)
5199 if (count < event->read_size)
5202 WARN_ON_ONCE(event->ctx->parent_ctx);
5203 if (read_format & PERF_FORMAT_GROUP)
5204 ret = perf_read_group(event, read_format, buf);
5206 ret = perf_read_one(event, read_format, buf);
5212 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5214 struct perf_event *event = file->private_data;
5215 struct perf_event_context *ctx;
5218 ret = security_perf_event_read(event);
5222 ctx = perf_event_ctx_lock(event);
5223 ret = __perf_read(event, buf, count);
5224 perf_event_ctx_unlock(event, ctx);
5229 static __poll_t perf_poll(struct file *file, poll_table *wait)
5231 struct perf_event *event = file->private_data;
5232 struct perf_buffer *rb;
5233 __poll_t events = EPOLLHUP;
5235 poll_wait(file, &event->waitq, wait);
5237 if (is_event_hup(event))
5241 * Pin the event->rb by taking event->mmap_mutex; otherwise
5242 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5244 mutex_lock(&event->mmap_mutex);
5247 events = atomic_xchg(&rb->poll, 0);
5248 mutex_unlock(&event->mmap_mutex);
5252 static void _perf_event_reset(struct perf_event *event)
5254 (void)perf_event_read(event, false);
5255 local64_set(&event->count, 0);
5256 perf_event_update_userpage(event);
5259 /* Assume it's not an event with inherit set. */
5260 u64 perf_event_pause(struct perf_event *event, bool reset)
5262 struct perf_event_context *ctx;
5265 ctx = perf_event_ctx_lock(event);
5266 WARN_ON_ONCE(event->attr.inherit);
5267 _perf_event_disable(event);
5268 count = local64_read(&event->count);
5270 local64_set(&event->count, 0);
5271 perf_event_ctx_unlock(event, ctx);
5275 EXPORT_SYMBOL_GPL(perf_event_pause);
5278 * Holding the top-level event's child_mutex means that any
5279 * descendant process that has inherited this event will block
5280 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5281 * task existence requirements of perf_event_enable/disable.
5283 static void perf_event_for_each_child(struct perf_event *event,
5284 void (*func)(struct perf_event *))
5286 struct perf_event *child;
5288 WARN_ON_ONCE(event->ctx->parent_ctx);
5290 mutex_lock(&event->child_mutex);
5292 list_for_each_entry(child, &event->child_list, child_list)
5294 mutex_unlock(&event->child_mutex);
5297 static void perf_event_for_each(struct perf_event *event,
5298 void (*func)(struct perf_event *))
5300 struct perf_event_context *ctx = event->ctx;
5301 struct perf_event *sibling;
5303 lockdep_assert_held(&ctx->mutex);
5305 event = event->group_leader;
5307 perf_event_for_each_child(event, func);
5308 for_each_sibling_event(sibling, event)
5309 perf_event_for_each_child(sibling, func);
5312 static void __perf_event_period(struct perf_event *event,
5313 struct perf_cpu_context *cpuctx,
5314 struct perf_event_context *ctx,
5317 u64 value = *((u64 *)info);
5320 if (event->attr.freq) {
5321 event->attr.sample_freq = value;
5323 event->attr.sample_period = value;
5324 event->hw.sample_period = value;
5327 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5329 perf_pmu_disable(ctx->pmu);
5331 * We could be throttled; unthrottle now to avoid the tick
5332 * trying to unthrottle while we already re-started the event.
5334 if (event->hw.interrupts == MAX_INTERRUPTS) {
5335 event->hw.interrupts = 0;
5336 perf_log_throttle(event, 1);
5338 event->pmu->stop(event, PERF_EF_UPDATE);
5341 local64_set(&event->hw.period_left, 0);
5344 event->pmu->start(event, PERF_EF_RELOAD);
5345 perf_pmu_enable(ctx->pmu);
5349 static int perf_event_check_period(struct perf_event *event, u64 value)
5351 return event->pmu->check_period(event, value);
5354 static int _perf_event_period(struct perf_event *event, u64 value)
5356 if (!is_sampling_event(event))
5362 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5365 if (perf_event_check_period(event, value))
5368 if (!event->attr.freq && (value & (1ULL << 63)))
5371 event_function_call(event, __perf_event_period, &value);
5376 int perf_event_period(struct perf_event *event, u64 value)
5378 struct perf_event_context *ctx;
5381 ctx = perf_event_ctx_lock(event);
5382 ret = _perf_event_period(event, value);
5383 perf_event_ctx_unlock(event, ctx);
5387 EXPORT_SYMBOL_GPL(perf_event_period);
5389 static const struct file_operations perf_fops;
5391 static inline int perf_fget_light(int fd, struct fd *p)
5393 struct fd f = fdget(fd);
5397 if (f.file->f_op != &perf_fops) {
5405 static int perf_event_set_output(struct perf_event *event,
5406 struct perf_event *output_event);
5407 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5408 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5409 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5410 struct perf_event_attr *attr);
5412 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5414 void (*func)(struct perf_event *);
5418 case PERF_EVENT_IOC_ENABLE:
5419 func = _perf_event_enable;
5421 case PERF_EVENT_IOC_DISABLE:
5422 func = _perf_event_disable;
5424 case PERF_EVENT_IOC_RESET:
5425 func = _perf_event_reset;
5428 case PERF_EVENT_IOC_REFRESH:
5429 return _perf_event_refresh(event, arg);
5431 case PERF_EVENT_IOC_PERIOD:
5435 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5438 return _perf_event_period(event, value);
5440 case PERF_EVENT_IOC_ID:
5442 u64 id = primary_event_id(event);
5444 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5449 case PERF_EVENT_IOC_SET_OUTPUT:
5453 struct perf_event *output_event;
5455 ret = perf_fget_light(arg, &output);
5458 output_event = output.file->private_data;
5459 ret = perf_event_set_output(event, output_event);
5462 ret = perf_event_set_output(event, NULL);
5467 case PERF_EVENT_IOC_SET_FILTER:
5468 return perf_event_set_filter(event, (void __user *)arg);
5470 case PERF_EVENT_IOC_SET_BPF:
5471 return perf_event_set_bpf_prog(event, arg);
5473 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5474 struct perf_buffer *rb;
5477 rb = rcu_dereference(event->rb);
5478 if (!rb || !rb->nr_pages) {
5482 rb_toggle_paused(rb, !!arg);
5487 case PERF_EVENT_IOC_QUERY_BPF:
5488 return perf_event_query_prog_array(event, (void __user *)arg);
5490 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5491 struct perf_event_attr new_attr;
5492 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5498 return perf_event_modify_attr(event, &new_attr);
5504 if (flags & PERF_IOC_FLAG_GROUP)
5505 perf_event_for_each(event, func);
5507 perf_event_for_each_child(event, func);
5512 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5514 struct perf_event *event = file->private_data;
5515 struct perf_event_context *ctx;
5518 /* Treat ioctl like writes as it is likely a mutating operation. */
5519 ret = security_perf_event_write(event);
5523 ctx = perf_event_ctx_lock(event);
5524 ret = _perf_ioctl(event, cmd, arg);
5525 perf_event_ctx_unlock(event, ctx);
5530 #ifdef CONFIG_COMPAT
5531 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5534 switch (_IOC_NR(cmd)) {
5535 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5536 case _IOC_NR(PERF_EVENT_IOC_ID):
5537 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5538 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5539 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5540 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5541 cmd &= ~IOCSIZE_MASK;
5542 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5546 return perf_ioctl(file, cmd, arg);
5549 # define perf_compat_ioctl NULL
5552 int perf_event_task_enable(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_enable);
5561 perf_event_ctx_unlock(event, ctx);
5563 mutex_unlock(¤t->perf_event_mutex);
5568 int perf_event_task_disable(void)
5570 struct perf_event_context *ctx;
5571 struct perf_event *event;
5573 mutex_lock(¤t->perf_event_mutex);
5574 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5575 ctx = perf_event_ctx_lock(event);
5576 perf_event_for_each_child(event, _perf_event_disable);
5577 perf_event_ctx_unlock(event, ctx);
5579 mutex_unlock(¤t->perf_event_mutex);
5584 static int perf_event_index(struct perf_event *event)
5586 if (event->hw.state & PERF_HES_STOPPED)
5589 if (event->state != PERF_EVENT_STATE_ACTIVE)
5592 return event->pmu->event_idx(event);
5595 static void calc_timer_values(struct perf_event *event,
5602 *now = perf_clock();
5603 ctx_time = event->shadow_ctx_time + *now;
5604 __perf_update_times(event, ctx_time, enabled, running);
5607 static void perf_event_init_userpage(struct perf_event *event)
5609 struct perf_event_mmap_page *userpg;
5610 struct perf_buffer *rb;
5613 rb = rcu_dereference(event->rb);
5617 userpg = rb->user_page;
5619 /* Allow new userspace to detect that bit 0 is deprecated */
5620 userpg->cap_bit0_is_deprecated = 1;
5621 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5622 userpg->data_offset = PAGE_SIZE;
5623 userpg->data_size = perf_data_size(rb);
5629 void __weak arch_perf_update_userpage(
5630 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5635 * Callers need to ensure there can be no nesting of this function, otherwise
5636 * the seqlock logic goes bad. We can not serialize this because the arch
5637 * code calls this from NMI context.
5639 void perf_event_update_userpage(struct perf_event *event)
5641 struct perf_event_mmap_page *userpg;
5642 struct perf_buffer *rb;
5643 u64 enabled, running, now;
5646 rb = rcu_dereference(event->rb);
5651 * compute total_time_enabled, total_time_running
5652 * based on snapshot values taken when the event
5653 * was last scheduled in.
5655 * we cannot simply called update_context_time()
5656 * because of locking issue as we can be called in
5659 calc_timer_values(event, &now, &enabled, &running);
5661 userpg = rb->user_page;
5663 * Disable preemption to guarantee consistent time stamps are stored to
5669 userpg->index = perf_event_index(event);
5670 userpg->offset = perf_event_count(event);
5672 userpg->offset -= local64_read(&event->hw.prev_count);
5674 userpg->time_enabled = enabled +
5675 atomic64_read(&event->child_total_time_enabled);
5677 userpg->time_running = running +
5678 atomic64_read(&event->child_total_time_running);
5680 arch_perf_update_userpage(event, userpg, now);
5688 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5690 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5692 struct perf_event *event = vmf->vma->vm_file->private_data;
5693 struct perf_buffer *rb;
5694 vm_fault_t ret = VM_FAULT_SIGBUS;
5696 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5697 if (vmf->pgoff == 0)
5703 rb = rcu_dereference(event->rb);
5707 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5710 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5714 get_page(vmf->page);
5715 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5716 vmf->page->index = vmf->pgoff;
5725 static void ring_buffer_attach(struct perf_event *event,
5726 struct perf_buffer *rb)
5728 struct perf_buffer *old_rb = NULL;
5729 unsigned long flags;
5733 * Should be impossible, we set this when removing
5734 * event->rb_entry and wait/clear when adding event->rb_entry.
5736 WARN_ON_ONCE(event->rcu_pending);
5739 spin_lock_irqsave(&old_rb->event_lock, flags);
5740 list_del_rcu(&event->rb_entry);
5741 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5743 event->rcu_batches = get_state_synchronize_rcu();
5744 event->rcu_pending = 1;
5748 if (event->rcu_pending) {
5749 cond_synchronize_rcu(event->rcu_batches);
5750 event->rcu_pending = 0;
5753 spin_lock_irqsave(&rb->event_lock, flags);
5754 list_add_rcu(&event->rb_entry, &rb->event_list);
5755 spin_unlock_irqrestore(&rb->event_lock, flags);
5759 * Avoid racing with perf_mmap_close(AUX): stop the event
5760 * before swizzling the event::rb pointer; if it's getting
5761 * unmapped, its aux_mmap_count will be 0 and it won't
5762 * restart. See the comment in __perf_pmu_output_stop().
5764 * Data will inevitably be lost when set_output is done in
5765 * mid-air, but then again, whoever does it like this is
5766 * not in for the data anyway.
5769 perf_event_stop(event, 0);
5771 rcu_assign_pointer(event->rb, rb);
5774 ring_buffer_put(old_rb);
5776 * Since we detached before setting the new rb, so that we
5777 * could attach the new rb, we could have missed a wakeup.
5780 wake_up_all(&event->waitq);
5784 static void ring_buffer_wakeup(struct perf_event *event)
5786 struct perf_buffer *rb;
5789 rb = rcu_dereference(event->rb);
5791 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5792 wake_up_all(&event->waitq);
5797 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5799 struct perf_buffer *rb;
5802 rb = rcu_dereference(event->rb);
5804 if (!refcount_inc_not_zero(&rb->refcount))
5812 void ring_buffer_put(struct perf_buffer *rb)
5814 if (!refcount_dec_and_test(&rb->refcount))
5817 WARN_ON_ONCE(!list_empty(&rb->event_list));
5819 call_rcu(&rb->rcu_head, rb_free_rcu);
5822 static void perf_mmap_open(struct vm_area_struct *vma)
5824 struct perf_event *event = vma->vm_file->private_data;
5826 atomic_inc(&event->mmap_count);
5827 atomic_inc(&event->rb->mmap_count);
5830 atomic_inc(&event->rb->aux_mmap_count);
5832 if (event->pmu->event_mapped)
5833 event->pmu->event_mapped(event, vma->vm_mm);
5836 static void perf_pmu_output_stop(struct perf_event *event);
5839 * A buffer can be mmap()ed multiple times; either directly through the same
5840 * event, or through other events by use of perf_event_set_output().
5842 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5843 * the buffer here, where we still have a VM context. This means we need
5844 * to detach all events redirecting to us.
5846 static void perf_mmap_close(struct vm_area_struct *vma)
5848 struct perf_event *event = vma->vm_file->private_data;
5850 struct perf_buffer *rb = ring_buffer_get(event);
5851 struct user_struct *mmap_user = rb->mmap_user;
5852 int mmap_locked = rb->mmap_locked;
5853 unsigned long size = perf_data_size(rb);
5855 if (event->pmu->event_unmapped)
5856 event->pmu->event_unmapped(event, vma->vm_mm);
5859 * rb->aux_mmap_count will always drop before rb->mmap_count and
5860 * event->mmap_count, so it is ok to use event->mmap_mutex to
5861 * serialize with perf_mmap here.
5863 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5864 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5866 * Stop all AUX events that are writing to this buffer,
5867 * so that we can free its AUX pages and corresponding PMU
5868 * data. Note that after rb::aux_mmap_count dropped to zero,
5869 * they won't start any more (see perf_aux_output_begin()).
5871 perf_pmu_output_stop(event);
5873 /* now it's safe to free the pages */
5874 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5875 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5877 /* this has to be the last one */
5879 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5881 mutex_unlock(&event->mmap_mutex);
5884 atomic_dec(&rb->mmap_count);
5886 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5889 ring_buffer_attach(event, NULL);
5890 mutex_unlock(&event->mmap_mutex);
5892 /* If there's still other mmap()s of this buffer, we're done. */
5893 if (atomic_read(&rb->mmap_count))
5897 * No other mmap()s, detach from all other events that might redirect
5898 * into the now unreachable buffer. Somewhat complicated by the
5899 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5903 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5904 if (!atomic_long_inc_not_zero(&event->refcount)) {
5906 * This event is en-route to free_event() which will
5907 * detach it and remove it from the list.
5913 mutex_lock(&event->mmap_mutex);
5915 * Check we didn't race with perf_event_set_output() which can
5916 * swizzle the rb from under us while we were waiting to
5917 * acquire mmap_mutex.
5919 * If we find a different rb; ignore this event, a next
5920 * iteration will no longer find it on the list. We have to
5921 * still restart the iteration to make sure we're not now
5922 * iterating the wrong list.
5924 if (event->rb == rb)
5925 ring_buffer_attach(event, NULL);
5927 mutex_unlock(&event->mmap_mutex);
5931 * Restart the iteration; either we're on the wrong list or
5932 * destroyed its integrity by doing a deletion.
5939 * It could be there's still a few 0-ref events on the list; they'll
5940 * get cleaned up by free_event() -- they'll also still have their
5941 * ref on the rb and will free it whenever they are done with it.
5943 * Aside from that, this buffer is 'fully' detached and unmapped,
5944 * undo the VM accounting.
5947 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5948 &mmap_user->locked_vm);
5949 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5950 free_uid(mmap_user);
5953 ring_buffer_put(rb); /* could be last */
5956 static const struct vm_operations_struct perf_mmap_vmops = {
5957 .open = perf_mmap_open,
5958 .close = perf_mmap_close, /* non mergeable */
5959 .fault = perf_mmap_fault,
5960 .page_mkwrite = perf_mmap_fault,
5963 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5965 struct perf_event *event = file->private_data;
5966 unsigned long user_locked, user_lock_limit;
5967 struct user_struct *user = current_user();
5968 struct perf_buffer *rb = NULL;
5969 unsigned long locked, lock_limit;
5970 unsigned long vma_size;
5971 unsigned long nr_pages;
5972 long user_extra = 0, extra = 0;
5973 int ret = 0, flags = 0;
5976 * Don't allow mmap() of inherited per-task counters. This would
5977 * create a performance issue due to all children writing to the
5980 if (event->cpu == -1 && event->attr.inherit)
5983 if (!(vma->vm_flags & VM_SHARED))
5986 ret = security_perf_event_read(event);
5990 vma_size = vma->vm_end - vma->vm_start;
5992 if (vma->vm_pgoff == 0) {
5993 nr_pages = (vma_size / PAGE_SIZE) - 1;
5996 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5997 * mapped, all subsequent mappings should have the same size
5998 * and offset. Must be above the normal perf buffer.
6000 u64 aux_offset, aux_size;
6005 nr_pages = vma_size / PAGE_SIZE;
6007 mutex_lock(&event->mmap_mutex);
6014 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6015 aux_size = READ_ONCE(rb->user_page->aux_size);
6017 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6020 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6023 /* already mapped with a different offset */
6024 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6027 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6030 /* already mapped with a different size */
6031 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6034 if (!is_power_of_2(nr_pages))
6037 if (!atomic_inc_not_zero(&rb->mmap_count))
6040 if (rb_has_aux(rb)) {
6041 atomic_inc(&rb->aux_mmap_count);
6046 atomic_set(&rb->aux_mmap_count, 1);
6047 user_extra = nr_pages;
6053 * If we have rb pages ensure they're a power-of-two number, so we
6054 * can do bitmasks instead of modulo.
6056 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6059 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6062 WARN_ON_ONCE(event->ctx->parent_ctx);
6064 mutex_lock(&event->mmap_mutex);
6066 if (event->rb->nr_pages != nr_pages) {
6071 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6073 * Raced against perf_mmap_close() through
6074 * perf_event_set_output(). Try again, hope for better
6077 mutex_unlock(&event->mmap_mutex);
6084 user_extra = nr_pages + 1;
6087 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6090 * Increase the limit linearly with more CPUs:
6092 user_lock_limit *= num_online_cpus();
6094 user_locked = atomic_long_read(&user->locked_vm);
6097 * sysctl_perf_event_mlock may have changed, so that
6098 * user->locked_vm > user_lock_limit
6100 if (user_locked > user_lock_limit)
6101 user_locked = user_lock_limit;
6102 user_locked += user_extra;
6104 if (user_locked > user_lock_limit) {
6106 * charge locked_vm until it hits user_lock_limit;
6107 * charge the rest from pinned_vm
6109 extra = user_locked - user_lock_limit;
6110 user_extra -= extra;
6113 lock_limit = rlimit(RLIMIT_MEMLOCK);
6114 lock_limit >>= PAGE_SHIFT;
6115 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6117 if ((locked > lock_limit) && perf_is_paranoid() &&
6118 !capable(CAP_IPC_LOCK)) {
6123 WARN_ON(!rb && event->rb);
6125 if (vma->vm_flags & VM_WRITE)
6126 flags |= RING_BUFFER_WRITABLE;
6129 rb = rb_alloc(nr_pages,
6130 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6138 atomic_set(&rb->mmap_count, 1);
6139 rb->mmap_user = get_current_user();
6140 rb->mmap_locked = extra;
6142 ring_buffer_attach(event, rb);
6144 perf_event_init_userpage(event);
6145 perf_event_update_userpage(event);
6147 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6148 event->attr.aux_watermark, flags);
6150 rb->aux_mmap_locked = extra;
6155 atomic_long_add(user_extra, &user->locked_vm);
6156 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6158 atomic_inc(&event->mmap_count);
6160 atomic_dec(&rb->mmap_count);
6163 mutex_unlock(&event->mmap_mutex);
6166 * Since pinned accounting is per vm we cannot allow fork() to copy our
6169 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6170 vma->vm_ops = &perf_mmap_vmops;
6172 if (event->pmu->event_mapped)
6173 event->pmu->event_mapped(event, vma->vm_mm);
6178 static int perf_fasync(int fd, struct file *filp, int on)
6180 struct inode *inode = file_inode(filp);
6181 struct perf_event *event = filp->private_data;
6185 retval = fasync_helper(fd, filp, on, &event->fasync);
6186 inode_unlock(inode);
6194 static const struct file_operations perf_fops = {
6195 .llseek = no_llseek,
6196 .release = perf_release,
6199 .unlocked_ioctl = perf_ioctl,
6200 .compat_ioctl = perf_compat_ioctl,
6202 .fasync = perf_fasync,
6208 * If there's data, ensure we set the poll() state and publish everything
6209 * to user-space before waking everybody up.
6212 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6214 /* only the parent has fasync state */
6216 event = event->parent;
6217 return &event->fasync;
6220 void perf_event_wakeup(struct perf_event *event)
6222 ring_buffer_wakeup(event);
6224 if (event->pending_kill) {
6225 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6226 event->pending_kill = 0;
6230 static void perf_pending_event_disable(struct perf_event *event)
6232 int cpu = READ_ONCE(event->pending_disable);
6237 if (cpu == smp_processor_id()) {
6238 WRITE_ONCE(event->pending_disable, -1);
6239 perf_event_disable_local(event);
6246 * perf_event_disable_inatomic()
6247 * @pending_disable = CPU-A;
6251 * @pending_disable = -1;
6254 * perf_event_disable_inatomic()
6255 * @pending_disable = CPU-B;
6256 * irq_work_queue(); // FAILS
6259 * perf_pending_event()
6261 * But the event runs on CPU-B and wants disabling there.
6263 irq_work_queue_on(&event->pending, cpu);
6266 static void perf_pending_event(struct irq_work *entry)
6268 struct perf_event *event = container_of(entry, struct perf_event, pending);
6271 rctx = perf_swevent_get_recursion_context();
6273 * If we 'fail' here, that's OK, it means recursion is already disabled
6274 * and we won't recurse 'further'.
6277 perf_pending_event_disable(event);
6279 if (event->pending_wakeup) {
6280 event->pending_wakeup = 0;
6281 perf_event_wakeup(event);
6285 perf_swevent_put_recursion_context(rctx);
6289 * We assume there is only KVM supporting the callbacks.
6290 * Later on, we might change it to a list if there is
6291 * another virtualization implementation supporting the callbacks.
6293 struct perf_guest_info_callbacks *perf_guest_cbs;
6295 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6297 perf_guest_cbs = cbs;
6300 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6302 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6304 perf_guest_cbs = NULL;
6307 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6310 perf_output_sample_regs(struct perf_output_handle *handle,
6311 struct pt_regs *regs, u64 mask)
6314 DECLARE_BITMAP(_mask, 64);
6316 bitmap_from_u64(_mask, mask);
6317 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6320 val = perf_reg_value(regs, bit);
6321 perf_output_put(handle, val);
6325 static void perf_sample_regs_user(struct perf_regs *regs_user,
6326 struct pt_regs *regs,
6327 struct pt_regs *regs_user_copy)
6329 if (user_mode(regs)) {
6330 regs_user->abi = perf_reg_abi(current);
6331 regs_user->regs = regs;
6332 } else if (!(current->flags & PF_KTHREAD)) {
6333 perf_get_regs_user(regs_user, regs, regs_user_copy);
6335 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6336 regs_user->regs = NULL;
6340 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6341 struct pt_regs *regs)
6343 regs_intr->regs = regs;
6344 regs_intr->abi = perf_reg_abi(current);
6349 * Get remaining task size from user stack pointer.
6351 * It'd be better to take stack vma map and limit this more
6352 * precisely, but there's no way to get it safely under interrupt,
6353 * so using TASK_SIZE as limit.
6355 static u64 perf_ustack_task_size(struct pt_regs *regs)
6357 unsigned long addr = perf_user_stack_pointer(regs);
6359 if (!addr || addr >= TASK_SIZE)
6362 return TASK_SIZE - addr;
6366 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6367 struct pt_regs *regs)
6371 /* No regs, no stack pointer, no dump. */
6376 * Check if we fit in with the requested stack size into the:
6378 * If we don't, we limit the size to the TASK_SIZE.
6380 * - remaining sample size
6381 * If we don't, we customize the stack size to
6382 * fit in to the remaining sample size.
6385 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6386 stack_size = min(stack_size, (u16) task_size);
6388 /* Current header size plus static size and dynamic size. */
6389 header_size += 2 * sizeof(u64);
6391 /* Do we fit in with the current stack dump size? */
6392 if ((u16) (header_size + stack_size) < header_size) {
6394 * If we overflow the maximum size for the sample,
6395 * we customize the stack dump size to fit in.
6397 stack_size = USHRT_MAX - header_size - sizeof(u64);
6398 stack_size = round_up(stack_size, sizeof(u64));
6405 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6406 struct pt_regs *regs)
6408 /* Case of a kernel thread, nothing to dump */
6411 perf_output_put(handle, size);
6421 * - the size requested by user or the best one we can fit
6422 * in to the sample max size
6424 * - user stack dump data
6426 * - the actual dumped size
6430 perf_output_put(handle, dump_size);
6433 sp = perf_user_stack_pointer(regs);
6436 rem = __output_copy_user(handle, (void *) sp, dump_size);
6438 dyn_size = dump_size - rem;
6440 perf_output_skip(handle, rem);
6443 perf_output_put(handle, dyn_size);
6447 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6448 struct perf_sample_data *data,
6451 struct perf_event *sampler = event->aux_event;
6452 struct perf_buffer *rb;
6459 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6462 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6465 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6470 * If this is an NMI hit inside sampling code, don't take
6471 * the sample. See also perf_aux_sample_output().
6473 if (READ_ONCE(rb->aux_in_sampling)) {
6476 size = min_t(size_t, size, perf_aux_size(rb));
6477 data->aux_size = ALIGN(size, sizeof(u64));
6479 ring_buffer_put(rb);
6482 return data->aux_size;
6485 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6486 struct perf_event *event,
6487 struct perf_output_handle *handle,
6490 unsigned long flags;
6494 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6495 * paths. If we start calling them in NMI context, they may race with
6496 * the IRQ ones, that is, for example, re-starting an event that's just
6497 * been stopped, which is why we're using a separate callback that
6498 * doesn't change the event state.
6500 * IRQs need to be disabled to prevent IPIs from racing with us.
6502 local_irq_save(flags);
6504 * Guard against NMI hits inside the critical section;
6505 * see also perf_prepare_sample_aux().
6507 WRITE_ONCE(rb->aux_in_sampling, 1);
6510 ret = event->pmu->snapshot_aux(event, handle, size);
6513 WRITE_ONCE(rb->aux_in_sampling, 0);
6514 local_irq_restore(flags);
6519 static void perf_aux_sample_output(struct perf_event *event,
6520 struct perf_output_handle *handle,
6521 struct perf_sample_data *data)
6523 struct perf_event *sampler = event->aux_event;
6524 struct perf_buffer *rb;
6528 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6531 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6535 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6538 * An error here means that perf_output_copy() failed (returned a
6539 * non-zero surplus that it didn't copy), which in its current
6540 * enlightened implementation is not possible. If that changes, we'd
6543 if (WARN_ON_ONCE(size < 0))
6547 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6548 * perf_prepare_sample_aux(), so should not be more than that.
6550 pad = data->aux_size - size;
6551 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6556 perf_output_copy(handle, &zero, pad);
6560 ring_buffer_put(rb);
6563 static void __perf_event_header__init_id(struct perf_event_header *header,
6564 struct perf_sample_data *data,
6565 struct perf_event *event)
6567 u64 sample_type = event->attr.sample_type;
6569 data->type = sample_type;
6570 header->size += event->id_header_size;
6572 if (sample_type & PERF_SAMPLE_TID) {
6573 /* namespace issues */
6574 data->tid_entry.pid = perf_event_pid(event, current);
6575 data->tid_entry.tid = perf_event_tid(event, current);
6578 if (sample_type & PERF_SAMPLE_TIME)
6579 data->time = perf_event_clock(event);
6581 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6582 data->id = primary_event_id(event);
6584 if (sample_type & PERF_SAMPLE_STREAM_ID)
6585 data->stream_id = event->id;
6587 if (sample_type & PERF_SAMPLE_CPU) {
6588 data->cpu_entry.cpu = raw_smp_processor_id();
6589 data->cpu_entry.reserved = 0;
6593 void perf_event_header__init_id(struct perf_event_header *header,
6594 struct perf_sample_data *data,
6595 struct perf_event *event)
6597 if (event->attr.sample_id_all)
6598 __perf_event_header__init_id(header, data, event);
6601 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6602 struct perf_sample_data *data)
6604 u64 sample_type = data->type;
6606 if (sample_type & PERF_SAMPLE_TID)
6607 perf_output_put(handle, data->tid_entry);
6609 if (sample_type & PERF_SAMPLE_TIME)
6610 perf_output_put(handle, data->time);
6612 if (sample_type & PERF_SAMPLE_ID)
6613 perf_output_put(handle, data->id);
6615 if (sample_type & PERF_SAMPLE_STREAM_ID)
6616 perf_output_put(handle, data->stream_id);
6618 if (sample_type & PERF_SAMPLE_CPU)
6619 perf_output_put(handle, data->cpu_entry);
6621 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6622 perf_output_put(handle, data->id);
6625 void perf_event__output_id_sample(struct perf_event *event,
6626 struct perf_output_handle *handle,
6627 struct perf_sample_data *sample)
6629 if (event->attr.sample_id_all)
6630 __perf_event__output_id_sample(handle, sample);
6633 static void perf_output_read_one(struct perf_output_handle *handle,
6634 struct perf_event *event,
6635 u64 enabled, u64 running)
6637 u64 read_format = event->attr.read_format;
6641 values[n++] = perf_event_count(event);
6642 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6643 values[n++] = enabled +
6644 atomic64_read(&event->child_total_time_enabled);
6646 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6647 values[n++] = running +
6648 atomic64_read(&event->child_total_time_running);
6650 if (read_format & PERF_FORMAT_ID)
6651 values[n++] = primary_event_id(event);
6653 __output_copy(handle, values, n * sizeof(u64));
6656 static void perf_output_read_group(struct perf_output_handle *handle,
6657 struct perf_event *event,
6658 u64 enabled, u64 running)
6660 struct perf_event *leader = event->group_leader, *sub;
6661 u64 read_format = event->attr.read_format;
6665 values[n++] = 1 + leader->nr_siblings;
6667 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6668 values[n++] = enabled;
6670 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6671 values[n++] = running;
6673 if ((leader != event) &&
6674 (leader->state == PERF_EVENT_STATE_ACTIVE))
6675 leader->pmu->read(leader);
6677 values[n++] = perf_event_count(leader);
6678 if (read_format & PERF_FORMAT_ID)
6679 values[n++] = primary_event_id(leader);
6681 __output_copy(handle, values, n * sizeof(u64));
6683 for_each_sibling_event(sub, leader) {
6686 if ((sub != event) &&
6687 (sub->state == PERF_EVENT_STATE_ACTIVE))
6688 sub->pmu->read(sub);
6690 values[n++] = perf_event_count(sub);
6691 if (read_format & PERF_FORMAT_ID)
6692 values[n++] = primary_event_id(sub);
6694 __output_copy(handle, values, n * sizeof(u64));
6698 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6699 PERF_FORMAT_TOTAL_TIME_RUNNING)
6702 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6704 * The problem is that its both hard and excessively expensive to iterate the
6705 * child list, not to mention that its impossible to IPI the children running
6706 * on another CPU, from interrupt/NMI context.
6708 static void perf_output_read(struct perf_output_handle *handle,
6709 struct perf_event *event)
6711 u64 enabled = 0, running = 0, now;
6712 u64 read_format = event->attr.read_format;
6715 * compute total_time_enabled, total_time_running
6716 * based on snapshot values taken when the event
6717 * was last scheduled in.
6719 * we cannot simply called update_context_time()
6720 * because of locking issue as we are called in
6723 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6724 calc_timer_values(event, &now, &enabled, &running);
6726 if (event->attr.read_format & PERF_FORMAT_GROUP)
6727 perf_output_read_group(handle, event, enabled, running);
6729 perf_output_read_one(handle, event, enabled, running);
6732 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6734 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6737 void perf_output_sample(struct perf_output_handle *handle,
6738 struct perf_event_header *header,
6739 struct perf_sample_data *data,
6740 struct perf_event *event)
6742 u64 sample_type = data->type;
6744 perf_output_put(handle, *header);
6746 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6747 perf_output_put(handle, data->id);
6749 if (sample_type & PERF_SAMPLE_IP)
6750 perf_output_put(handle, data->ip);
6752 if (sample_type & PERF_SAMPLE_TID)
6753 perf_output_put(handle, data->tid_entry);
6755 if (sample_type & PERF_SAMPLE_TIME)
6756 perf_output_put(handle, data->time);
6758 if (sample_type & PERF_SAMPLE_ADDR)
6759 perf_output_put(handle, data->addr);
6761 if (sample_type & PERF_SAMPLE_ID)
6762 perf_output_put(handle, data->id);
6764 if (sample_type & PERF_SAMPLE_STREAM_ID)
6765 perf_output_put(handle, data->stream_id);
6767 if (sample_type & PERF_SAMPLE_CPU)
6768 perf_output_put(handle, data->cpu_entry);
6770 if (sample_type & PERF_SAMPLE_PERIOD)
6771 perf_output_put(handle, data->period);
6773 if (sample_type & PERF_SAMPLE_READ)
6774 perf_output_read(handle, event);
6776 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6779 size += data->callchain->nr;
6780 size *= sizeof(u64);
6781 __output_copy(handle, data->callchain, size);
6784 if (sample_type & PERF_SAMPLE_RAW) {
6785 struct perf_raw_record *raw = data->raw;
6788 struct perf_raw_frag *frag = &raw->frag;
6790 perf_output_put(handle, raw->size);
6793 __output_custom(handle, frag->copy,
6794 frag->data, frag->size);
6796 __output_copy(handle, frag->data,
6799 if (perf_raw_frag_last(frag))
6804 __output_skip(handle, NULL, frag->pad);
6810 .size = sizeof(u32),
6813 perf_output_put(handle, raw);
6817 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6818 if (data->br_stack) {
6821 size = data->br_stack->nr
6822 * sizeof(struct perf_branch_entry);
6824 perf_output_put(handle, data->br_stack->nr);
6825 if (perf_sample_save_hw_index(event))
6826 perf_output_put(handle, data->br_stack->hw_idx);
6827 perf_output_copy(handle, data->br_stack->entries, size);
6830 * we always store at least the value of nr
6833 perf_output_put(handle, nr);
6837 if (sample_type & PERF_SAMPLE_REGS_USER) {
6838 u64 abi = data->regs_user.abi;
6841 * If there are no regs to dump, notice it through
6842 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6844 perf_output_put(handle, abi);
6847 u64 mask = event->attr.sample_regs_user;
6848 perf_output_sample_regs(handle,
6849 data->regs_user.regs,
6854 if (sample_type & PERF_SAMPLE_STACK_USER) {
6855 perf_output_sample_ustack(handle,
6856 data->stack_user_size,
6857 data->regs_user.regs);
6860 if (sample_type & PERF_SAMPLE_WEIGHT)
6861 perf_output_put(handle, data->weight);
6863 if (sample_type & PERF_SAMPLE_DATA_SRC)
6864 perf_output_put(handle, data->data_src.val);
6866 if (sample_type & PERF_SAMPLE_TRANSACTION)
6867 perf_output_put(handle, data->txn);
6869 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6870 u64 abi = data->regs_intr.abi;
6872 * If there are no regs to dump, notice it through
6873 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6875 perf_output_put(handle, abi);
6878 u64 mask = event->attr.sample_regs_intr;
6880 perf_output_sample_regs(handle,
6881 data->regs_intr.regs,
6886 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6887 perf_output_put(handle, data->phys_addr);
6889 if (sample_type & PERF_SAMPLE_CGROUP)
6890 perf_output_put(handle, data->cgroup);
6892 if (sample_type & PERF_SAMPLE_AUX) {
6893 perf_output_put(handle, data->aux_size);
6896 perf_aux_sample_output(event, handle, data);
6899 if (!event->attr.watermark) {
6900 int wakeup_events = event->attr.wakeup_events;
6902 if (wakeup_events) {
6903 struct perf_buffer *rb = handle->rb;
6904 int events = local_inc_return(&rb->events);
6906 if (events >= wakeup_events) {
6907 local_sub(wakeup_events, &rb->events);
6908 local_inc(&rb->wakeup);
6914 static u64 perf_virt_to_phys(u64 virt)
6917 struct page *p = NULL;
6922 if (virt >= TASK_SIZE) {
6923 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6924 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6925 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6926 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6929 * Walking the pages tables for user address.
6930 * Interrupts are disabled, so it prevents any tear down
6931 * of the page tables.
6932 * Try IRQ-safe __get_user_pages_fast first.
6933 * If failed, leave phys_addr as 0.
6935 if (current->mm != NULL) {
6936 pagefault_disable();
6937 if (__get_user_pages_fast(virt, 1, 0, &p) == 1)
6938 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6949 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6951 struct perf_callchain_entry *
6952 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6954 bool kernel = !event->attr.exclude_callchain_kernel;
6955 bool user = !event->attr.exclude_callchain_user;
6956 /* Disallow cross-task user callchains. */
6957 bool crosstask = event->ctx->task && event->ctx->task != current;
6958 const u32 max_stack = event->attr.sample_max_stack;
6959 struct perf_callchain_entry *callchain;
6961 if (!kernel && !user)
6962 return &__empty_callchain;
6964 callchain = get_perf_callchain(regs, 0, kernel, user,
6965 max_stack, crosstask, true);
6966 return callchain ?: &__empty_callchain;
6969 void perf_prepare_sample(struct perf_event_header *header,
6970 struct perf_sample_data *data,
6971 struct perf_event *event,
6972 struct pt_regs *regs)
6974 u64 sample_type = event->attr.sample_type;
6976 header->type = PERF_RECORD_SAMPLE;
6977 header->size = sizeof(*header) + event->header_size;
6980 header->misc |= perf_misc_flags(regs);
6982 __perf_event_header__init_id(header, data, event);
6984 if (sample_type & PERF_SAMPLE_IP)
6985 data->ip = perf_instruction_pointer(regs);
6987 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6990 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
6991 data->callchain = perf_callchain(event, regs);
6993 size += data->callchain->nr;
6995 header->size += size * sizeof(u64);
6998 if (sample_type & PERF_SAMPLE_RAW) {
6999 struct perf_raw_record *raw = data->raw;
7003 struct perf_raw_frag *frag = &raw->frag;
7008 if (perf_raw_frag_last(frag))
7013 size = round_up(sum + sizeof(u32), sizeof(u64));
7014 raw->size = size - sizeof(u32);
7015 frag->pad = raw->size - sum;
7020 header->size += size;
7023 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7024 int size = sizeof(u64); /* nr */
7025 if (data->br_stack) {
7026 if (perf_sample_save_hw_index(event))
7027 size += sizeof(u64);
7029 size += data->br_stack->nr
7030 * sizeof(struct perf_branch_entry);
7032 header->size += size;
7035 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7036 perf_sample_regs_user(&data->regs_user, regs,
7037 &data->regs_user_copy);
7039 if (sample_type & PERF_SAMPLE_REGS_USER) {
7040 /* regs dump ABI info */
7041 int size = sizeof(u64);
7043 if (data->regs_user.regs) {
7044 u64 mask = event->attr.sample_regs_user;
7045 size += hweight64(mask) * sizeof(u64);
7048 header->size += size;
7051 if (sample_type & PERF_SAMPLE_STACK_USER) {
7053 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7054 * processed as the last one or have additional check added
7055 * in case new sample type is added, because we could eat
7056 * up the rest of the sample size.
7058 u16 stack_size = event->attr.sample_stack_user;
7059 u16 size = sizeof(u64);
7061 stack_size = perf_sample_ustack_size(stack_size, header->size,
7062 data->regs_user.regs);
7065 * If there is something to dump, add space for the dump
7066 * itself and for the field that tells the dynamic size,
7067 * which is how many have been actually dumped.
7070 size += sizeof(u64) + stack_size;
7072 data->stack_user_size = stack_size;
7073 header->size += size;
7076 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7077 /* regs dump ABI info */
7078 int size = sizeof(u64);
7080 perf_sample_regs_intr(&data->regs_intr, regs);
7082 if (data->regs_intr.regs) {
7083 u64 mask = event->attr.sample_regs_intr;
7085 size += hweight64(mask) * sizeof(u64);
7088 header->size += size;
7091 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7092 data->phys_addr = perf_virt_to_phys(data->addr);
7094 #ifdef CONFIG_CGROUP_PERF
7095 if (sample_type & PERF_SAMPLE_CGROUP) {
7096 struct cgroup *cgrp;
7098 /* protected by RCU */
7099 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7100 data->cgroup = cgroup_id(cgrp);
7104 if (sample_type & PERF_SAMPLE_AUX) {
7107 header->size += sizeof(u64); /* size */
7110 * Given the 16bit nature of header::size, an AUX sample can
7111 * easily overflow it, what with all the preceding sample bits.
7112 * Make sure this doesn't happen by using up to U16_MAX bytes
7113 * per sample in total (rounded down to 8 byte boundary).
7115 size = min_t(size_t, U16_MAX - header->size,
7116 event->attr.aux_sample_size);
7117 size = rounddown(size, 8);
7118 size = perf_prepare_sample_aux(event, data, size);
7120 WARN_ON_ONCE(size + header->size > U16_MAX);
7121 header->size += size;
7124 * If you're adding more sample types here, you likely need to do
7125 * something about the overflowing header::size, like repurpose the
7126 * lowest 3 bits of size, which should be always zero at the moment.
7127 * This raises a more important question, do we really need 512k sized
7128 * samples and why, so good argumentation is in order for whatever you
7131 WARN_ON_ONCE(header->size & 7);
7134 static __always_inline int
7135 __perf_event_output(struct perf_event *event,
7136 struct perf_sample_data *data,
7137 struct pt_regs *regs,
7138 int (*output_begin)(struct perf_output_handle *,
7139 struct perf_event *,
7142 struct perf_output_handle handle;
7143 struct perf_event_header header;
7146 /* protect the callchain buffers */
7149 perf_prepare_sample(&header, data, event, regs);
7151 err = output_begin(&handle, event, header.size);
7155 perf_output_sample(&handle, &header, data, event);
7157 perf_output_end(&handle);
7165 perf_event_output_forward(struct perf_event *event,
7166 struct perf_sample_data *data,
7167 struct pt_regs *regs)
7169 __perf_event_output(event, data, regs, perf_output_begin_forward);
7173 perf_event_output_backward(struct perf_event *event,
7174 struct perf_sample_data *data,
7175 struct pt_regs *regs)
7177 __perf_event_output(event, data, regs, perf_output_begin_backward);
7181 perf_event_output(struct perf_event *event,
7182 struct perf_sample_data *data,
7183 struct pt_regs *regs)
7185 return __perf_event_output(event, data, regs, perf_output_begin);
7192 struct perf_read_event {
7193 struct perf_event_header header;
7200 perf_event_read_event(struct perf_event *event,
7201 struct task_struct *task)
7203 struct perf_output_handle handle;
7204 struct perf_sample_data sample;
7205 struct perf_read_event read_event = {
7207 .type = PERF_RECORD_READ,
7209 .size = sizeof(read_event) + event->read_size,
7211 .pid = perf_event_pid(event, task),
7212 .tid = perf_event_tid(event, task),
7216 perf_event_header__init_id(&read_event.header, &sample, event);
7217 ret = perf_output_begin(&handle, event, read_event.header.size);
7221 perf_output_put(&handle, read_event);
7222 perf_output_read(&handle, event);
7223 perf_event__output_id_sample(event, &handle, &sample);
7225 perf_output_end(&handle);
7228 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7231 perf_iterate_ctx(struct perf_event_context *ctx,
7232 perf_iterate_f output,
7233 void *data, bool all)
7235 struct perf_event *event;
7237 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7239 if (event->state < PERF_EVENT_STATE_INACTIVE)
7241 if (!event_filter_match(event))
7245 output(event, data);
7249 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7251 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7252 struct perf_event *event;
7254 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7256 * Skip events that are not fully formed yet; ensure that
7257 * if we observe event->ctx, both event and ctx will be
7258 * complete enough. See perf_install_in_context().
7260 if (!smp_load_acquire(&event->ctx))
7263 if (event->state < PERF_EVENT_STATE_INACTIVE)
7265 if (!event_filter_match(event))
7267 output(event, data);
7272 * Iterate all events that need to receive side-band events.
7274 * For new callers; ensure that account_pmu_sb_event() includes
7275 * your event, otherwise it might not get delivered.
7278 perf_iterate_sb(perf_iterate_f output, void *data,
7279 struct perf_event_context *task_ctx)
7281 struct perf_event_context *ctx;
7288 * If we have task_ctx != NULL we only notify the task context itself.
7289 * The task_ctx is set only for EXIT events before releasing task
7293 perf_iterate_ctx(task_ctx, output, data, false);
7297 perf_iterate_sb_cpu(output, data);
7299 for_each_task_context_nr(ctxn) {
7300 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7302 perf_iterate_ctx(ctx, output, data, false);
7310 * Clear all file-based filters at exec, they'll have to be
7311 * re-instated when/if these objects are mmapped again.
7313 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7315 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7316 struct perf_addr_filter *filter;
7317 unsigned int restart = 0, count = 0;
7318 unsigned long flags;
7320 if (!has_addr_filter(event))
7323 raw_spin_lock_irqsave(&ifh->lock, flags);
7324 list_for_each_entry(filter, &ifh->list, entry) {
7325 if (filter->path.dentry) {
7326 event->addr_filter_ranges[count].start = 0;
7327 event->addr_filter_ranges[count].size = 0;
7335 event->addr_filters_gen++;
7336 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7339 perf_event_stop(event, 1);
7342 void perf_event_exec(void)
7344 struct perf_event_context *ctx;
7348 for_each_task_context_nr(ctxn) {
7349 ctx = current->perf_event_ctxp[ctxn];
7353 perf_event_enable_on_exec(ctxn);
7355 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7361 struct remote_output {
7362 struct perf_buffer *rb;
7366 static void __perf_event_output_stop(struct perf_event *event, void *data)
7368 struct perf_event *parent = event->parent;
7369 struct remote_output *ro = data;
7370 struct perf_buffer *rb = ro->rb;
7371 struct stop_event_data sd = {
7375 if (!has_aux(event))
7382 * In case of inheritance, it will be the parent that links to the
7383 * ring-buffer, but it will be the child that's actually using it.
7385 * We are using event::rb to determine if the event should be stopped,
7386 * however this may race with ring_buffer_attach() (through set_output),
7387 * which will make us skip the event that actually needs to be stopped.
7388 * So ring_buffer_attach() has to stop an aux event before re-assigning
7391 if (rcu_dereference(parent->rb) == rb)
7392 ro->err = __perf_event_stop(&sd);
7395 static int __perf_pmu_output_stop(void *info)
7397 struct perf_event *event = info;
7398 struct pmu *pmu = event->ctx->pmu;
7399 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7400 struct remote_output ro = {
7405 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7406 if (cpuctx->task_ctx)
7407 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7414 static void perf_pmu_output_stop(struct perf_event *event)
7416 struct perf_event *iter;
7421 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7423 * For per-CPU events, we need to make sure that neither they
7424 * nor their children are running; for cpu==-1 events it's
7425 * sufficient to stop the event itself if it's active, since
7426 * it can't have children.
7430 cpu = READ_ONCE(iter->oncpu);
7435 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7436 if (err == -EAGAIN) {
7445 * task tracking -- fork/exit
7447 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7450 struct perf_task_event {
7451 struct task_struct *task;
7452 struct perf_event_context *task_ctx;
7455 struct perf_event_header header;
7465 static int perf_event_task_match(struct perf_event *event)
7467 return event->attr.comm || event->attr.mmap ||
7468 event->attr.mmap2 || event->attr.mmap_data ||
7472 static void perf_event_task_output(struct perf_event *event,
7475 struct perf_task_event *task_event = data;
7476 struct perf_output_handle handle;
7477 struct perf_sample_data sample;
7478 struct task_struct *task = task_event->task;
7479 int ret, size = task_event->event_id.header.size;
7481 if (!perf_event_task_match(event))
7484 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7486 ret = perf_output_begin(&handle, event,
7487 task_event->event_id.header.size);
7491 task_event->event_id.pid = perf_event_pid(event, task);
7492 task_event->event_id.ppid = perf_event_pid(event, current);
7494 task_event->event_id.tid = perf_event_tid(event, task);
7495 task_event->event_id.ptid = perf_event_tid(event, current);
7497 task_event->event_id.time = perf_event_clock(event);
7499 perf_output_put(&handle, task_event->event_id);
7501 perf_event__output_id_sample(event, &handle, &sample);
7503 perf_output_end(&handle);
7505 task_event->event_id.header.size = size;
7508 static void perf_event_task(struct task_struct *task,
7509 struct perf_event_context *task_ctx,
7512 struct perf_task_event task_event;
7514 if (!atomic_read(&nr_comm_events) &&
7515 !atomic_read(&nr_mmap_events) &&
7516 !atomic_read(&nr_task_events))
7519 task_event = (struct perf_task_event){
7521 .task_ctx = task_ctx,
7524 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7526 .size = sizeof(task_event.event_id),
7536 perf_iterate_sb(perf_event_task_output,
7541 void perf_event_fork(struct task_struct *task)
7543 perf_event_task(task, NULL, 1);
7544 perf_event_namespaces(task);
7551 struct perf_comm_event {
7552 struct task_struct *task;
7557 struct perf_event_header header;
7564 static int perf_event_comm_match(struct perf_event *event)
7566 return event->attr.comm;
7569 static void perf_event_comm_output(struct perf_event *event,
7572 struct perf_comm_event *comm_event = data;
7573 struct perf_output_handle handle;
7574 struct perf_sample_data sample;
7575 int size = comm_event->event_id.header.size;
7578 if (!perf_event_comm_match(event))
7581 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7582 ret = perf_output_begin(&handle, event,
7583 comm_event->event_id.header.size);
7588 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7589 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7591 perf_output_put(&handle, comm_event->event_id);
7592 __output_copy(&handle, comm_event->comm,
7593 comm_event->comm_size);
7595 perf_event__output_id_sample(event, &handle, &sample);
7597 perf_output_end(&handle);
7599 comm_event->event_id.header.size = size;
7602 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7604 char comm[TASK_COMM_LEN];
7607 memset(comm, 0, sizeof(comm));
7608 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7609 size = ALIGN(strlen(comm)+1, sizeof(u64));
7611 comm_event->comm = comm;
7612 comm_event->comm_size = size;
7614 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7616 perf_iterate_sb(perf_event_comm_output,
7621 void perf_event_comm(struct task_struct *task, bool exec)
7623 struct perf_comm_event comm_event;
7625 if (!atomic_read(&nr_comm_events))
7628 comm_event = (struct perf_comm_event){
7634 .type = PERF_RECORD_COMM,
7635 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7643 perf_event_comm_event(&comm_event);
7647 * namespaces tracking
7650 struct perf_namespaces_event {
7651 struct task_struct *task;
7654 struct perf_event_header header;
7659 struct perf_ns_link_info link_info[NR_NAMESPACES];
7663 static int perf_event_namespaces_match(struct perf_event *event)
7665 return event->attr.namespaces;
7668 static void perf_event_namespaces_output(struct perf_event *event,
7671 struct perf_namespaces_event *namespaces_event = data;
7672 struct perf_output_handle handle;
7673 struct perf_sample_data sample;
7674 u16 header_size = namespaces_event->event_id.header.size;
7677 if (!perf_event_namespaces_match(event))
7680 perf_event_header__init_id(&namespaces_event->event_id.header,
7682 ret = perf_output_begin(&handle, event,
7683 namespaces_event->event_id.header.size);
7687 namespaces_event->event_id.pid = perf_event_pid(event,
7688 namespaces_event->task);
7689 namespaces_event->event_id.tid = perf_event_tid(event,
7690 namespaces_event->task);
7692 perf_output_put(&handle, namespaces_event->event_id);
7694 perf_event__output_id_sample(event, &handle, &sample);
7696 perf_output_end(&handle);
7698 namespaces_event->event_id.header.size = header_size;
7701 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7702 struct task_struct *task,
7703 const struct proc_ns_operations *ns_ops)
7705 struct path ns_path;
7706 struct inode *ns_inode;
7709 error = ns_get_path(&ns_path, task, ns_ops);
7711 ns_inode = ns_path.dentry->d_inode;
7712 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7713 ns_link_info->ino = ns_inode->i_ino;
7718 void perf_event_namespaces(struct task_struct *task)
7720 struct perf_namespaces_event namespaces_event;
7721 struct perf_ns_link_info *ns_link_info;
7723 if (!atomic_read(&nr_namespaces_events))
7726 namespaces_event = (struct perf_namespaces_event){
7730 .type = PERF_RECORD_NAMESPACES,
7732 .size = sizeof(namespaces_event.event_id),
7736 .nr_namespaces = NR_NAMESPACES,
7737 /* .link_info[NR_NAMESPACES] */
7741 ns_link_info = namespaces_event.event_id.link_info;
7743 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7744 task, &mntns_operations);
7746 #ifdef CONFIG_USER_NS
7747 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7748 task, &userns_operations);
7750 #ifdef CONFIG_NET_NS
7751 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7752 task, &netns_operations);
7754 #ifdef CONFIG_UTS_NS
7755 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7756 task, &utsns_operations);
7758 #ifdef CONFIG_IPC_NS
7759 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7760 task, &ipcns_operations);
7762 #ifdef CONFIG_PID_NS
7763 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7764 task, &pidns_operations);
7766 #ifdef CONFIG_CGROUPS
7767 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7768 task, &cgroupns_operations);
7771 perf_iterate_sb(perf_event_namespaces_output,
7779 #ifdef CONFIG_CGROUP_PERF
7781 struct perf_cgroup_event {
7785 struct perf_event_header header;
7791 static int perf_event_cgroup_match(struct perf_event *event)
7793 return event->attr.cgroup;
7796 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7798 struct perf_cgroup_event *cgroup_event = data;
7799 struct perf_output_handle handle;
7800 struct perf_sample_data sample;
7801 u16 header_size = cgroup_event->event_id.header.size;
7804 if (!perf_event_cgroup_match(event))
7807 perf_event_header__init_id(&cgroup_event->event_id.header,
7809 ret = perf_output_begin(&handle, event,
7810 cgroup_event->event_id.header.size);
7814 perf_output_put(&handle, cgroup_event->event_id);
7815 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7817 perf_event__output_id_sample(event, &handle, &sample);
7819 perf_output_end(&handle);
7821 cgroup_event->event_id.header.size = header_size;
7824 static void perf_event_cgroup(struct cgroup *cgrp)
7826 struct perf_cgroup_event cgroup_event;
7827 char path_enomem[16] = "//enomem";
7831 if (!atomic_read(&nr_cgroup_events))
7834 cgroup_event = (struct perf_cgroup_event){
7837 .type = PERF_RECORD_CGROUP,
7839 .size = sizeof(cgroup_event.event_id),
7841 .id = cgroup_id(cgrp),
7845 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7846 if (pathname == NULL) {
7847 cgroup_event.path = path_enomem;
7849 /* just to be sure to have enough space for alignment */
7850 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7851 cgroup_event.path = pathname;
7855 * Since our buffer works in 8 byte units we need to align our string
7856 * size to a multiple of 8. However, we must guarantee the tail end is
7857 * zero'd out to avoid leaking random bits to userspace.
7859 size = strlen(cgroup_event.path) + 1;
7860 while (!IS_ALIGNED(size, sizeof(u64)))
7861 cgroup_event.path[size++] = '\0';
7863 cgroup_event.event_id.header.size += size;
7864 cgroup_event.path_size = size;
7866 perf_iterate_sb(perf_event_cgroup_output,
7879 struct perf_mmap_event {
7880 struct vm_area_struct *vma;
7882 const char *file_name;
7890 struct perf_event_header header;
7900 static int perf_event_mmap_match(struct perf_event *event,
7903 struct perf_mmap_event *mmap_event = data;
7904 struct vm_area_struct *vma = mmap_event->vma;
7905 int executable = vma->vm_flags & VM_EXEC;
7907 return (!executable && event->attr.mmap_data) ||
7908 (executable && (event->attr.mmap || event->attr.mmap2));
7911 static void perf_event_mmap_output(struct perf_event *event,
7914 struct perf_mmap_event *mmap_event = data;
7915 struct perf_output_handle handle;
7916 struct perf_sample_data sample;
7917 int size = mmap_event->event_id.header.size;
7918 u32 type = mmap_event->event_id.header.type;
7921 if (!perf_event_mmap_match(event, data))
7924 if (event->attr.mmap2) {
7925 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7926 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7927 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7928 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7929 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7930 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7931 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7934 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7935 ret = perf_output_begin(&handle, event,
7936 mmap_event->event_id.header.size);
7940 mmap_event->event_id.pid = perf_event_pid(event, current);
7941 mmap_event->event_id.tid = perf_event_tid(event, current);
7943 perf_output_put(&handle, mmap_event->event_id);
7945 if (event->attr.mmap2) {
7946 perf_output_put(&handle, mmap_event->maj);
7947 perf_output_put(&handle, mmap_event->min);
7948 perf_output_put(&handle, mmap_event->ino);
7949 perf_output_put(&handle, mmap_event->ino_generation);
7950 perf_output_put(&handle, mmap_event->prot);
7951 perf_output_put(&handle, mmap_event->flags);
7954 __output_copy(&handle, mmap_event->file_name,
7955 mmap_event->file_size);
7957 perf_event__output_id_sample(event, &handle, &sample);
7959 perf_output_end(&handle);
7961 mmap_event->event_id.header.size = size;
7962 mmap_event->event_id.header.type = type;
7965 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7967 struct vm_area_struct *vma = mmap_event->vma;
7968 struct file *file = vma->vm_file;
7969 int maj = 0, min = 0;
7970 u64 ino = 0, gen = 0;
7971 u32 prot = 0, flags = 0;
7977 if (vma->vm_flags & VM_READ)
7979 if (vma->vm_flags & VM_WRITE)
7981 if (vma->vm_flags & VM_EXEC)
7984 if (vma->vm_flags & VM_MAYSHARE)
7987 flags = MAP_PRIVATE;
7989 if (vma->vm_flags & VM_DENYWRITE)
7990 flags |= MAP_DENYWRITE;
7991 if (vma->vm_flags & VM_MAYEXEC)
7992 flags |= MAP_EXECUTABLE;
7993 if (vma->vm_flags & VM_LOCKED)
7994 flags |= MAP_LOCKED;
7995 if (is_vm_hugetlb_page(vma))
7996 flags |= MAP_HUGETLB;
7999 struct inode *inode;
8002 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8008 * d_path() works from the end of the rb backwards, so we
8009 * need to add enough zero bytes after the string to handle
8010 * the 64bit alignment we do later.
8012 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8017 inode = file_inode(vma->vm_file);
8018 dev = inode->i_sb->s_dev;
8020 gen = inode->i_generation;
8026 if (vma->vm_ops && vma->vm_ops->name) {
8027 name = (char *) vma->vm_ops->name(vma);
8032 name = (char *)arch_vma_name(vma);
8036 if (vma->vm_start <= vma->vm_mm->start_brk &&
8037 vma->vm_end >= vma->vm_mm->brk) {
8041 if (vma->vm_start <= vma->vm_mm->start_stack &&
8042 vma->vm_end >= vma->vm_mm->start_stack) {
8052 strlcpy(tmp, name, sizeof(tmp));
8056 * Since our buffer works in 8 byte units we need to align our string
8057 * size to a multiple of 8. However, we must guarantee the tail end is
8058 * zero'd out to avoid leaking random bits to userspace.
8060 size = strlen(name)+1;
8061 while (!IS_ALIGNED(size, sizeof(u64)))
8062 name[size++] = '\0';
8064 mmap_event->file_name = name;
8065 mmap_event->file_size = size;
8066 mmap_event->maj = maj;
8067 mmap_event->min = min;
8068 mmap_event->ino = ino;
8069 mmap_event->ino_generation = gen;
8070 mmap_event->prot = prot;
8071 mmap_event->flags = flags;
8073 if (!(vma->vm_flags & VM_EXEC))
8074 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8076 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8078 perf_iterate_sb(perf_event_mmap_output,
8086 * Check whether inode and address range match filter criteria.
8088 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8089 struct file *file, unsigned long offset,
8092 /* d_inode(NULL) won't be equal to any mapped user-space file */
8093 if (!filter->path.dentry)
8096 if (d_inode(filter->path.dentry) != file_inode(file))
8099 if (filter->offset > offset + size)
8102 if (filter->offset + filter->size < offset)
8108 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8109 struct vm_area_struct *vma,
8110 struct perf_addr_filter_range *fr)
8112 unsigned long vma_size = vma->vm_end - vma->vm_start;
8113 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8114 struct file *file = vma->vm_file;
8116 if (!perf_addr_filter_match(filter, file, off, vma_size))
8119 if (filter->offset < off) {
8120 fr->start = vma->vm_start;
8121 fr->size = min(vma_size, filter->size - (off - filter->offset));
8123 fr->start = vma->vm_start + filter->offset - off;
8124 fr->size = min(vma->vm_end - fr->start, filter->size);
8130 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8132 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8133 struct vm_area_struct *vma = data;
8134 struct perf_addr_filter *filter;
8135 unsigned int restart = 0, count = 0;
8136 unsigned long flags;
8138 if (!has_addr_filter(event))
8144 raw_spin_lock_irqsave(&ifh->lock, flags);
8145 list_for_each_entry(filter, &ifh->list, entry) {
8146 if (perf_addr_filter_vma_adjust(filter, vma,
8147 &event->addr_filter_ranges[count]))
8154 event->addr_filters_gen++;
8155 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8158 perf_event_stop(event, 1);
8162 * Adjust all task's events' filters to the new vma
8164 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8166 struct perf_event_context *ctx;
8170 * Data tracing isn't supported yet and as such there is no need
8171 * to keep track of anything that isn't related to executable code:
8173 if (!(vma->vm_flags & VM_EXEC))
8177 for_each_task_context_nr(ctxn) {
8178 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8182 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8187 void perf_event_mmap(struct vm_area_struct *vma)
8189 struct perf_mmap_event mmap_event;
8191 if (!atomic_read(&nr_mmap_events))
8194 mmap_event = (struct perf_mmap_event){
8200 .type = PERF_RECORD_MMAP,
8201 .misc = PERF_RECORD_MISC_USER,
8206 .start = vma->vm_start,
8207 .len = vma->vm_end - vma->vm_start,
8208 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8210 /* .maj (attr_mmap2 only) */
8211 /* .min (attr_mmap2 only) */
8212 /* .ino (attr_mmap2 only) */
8213 /* .ino_generation (attr_mmap2 only) */
8214 /* .prot (attr_mmap2 only) */
8215 /* .flags (attr_mmap2 only) */
8218 perf_addr_filters_adjust(vma);
8219 perf_event_mmap_event(&mmap_event);
8222 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8223 unsigned long size, u64 flags)
8225 struct perf_output_handle handle;
8226 struct perf_sample_data sample;
8227 struct perf_aux_event {
8228 struct perf_event_header header;
8234 .type = PERF_RECORD_AUX,
8236 .size = sizeof(rec),
8244 perf_event_header__init_id(&rec.header, &sample, event);
8245 ret = perf_output_begin(&handle, event, rec.header.size);
8250 perf_output_put(&handle, rec);
8251 perf_event__output_id_sample(event, &handle, &sample);
8253 perf_output_end(&handle);
8257 * Lost/dropped samples logging
8259 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8261 struct perf_output_handle handle;
8262 struct perf_sample_data sample;
8266 struct perf_event_header header;
8268 } lost_samples_event = {
8270 .type = PERF_RECORD_LOST_SAMPLES,
8272 .size = sizeof(lost_samples_event),
8277 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8279 ret = perf_output_begin(&handle, event,
8280 lost_samples_event.header.size);
8284 perf_output_put(&handle, lost_samples_event);
8285 perf_event__output_id_sample(event, &handle, &sample);
8286 perf_output_end(&handle);
8290 * context_switch tracking
8293 struct perf_switch_event {
8294 struct task_struct *task;
8295 struct task_struct *next_prev;
8298 struct perf_event_header header;
8304 static int perf_event_switch_match(struct perf_event *event)
8306 return event->attr.context_switch;
8309 static void perf_event_switch_output(struct perf_event *event, void *data)
8311 struct perf_switch_event *se = data;
8312 struct perf_output_handle handle;
8313 struct perf_sample_data sample;
8316 if (!perf_event_switch_match(event))
8319 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8320 if (event->ctx->task) {
8321 se->event_id.header.type = PERF_RECORD_SWITCH;
8322 se->event_id.header.size = sizeof(se->event_id.header);
8324 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8325 se->event_id.header.size = sizeof(se->event_id);
8326 se->event_id.next_prev_pid =
8327 perf_event_pid(event, se->next_prev);
8328 se->event_id.next_prev_tid =
8329 perf_event_tid(event, se->next_prev);
8332 perf_event_header__init_id(&se->event_id.header, &sample, event);
8334 ret = perf_output_begin(&handle, event, se->event_id.header.size);
8338 if (event->ctx->task)
8339 perf_output_put(&handle, se->event_id.header);
8341 perf_output_put(&handle, se->event_id);
8343 perf_event__output_id_sample(event, &handle, &sample);
8345 perf_output_end(&handle);
8348 static void perf_event_switch(struct task_struct *task,
8349 struct task_struct *next_prev, bool sched_in)
8351 struct perf_switch_event switch_event;
8353 /* N.B. caller checks nr_switch_events != 0 */
8355 switch_event = (struct perf_switch_event){
8357 .next_prev = next_prev,
8361 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8364 /* .next_prev_pid */
8365 /* .next_prev_tid */
8369 if (!sched_in && task->state == TASK_RUNNING)
8370 switch_event.event_id.header.misc |=
8371 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8373 perf_iterate_sb(perf_event_switch_output,
8379 * IRQ throttle logging
8382 static void perf_log_throttle(struct perf_event *event, int enable)
8384 struct perf_output_handle handle;
8385 struct perf_sample_data sample;
8389 struct perf_event_header header;
8393 } throttle_event = {
8395 .type = PERF_RECORD_THROTTLE,
8397 .size = sizeof(throttle_event),
8399 .time = perf_event_clock(event),
8400 .id = primary_event_id(event),
8401 .stream_id = event->id,
8405 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8407 perf_event_header__init_id(&throttle_event.header, &sample, event);
8409 ret = perf_output_begin(&handle, event,
8410 throttle_event.header.size);
8414 perf_output_put(&handle, throttle_event);
8415 perf_event__output_id_sample(event, &handle, &sample);
8416 perf_output_end(&handle);
8420 * ksymbol register/unregister tracking
8423 struct perf_ksymbol_event {
8427 struct perf_event_header header;
8435 static int perf_event_ksymbol_match(struct perf_event *event)
8437 return event->attr.ksymbol;
8440 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8442 struct perf_ksymbol_event *ksymbol_event = data;
8443 struct perf_output_handle handle;
8444 struct perf_sample_data sample;
8447 if (!perf_event_ksymbol_match(event))
8450 perf_event_header__init_id(&ksymbol_event->event_id.header,
8452 ret = perf_output_begin(&handle, event,
8453 ksymbol_event->event_id.header.size);
8457 perf_output_put(&handle, ksymbol_event->event_id);
8458 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8459 perf_event__output_id_sample(event, &handle, &sample);
8461 perf_output_end(&handle);
8464 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8467 struct perf_ksymbol_event ksymbol_event;
8468 char name[KSYM_NAME_LEN];
8472 if (!atomic_read(&nr_ksymbol_events))
8475 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8476 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8479 strlcpy(name, sym, KSYM_NAME_LEN);
8480 name_len = strlen(name) + 1;
8481 while (!IS_ALIGNED(name_len, sizeof(u64)))
8482 name[name_len++] = '\0';
8483 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8486 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8488 ksymbol_event = (struct perf_ksymbol_event){
8490 .name_len = name_len,
8493 .type = PERF_RECORD_KSYMBOL,
8494 .size = sizeof(ksymbol_event.event_id) +
8499 .ksym_type = ksym_type,
8504 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8507 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8511 * bpf program load/unload tracking
8514 struct perf_bpf_event {
8515 struct bpf_prog *prog;
8517 struct perf_event_header header;
8521 u8 tag[BPF_TAG_SIZE];
8525 static int perf_event_bpf_match(struct perf_event *event)
8527 return event->attr.bpf_event;
8530 static void perf_event_bpf_output(struct perf_event *event, void *data)
8532 struct perf_bpf_event *bpf_event = data;
8533 struct perf_output_handle handle;
8534 struct perf_sample_data sample;
8537 if (!perf_event_bpf_match(event))
8540 perf_event_header__init_id(&bpf_event->event_id.header,
8542 ret = perf_output_begin(&handle, event,
8543 bpf_event->event_id.header.size);
8547 perf_output_put(&handle, bpf_event->event_id);
8548 perf_event__output_id_sample(event, &handle, &sample);
8550 perf_output_end(&handle);
8553 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8554 enum perf_bpf_event_type type)
8556 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8559 if (prog->aux->func_cnt == 0) {
8560 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8561 (u64)(unsigned long)prog->bpf_func,
8562 prog->jited_len, unregister,
8563 prog->aux->ksym.name);
8565 for (i = 0; i < prog->aux->func_cnt; i++) {
8566 struct bpf_prog *subprog = prog->aux->func[i];
8569 PERF_RECORD_KSYMBOL_TYPE_BPF,
8570 (u64)(unsigned long)subprog->bpf_func,
8571 subprog->jited_len, unregister,
8572 prog->aux->ksym.name);
8577 void perf_event_bpf_event(struct bpf_prog *prog,
8578 enum perf_bpf_event_type type,
8581 struct perf_bpf_event bpf_event;
8583 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8584 type >= PERF_BPF_EVENT_MAX)
8588 case PERF_BPF_EVENT_PROG_LOAD:
8589 case PERF_BPF_EVENT_PROG_UNLOAD:
8590 if (atomic_read(&nr_ksymbol_events))
8591 perf_event_bpf_emit_ksymbols(prog, type);
8597 if (!atomic_read(&nr_bpf_events))
8600 bpf_event = (struct perf_bpf_event){
8604 .type = PERF_RECORD_BPF_EVENT,
8605 .size = sizeof(bpf_event.event_id),
8609 .id = prog->aux->id,
8613 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8615 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8616 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8619 void perf_event_itrace_started(struct perf_event *event)
8621 event->attach_state |= PERF_ATTACH_ITRACE;
8624 static void perf_log_itrace_start(struct perf_event *event)
8626 struct perf_output_handle handle;
8627 struct perf_sample_data sample;
8628 struct perf_aux_event {
8629 struct perf_event_header header;
8636 event = event->parent;
8638 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8639 event->attach_state & PERF_ATTACH_ITRACE)
8642 rec.header.type = PERF_RECORD_ITRACE_START;
8643 rec.header.misc = 0;
8644 rec.header.size = sizeof(rec);
8645 rec.pid = perf_event_pid(event, current);
8646 rec.tid = perf_event_tid(event, current);
8648 perf_event_header__init_id(&rec.header, &sample, event);
8649 ret = perf_output_begin(&handle, event, rec.header.size);
8654 perf_output_put(&handle, rec);
8655 perf_event__output_id_sample(event, &handle, &sample);
8657 perf_output_end(&handle);
8661 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8663 struct hw_perf_event *hwc = &event->hw;
8667 seq = __this_cpu_read(perf_throttled_seq);
8668 if (seq != hwc->interrupts_seq) {
8669 hwc->interrupts_seq = seq;
8670 hwc->interrupts = 1;
8673 if (unlikely(throttle
8674 && hwc->interrupts >= max_samples_per_tick)) {
8675 __this_cpu_inc(perf_throttled_count);
8676 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8677 hwc->interrupts = MAX_INTERRUPTS;
8678 perf_log_throttle(event, 0);
8683 if (event->attr.freq) {
8684 u64 now = perf_clock();
8685 s64 delta = now - hwc->freq_time_stamp;
8687 hwc->freq_time_stamp = now;
8689 if (delta > 0 && delta < 2*TICK_NSEC)
8690 perf_adjust_period(event, delta, hwc->last_period, true);
8696 int perf_event_account_interrupt(struct perf_event *event)
8698 return __perf_event_account_interrupt(event, 1);
8702 * Generic event overflow handling, sampling.
8705 static int __perf_event_overflow(struct perf_event *event,
8706 int throttle, struct perf_sample_data *data,
8707 struct pt_regs *regs)
8709 int events = atomic_read(&event->event_limit);
8713 * Non-sampling counters might still use the PMI to fold short
8714 * hardware counters, ignore those.
8716 if (unlikely(!is_sampling_event(event)))
8719 ret = __perf_event_account_interrupt(event, throttle);
8722 * XXX event_limit might not quite work as expected on inherited
8726 event->pending_kill = POLL_IN;
8727 if (events && atomic_dec_and_test(&event->event_limit)) {
8729 event->pending_kill = POLL_HUP;
8731 perf_event_disable_inatomic(event);
8734 READ_ONCE(event->overflow_handler)(event, data, regs);
8736 if (*perf_event_fasync(event) && event->pending_kill) {
8737 event->pending_wakeup = 1;
8738 irq_work_queue(&event->pending);
8744 int perf_event_overflow(struct perf_event *event,
8745 struct perf_sample_data *data,
8746 struct pt_regs *regs)
8748 return __perf_event_overflow(event, 1, data, regs);
8752 * Generic software event infrastructure
8755 struct swevent_htable {
8756 struct swevent_hlist *swevent_hlist;
8757 struct mutex hlist_mutex;
8760 /* Recursion avoidance in each contexts */
8761 int recursion[PERF_NR_CONTEXTS];
8764 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8767 * We directly increment event->count and keep a second value in
8768 * event->hw.period_left to count intervals. This period event
8769 * is kept in the range [-sample_period, 0] so that we can use the
8773 u64 perf_swevent_set_period(struct perf_event *event)
8775 struct hw_perf_event *hwc = &event->hw;
8776 u64 period = hwc->last_period;
8780 hwc->last_period = hwc->sample_period;
8783 old = val = local64_read(&hwc->period_left);
8787 nr = div64_u64(period + val, period);
8788 offset = nr * period;
8790 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8796 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8797 struct perf_sample_data *data,
8798 struct pt_regs *regs)
8800 struct hw_perf_event *hwc = &event->hw;
8804 overflow = perf_swevent_set_period(event);
8806 if (hwc->interrupts == MAX_INTERRUPTS)
8809 for (; overflow; overflow--) {
8810 if (__perf_event_overflow(event, throttle,
8813 * We inhibit the overflow from happening when
8814 * hwc->interrupts == MAX_INTERRUPTS.
8822 static void perf_swevent_event(struct perf_event *event, u64 nr,
8823 struct perf_sample_data *data,
8824 struct pt_regs *regs)
8826 struct hw_perf_event *hwc = &event->hw;
8828 local64_add(nr, &event->count);
8833 if (!is_sampling_event(event))
8836 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8838 return perf_swevent_overflow(event, 1, data, regs);
8840 data->period = event->hw.last_period;
8842 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8843 return perf_swevent_overflow(event, 1, data, regs);
8845 if (local64_add_negative(nr, &hwc->period_left))
8848 perf_swevent_overflow(event, 0, data, regs);
8851 static int perf_exclude_event(struct perf_event *event,
8852 struct pt_regs *regs)
8854 if (event->hw.state & PERF_HES_STOPPED)
8858 if (event->attr.exclude_user && user_mode(regs))
8861 if (event->attr.exclude_kernel && !user_mode(regs))
8868 static int perf_swevent_match(struct perf_event *event,
8869 enum perf_type_id type,
8871 struct perf_sample_data *data,
8872 struct pt_regs *regs)
8874 if (event->attr.type != type)
8877 if (event->attr.config != event_id)
8880 if (perf_exclude_event(event, regs))
8886 static inline u64 swevent_hash(u64 type, u32 event_id)
8888 u64 val = event_id | (type << 32);
8890 return hash_64(val, SWEVENT_HLIST_BITS);
8893 static inline struct hlist_head *
8894 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
8896 u64 hash = swevent_hash(type, event_id);
8898 return &hlist->heads[hash];
8901 /* For the read side: events when they trigger */
8902 static inline struct hlist_head *
8903 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
8905 struct swevent_hlist *hlist;
8907 hlist = rcu_dereference(swhash->swevent_hlist);
8911 return __find_swevent_head(hlist, type, event_id);
8914 /* For the event head insertion and removal in the hlist */
8915 static inline struct hlist_head *
8916 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
8918 struct swevent_hlist *hlist;
8919 u32 event_id = event->attr.config;
8920 u64 type = event->attr.type;
8923 * Event scheduling is always serialized against hlist allocation
8924 * and release. Which makes the protected version suitable here.
8925 * The context lock guarantees that.
8927 hlist = rcu_dereference_protected(swhash->swevent_hlist,
8928 lockdep_is_held(&event->ctx->lock));
8932 return __find_swevent_head(hlist, type, event_id);
8935 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
8937 struct perf_sample_data *data,
8938 struct pt_regs *regs)
8940 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8941 struct perf_event *event;
8942 struct hlist_head *head;
8945 head = find_swevent_head_rcu(swhash, type, event_id);
8949 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8950 if (perf_swevent_match(event, type, event_id, data, regs))
8951 perf_swevent_event(event, nr, data, regs);
8957 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
8959 int perf_swevent_get_recursion_context(void)
8961 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8963 return get_recursion_context(swhash->recursion);
8965 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
8967 void perf_swevent_put_recursion_context(int rctx)
8969 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8971 put_recursion_context(swhash->recursion, rctx);
8974 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8976 struct perf_sample_data data;
8978 if (WARN_ON_ONCE(!regs))
8981 perf_sample_data_init(&data, addr, 0);
8982 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
8985 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8989 preempt_disable_notrace();
8990 rctx = perf_swevent_get_recursion_context();
8991 if (unlikely(rctx < 0))
8994 ___perf_sw_event(event_id, nr, regs, addr);
8996 perf_swevent_put_recursion_context(rctx);
8998 preempt_enable_notrace();
9001 static void perf_swevent_read(struct perf_event *event)
9005 static int perf_swevent_add(struct perf_event *event, int flags)
9007 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9008 struct hw_perf_event *hwc = &event->hw;
9009 struct hlist_head *head;
9011 if (is_sampling_event(event)) {
9012 hwc->last_period = hwc->sample_period;
9013 perf_swevent_set_period(event);
9016 hwc->state = !(flags & PERF_EF_START);
9018 head = find_swevent_head(swhash, event);
9019 if (WARN_ON_ONCE(!head))
9022 hlist_add_head_rcu(&event->hlist_entry, head);
9023 perf_event_update_userpage(event);
9028 static void perf_swevent_del(struct perf_event *event, int flags)
9030 hlist_del_rcu(&event->hlist_entry);
9033 static void perf_swevent_start(struct perf_event *event, int flags)
9035 event->hw.state = 0;
9038 static void perf_swevent_stop(struct perf_event *event, int flags)
9040 event->hw.state = PERF_HES_STOPPED;
9043 /* Deref the hlist from the update side */
9044 static inline struct swevent_hlist *
9045 swevent_hlist_deref(struct swevent_htable *swhash)
9047 return rcu_dereference_protected(swhash->swevent_hlist,
9048 lockdep_is_held(&swhash->hlist_mutex));
9051 static void swevent_hlist_release(struct swevent_htable *swhash)
9053 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9058 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9059 kfree_rcu(hlist, rcu_head);
9062 static void swevent_hlist_put_cpu(int cpu)
9064 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9066 mutex_lock(&swhash->hlist_mutex);
9068 if (!--swhash->hlist_refcount)
9069 swevent_hlist_release(swhash);
9071 mutex_unlock(&swhash->hlist_mutex);
9074 static void swevent_hlist_put(void)
9078 for_each_possible_cpu(cpu)
9079 swevent_hlist_put_cpu(cpu);
9082 static int swevent_hlist_get_cpu(int cpu)
9084 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9087 mutex_lock(&swhash->hlist_mutex);
9088 if (!swevent_hlist_deref(swhash) &&
9089 cpumask_test_cpu(cpu, perf_online_mask)) {
9090 struct swevent_hlist *hlist;
9092 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9097 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9099 swhash->hlist_refcount++;
9101 mutex_unlock(&swhash->hlist_mutex);
9106 static int swevent_hlist_get(void)
9108 int err, cpu, failed_cpu;
9110 mutex_lock(&pmus_lock);
9111 for_each_possible_cpu(cpu) {
9112 err = swevent_hlist_get_cpu(cpu);
9118 mutex_unlock(&pmus_lock);
9121 for_each_possible_cpu(cpu) {
9122 if (cpu == failed_cpu)
9124 swevent_hlist_put_cpu(cpu);
9126 mutex_unlock(&pmus_lock);
9130 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9132 static void sw_perf_event_destroy(struct perf_event *event)
9134 u64 event_id = event->attr.config;
9136 WARN_ON(event->parent);
9138 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9139 swevent_hlist_put();
9142 static int perf_swevent_init(struct perf_event *event)
9144 u64 event_id = event->attr.config;
9146 if (event->attr.type != PERF_TYPE_SOFTWARE)
9150 * no branch sampling for software events
9152 if (has_branch_stack(event))
9156 case PERF_COUNT_SW_CPU_CLOCK:
9157 case PERF_COUNT_SW_TASK_CLOCK:
9164 if (event_id >= PERF_COUNT_SW_MAX)
9167 if (!event->parent) {
9170 err = swevent_hlist_get();
9174 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9175 event->destroy = sw_perf_event_destroy;
9181 static struct pmu perf_swevent = {
9182 .task_ctx_nr = perf_sw_context,
9184 .capabilities = PERF_PMU_CAP_NO_NMI,
9186 .event_init = perf_swevent_init,
9187 .add = perf_swevent_add,
9188 .del = perf_swevent_del,
9189 .start = perf_swevent_start,
9190 .stop = perf_swevent_stop,
9191 .read = perf_swevent_read,
9194 #ifdef CONFIG_EVENT_TRACING
9196 static int perf_tp_filter_match(struct perf_event *event,
9197 struct perf_sample_data *data)
9199 void *record = data->raw->frag.data;
9201 /* only top level events have filters set */
9203 event = event->parent;
9205 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9210 static int perf_tp_event_match(struct perf_event *event,
9211 struct perf_sample_data *data,
9212 struct pt_regs *regs)
9214 if (event->hw.state & PERF_HES_STOPPED)
9217 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9219 if (event->attr.exclude_kernel && !user_mode(regs))
9222 if (!perf_tp_filter_match(event, data))
9228 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9229 struct trace_event_call *call, u64 count,
9230 struct pt_regs *regs, struct hlist_head *head,
9231 struct task_struct *task)
9233 if (bpf_prog_array_valid(call)) {
9234 *(struct pt_regs **)raw_data = regs;
9235 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9236 perf_swevent_put_recursion_context(rctx);
9240 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9243 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9245 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9246 struct pt_regs *regs, struct hlist_head *head, int rctx,
9247 struct task_struct *task)
9249 struct perf_sample_data data;
9250 struct perf_event *event;
9252 struct perf_raw_record raw = {
9259 perf_sample_data_init(&data, 0, 0);
9262 perf_trace_buf_update(record, event_type);
9264 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9265 if (perf_tp_event_match(event, &data, regs))
9266 perf_swevent_event(event, count, &data, regs);
9270 * If we got specified a target task, also iterate its context and
9271 * deliver this event there too.
9273 if (task && task != current) {
9274 struct perf_event_context *ctx;
9275 struct trace_entry *entry = record;
9278 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9282 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9283 if (event->cpu != smp_processor_id())
9285 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9287 if (event->attr.config != entry->type)
9289 if (perf_tp_event_match(event, &data, regs))
9290 perf_swevent_event(event, count, &data, regs);
9296 perf_swevent_put_recursion_context(rctx);
9298 EXPORT_SYMBOL_GPL(perf_tp_event);
9300 static void tp_perf_event_destroy(struct perf_event *event)
9302 perf_trace_destroy(event);
9305 static int perf_tp_event_init(struct perf_event *event)
9309 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9313 * no branch sampling for tracepoint events
9315 if (has_branch_stack(event))
9318 err = perf_trace_init(event);
9322 event->destroy = tp_perf_event_destroy;
9327 static struct pmu perf_tracepoint = {
9328 .task_ctx_nr = perf_sw_context,
9330 .event_init = perf_tp_event_init,
9331 .add = perf_trace_add,
9332 .del = perf_trace_del,
9333 .start = perf_swevent_start,
9334 .stop = perf_swevent_stop,
9335 .read = perf_swevent_read,
9338 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9340 * Flags in config, used by dynamic PMU kprobe and uprobe
9341 * The flags should match following PMU_FORMAT_ATTR().
9343 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9344 * if not set, create kprobe/uprobe
9346 * The following values specify a reference counter (or semaphore in the
9347 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9348 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9350 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9351 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9353 enum perf_probe_config {
9354 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9355 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9356 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9359 PMU_FORMAT_ATTR(retprobe, "config:0");
9362 #ifdef CONFIG_KPROBE_EVENTS
9363 static struct attribute *kprobe_attrs[] = {
9364 &format_attr_retprobe.attr,
9368 static struct attribute_group kprobe_format_group = {
9370 .attrs = kprobe_attrs,
9373 static const struct attribute_group *kprobe_attr_groups[] = {
9374 &kprobe_format_group,
9378 static int perf_kprobe_event_init(struct perf_event *event);
9379 static struct pmu perf_kprobe = {
9380 .task_ctx_nr = perf_sw_context,
9381 .event_init = perf_kprobe_event_init,
9382 .add = perf_trace_add,
9383 .del = perf_trace_del,
9384 .start = perf_swevent_start,
9385 .stop = perf_swevent_stop,
9386 .read = perf_swevent_read,
9387 .attr_groups = kprobe_attr_groups,
9390 static int perf_kprobe_event_init(struct perf_event *event)
9395 if (event->attr.type != perf_kprobe.type)
9398 if (!capable(CAP_SYS_ADMIN))
9402 * no branch sampling for probe events
9404 if (has_branch_stack(event))
9407 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9408 err = perf_kprobe_init(event, is_retprobe);
9412 event->destroy = perf_kprobe_destroy;
9416 #endif /* CONFIG_KPROBE_EVENTS */
9418 #ifdef CONFIG_UPROBE_EVENTS
9419 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9421 static struct attribute *uprobe_attrs[] = {
9422 &format_attr_retprobe.attr,
9423 &format_attr_ref_ctr_offset.attr,
9427 static struct attribute_group uprobe_format_group = {
9429 .attrs = uprobe_attrs,
9432 static const struct attribute_group *uprobe_attr_groups[] = {
9433 &uprobe_format_group,
9437 static int perf_uprobe_event_init(struct perf_event *event);
9438 static struct pmu perf_uprobe = {
9439 .task_ctx_nr = perf_sw_context,
9440 .event_init = perf_uprobe_event_init,
9441 .add = perf_trace_add,
9442 .del = perf_trace_del,
9443 .start = perf_swevent_start,
9444 .stop = perf_swevent_stop,
9445 .read = perf_swevent_read,
9446 .attr_groups = uprobe_attr_groups,
9449 static int perf_uprobe_event_init(struct perf_event *event)
9452 unsigned long ref_ctr_offset;
9455 if (event->attr.type != perf_uprobe.type)
9458 if (!capable(CAP_SYS_ADMIN))
9462 * no branch sampling for probe events
9464 if (has_branch_stack(event))
9467 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9468 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9469 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9473 event->destroy = perf_uprobe_destroy;
9477 #endif /* CONFIG_UPROBE_EVENTS */
9479 static inline void perf_tp_register(void)
9481 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9482 #ifdef CONFIG_KPROBE_EVENTS
9483 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9485 #ifdef CONFIG_UPROBE_EVENTS
9486 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9490 static void perf_event_free_filter(struct perf_event *event)
9492 ftrace_profile_free_filter(event);
9495 #ifdef CONFIG_BPF_SYSCALL
9496 static void bpf_overflow_handler(struct perf_event *event,
9497 struct perf_sample_data *data,
9498 struct pt_regs *regs)
9500 struct bpf_perf_event_data_kern ctx = {
9506 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9507 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9510 ret = BPF_PROG_RUN(event->prog, &ctx);
9513 __this_cpu_dec(bpf_prog_active);
9517 event->orig_overflow_handler(event, data, regs);
9520 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9522 struct bpf_prog *prog;
9524 if (event->overflow_handler_context)
9525 /* hw breakpoint or kernel counter */
9531 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9533 return PTR_ERR(prog);
9536 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9537 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9541 static void perf_event_free_bpf_handler(struct perf_event *event)
9543 struct bpf_prog *prog = event->prog;
9548 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9553 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9557 static void perf_event_free_bpf_handler(struct perf_event *event)
9563 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9564 * with perf_event_open()
9566 static inline bool perf_event_is_tracing(struct perf_event *event)
9568 if (event->pmu == &perf_tracepoint)
9570 #ifdef CONFIG_KPROBE_EVENTS
9571 if (event->pmu == &perf_kprobe)
9574 #ifdef CONFIG_UPROBE_EVENTS
9575 if (event->pmu == &perf_uprobe)
9581 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9583 bool is_kprobe, is_tracepoint, is_syscall_tp;
9584 struct bpf_prog *prog;
9587 if (!perf_event_is_tracing(event))
9588 return perf_event_set_bpf_handler(event, prog_fd);
9590 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9591 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9592 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9593 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9594 /* bpf programs can only be attached to u/kprobe or tracepoint */
9597 prog = bpf_prog_get(prog_fd);
9599 return PTR_ERR(prog);
9601 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9602 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9603 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9604 /* valid fd, but invalid bpf program type */
9609 /* Kprobe override only works for kprobes, not uprobes. */
9610 if (prog->kprobe_override &&
9611 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9616 if (is_tracepoint || is_syscall_tp) {
9617 int off = trace_event_get_offsets(event->tp_event);
9619 if (prog->aux->max_ctx_offset > off) {
9625 ret = perf_event_attach_bpf_prog(event, prog);
9631 static void perf_event_free_bpf_prog(struct perf_event *event)
9633 if (!perf_event_is_tracing(event)) {
9634 perf_event_free_bpf_handler(event);
9637 perf_event_detach_bpf_prog(event);
9642 static inline void perf_tp_register(void)
9646 static void perf_event_free_filter(struct perf_event *event)
9650 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9655 static void perf_event_free_bpf_prog(struct perf_event *event)
9658 #endif /* CONFIG_EVENT_TRACING */
9660 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9661 void perf_bp_event(struct perf_event *bp, void *data)
9663 struct perf_sample_data sample;
9664 struct pt_regs *regs = data;
9666 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9668 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9669 perf_swevent_event(bp, 1, &sample, regs);
9674 * Allocate a new address filter
9676 static struct perf_addr_filter *
9677 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9679 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9680 struct perf_addr_filter *filter;
9682 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9686 INIT_LIST_HEAD(&filter->entry);
9687 list_add_tail(&filter->entry, filters);
9692 static void free_filters_list(struct list_head *filters)
9694 struct perf_addr_filter *filter, *iter;
9696 list_for_each_entry_safe(filter, iter, filters, entry) {
9697 path_put(&filter->path);
9698 list_del(&filter->entry);
9704 * Free existing address filters and optionally install new ones
9706 static void perf_addr_filters_splice(struct perf_event *event,
9707 struct list_head *head)
9709 unsigned long flags;
9712 if (!has_addr_filter(event))
9715 /* don't bother with children, they don't have their own filters */
9719 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9721 list_splice_init(&event->addr_filters.list, &list);
9723 list_splice(head, &event->addr_filters.list);
9725 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9727 free_filters_list(&list);
9731 * Scan through mm's vmas and see if one of them matches the
9732 * @filter; if so, adjust filter's address range.
9733 * Called with mm::mmap_sem down for reading.
9735 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9736 struct mm_struct *mm,
9737 struct perf_addr_filter_range *fr)
9739 struct vm_area_struct *vma;
9741 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9745 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9751 * Update event's address range filters based on the
9752 * task's existing mappings, if any.
9754 static void perf_event_addr_filters_apply(struct perf_event *event)
9756 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9757 struct task_struct *task = READ_ONCE(event->ctx->task);
9758 struct perf_addr_filter *filter;
9759 struct mm_struct *mm = NULL;
9760 unsigned int count = 0;
9761 unsigned long flags;
9764 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9765 * will stop on the parent's child_mutex that our caller is also holding
9767 if (task == TASK_TOMBSTONE)
9770 if (ifh->nr_file_filters) {
9771 mm = get_task_mm(event->ctx->task);
9775 down_read(&mm->mmap_sem);
9778 raw_spin_lock_irqsave(&ifh->lock, flags);
9779 list_for_each_entry(filter, &ifh->list, entry) {
9780 if (filter->path.dentry) {
9782 * Adjust base offset if the filter is associated to a
9783 * binary that needs to be mapped:
9785 event->addr_filter_ranges[count].start = 0;
9786 event->addr_filter_ranges[count].size = 0;
9788 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9790 event->addr_filter_ranges[count].start = filter->offset;
9791 event->addr_filter_ranges[count].size = filter->size;
9797 event->addr_filters_gen++;
9798 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9800 if (ifh->nr_file_filters) {
9801 up_read(&mm->mmap_sem);
9807 perf_event_stop(event, 1);
9811 * Address range filtering: limiting the data to certain
9812 * instruction address ranges. Filters are ioctl()ed to us from
9813 * userspace as ascii strings.
9815 * Filter string format:
9818 * where ACTION is one of the
9819 * * "filter": limit the trace to this region
9820 * * "start": start tracing from this address
9821 * * "stop": stop tracing at this address/region;
9823 * * for kernel addresses: <start address>[/<size>]
9824 * * for object files: <start address>[/<size>]@</path/to/object/file>
9826 * if <size> is not specified or is zero, the range is treated as a single
9827 * address; not valid for ACTION=="filter".
9841 IF_STATE_ACTION = 0,
9846 static const match_table_t if_tokens = {
9847 { IF_ACT_FILTER, "filter" },
9848 { IF_ACT_START, "start" },
9849 { IF_ACT_STOP, "stop" },
9850 { IF_SRC_FILE, "%u/%u@%s" },
9851 { IF_SRC_KERNEL, "%u/%u" },
9852 { IF_SRC_FILEADDR, "%u@%s" },
9853 { IF_SRC_KERNELADDR, "%u" },
9854 { IF_ACT_NONE, NULL },
9858 * Address filter string parser
9861 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9862 struct list_head *filters)
9864 struct perf_addr_filter *filter = NULL;
9865 char *start, *orig, *filename = NULL;
9866 substring_t args[MAX_OPT_ARGS];
9867 int state = IF_STATE_ACTION, token;
9868 unsigned int kernel = 0;
9871 orig = fstr = kstrdup(fstr, GFP_KERNEL);
9875 while ((start = strsep(&fstr, " ,\n")) != NULL) {
9876 static const enum perf_addr_filter_action_t actions[] = {
9877 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
9878 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
9879 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
9886 /* filter definition begins */
9887 if (state == IF_STATE_ACTION) {
9888 filter = perf_addr_filter_new(event, filters);
9893 token = match_token(start, if_tokens, args);
9898 if (state != IF_STATE_ACTION)
9901 filter->action = actions[token];
9902 state = IF_STATE_SOURCE;
9905 case IF_SRC_KERNELADDR:
9910 case IF_SRC_FILEADDR:
9912 if (state != IF_STATE_SOURCE)
9916 ret = kstrtoul(args[0].from, 0, &filter->offset);
9920 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
9922 ret = kstrtoul(args[1].from, 0, &filter->size);
9927 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
9928 int fpos = token == IF_SRC_FILE ? 2 : 1;
9930 filename = match_strdup(&args[fpos]);
9937 state = IF_STATE_END;
9945 * Filter definition is fully parsed, validate and install it.
9946 * Make sure that it doesn't contradict itself or the event's
9949 if (state == IF_STATE_END) {
9951 if (kernel && event->attr.exclude_kernel)
9955 * ACTION "filter" must have a non-zero length region
9958 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
9967 * For now, we only support file-based filters
9968 * in per-task events; doing so for CPU-wide
9969 * events requires additional context switching
9970 * trickery, since same object code will be
9971 * mapped at different virtual addresses in
9972 * different processes.
9975 if (!event->ctx->task)
9976 goto fail_free_name;
9978 /* look up the path and grab its inode */
9979 ret = kern_path(filename, LOOKUP_FOLLOW,
9982 goto fail_free_name;
9988 if (!filter->path.dentry ||
9989 !S_ISREG(d_inode(filter->path.dentry)
9993 event->addr_filters.nr_file_filters++;
9996 /* ready to consume more filters */
9997 state = IF_STATE_ACTION;
10002 if (state != IF_STATE_ACTION)
10012 free_filters_list(filters);
10019 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10021 LIST_HEAD(filters);
10025 * Since this is called in perf_ioctl() path, we're already holding
10028 lockdep_assert_held(&event->ctx->mutex);
10030 if (WARN_ON_ONCE(event->parent))
10033 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10035 goto fail_clear_files;
10037 ret = event->pmu->addr_filters_validate(&filters);
10039 goto fail_free_filters;
10041 /* remove existing filters, if any */
10042 perf_addr_filters_splice(event, &filters);
10044 /* install new filters */
10045 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10050 free_filters_list(&filters);
10053 event->addr_filters.nr_file_filters = 0;
10058 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10063 filter_str = strndup_user(arg, PAGE_SIZE);
10064 if (IS_ERR(filter_str))
10065 return PTR_ERR(filter_str);
10067 #ifdef CONFIG_EVENT_TRACING
10068 if (perf_event_is_tracing(event)) {
10069 struct perf_event_context *ctx = event->ctx;
10072 * Beware, here be dragons!!
10074 * the tracepoint muck will deadlock against ctx->mutex, but
10075 * the tracepoint stuff does not actually need it. So
10076 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10077 * already have a reference on ctx.
10079 * This can result in event getting moved to a different ctx,
10080 * but that does not affect the tracepoint state.
10082 mutex_unlock(&ctx->mutex);
10083 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10084 mutex_lock(&ctx->mutex);
10087 if (has_addr_filter(event))
10088 ret = perf_event_set_addr_filter(event, filter_str);
10095 * hrtimer based swevent callback
10098 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10100 enum hrtimer_restart ret = HRTIMER_RESTART;
10101 struct perf_sample_data data;
10102 struct pt_regs *regs;
10103 struct perf_event *event;
10106 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10108 if (event->state != PERF_EVENT_STATE_ACTIVE)
10109 return HRTIMER_NORESTART;
10111 event->pmu->read(event);
10113 perf_sample_data_init(&data, 0, event->hw.last_period);
10114 regs = get_irq_regs();
10116 if (regs && !perf_exclude_event(event, regs)) {
10117 if (!(event->attr.exclude_idle && is_idle_task(current)))
10118 if (__perf_event_overflow(event, 1, &data, regs))
10119 ret = HRTIMER_NORESTART;
10122 period = max_t(u64, 10000, event->hw.sample_period);
10123 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10128 static void perf_swevent_start_hrtimer(struct perf_event *event)
10130 struct hw_perf_event *hwc = &event->hw;
10133 if (!is_sampling_event(event))
10136 period = local64_read(&hwc->period_left);
10141 local64_set(&hwc->period_left, 0);
10143 period = max_t(u64, 10000, hwc->sample_period);
10145 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10146 HRTIMER_MODE_REL_PINNED_HARD);
10149 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10151 struct hw_perf_event *hwc = &event->hw;
10153 if (is_sampling_event(event)) {
10154 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10155 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10157 hrtimer_cancel(&hwc->hrtimer);
10161 static void perf_swevent_init_hrtimer(struct perf_event *event)
10163 struct hw_perf_event *hwc = &event->hw;
10165 if (!is_sampling_event(event))
10168 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10169 hwc->hrtimer.function = perf_swevent_hrtimer;
10172 * Since hrtimers have a fixed rate, we can do a static freq->period
10173 * mapping and avoid the whole period adjust feedback stuff.
10175 if (event->attr.freq) {
10176 long freq = event->attr.sample_freq;
10178 event->attr.sample_period = NSEC_PER_SEC / freq;
10179 hwc->sample_period = event->attr.sample_period;
10180 local64_set(&hwc->period_left, hwc->sample_period);
10181 hwc->last_period = hwc->sample_period;
10182 event->attr.freq = 0;
10187 * Software event: cpu wall time clock
10190 static void cpu_clock_event_update(struct perf_event *event)
10195 now = local_clock();
10196 prev = local64_xchg(&event->hw.prev_count, now);
10197 local64_add(now - prev, &event->count);
10200 static void cpu_clock_event_start(struct perf_event *event, int flags)
10202 local64_set(&event->hw.prev_count, local_clock());
10203 perf_swevent_start_hrtimer(event);
10206 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10208 perf_swevent_cancel_hrtimer(event);
10209 cpu_clock_event_update(event);
10212 static int cpu_clock_event_add(struct perf_event *event, int flags)
10214 if (flags & PERF_EF_START)
10215 cpu_clock_event_start(event, flags);
10216 perf_event_update_userpage(event);
10221 static void cpu_clock_event_del(struct perf_event *event, int flags)
10223 cpu_clock_event_stop(event, flags);
10226 static void cpu_clock_event_read(struct perf_event *event)
10228 cpu_clock_event_update(event);
10231 static int cpu_clock_event_init(struct perf_event *event)
10233 if (event->attr.type != PERF_TYPE_SOFTWARE)
10236 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10240 * no branch sampling for software events
10242 if (has_branch_stack(event))
10243 return -EOPNOTSUPP;
10245 perf_swevent_init_hrtimer(event);
10250 static struct pmu perf_cpu_clock = {
10251 .task_ctx_nr = perf_sw_context,
10253 .capabilities = PERF_PMU_CAP_NO_NMI,
10255 .event_init = cpu_clock_event_init,
10256 .add = cpu_clock_event_add,
10257 .del = cpu_clock_event_del,
10258 .start = cpu_clock_event_start,
10259 .stop = cpu_clock_event_stop,
10260 .read = cpu_clock_event_read,
10264 * Software event: task time clock
10267 static void task_clock_event_update(struct perf_event *event, u64 now)
10272 prev = local64_xchg(&event->hw.prev_count, now);
10273 delta = now - prev;
10274 local64_add(delta, &event->count);
10277 static void task_clock_event_start(struct perf_event *event, int flags)
10279 local64_set(&event->hw.prev_count, event->ctx->time);
10280 perf_swevent_start_hrtimer(event);
10283 static void task_clock_event_stop(struct perf_event *event, int flags)
10285 perf_swevent_cancel_hrtimer(event);
10286 task_clock_event_update(event, event->ctx->time);
10289 static int task_clock_event_add(struct perf_event *event, int flags)
10291 if (flags & PERF_EF_START)
10292 task_clock_event_start(event, flags);
10293 perf_event_update_userpage(event);
10298 static void task_clock_event_del(struct perf_event *event, int flags)
10300 task_clock_event_stop(event, PERF_EF_UPDATE);
10303 static void task_clock_event_read(struct perf_event *event)
10305 u64 now = perf_clock();
10306 u64 delta = now - event->ctx->timestamp;
10307 u64 time = event->ctx->time + delta;
10309 task_clock_event_update(event, time);
10312 static int task_clock_event_init(struct perf_event *event)
10314 if (event->attr.type != PERF_TYPE_SOFTWARE)
10317 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10321 * no branch sampling for software events
10323 if (has_branch_stack(event))
10324 return -EOPNOTSUPP;
10326 perf_swevent_init_hrtimer(event);
10331 static struct pmu perf_task_clock = {
10332 .task_ctx_nr = perf_sw_context,
10334 .capabilities = PERF_PMU_CAP_NO_NMI,
10336 .event_init = task_clock_event_init,
10337 .add = task_clock_event_add,
10338 .del = task_clock_event_del,
10339 .start = task_clock_event_start,
10340 .stop = task_clock_event_stop,
10341 .read = task_clock_event_read,
10344 static void perf_pmu_nop_void(struct pmu *pmu)
10348 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10352 static int perf_pmu_nop_int(struct pmu *pmu)
10357 static int perf_event_nop_int(struct perf_event *event, u64 value)
10362 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10364 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10366 __this_cpu_write(nop_txn_flags, flags);
10368 if (flags & ~PERF_PMU_TXN_ADD)
10371 perf_pmu_disable(pmu);
10374 static int perf_pmu_commit_txn(struct pmu *pmu)
10376 unsigned int flags = __this_cpu_read(nop_txn_flags);
10378 __this_cpu_write(nop_txn_flags, 0);
10380 if (flags & ~PERF_PMU_TXN_ADD)
10383 perf_pmu_enable(pmu);
10387 static void perf_pmu_cancel_txn(struct pmu *pmu)
10389 unsigned int flags = __this_cpu_read(nop_txn_flags);
10391 __this_cpu_write(nop_txn_flags, 0);
10393 if (flags & ~PERF_PMU_TXN_ADD)
10396 perf_pmu_enable(pmu);
10399 static int perf_event_idx_default(struct perf_event *event)
10405 * Ensures all contexts with the same task_ctx_nr have the same
10406 * pmu_cpu_context too.
10408 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10415 list_for_each_entry(pmu, &pmus, entry) {
10416 if (pmu->task_ctx_nr == ctxn)
10417 return pmu->pmu_cpu_context;
10423 static void free_pmu_context(struct pmu *pmu)
10426 * Static contexts such as perf_sw_context have a global lifetime
10427 * and may be shared between different PMUs. Avoid freeing them
10428 * when a single PMU is going away.
10430 if (pmu->task_ctx_nr > perf_invalid_context)
10433 free_percpu(pmu->pmu_cpu_context);
10437 * Let userspace know that this PMU supports address range filtering:
10439 static ssize_t nr_addr_filters_show(struct device *dev,
10440 struct device_attribute *attr,
10443 struct pmu *pmu = dev_get_drvdata(dev);
10445 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10447 DEVICE_ATTR_RO(nr_addr_filters);
10449 static struct idr pmu_idr;
10452 type_show(struct device *dev, struct device_attribute *attr, char *page)
10454 struct pmu *pmu = dev_get_drvdata(dev);
10456 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10458 static DEVICE_ATTR_RO(type);
10461 perf_event_mux_interval_ms_show(struct device *dev,
10462 struct device_attribute *attr,
10465 struct pmu *pmu = dev_get_drvdata(dev);
10467 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10470 static DEFINE_MUTEX(mux_interval_mutex);
10473 perf_event_mux_interval_ms_store(struct device *dev,
10474 struct device_attribute *attr,
10475 const char *buf, size_t count)
10477 struct pmu *pmu = dev_get_drvdata(dev);
10478 int timer, cpu, ret;
10480 ret = kstrtoint(buf, 0, &timer);
10487 /* same value, noting to do */
10488 if (timer == pmu->hrtimer_interval_ms)
10491 mutex_lock(&mux_interval_mutex);
10492 pmu->hrtimer_interval_ms = timer;
10494 /* update all cpuctx for this PMU */
10496 for_each_online_cpu(cpu) {
10497 struct perf_cpu_context *cpuctx;
10498 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10499 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10501 cpu_function_call(cpu,
10502 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10504 cpus_read_unlock();
10505 mutex_unlock(&mux_interval_mutex);
10509 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10511 static struct attribute *pmu_dev_attrs[] = {
10512 &dev_attr_type.attr,
10513 &dev_attr_perf_event_mux_interval_ms.attr,
10516 ATTRIBUTE_GROUPS(pmu_dev);
10518 static int pmu_bus_running;
10519 static struct bus_type pmu_bus = {
10520 .name = "event_source",
10521 .dev_groups = pmu_dev_groups,
10524 static void pmu_dev_release(struct device *dev)
10529 static int pmu_dev_alloc(struct pmu *pmu)
10533 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10537 pmu->dev->groups = pmu->attr_groups;
10538 device_initialize(pmu->dev);
10539 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10543 dev_set_drvdata(pmu->dev, pmu);
10544 pmu->dev->bus = &pmu_bus;
10545 pmu->dev->release = pmu_dev_release;
10546 ret = device_add(pmu->dev);
10550 /* For PMUs with address filters, throw in an extra attribute: */
10551 if (pmu->nr_addr_filters)
10552 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10557 if (pmu->attr_update)
10558 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10567 device_del(pmu->dev);
10570 put_device(pmu->dev);
10574 static struct lock_class_key cpuctx_mutex;
10575 static struct lock_class_key cpuctx_lock;
10577 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10579 int cpu, ret, max = PERF_TYPE_MAX;
10581 mutex_lock(&pmus_lock);
10583 pmu->pmu_disable_count = alloc_percpu(int);
10584 if (!pmu->pmu_disable_count)
10592 if (type != PERF_TYPE_SOFTWARE) {
10596 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10600 WARN_ON(type >= 0 && ret != type);
10606 if (pmu_bus_running) {
10607 ret = pmu_dev_alloc(pmu);
10613 if (pmu->task_ctx_nr == perf_hw_context) {
10614 static int hw_context_taken = 0;
10617 * Other than systems with heterogeneous CPUs, it never makes
10618 * sense for two PMUs to share perf_hw_context. PMUs which are
10619 * uncore must use perf_invalid_context.
10621 if (WARN_ON_ONCE(hw_context_taken &&
10622 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10623 pmu->task_ctx_nr = perf_invalid_context;
10625 hw_context_taken = 1;
10628 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10629 if (pmu->pmu_cpu_context)
10630 goto got_cpu_context;
10633 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10634 if (!pmu->pmu_cpu_context)
10637 for_each_possible_cpu(cpu) {
10638 struct perf_cpu_context *cpuctx;
10640 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10641 __perf_event_init_context(&cpuctx->ctx);
10642 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10643 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10644 cpuctx->ctx.pmu = pmu;
10645 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10647 __perf_mux_hrtimer_init(cpuctx, cpu);
10649 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10650 cpuctx->heap = cpuctx->heap_default;
10654 if (!pmu->start_txn) {
10655 if (pmu->pmu_enable) {
10657 * If we have pmu_enable/pmu_disable calls, install
10658 * transaction stubs that use that to try and batch
10659 * hardware accesses.
10661 pmu->start_txn = perf_pmu_start_txn;
10662 pmu->commit_txn = perf_pmu_commit_txn;
10663 pmu->cancel_txn = perf_pmu_cancel_txn;
10665 pmu->start_txn = perf_pmu_nop_txn;
10666 pmu->commit_txn = perf_pmu_nop_int;
10667 pmu->cancel_txn = perf_pmu_nop_void;
10671 if (!pmu->pmu_enable) {
10672 pmu->pmu_enable = perf_pmu_nop_void;
10673 pmu->pmu_disable = perf_pmu_nop_void;
10676 if (!pmu->check_period)
10677 pmu->check_period = perf_event_nop_int;
10679 if (!pmu->event_idx)
10680 pmu->event_idx = perf_event_idx_default;
10683 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10684 * since these cannot be in the IDR. This way the linear search
10685 * is fast, provided a valid software event is provided.
10687 if (type == PERF_TYPE_SOFTWARE || !name)
10688 list_add_rcu(&pmu->entry, &pmus);
10690 list_add_tail_rcu(&pmu->entry, &pmus);
10692 atomic_set(&pmu->exclusive_cnt, 0);
10695 mutex_unlock(&pmus_lock);
10700 device_del(pmu->dev);
10701 put_device(pmu->dev);
10704 if (pmu->type != PERF_TYPE_SOFTWARE)
10705 idr_remove(&pmu_idr, pmu->type);
10708 free_percpu(pmu->pmu_disable_count);
10711 EXPORT_SYMBOL_GPL(perf_pmu_register);
10713 void perf_pmu_unregister(struct pmu *pmu)
10715 mutex_lock(&pmus_lock);
10716 list_del_rcu(&pmu->entry);
10719 * We dereference the pmu list under both SRCU and regular RCU, so
10720 * synchronize against both of those.
10722 synchronize_srcu(&pmus_srcu);
10725 free_percpu(pmu->pmu_disable_count);
10726 if (pmu->type != PERF_TYPE_SOFTWARE)
10727 idr_remove(&pmu_idr, pmu->type);
10728 if (pmu_bus_running) {
10729 if (pmu->nr_addr_filters)
10730 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10731 device_del(pmu->dev);
10732 put_device(pmu->dev);
10734 free_pmu_context(pmu);
10735 mutex_unlock(&pmus_lock);
10737 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10739 static inline bool has_extended_regs(struct perf_event *event)
10741 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10742 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10745 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10747 struct perf_event_context *ctx = NULL;
10750 if (!try_module_get(pmu->module))
10754 * A number of pmu->event_init() methods iterate the sibling_list to,
10755 * for example, validate if the group fits on the PMU. Therefore,
10756 * if this is a sibling event, acquire the ctx->mutex to protect
10757 * the sibling_list.
10759 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10761 * This ctx->mutex can nest when we're called through
10762 * inheritance. See the perf_event_ctx_lock_nested() comment.
10764 ctx = perf_event_ctx_lock_nested(event->group_leader,
10765 SINGLE_DEPTH_NESTING);
10770 ret = pmu->event_init(event);
10773 perf_event_ctx_unlock(event->group_leader, ctx);
10776 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10777 has_extended_regs(event))
10780 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10781 event_has_any_exclude_flag(event))
10784 if (ret && event->destroy)
10785 event->destroy(event);
10789 module_put(pmu->module);
10794 static struct pmu *perf_init_event(struct perf_event *event)
10796 int idx, type, ret;
10799 idx = srcu_read_lock(&pmus_srcu);
10801 /* Try parent's PMU first: */
10802 if (event->parent && event->parent->pmu) {
10803 pmu = event->parent->pmu;
10804 ret = perf_try_init_event(pmu, event);
10810 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
10811 * are often aliases for PERF_TYPE_RAW.
10813 type = event->attr.type;
10814 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
10815 type = PERF_TYPE_RAW;
10819 pmu = idr_find(&pmu_idr, type);
10822 ret = perf_try_init_event(pmu, event);
10823 if (ret == -ENOENT && event->attr.type != type) {
10824 type = event->attr.type;
10829 pmu = ERR_PTR(ret);
10834 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
10835 ret = perf_try_init_event(pmu, event);
10839 if (ret != -ENOENT) {
10840 pmu = ERR_PTR(ret);
10844 pmu = ERR_PTR(-ENOENT);
10846 srcu_read_unlock(&pmus_srcu, idx);
10851 static void attach_sb_event(struct perf_event *event)
10853 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10855 raw_spin_lock(&pel->lock);
10856 list_add_rcu(&event->sb_list, &pel->list);
10857 raw_spin_unlock(&pel->lock);
10861 * We keep a list of all !task (and therefore per-cpu) events
10862 * that need to receive side-band records.
10864 * This avoids having to scan all the various PMU per-cpu contexts
10865 * looking for them.
10867 static void account_pmu_sb_event(struct perf_event *event)
10869 if (is_sb_event(event))
10870 attach_sb_event(event);
10873 static void account_event_cpu(struct perf_event *event, int cpu)
10878 if (is_cgroup_event(event))
10879 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
10882 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
10883 static void account_freq_event_nohz(void)
10885 #ifdef CONFIG_NO_HZ_FULL
10886 /* Lock so we don't race with concurrent unaccount */
10887 spin_lock(&nr_freq_lock);
10888 if (atomic_inc_return(&nr_freq_events) == 1)
10889 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
10890 spin_unlock(&nr_freq_lock);
10894 static void account_freq_event(void)
10896 if (tick_nohz_full_enabled())
10897 account_freq_event_nohz();
10899 atomic_inc(&nr_freq_events);
10903 static void account_event(struct perf_event *event)
10910 if (event->attach_state & PERF_ATTACH_TASK)
10912 if (event->attr.mmap || event->attr.mmap_data)
10913 atomic_inc(&nr_mmap_events);
10914 if (event->attr.comm)
10915 atomic_inc(&nr_comm_events);
10916 if (event->attr.namespaces)
10917 atomic_inc(&nr_namespaces_events);
10918 if (event->attr.cgroup)
10919 atomic_inc(&nr_cgroup_events);
10920 if (event->attr.task)
10921 atomic_inc(&nr_task_events);
10922 if (event->attr.freq)
10923 account_freq_event();
10924 if (event->attr.context_switch) {
10925 atomic_inc(&nr_switch_events);
10928 if (has_branch_stack(event))
10930 if (is_cgroup_event(event))
10932 if (event->attr.ksymbol)
10933 atomic_inc(&nr_ksymbol_events);
10934 if (event->attr.bpf_event)
10935 atomic_inc(&nr_bpf_events);
10939 * We need the mutex here because static_branch_enable()
10940 * must complete *before* the perf_sched_count increment
10943 if (atomic_inc_not_zero(&perf_sched_count))
10946 mutex_lock(&perf_sched_mutex);
10947 if (!atomic_read(&perf_sched_count)) {
10948 static_branch_enable(&perf_sched_events);
10950 * Guarantee that all CPUs observe they key change and
10951 * call the perf scheduling hooks before proceeding to
10952 * install events that need them.
10957 * Now that we have waited for the sync_sched(), allow further
10958 * increments to by-pass the mutex.
10960 atomic_inc(&perf_sched_count);
10961 mutex_unlock(&perf_sched_mutex);
10965 account_event_cpu(event, event->cpu);
10967 account_pmu_sb_event(event);
10971 * Allocate and initialize an event structure
10973 static struct perf_event *
10974 perf_event_alloc(struct perf_event_attr *attr, int cpu,
10975 struct task_struct *task,
10976 struct perf_event *group_leader,
10977 struct perf_event *parent_event,
10978 perf_overflow_handler_t overflow_handler,
10979 void *context, int cgroup_fd)
10982 struct perf_event *event;
10983 struct hw_perf_event *hwc;
10984 long err = -EINVAL;
10986 if ((unsigned)cpu >= nr_cpu_ids) {
10987 if (!task || cpu != -1)
10988 return ERR_PTR(-EINVAL);
10991 event = kzalloc(sizeof(*event), GFP_KERNEL);
10993 return ERR_PTR(-ENOMEM);
10996 * Single events are their own group leaders, with an
10997 * empty sibling list:
11000 group_leader = event;
11002 mutex_init(&event->child_mutex);
11003 INIT_LIST_HEAD(&event->child_list);
11005 INIT_LIST_HEAD(&event->event_entry);
11006 INIT_LIST_HEAD(&event->sibling_list);
11007 INIT_LIST_HEAD(&event->active_list);
11008 init_event_group(event);
11009 INIT_LIST_HEAD(&event->rb_entry);
11010 INIT_LIST_HEAD(&event->active_entry);
11011 INIT_LIST_HEAD(&event->addr_filters.list);
11012 INIT_HLIST_NODE(&event->hlist_entry);
11015 init_waitqueue_head(&event->waitq);
11016 event->pending_disable = -1;
11017 init_irq_work(&event->pending, perf_pending_event);
11019 mutex_init(&event->mmap_mutex);
11020 raw_spin_lock_init(&event->addr_filters.lock);
11022 atomic_long_set(&event->refcount, 1);
11024 event->attr = *attr;
11025 event->group_leader = group_leader;
11029 event->parent = parent_event;
11031 event->ns = get_pid_ns(task_active_pid_ns(current));
11032 event->id = atomic64_inc_return(&perf_event_id);
11034 event->state = PERF_EVENT_STATE_INACTIVE;
11037 event->attach_state = PERF_ATTACH_TASK;
11039 * XXX pmu::event_init needs to know what task to account to
11040 * and we cannot use the ctx information because we need the
11041 * pmu before we get a ctx.
11043 event->hw.target = get_task_struct(task);
11046 event->clock = &local_clock;
11048 event->clock = parent_event->clock;
11050 if (!overflow_handler && parent_event) {
11051 overflow_handler = parent_event->overflow_handler;
11052 context = parent_event->overflow_handler_context;
11053 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11054 if (overflow_handler == bpf_overflow_handler) {
11055 struct bpf_prog *prog = parent_event->prog;
11057 bpf_prog_inc(prog);
11058 event->prog = prog;
11059 event->orig_overflow_handler =
11060 parent_event->orig_overflow_handler;
11065 if (overflow_handler) {
11066 event->overflow_handler = overflow_handler;
11067 event->overflow_handler_context = context;
11068 } else if (is_write_backward(event)){
11069 event->overflow_handler = perf_event_output_backward;
11070 event->overflow_handler_context = NULL;
11072 event->overflow_handler = perf_event_output_forward;
11073 event->overflow_handler_context = NULL;
11076 perf_event__state_init(event);
11081 hwc->sample_period = attr->sample_period;
11082 if (attr->freq && attr->sample_freq)
11083 hwc->sample_period = 1;
11084 hwc->last_period = hwc->sample_period;
11086 local64_set(&hwc->period_left, hwc->sample_period);
11089 * We currently do not support PERF_SAMPLE_READ on inherited events.
11090 * See perf_output_read().
11092 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11095 if (!has_branch_stack(event))
11096 event->attr.branch_sample_type = 0;
11098 pmu = perf_init_event(event);
11100 err = PTR_ERR(pmu);
11105 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11106 * be different on other CPUs in the uncore mask.
11108 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11113 if (event->attr.aux_output &&
11114 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11119 if (cgroup_fd != -1) {
11120 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11125 err = exclusive_event_init(event);
11129 if (has_addr_filter(event)) {
11130 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11131 sizeof(struct perf_addr_filter_range),
11133 if (!event->addr_filter_ranges) {
11139 * Clone the parent's vma offsets: they are valid until exec()
11140 * even if the mm is not shared with the parent.
11142 if (event->parent) {
11143 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11145 raw_spin_lock_irq(&ifh->lock);
11146 memcpy(event->addr_filter_ranges,
11147 event->parent->addr_filter_ranges,
11148 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11149 raw_spin_unlock_irq(&ifh->lock);
11152 /* force hw sync on the address filters */
11153 event->addr_filters_gen = 1;
11156 if (!event->parent) {
11157 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11158 err = get_callchain_buffers(attr->sample_max_stack);
11160 goto err_addr_filters;
11164 err = security_perf_event_alloc(event);
11166 goto err_callchain_buffer;
11168 /* symmetric to unaccount_event() in _free_event() */
11169 account_event(event);
11173 err_callchain_buffer:
11174 if (!event->parent) {
11175 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11176 put_callchain_buffers();
11179 kfree(event->addr_filter_ranges);
11182 exclusive_event_destroy(event);
11185 if (is_cgroup_event(event))
11186 perf_detach_cgroup(event);
11187 if (event->destroy)
11188 event->destroy(event);
11189 module_put(pmu->module);
11192 put_pid_ns(event->ns);
11193 if (event->hw.target)
11194 put_task_struct(event->hw.target);
11197 return ERR_PTR(err);
11200 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11201 struct perf_event_attr *attr)
11206 /* Zero the full structure, so that a short copy will be nice. */
11207 memset(attr, 0, sizeof(*attr));
11209 ret = get_user(size, &uattr->size);
11213 /* ABI compatibility quirk: */
11215 size = PERF_ATTR_SIZE_VER0;
11216 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11219 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11228 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11231 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11234 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11237 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11238 u64 mask = attr->branch_sample_type;
11240 /* only using defined bits */
11241 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11244 /* at least one branch bit must be set */
11245 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11248 /* propagate priv level, when not set for branch */
11249 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11251 /* exclude_kernel checked on syscall entry */
11252 if (!attr->exclude_kernel)
11253 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11255 if (!attr->exclude_user)
11256 mask |= PERF_SAMPLE_BRANCH_USER;
11258 if (!attr->exclude_hv)
11259 mask |= PERF_SAMPLE_BRANCH_HV;
11261 * adjust user setting (for HW filter setup)
11263 attr->branch_sample_type = mask;
11265 /* privileged levels capture (kernel, hv): check permissions */
11266 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11267 ret = perf_allow_kernel(attr);
11273 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11274 ret = perf_reg_validate(attr->sample_regs_user);
11279 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11280 if (!arch_perf_have_user_stack_dump())
11284 * We have __u32 type for the size, but so far
11285 * we can only use __u16 as maximum due to the
11286 * __u16 sample size limit.
11288 if (attr->sample_stack_user >= USHRT_MAX)
11290 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11294 if (!attr->sample_max_stack)
11295 attr->sample_max_stack = sysctl_perf_event_max_stack;
11297 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11298 ret = perf_reg_validate(attr->sample_regs_intr);
11300 #ifndef CONFIG_CGROUP_PERF
11301 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11309 put_user(sizeof(*attr), &uattr->size);
11315 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11317 struct perf_buffer *rb = NULL;
11323 /* don't allow circular references */
11324 if (event == output_event)
11328 * Don't allow cross-cpu buffers
11330 if (output_event->cpu != event->cpu)
11334 * If its not a per-cpu rb, it must be the same task.
11336 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11340 * Mixing clocks in the same buffer is trouble you don't need.
11342 if (output_event->clock != event->clock)
11346 * Either writing ring buffer from beginning or from end.
11347 * Mixing is not allowed.
11349 if (is_write_backward(output_event) != is_write_backward(event))
11353 * If both events generate aux data, they must be on the same PMU
11355 if (has_aux(event) && has_aux(output_event) &&
11356 event->pmu != output_event->pmu)
11360 mutex_lock(&event->mmap_mutex);
11361 /* Can't redirect output if we've got an active mmap() */
11362 if (atomic_read(&event->mmap_count))
11365 if (output_event) {
11366 /* get the rb we want to redirect to */
11367 rb = ring_buffer_get(output_event);
11372 ring_buffer_attach(event, rb);
11376 mutex_unlock(&event->mmap_mutex);
11382 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11388 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11391 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11393 bool nmi_safe = false;
11396 case CLOCK_MONOTONIC:
11397 event->clock = &ktime_get_mono_fast_ns;
11401 case CLOCK_MONOTONIC_RAW:
11402 event->clock = &ktime_get_raw_fast_ns;
11406 case CLOCK_REALTIME:
11407 event->clock = &ktime_get_real_ns;
11410 case CLOCK_BOOTTIME:
11411 event->clock = &ktime_get_boottime_ns;
11415 event->clock = &ktime_get_clocktai_ns;
11422 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11429 * Variation on perf_event_ctx_lock_nested(), except we take two context
11432 static struct perf_event_context *
11433 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11434 struct perf_event_context *ctx)
11436 struct perf_event_context *gctx;
11440 gctx = READ_ONCE(group_leader->ctx);
11441 if (!refcount_inc_not_zero(&gctx->refcount)) {
11447 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11449 if (group_leader->ctx != gctx) {
11450 mutex_unlock(&ctx->mutex);
11451 mutex_unlock(&gctx->mutex);
11460 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11462 * @attr_uptr: event_id type attributes for monitoring/sampling
11465 * @group_fd: group leader event fd
11467 SYSCALL_DEFINE5(perf_event_open,
11468 struct perf_event_attr __user *, attr_uptr,
11469 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11471 struct perf_event *group_leader = NULL, *output_event = NULL;
11472 struct perf_event *event, *sibling;
11473 struct perf_event_attr attr;
11474 struct perf_event_context *ctx, *uninitialized_var(gctx);
11475 struct file *event_file = NULL;
11476 struct fd group = {NULL, 0};
11477 struct task_struct *task = NULL;
11480 int move_group = 0;
11482 int f_flags = O_RDWR;
11483 int cgroup_fd = -1;
11485 /* for future expandability... */
11486 if (flags & ~PERF_FLAG_ALL)
11489 /* Do we allow access to perf_event_open(2) ? */
11490 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11494 err = perf_copy_attr(attr_uptr, &attr);
11498 if (!attr.exclude_kernel) {
11499 err = perf_allow_kernel(&attr);
11504 if (attr.namespaces) {
11505 if (!capable(CAP_SYS_ADMIN))
11510 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11513 if (attr.sample_period & (1ULL << 63))
11517 /* Only privileged users can get physical addresses */
11518 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11519 err = perf_allow_kernel(&attr);
11524 err = security_locked_down(LOCKDOWN_PERF);
11525 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11526 /* REGS_INTR can leak data, lockdown must prevent this */
11532 * In cgroup mode, the pid argument is used to pass the fd
11533 * opened to the cgroup directory in cgroupfs. The cpu argument
11534 * designates the cpu on which to monitor threads from that
11537 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11540 if (flags & PERF_FLAG_FD_CLOEXEC)
11541 f_flags |= O_CLOEXEC;
11543 event_fd = get_unused_fd_flags(f_flags);
11547 if (group_fd != -1) {
11548 err = perf_fget_light(group_fd, &group);
11551 group_leader = group.file->private_data;
11552 if (flags & PERF_FLAG_FD_OUTPUT)
11553 output_event = group_leader;
11554 if (flags & PERF_FLAG_FD_NO_GROUP)
11555 group_leader = NULL;
11558 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11559 task = find_lively_task_by_vpid(pid);
11560 if (IS_ERR(task)) {
11561 err = PTR_ERR(task);
11566 if (task && group_leader &&
11567 group_leader->attr.inherit != attr.inherit) {
11573 err = mutex_lock_interruptible(&task->signal->exec_update_mutex);
11578 * Reuse ptrace permission checks for now.
11580 * We must hold exec_update_mutex across this and any potential
11581 * perf_install_in_context() call for this new event to
11582 * serialize against exec() altering our credentials (and the
11583 * perf_event_exit_task() that could imply).
11586 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11590 if (flags & PERF_FLAG_PID_CGROUP)
11593 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11594 NULL, NULL, cgroup_fd);
11595 if (IS_ERR(event)) {
11596 err = PTR_ERR(event);
11600 if (is_sampling_event(event)) {
11601 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11608 * Special case software events and allow them to be part of
11609 * any hardware group.
11613 if (attr.use_clockid) {
11614 err = perf_event_set_clock(event, attr.clockid);
11619 if (pmu->task_ctx_nr == perf_sw_context)
11620 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11622 if (group_leader) {
11623 if (is_software_event(event) &&
11624 !in_software_context(group_leader)) {
11626 * If the event is a sw event, but the group_leader
11627 * is on hw context.
11629 * Allow the addition of software events to hw
11630 * groups, this is safe because software events
11631 * never fail to schedule.
11633 pmu = group_leader->ctx->pmu;
11634 } else if (!is_software_event(event) &&
11635 is_software_event(group_leader) &&
11636 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11638 * In case the group is a pure software group, and we
11639 * try to add a hardware event, move the whole group to
11640 * the hardware context.
11647 * Get the target context (task or percpu):
11649 ctx = find_get_context(pmu, task, event);
11651 err = PTR_ERR(ctx);
11656 * Look up the group leader (we will attach this event to it):
11658 if (group_leader) {
11662 * Do not allow a recursive hierarchy (this new sibling
11663 * becoming part of another group-sibling):
11665 if (group_leader->group_leader != group_leader)
11668 /* All events in a group should have the same clock */
11669 if (group_leader->clock != event->clock)
11673 * Make sure we're both events for the same CPU;
11674 * grouping events for different CPUs is broken; since
11675 * you can never concurrently schedule them anyhow.
11677 if (group_leader->cpu != event->cpu)
11681 * Make sure we're both on the same task, or both
11684 if (group_leader->ctx->task != ctx->task)
11688 * Do not allow to attach to a group in a different task
11689 * or CPU context. If we're moving SW events, we'll fix
11690 * this up later, so allow that.
11692 if (!move_group && group_leader->ctx != ctx)
11696 * Only a group leader can be exclusive or pinned
11698 if (attr.exclusive || attr.pinned)
11702 if (output_event) {
11703 err = perf_event_set_output(event, output_event);
11708 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11710 if (IS_ERR(event_file)) {
11711 err = PTR_ERR(event_file);
11717 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11719 if (gctx->task == TASK_TOMBSTONE) {
11725 * Check if we raced against another sys_perf_event_open() call
11726 * moving the software group underneath us.
11728 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11730 * If someone moved the group out from under us, check
11731 * if this new event wound up on the same ctx, if so
11732 * its the regular !move_group case, otherwise fail.
11738 perf_event_ctx_unlock(group_leader, gctx);
11744 * Failure to create exclusive events returns -EBUSY.
11747 if (!exclusive_event_installable(group_leader, ctx))
11750 for_each_sibling_event(sibling, group_leader) {
11751 if (!exclusive_event_installable(sibling, ctx))
11755 mutex_lock(&ctx->mutex);
11758 if (ctx->task == TASK_TOMBSTONE) {
11763 if (!perf_event_validate_size(event)) {
11770 * Check if the @cpu we're creating an event for is online.
11772 * We use the perf_cpu_context::ctx::mutex to serialize against
11773 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11775 struct perf_cpu_context *cpuctx =
11776 container_of(ctx, struct perf_cpu_context, ctx);
11778 if (!cpuctx->online) {
11784 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
11790 * Must be under the same ctx::mutex as perf_install_in_context(),
11791 * because we need to serialize with concurrent event creation.
11793 if (!exclusive_event_installable(event, ctx)) {
11798 WARN_ON_ONCE(ctx->parent_ctx);
11801 * This is the point on no return; we cannot fail hereafter. This is
11802 * where we start modifying current state.
11807 * See perf_event_ctx_lock() for comments on the details
11808 * of swizzling perf_event::ctx.
11810 perf_remove_from_context(group_leader, 0);
11813 for_each_sibling_event(sibling, group_leader) {
11814 perf_remove_from_context(sibling, 0);
11819 * Wait for everybody to stop referencing the events through
11820 * the old lists, before installing it on new lists.
11825 * Install the group siblings before the group leader.
11827 * Because a group leader will try and install the entire group
11828 * (through the sibling list, which is still in-tact), we can
11829 * end up with siblings installed in the wrong context.
11831 * By installing siblings first we NO-OP because they're not
11832 * reachable through the group lists.
11834 for_each_sibling_event(sibling, group_leader) {
11835 perf_event__state_init(sibling);
11836 perf_install_in_context(ctx, sibling, sibling->cpu);
11841 * Removing from the context ends up with disabled
11842 * event. What we want here is event in the initial
11843 * startup state, ready to be add into new context.
11845 perf_event__state_init(group_leader);
11846 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11851 * Precalculate sample_data sizes; do while holding ctx::mutex such
11852 * that we're serialized against further additions and before
11853 * perf_install_in_context() which is the point the event is active and
11854 * can use these values.
11856 perf_event__header_size(event);
11857 perf_event__id_header_size(event);
11859 event->owner = current;
11861 perf_install_in_context(ctx, event, event->cpu);
11862 perf_unpin_context(ctx);
11865 perf_event_ctx_unlock(group_leader, gctx);
11866 mutex_unlock(&ctx->mutex);
11869 mutex_unlock(&task->signal->exec_update_mutex);
11870 put_task_struct(task);
11873 mutex_lock(¤t->perf_event_mutex);
11874 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
11875 mutex_unlock(¤t->perf_event_mutex);
11878 * Drop the reference on the group_event after placing the
11879 * new event on the sibling_list. This ensures destruction
11880 * of the group leader will find the pointer to itself in
11881 * perf_group_detach().
11884 fd_install(event_fd, event_file);
11889 perf_event_ctx_unlock(group_leader, gctx);
11890 mutex_unlock(&ctx->mutex);
11894 perf_unpin_context(ctx);
11898 * If event_file is set, the fput() above will have called ->release()
11899 * and that will take care of freeing the event.
11905 mutex_unlock(&task->signal->exec_update_mutex);
11908 put_task_struct(task);
11912 put_unused_fd(event_fd);
11917 * perf_event_create_kernel_counter
11919 * @attr: attributes of the counter to create
11920 * @cpu: cpu in which the counter is bound
11921 * @task: task to profile (NULL for percpu)
11923 struct perf_event *
11924 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
11925 struct task_struct *task,
11926 perf_overflow_handler_t overflow_handler,
11929 struct perf_event_context *ctx;
11930 struct perf_event *event;
11934 * Grouping is not supported for kernel events, neither is 'AUX',
11935 * make sure the caller's intentions are adjusted.
11937 if (attr->aux_output)
11938 return ERR_PTR(-EINVAL);
11940 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
11941 overflow_handler, context, -1);
11942 if (IS_ERR(event)) {
11943 err = PTR_ERR(event);
11947 /* Mark owner so we could distinguish it from user events. */
11948 event->owner = TASK_TOMBSTONE;
11951 * Get the target context (task or percpu):
11953 ctx = find_get_context(event->pmu, task, event);
11955 err = PTR_ERR(ctx);
11959 WARN_ON_ONCE(ctx->parent_ctx);
11960 mutex_lock(&ctx->mutex);
11961 if (ctx->task == TASK_TOMBSTONE) {
11968 * Check if the @cpu we're creating an event for is online.
11970 * We use the perf_cpu_context::ctx::mutex to serialize against
11971 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11973 struct perf_cpu_context *cpuctx =
11974 container_of(ctx, struct perf_cpu_context, ctx);
11975 if (!cpuctx->online) {
11981 if (!exclusive_event_installable(event, ctx)) {
11986 perf_install_in_context(ctx, event, event->cpu);
11987 perf_unpin_context(ctx);
11988 mutex_unlock(&ctx->mutex);
11993 mutex_unlock(&ctx->mutex);
11994 perf_unpin_context(ctx);
11999 return ERR_PTR(err);
12001 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12003 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12005 struct perf_event_context *src_ctx;
12006 struct perf_event_context *dst_ctx;
12007 struct perf_event *event, *tmp;
12010 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12011 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12014 * See perf_event_ctx_lock() for comments on the details
12015 * of swizzling perf_event::ctx.
12017 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12018 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12020 perf_remove_from_context(event, 0);
12021 unaccount_event_cpu(event, src_cpu);
12023 list_add(&event->migrate_entry, &events);
12027 * Wait for the events to quiesce before re-instating them.
12032 * Re-instate events in 2 passes.
12034 * Skip over group leaders and only install siblings on this first
12035 * pass, siblings will not get enabled without a leader, however a
12036 * leader will enable its siblings, even if those are still on the old
12039 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12040 if (event->group_leader == event)
12043 list_del(&event->migrate_entry);
12044 if (event->state >= PERF_EVENT_STATE_OFF)
12045 event->state = PERF_EVENT_STATE_INACTIVE;
12046 account_event_cpu(event, dst_cpu);
12047 perf_install_in_context(dst_ctx, event, dst_cpu);
12052 * Once all the siblings are setup properly, install the group leaders
12055 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12056 list_del(&event->migrate_entry);
12057 if (event->state >= PERF_EVENT_STATE_OFF)
12058 event->state = PERF_EVENT_STATE_INACTIVE;
12059 account_event_cpu(event, dst_cpu);
12060 perf_install_in_context(dst_ctx, event, dst_cpu);
12063 mutex_unlock(&dst_ctx->mutex);
12064 mutex_unlock(&src_ctx->mutex);
12066 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12068 static void sync_child_event(struct perf_event *child_event,
12069 struct task_struct *child)
12071 struct perf_event *parent_event = child_event->parent;
12074 if (child_event->attr.inherit_stat)
12075 perf_event_read_event(child_event, child);
12077 child_val = perf_event_count(child_event);
12080 * Add back the child's count to the parent's count:
12082 atomic64_add(child_val, &parent_event->child_count);
12083 atomic64_add(child_event->total_time_enabled,
12084 &parent_event->child_total_time_enabled);
12085 atomic64_add(child_event->total_time_running,
12086 &parent_event->child_total_time_running);
12090 perf_event_exit_event(struct perf_event *child_event,
12091 struct perf_event_context *child_ctx,
12092 struct task_struct *child)
12094 struct perf_event *parent_event = child_event->parent;
12097 * Do not destroy the 'original' grouping; because of the context
12098 * switch optimization the original events could've ended up in a
12099 * random child task.
12101 * If we were to destroy the original group, all group related
12102 * operations would cease to function properly after this random
12105 * Do destroy all inherited groups, we don't care about those
12106 * and being thorough is better.
12108 raw_spin_lock_irq(&child_ctx->lock);
12109 WARN_ON_ONCE(child_ctx->is_active);
12112 perf_group_detach(child_event);
12113 list_del_event(child_event, child_ctx);
12114 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12115 raw_spin_unlock_irq(&child_ctx->lock);
12118 * Parent events are governed by their filedesc, retain them.
12120 if (!parent_event) {
12121 perf_event_wakeup(child_event);
12125 * Child events can be cleaned up.
12128 sync_child_event(child_event, child);
12131 * Remove this event from the parent's list
12133 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12134 mutex_lock(&parent_event->child_mutex);
12135 list_del_init(&child_event->child_list);
12136 mutex_unlock(&parent_event->child_mutex);
12139 * Kick perf_poll() for is_event_hup().
12141 perf_event_wakeup(parent_event);
12142 free_event(child_event);
12143 put_event(parent_event);
12146 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12148 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12149 struct perf_event *child_event, *next;
12151 WARN_ON_ONCE(child != current);
12153 child_ctx = perf_pin_task_context(child, ctxn);
12158 * In order to reduce the amount of tricky in ctx tear-down, we hold
12159 * ctx::mutex over the entire thing. This serializes against almost
12160 * everything that wants to access the ctx.
12162 * The exception is sys_perf_event_open() /
12163 * perf_event_create_kernel_count() which does find_get_context()
12164 * without ctx::mutex (it cannot because of the move_group double mutex
12165 * lock thing). See the comments in perf_install_in_context().
12167 mutex_lock(&child_ctx->mutex);
12170 * In a single ctx::lock section, de-schedule the events and detach the
12171 * context from the task such that we cannot ever get it scheduled back
12174 raw_spin_lock_irq(&child_ctx->lock);
12175 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12178 * Now that the context is inactive, destroy the task <-> ctx relation
12179 * and mark the context dead.
12181 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12182 put_ctx(child_ctx); /* cannot be last */
12183 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12184 put_task_struct(current); /* cannot be last */
12186 clone_ctx = unclone_ctx(child_ctx);
12187 raw_spin_unlock_irq(&child_ctx->lock);
12190 put_ctx(clone_ctx);
12193 * Report the task dead after unscheduling the events so that we
12194 * won't get any samples after PERF_RECORD_EXIT. We can however still
12195 * get a few PERF_RECORD_READ events.
12197 perf_event_task(child, child_ctx, 0);
12199 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12200 perf_event_exit_event(child_event, child_ctx, child);
12202 mutex_unlock(&child_ctx->mutex);
12204 put_ctx(child_ctx);
12208 * When a child task exits, feed back event values to parent events.
12210 * Can be called with exec_update_mutex held when called from
12211 * install_exec_creds().
12213 void perf_event_exit_task(struct task_struct *child)
12215 struct perf_event *event, *tmp;
12218 mutex_lock(&child->perf_event_mutex);
12219 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12221 list_del_init(&event->owner_entry);
12224 * Ensure the list deletion is visible before we clear
12225 * the owner, closes a race against perf_release() where
12226 * we need to serialize on the owner->perf_event_mutex.
12228 smp_store_release(&event->owner, NULL);
12230 mutex_unlock(&child->perf_event_mutex);
12232 for_each_task_context_nr(ctxn)
12233 perf_event_exit_task_context(child, ctxn);
12236 * The perf_event_exit_task_context calls perf_event_task
12237 * with child's task_ctx, which generates EXIT events for
12238 * child contexts and sets child->perf_event_ctxp[] to NULL.
12239 * At this point we need to send EXIT events to cpu contexts.
12241 perf_event_task(child, NULL, 0);
12244 static void perf_free_event(struct perf_event *event,
12245 struct perf_event_context *ctx)
12247 struct perf_event *parent = event->parent;
12249 if (WARN_ON_ONCE(!parent))
12252 mutex_lock(&parent->child_mutex);
12253 list_del_init(&event->child_list);
12254 mutex_unlock(&parent->child_mutex);
12258 raw_spin_lock_irq(&ctx->lock);
12259 perf_group_detach(event);
12260 list_del_event(event, ctx);
12261 raw_spin_unlock_irq(&ctx->lock);
12266 * Free a context as created by inheritance by perf_event_init_task() below,
12267 * used by fork() in case of fail.
12269 * Even though the task has never lived, the context and events have been
12270 * exposed through the child_list, so we must take care tearing it all down.
12272 void perf_event_free_task(struct task_struct *task)
12274 struct perf_event_context *ctx;
12275 struct perf_event *event, *tmp;
12278 for_each_task_context_nr(ctxn) {
12279 ctx = task->perf_event_ctxp[ctxn];
12283 mutex_lock(&ctx->mutex);
12284 raw_spin_lock_irq(&ctx->lock);
12286 * Destroy the task <-> ctx relation and mark the context dead.
12288 * This is important because even though the task hasn't been
12289 * exposed yet the context has been (through child_list).
12291 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12292 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12293 put_task_struct(task); /* cannot be last */
12294 raw_spin_unlock_irq(&ctx->lock);
12296 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12297 perf_free_event(event, ctx);
12299 mutex_unlock(&ctx->mutex);
12302 * perf_event_release_kernel() could've stolen some of our
12303 * child events and still have them on its free_list. In that
12304 * case we must wait for these events to have been freed (in
12305 * particular all their references to this task must've been
12308 * Without this copy_process() will unconditionally free this
12309 * task (irrespective of its reference count) and
12310 * _free_event()'s put_task_struct(event->hw.target) will be a
12313 * Wait for all events to drop their context reference.
12315 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12316 put_ctx(ctx); /* must be last */
12320 void perf_event_delayed_put(struct task_struct *task)
12324 for_each_task_context_nr(ctxn)
12325 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12328 struct file *perf_event_get(unsigned int fd)
12330 struct file *file = fget(fd);
12332 return ERR_PTR(-EBADF);
12334 if (file->f_op != &perf_fops) {
12336 return ERR_PTR(-EBADF);
12342 const struct perf_event *perf_get_event(struct file *file)
12344 if (file->f_op != &perf_fops)
12345 return ERR_PTR(-EINVAL);
12347 return file->private_data;
12350 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12353 return ERR_PTR(-EINVAL);
12355 return &event->attr;
12359 * Inherit an event from parent task to child task.
12362 * - valid pointer on success
12363 * - NULL for orphaned events
12364 * - IS_ERR() on error
12366 static struct perf_event *
12367 inherit_event(struct perf_event *parent_event,
12368 struct task_struct *parent,
12369 struct perf_event_context *parent_ctx,
12370 struct task_struct *child,
12371 struct perf_event *group_leader,
12372 struct perf_event_context *child_ctx)
12374 enum perf_event_state parent_state = parent_event->state;
12375 struct perf_event *child_event;
12376 unsigned long flags;
12379 * Instead of creating recursive hierarchies of events,
12380 * we link inherited events back to the original parent,
12381 * which has a filp for sure, which we use as the reference
12384 if (parent_event->parent)
12385 parent_event = parent_event->parent;
12387 child_event = perf_event_alloc(&parent_event->attr,
12390 group_leader, parent_event,
12392 if (IS_ERR(child_event))
12393 return child_event;
12396 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12397 !child_ctx->task_ctx_data) {
12398 struct pmu *pmu = child_event->pmu;
12400 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
12402 if (!child_ctx->task_ctx_data) {
12403 free_event(child_event);
12404 return ERR_PTR(-ENOMEM);
12409 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12410 * must be under the same lock in order to serialize against
12411 * perf_event_release_kernel(), such that either we must observe
12412 * is_orphaned_event() or they will observe us on the child_list.
12414 mutex_lock(&parent_event->child_mutex);
12415 if (is_orphaned_event(parent_event) ||
12416 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12417 mutex_unlock(&parent_event->child_mutex);
12418 /* task_ctx_data is freed with child_ctx */
12419 free_event(child_event);
12423 get_ctx(child_ctx);
12426 * Make the child state follow the state of the parent event,
12427 * not its attr.disabled bit. We hold the parent's mutex,
12428 * so we won't race with perf_event_{en, dis}able_family.
12430 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12431 child_event->state = PERF_EVENT_STATE_INACTIVE;
12433 child_event->state = PERF_EVENT_STATE_OFF;
12435 if (parent_event->attr.freq) {
12436 u64 sample_period = parent_event->hw.sample_period;
12437 struct hw_perf_event *hwc = &child_event->hw;
12439 hwc->sample_period = sample_period;
12440 hwc->last_period = sample_period;
12442 local64_set(&hwc->period_left, sample_period);
12445 child_event->ctx = child_ctx;
12446 child_event->overflow_handler = parent_event->overflow_handler;
12447 child_event->overflow_handler_context
12448 = parent_event->overflow_handler_context;
12451 * Precalculate sample_data sizes
12453 perf_event__header_size(child_event);
12454 perf_event__id_header_size(child_event);
12457 * Link it up in the child's context:
12459 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12460 add_event_to_ctx(child_event, child_ctx);
12461 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12464 * Link this into the parent event's child list
12466 list_add_tail(&child_event->child_list, &parent_event->child_list);
12467 mutex_unlock(&parent_event->child_mutex);
12469 return child_event;
12473 * Inherits an event group.
12475 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12476 * This matches with perf_event_release_kernel() removing all child events.
12482 static int inherit_group(struct perf_event *parent_event,
12483 struct task_struct *parent,
12484 struct perf_event_context *parent_ctx,
12485 struct task_struct *child,
12486 struct perf_event_context *child_ctx)
12488 struct perf_event *leader;
12489 struct perf_event *sub;
12490 struct perf_event *child_ctr;
12492 leader = inherit_event(parent_event, parent, parent_ctx,
12493 child, NULL, child_ctx);
12494 if (IS_ERR(leader))
12495 return PTR_ERR(leader);
12497 * @leader can be NULL here because of is_orphaned_event(). In this
12498 * case inherit_event() will create individual events, similar to what
12499 * perf_group_detach() would do anyway.
12501 for_each_sibling_event(sub, parent_event) {
12502 child_ctr = inherit_event(sub, parent, parent_ctx,
12503 child, leader, child_ctx);
12504 if (IS_ERR(child_ctr))
12505 return PTR_ERR(child_ctr);
12507 if (sub->aux_event == parent_event && child_ctr &&
12508 !perf_get_aux_event(child_ctr, leader))
12515 * Creates the child task context and tries to inherit the event-group.
12517 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12518 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12519 * consistent with perf_event_release_kernel() removing all child events.
12526 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12527 struct perf_event_context *parent_ctx,
12528 struct task_struct *child, int ctxn,
12529 int *inherited_all)
12532 struct perf_event_context *child_ctx;
12534 if (!event->attr.inherit) {
12535 *inherited_all = 0;
12539 child_ctx = child->perf_event_ctxp[ctxn];
12542 * This is executed from the parent task context, so
12543 * inherit events that have been marked for cloning.
12544 * First allocate and initialize a context for the
12547 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12551 child->perf_event_ctxp[ctxn] = child_ctx;
12554 ret = inherit_group(event, parent, parent_ctx,
12558 *inherited_all = 0;
12564 * Initialize the perf_event context in task_struct
12566 static int perf_event_init_context(struct task_struct *child, int ctxn)
12568 struct perf_event_context *child_ctx, *parent_ctx;
12569 struct perf_event_context *cloned_ctx;
12570 struct perf_event *event;
12571 struct task_struct *parent = current;
12572 int inherited_all = 1;
12573 unsigned long flags;
12576 if (likely(!parent->perf_event_ctxp[ctxn]))
12580 * If the parent's context is a clone, pin it so it won't get
12581 * swapped under us.
12583 parent_ctx = perf_pin_task_context(parent, ctxn);
12588 * No need to check if parent_ctx != NULL here; since we saw
12589 * it non-NULL earlier, the only reason for it to become NULL
12590 * is if we exit, and since we're currently in the middle of
12591 * a fork we can't be exiting at the same time.
12595 * Lock the parent list. No need to lock the child - not PID
12596 * hashed yet and not running, so nobody can access it.
12598 mutex_lock(&parent_ctx->mutex);
12601 * We dont have to disable NMIs - we are only looking at
12602 * the list, not manipulating it:
12604 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12605 ret = inherit_task_group(event, parent, parent_ctx,
12606 child, ctxn, &inherited_all);
12612 * We can't hold ctx->lock when iterating the ->flexible_group list due
12613 * to allocations, but we need to prevent rotation because
12614 * rotate_ctx() will change the list from interrupt context.
12616 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12617 parent_ctx->rotate_disable = 1;
12618 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12620 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12621 ret = inherit_task_group(event, parent, parent_ctx,
12622 child, ctxn, &inherited_all);
12627 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12628 parent_ctx->rotate_disable = 0;
12630 child_ctx = child->perf_event_ctxp[ctxn];
12632 if (child_ctx && inherited_all) {
12634 * Mark the child context as a clone of the parent
12635 * context, or of whatever the parent is a clone of.
12637 * Note that if the parent is a clone, the holding of
12638 * parent_ctx->lock avoids it from being uncloned.
12640 cloned_ctx = parent_ctx->parent_ctx;
12642 child_ctx->parent_ctx = cloned_ctx;
12643 child_ctx->parent_gen = parent_ctx->parent_gen;
12645 child_ctx->parent_ctx = parent_ctx;
12646 child_ctx->parent_gen = parent_ctx->generation;
12648 get_ctx(child_ctx->parent_ctx);
12651 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12653 mutex_unlock(&parent_ctx->mutex);
12655 perf_unpin_context(parent_ctx);
12656 put_ctx(parent_ctx);
12662 * Initialize the perf_event context in task_struct
12664 int perf_event_init_task(struct task_struct *child)
12668 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12669 mutex_init(&child->perf_event_mutex);
12670 INIT_LIST_HEAD(&child->perf_event_list);
12672 for_each_task_context_nr(ctxn) {
12673 ret = perf_event_init_context(child, ctxn);
12675 perf_event_free_task(child);
12683 static void __init perf_event_init_all_cpus(void)
12685 struct swevent_htable *swhash;
12688 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12690 for_each_possible_cpu(cpu) {
12691 swhash = &per_cpu(swevent_htable, cpu);
12692 mutex_init(&swhash->hlist_mutex);
12693 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12695 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12696 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12698 #ifdef CONFIG_CGROUP_PERF
12699 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12701 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
12705 static void perf_swevent_init_cpu(unsigned int cpu)
12707 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12709 mutex_lock(&swhash->hlist_mutex);
12710 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12711 struct swevent_hlist *hlist;
12713 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12715 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12717 mutex_unlock(&swhash->hlist_mutex);
12720 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12721 static void __perf_event_exit_context(void *__info)
12723 struct perf_event_context *ctx = __info;
12724 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12725 struct perf_event *event;
12727 raw_spin_lock(&ctx->lock);
12728 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12729 list_for_each_entry(event, &ctx->event_list, event_entry)
12730 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12731 raw_spin_unlock(&ctx->lock);
12734 static void perf_event_exit_cpu_context(int cpu)
12736 struct perf_cpu_context *cpuctx;
12737 struct perf_event_context *ctx;
12740 mutex_lock(&pmus_lock);
12741 list_for_each_entry(pmu, &pmus, entry) {
12742 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12743 ctx = &cpuctx->ctx;
12745 mutex_lock(&ctx->mutex);
12746 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12747 cpuctx->online = 0;
12748 mutex_unlock(&ctx->mutex);
12750 cpumask_clear_cpu(cpu, perf_online_mask);
12751 mutex_unlock(&pmus_lock);
12755 static void perf_event_exit_cpu_context(int cpu) { }
12759 int perf_event_init_cpu(unsigned int cpu)
12761 struct perf_cpu_context *cpuctx;
12762 struct perf_event_context *ctx;
12765 perf_swevent_init_cpu(cpu);
12767 mutex_lock(&pmus_lock);
12768 cpumask_set_cpu(cpu, perf_online_mask);
12769 list_for_each_entry(pmu, &pmus, entry) {
12770 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12771 ctx = &cpuctx->ctx;
12773 mutex_lock(&ctx->mutex);
12774 cpuctx->online = 1;
12775 mutex_unlock(&ctx->mutex);
12777 mutex_unlock(&pmus_lock);
12782 int perf_event_exit_cpu(unsigned int cpu)
12784 perf_event_exit_cpu_context(cpu);
12789 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12793 for_each_online_cpu(cpu)
12794 perf_event_exit_cpu(cpu);
12800 * Run the perf reboot notifier at the very last possible moment so that
12801 * the generic watchdog code runs as long as possible.
12803 static struct notifier_block perf_reboot_notifier = {
12804 .notifier_call = perf_reboot,
12805 .priority = INT_MIN,
12808 void __init perf_event_init(void)
12812 idr_init(&pmu_idr);
12814 perf_event_init_all_cpus();
12815 init_srcu_struct(&pmus_srcu);
12816 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12817 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12818 perf_pmu_register(&perf_task_clock, NULL, -1);
12819 perf_tp_register();
12820 perf_event_init_cpu(smp_processor_id());
12821 register_reboot_notifier(&perf_reboot_notifier);
12823 ret = init_hw_breakpoint();
12824 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12827 * Build time assertion that we keep the data_head at the intended
12828 * location. IOW, validation we got the __reserved[] size right.
12830 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12834 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12837 struct perf_pmu_events_attr *pmu_attr =
12838 container_of(attr, struct perf_pmu_events_attr, attr);
12840 if (pmu_attr->event_str)
12841 return sprintf(page, "%s\n", pmu_attr->event_str);
12845 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
12847 static int __init perf_event_sysfs_init(void)
12852 mutex_lock(&pmus_lock);
12854 ret = bus_register(&pmu_bus);
12858 list_for_each_entry(pmu, &pmus, entry) {
12859 if (!pmu->name || pmu->type < 0)
12862 ret = pmu_dev_alloc(pmu);
12863 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12865 pmu_bus_running = 1;
12869 mutex_unlock(&pmus_lock);
12873 device_initcall(perf_event_sysfs_init);
12875 #ifdef CONFIG_CGROUP_PERF
12876 static struct cgroup_subsys_state *
12877 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
12879 struct perf_cgroup *jc;
12881 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
12883 return ERR_PTR(-ENOMEM);
12885 jc->info = alloc_percpu(struct perf_cgroup_info);
12888 return ERR_PTR(-ENOMEM);
12894 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
12896 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
12898 free_percpu(jc->info);
12902 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
12904 perf_event_cgroup(css->cgroup);
12908 static int __perf_cgroup_move(void *info)
12910 struct task_struct *task = info;
12912 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
12917 static void perf_cgroup_attach(struct cgroup_taskset *tset)
12919 struct task_struct *task;
12920 struct cgroup_subsys_state *css;
12922 cgroup_taskset_for_each(task, css, tset)
12923 task_function_call(task, __perf_cgroup_move, task);
12926 struct cgroup_subsys perf_event_cgrp_subsys = {
12927 .css_alloc = perf_cgroup_css_alloc,
12928 .css_free = perf_cgroup_css_free,
12929 .css_online = perf_cgroup_css_online,
12930 .attach = perf_cgroup_attach,
12932 * Implicitly enable on dfl hierarchy so that perf events can
12933 * always be filtered by cgroup2 path as long as perf_event
12934 * controller is not mounted on a legacy hierarchy.
12936 .implicit_on_dfl = true,
12939 #endif /* CONFIG_CGROUP_PERF */