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>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
60 #include <asm/irq_regs.h>
62 typedef int (*remote_function_f)(void *);
64 struct remote_function_call {
65 struct task_struct *p;
66 remote_function_f func;
71 static void remote_function(void *data)
73 struct remote_function_call *tfc = data;
74 struct task_struct *p = tfc->p;
78 if (task_cpu(p) != smp_processor_id())
82 * Now that we're on right CPU with IRQs disabled, we can test
83 * if we hit the right task without races.
86 tfc->ret = -ESRCH; /* No such (running) process */
91 tfc->ret = tfc->func(tfc->info);
95 * task_function_call - call a function on the cpu on which a task runs
96 * @p: the task to evaluate
97 * @func: the function to be called
98 * @info: the function call argument
100 * Calls the function @func when the task is currently running. This might
101 * be on the current CPU, which just calls the function directly. This will
102 * retry due to any failures in smp_call_function_single(), such as if the
103 * task_cpu() goes offline concurrently.
105 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
108 task_function_call(struct task_struct *p, remote_function_f func, void *info)
110 struct remote_function_call data = {
119 ret = smp_call_function_single(task_cpu(p), remote_function,
134 * cpu_function_call - call a function on the cpu
135 * @func: the function to be called
136 * @info: the function call argument
138 * Calls the function @func on the remote cpu.
140 * returns: @func return value or -ENXIO when the cpu is offline
142 static int cpu_function_call(int cpu, remote_function_f func, void *info)
144 struct remote_function_call data = {
148 .ret = -ENXIO, /* No such CPU */
151 smp_call_function_single(cpu, remote_function, &data, 1);
156 static inline struct perf_cpu_context *
157 __get_cpu_context(struct perf_event_context *ctx)
159 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
162 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
163 struct perf_event_context *ctx)
165 raw_spin_lock(&cpuctx->ctx.lock);
167 raw_spin_lock(&ctx->lock);
170 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
171 struct perf_event_context *ctx)
174 raw_spin_unlock(&ctx->lock);
175 raw_spin_unlock(&cpuctx->ctx.lock);
178 #define TASK_TOMBSTONE ((void *)-1L)
180 static bool is_kernel_event(struct perf_event *event)
182 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
186 * On task ctx scheduling...
188 * When !ctx->nr_events a task context will not be scheduled. This means
189 * we can disable the scheduler hooks (for performance) without leaving
190 * pending task ctx state.
192 * This however results in two special cases:
194 * - removing the last event from a task ctx; this is relatively straight
195 * forward and is done in __perf_remove_from_context.
197 * - adding the first event to a task ctx; this is tricky because we cannot
198 * rely on ctx->is_active and therefore cannot use event_function_call().
199 * See perf_install_in_context().
201 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
204 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
205 struct perf_event_context *, void *);
207 struct event_function_struct {
208 struct perf_event *event;
213 static int event_function(void *info)
215 struct event_function_struct *efs = info;
216 struct perf_event *event = efs->event;
217 struct perf_event_context *ctx = event->ctx;
218 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
219 struct perf_event_context *task_ctx = cpuctx->task_ctx;
222 lockdep_assert_irqs_disabled();
224 perf_ctx_lock(cpuctx, task_ctx);
226 * Since we do the IPI call without holding ctx->lock things can have
227 * changed, double check we hit the task we set out to hit.
230 if (ctx->task != current) {
236 * We only use event_function_call() on established contexts,
237 * and event_function() is only ever called when active (or
238 * rather, we'll have bailed in task_function_call() or the
239 * above ctx->task != current test), therefore we must have
240 * ctx->is_active here.
242 WARN_ON_ONCE(!ctx->is_active);
244 * And since we have ctx->is_active, cpuctx->task_ctx must
247 WARN_ON_ONCE(task_ctx != ctx);
249 WARN_ON_ONCE(&cpuctx->ctx != ctx);
252 efs->func(event, cpuctx, ctx, efs->data);
254 perf_ctx_unlock(cpuctx, task_ctx);
259 static void event_function_call(struct perf_event *event, event_f func, void *data)
261 struct perf_event_context *ctx = event->ctx;
262 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
263 struct event_function_struct efs = {
269 if (!event->parent) {
271 * If this is a !child event, we must hold ctx::mutex to
272 * stabilize the the event->ctx relation. See
273 * perf_event_ctx_lock().
275 lockdep_assert_held(&ctx->mutex);
279 cpu_function_call(event->cpu, event_function, &efs);
283 if (task == TASK_TOMBSTONE)
287 if (!task_function_call(task, event_function, &efs))
290 raw_spin_lock_irq(&ctx->lock);
292 * Reload the task pointer, it might have been changed by
293 * a concurrent perf_event_context_sched_out().
296 if (task == TASK_TOMBSTONE) {
297 raw_spin_unlock_irq(&ctx->lock);
300 if (ctx->is_active) {
301 raw_spin_unlock_irq(&ctx->lock);
304 func(event, NULL, ctx, data);
305 raw_spin_unlock_irq(&ctx->lock);
309 * Similar to event_function_call() + event_function(), but hard assumes IRQs
310 * are already disabled and we're on the right CPU.
312 static void event_function_local(struct perf_event *event, event_f func, void *data)
314 struct perf_event_context *ctx = event->ctx;
315 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
316 struct task_struct *task = READ_ONCE(ctx->task);
317 struct perf_event_context *task_ctx = NULL;
319 lockdep_assert_irqs_disabled();
322 if (task == TASK_TOMBSTONE)
328 perf_ctx_lock(cpuctx, task_ctx);
331 if (task == TASK_TOMBSTONE)
336 * We must be either inactive or active and the right task,
337 * otherwise we're screwed, since we cannot IPI to somewhere
340 if (ctx->is_active) {
341 if (WARN_ON_ONCE(task != current))
344 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
348 WARN_ON_ONCE(&cpuctx->ctx != ctx);
351 func(event, cpuctx, ctx, data);
353 perf_ctx_unlock(cpuctx, task_ctx);
356 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
357 PERF_FLAG_FD_OUTPUT |\
358 PERF_FLAG_PID_CGROUP |\
359 PERF_FLAG_FD_CLOEXEC)
362 * branch priv levels that need permission checks
364 #define PERF_SAMPLE_BRANCH_PERM_PLM \
365 (PERF_SAMPLE_BRANCH_KERNEL |\
366 PERF_SAMPLE_BRANCH_HV)
369 EVENT_FLEXIBLE = 0x1,
372 /* see ctx_resched() for details */
374 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
378 * perf_sched_events : >0 events exist
379 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
382 static void perf_sched_delayed(struct work_struct *work);
383 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
384 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
385 static DEFINE_MUTEX(perf_sched_mutex);
386 static atomic_t perf_sched_count;
388 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
389 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
391 static atomic_t nr_mmap_events __read_mostly;
392 static atomic_t nr_comm_events __read_mostly;
393 static atomic_t nr_namespaces_events __read_mostly;
394 static atomic_t nr_task_events __read_mostly;
395 static atomic_t nr_freq_events __read_mostly;
396 static atomic_t nr_switch_events __read_mostly;
397 static atomic_t nr_ksymbol_events __read_mostly;
398 static atomic_t nr_bpf_events __read_mostly;
399 static atomic_t nr_cgroup_events __read_mostly;
400 static atomic_t nr_text_poke_events __read_mostly;
401 static atomic_t nr_build_id_events __read_mostly;
403 static LIST_HEAD(pmus);
404 static DEFINE_MUTEX(pmus_lock);
405 static struct srcu_struct pmus_srcu;
406 static cpumask_var_t perf_online_mask;
409 * perf event paranoia level:
410 * -1 - not paranoid at all
411 * 0 - disallow raw tracepoint access for unpriv
412 * 1 - disallow cpu events for unpriv
413 * 2 - disallow kernel profiling for unpriv
415 int sysctl_perf_event_paranoid __read_mostly = 2;
417 /* Minimum for 512 kiB + 1 user control page */
418 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
421 * max perf event sample rate
423 #define DEFAULT_MAX_SAMPLE_RATE 100000
424 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
425 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
427 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
429 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
430 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
432 static int perf_sample_allowed_ns __read_mostly =
433 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
435 static void update_perf_cpu_limits(void)
437 u64 tmp = perf_sample_period_ns;
439 tmp *= sysctl_perf_cpu_time_max_percent;
440 tmp = div_u64(tmp, 100);
444 WRITE_ONCE(perf_sample_allowed_ns, tmp);
447 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
449 int perf_proc_update_handler(struct ctl_table *table, int write,
450 void *buffer, size_t *lenp, loff_t *ppos)
453 int perf_cpu = sysctl_perf_cpu_time_max_percent;
455 * If throttling is disabled don't allow the write:
457 if (write && (perf_cpu == 100 || perf_cpu == 0))
460 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
464 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
465 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
466 update_perf_cpu_limits();
471 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
473 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
474 void *buffer, size_t *lenp, loff_t *ppos)
476 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
481 if (sysctl_perf_cpu_time_max_percent == 100 ||
482 sysctl_perf_cpu_time_max_percent == 0) {
484 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
485 WRITE_ONCE(perf_sample_allowed_ns, 0);
487 update_perf_cpu_limits();
494 * perf samples are done in some very critical code paths (NMIs).
495 * If they take too much CPU time, the system can lock up and not
496 * get any real work done. This will drop the sample rate when
497 * we detect that events are taking too long.
499 #define NR_ACCUMULATED_SAMPLES 128
500 static DEFINE_PER_CPU(u64, running_sample_length);
502 static u64 __report_avg;
503 static u64 __report_allowed;
505 static void perf_duration_warn(struct irq_work *w)
507 printk_ratelimited(KERN_INFO
508 "perf: interrupt took too long (%lld > %lld), lowering "
509 "kernel.perf_event_max_sample_rate to %d\n",
510 __report_avg, __report_allowed,
511 sysctl_perf_event_sample_rate);
514 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
516 void perf_sample_event_took(u64 sample_len_ns)
518 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
526 /* Decay the counter by 1 average sample. */
527 running_len = __this_cpu_read(running_sample_length);
528 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
529 running_len += sample_len_ns;
530 __this_cpu_write(running_sample_length, running_len);
533 * Note: this will be biased artifically low until we have
534 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
535 * from having to maintain a count.
537 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
538 if (avg_len <= max_len)
541 __report_avg = avg_len;
542 __report_allowed = max_len;
545 * Compute a throttle threshold 25% below the current duration.
547 avg_len += avg_len / 4;
548 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
554 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
555 WRITE_ONCE(max_samples_per_tick, max);
557 sysctl_perf_event_sample_rate = max * HZ;
558 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
560 if (!irq_work_queue(&perf_duration_work)) {
561 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
562 "kernel.perf_event_max_sample_rate to %d\n",
563 __report_avg, __report_allowed,
564 sysctl_perf_event_sample_rate);
568 static atomic64_t perf_event_id;
570 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
571 enum event_type_t event_type);
573 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
574 enum event_type_t event_type,
575 struct task_struct *task);
577 static void update_context_time(struct perf_event_context *ctx);
578 static u64 perf_event_time(struct perf_event *event);
580 void __weak perf_event_print_debug(void) { }
582 extern __weak const char *perf_pmu_name(void)
587 static inline u64 perf_clock(void)
589 return local_clock();
592 static inline u64 perf_event_clock(struct perf_event *event)
594 return event->clock();
598 * State based event timekeeping...
600 * The basic idea is to use event->state to determine which (if any) time
601 * fields to increment with the current delta. This means we only need to
602 * update timestamps when we change state or when they are explicitly requested
605 * Event groups make things a little more complicated, but not terribly so. The
606 * rules for a group are that if the group leader is OFF the entire group is
607 * OFF, irrespecive of what the group member states are. This results in
608 * __perf_effective_state().
610 * A futher ramification is that when a group leader flips between OFF and
611 * !OFF, we need to update all group member times.
614 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
615 * need to make sure the relevant context time is updated before we try and
616 * update our timestamps.
619 static __always_inline enum perf_event_state
620 __perf_effective_state(struct perf_event *event)
622 struct perf_event *leader = event->group_leader;
624 if (leader->state <= PERF_EVENT_STATE_OFF)
625 return leader->state;
630 static __always_inline void
631 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
633 enum perf_event_state state = __perf_effective_state(event);
634 u64 delta = now - event->tstamp;
636 *enabled = event->total_time_enabled;
637 if (state >= PERF_EVENT_STATE_INACTIVE)
640 *running = event->total_time_running;
641 if (state >= PERF_EVENT_STATE_ACTIVE)
645 static void perf_event_update_time(struct perf_event *event)
647 u64 now = perf_event_time(event);
649 __perf_update_times(event, now, &event->total_time_enabled,
650 &event->total_time_running);
654 static void perf_event_update_sibling_time(struct perf_event *leader)
656 struct perf_event *sibling;
658 for_each_sibling_event(sibling, leader)
659 perf_event_update_time(sibling);
663 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
665 if (event->state == state)
668 perf_event_update_time(event);
670 * If a group leader gets enabled/disabled all its siblings
673 if ((event->state < 0) ^ (state < 0))
674 perf_event_update_sibling_time(event);
676 WRITE_ONCE(event->state, state);
679 #ifdef CONFIG_CGROUP_PERF
682 perf_cgroup_match(struct perf_event *event)
684 struct perf_event_context *ctx = event->ctx;
685 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
687 /* @event doesn't care about cgroup */
691 /* wants specific cgroup scope but @cpuctx isn't associated with any */
696 * Cgroup scoping is recursive. An event enabled for a cgroup is
697 * also enabled for all its descendant cgroups. If @cpuctx's
698 * cgroup is a descendant of @event's (the test covers identity
699 * case), it's a match.
701 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
702 event->cgrp->css.cgroup);
705 static inline void perf_detach_cgroup(struct perf_event *event)
707 css_put(&event->cgrp->css);
711 static inline int is_cgroup_event(struct perf_event *event)
713 return event->cgrp != NULL;
716 static inline u64 perf_cgroup_event_time(struct perf_event *event)
718 struct perf_cgroup_info *t;
720 t = per_cpu_ptr(event->cgrp->info, event->cpu);
724 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
726 struct perf_cgroup_info *info;
731 info = this_cpu_ptr(cgrp->info);
733 info->time += now - info->timestamp;
734 info->timestamp = now;
737 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
739 struct perf_cgroup *cgrp = cpuctx->cgrp;
740 struct cgroup_subsys_state *css;
743 for (css = &cgrp->css; css; css = css->parent) {
744 cgrp = container_of(css, struct perf_cgroup, css);
745 __update_cgrp_time(cgrp);
750 static inline void update_cgrp_time_from_event(struct perf_event *event)
752 struct perf_cgroup *cgrp;
755 * ensure we access cgroup data only when needed and
756 * when we know the cgroup is pinned (css_get)
758 if (!is_cgroup_event(event))
761 cgrp = perf_cgroup_from_task(current, event->ctx);
763 * Do not update time when cgroup is not active
765 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
766 __update_cgrp_time(event->cgrp);
770 perf_cgroup_set_timestamp(struct task_struct *task,
771 struct perf_event_context *ctx)
773 struct perf_cgroup *cgrp;
774 struct perf_cgroup_info *info;
775 struct cgroup_subsys_state *css;
778 * ctx->lock held by caller
779 * ensure we do not access cgroup data
780 * unless we have the cgroup pinned (css_get)
782 if (!task || !ctx->nr_cgroups)
785 cgrp = perf_cgroup_from_task(task, ctx);
787 for (css = &cgrp->css; css; css = css->parent) {
788 cgrp = container_of(css, struct perf_cgroup, css);
789 info = this_cpu_ptr(cgrp->info);
790 info->timestamp = ctx->timestamp;
794 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
796 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
797 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
800 * reschedule events based on the cgroup constraint of task.
802 * mode SWOUT : schedule out everything
803 * mode SWIN : schedule in based on cgroup for next
805 static void perf_cgroup_switch(struct task_struct *task, int mode)
807 struct perf_cpu_context *cpuctx;
808 struct list_head *list;
812 * Disable interrupts and preemption to avoid this CPU's
813 * cgrp_cpuctx_entry to change under us.
815 local_irq_save(flags);
817 list = this_cpu_ptr(&cgrp_cpuctx_list);
818 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
819 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
821 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
822 perf_pmu_disable(cpuctx->ctx.pmu);
824 if (mode & PERF_CGROUP_SWOUT) {
825 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
827 * must not be done before ctxswout due
828 * to event_filter_match() in event_sched_out()
833 if (mode & PERF_CGROUP_SWIN) {
834 WARN_ON_ONCE(cpuctx->cgrp);
836 * set cgrp before ctxsw in to allow
837 * event_filter_match() to not have to pass
839 * we pass the cpuctx->ctx to perf_cgroup_from_task()
840 * because cgorup events are only per-cpu
842 cpuctx->cgrp = perf_cgroup_from_task(task,
844 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
846 perf_pmu_enable(cpuctx->ctx.pmu);
847 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
850 local_irq_restore(flags);
853 static inline void perf_cgroup_sched_out(struct task_struct *task,
854 struct task_struct *next)
856 struct perf_cgroup *cgrp1;
857 struct perf_cgroup *cgrp2 = NULL;
861 * we come here when we know perf_cgroup_events > 0
862 * we do not need to pass the ctx here because we know
863 * we are holding the rcu lock
865 cgrp1 = perf_cgroup_from_task(task, NULL);
866 cgrp2 = perf_cgroup_from_task(next, NULL);
869 * only schedule out current cgroup events if we know
870 * that we are switching to a different cgroup. Otherwise,
871 * do no touch the cgroup events.
874 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
879 static inline void perf_cgroup_sched_in(struct task_struct *prev,
880 struct task_struct *task)
882 struct perf_cgroup *cgrp1;
883 struct perf_cgroup *cgrp2 = NULL;
887 * we come here when we know perf_cgroup_events > 0
888 * we do not need to pass the ctx here because we know
889 * we are holding the rcu lock
891 cgrp1 = perf_cgroup_from_task(task, NULL);
892 cgrp2 = perf_cgroup_from_task(prev, NULL);
895 * only need to schedule in cgroup events if we are changing
896 * cgroup during ctxsw. Cgroup events were not scheduled
897 * out of ctxsw out if that was not the case.
900 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
905 static int perf_cgroup_ensure_storage(struct perf_event *event,
906 struct cgroup_subsys_state *css)
908 struct perf_cpu_context *cpuctx;
909 struct perf_event **storage;
910 int cpu, heap_size, ret = 0;
913 * Allow storage to have sufficent space for an iterator for each
914 * possibly nested cgroup plus an iterator for events with no cgroup.
916 for (heap_size = 1; css; css = css->parent)
919 for_each_possible_cpu(cpu) {
920 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
921 if (heap_size <= cpuctx->heap_size)
924 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
925 GFP_KERNEL, cpu_to_node(cpu));
931 raw_spin_lock_irq(&cpuctx->ctx.lock);
932 if (cpuctx->heap_size < heap_size) {
933 swap(cpuctx->heap, storage);
934 if (storage == cpuctx->heap_default)
936 cpuctx->heap_size = heap_size;
938 raw_spin_unlock_irq(&cpuctx->ctx.lock);
946 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
947 struct perf_event_attr *attr,
948 struct perf_event *group_leader)
950 struct perf_cgroup *cgrp;
951 struct cgroup_subsys_state *css;
952 struct fd f = fdget(fd);
958 css = css_tryget_online_from_dir(f.file->f_path.dentry,
959 &perf_event_cgrp_subsys);
965 ret = perf_cgroup_ensure_storage(event, css);
969 cgrp = container_of(css, struct perf_cgroup, css);
973 * all events in a group must monitor
974 * the same cgroup because a task belongs
975 * to only one perf cgroup at a time
977 if (group_leader && group_leader->cgrp != cgrp) {
978 perf_detach_cgroup(event);
987 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
989 struct perf_cgroup_info *t;
990 t = per_cpu_ptr(event->cgrp->info, event->cpu);
991 event->shadow_ctx_time = now - t->timestamp;
995 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
997 struct perf_cpu_context *cpuctx;
999 if (!is_cgroup_event(event))
1003 * Because cgroup events are always per-cpu events,
1004 * @ctx == &cpuctx->ctx.
1006 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1009 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1010 * matching the event's cgroup, we must do this for every new event,
1011 * because if the first would mismatch, the second would not try again
1012 * and we would leave cpuctx->cgrp unset.
1014 if (ctx->is_active && !cpuctx->cgrp) {
1015 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1017 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1018 cpuctx->cgrp = cgrp;
1021 if (ctx->nr_cgroups++)
1024 list_add(&cpuctx->cgrp_cpuctx_entry,
1025 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1029 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1031 struct perf_cpu_context *cpuctx;
1033 if (!is_cgroup_event(event))
1037 * Because cgroup events are always per-cpu events,
1038 * @ctx == &cpuctx->ctx.
1040 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1042 if (--ctx->nr_cgroups)
1045 if (ctx->is_active && cpuctx->cgrp)
1046 cpuctx->cgrp = NULL;
1048 list_del(&cpuctx->cgrp_cpuctx_entry);
1051 #else /* !CONFIG_CGROUP_PERF */
1054 perf_cgroup_match(struct perf_event *event)
1059 static inline void perf_detach_cgroup(struct perf_event *event)
1062 static inline int is_cgroup_event(struct perf_event *event)
1067 static inline void update_cgrp_time_from_event(struct perf_event *event)
1071 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1075 static inline void perf_cgroup_sched_out(struct task_struct *task,
1076 struct task_struct *next)
1080 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1081 struct task_struct *task)
1085 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1086 struct perf_event_attr *attr,
1087 struct perf_event *group_leader)
1093 perf_cgroup_set_timestamp(struct task_struct *task,
1094 struct perf_event_context *ctx)
1099 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1104 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1108 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1114 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1119 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1125 * set default to be dependent on timer tick just
1126 * like original code
1128 #define PERF_CPU_HRTIMER (1000 / HZ)
1130 * function must be called with interrupts disabled
1132 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1134 struct perf_cpu_context *cpuctx;
1137 lockdep_assert_irqs_disabled();
1139 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1140 rotations = perf_rotate_context(cpuctx);
1142 raw_spin_lock(&cpuctx->hrtimer_lock);
1144 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1146 cpuctx->hrtimer_active = 0;
1147 raw_spin_unlock(&cpuctx->hrtimer_lock);
1149 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1152 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1154 struct hrtimer *timer = &cpuctx->hrtimer;
1155 struct pmu *pmu = cpuctx->ctx.pmu;
1158 /* no multiplexing needed for SW PMU */
1159 if (pmu->task_ctx_nr == perf_sw_context)
1163 * check default is sane, if not set then force to
1164 * default interval (1/tick)
1166 interval = pmu->hrtimer_interval_ms;
1168 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1170 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1172 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1173 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1174 timer->function = perf_mux_hrtimer_handler;
1177 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1179 struct hrtimer *timer = &cpuctx->hrtimer;
1180 struct pmu *pmu = cpuctx->ctx.pmu;
1181 unsigned long flags;
1183 /* not for SW PMU */
1184 if (pmu->task_ctx_nr == perf_sw_context)
1187 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1188 if (!cpuctx->hrtimer_active) {
1189 cpuctx->hrtimer_active = 1;
1190 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1191 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1193 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1198 void perf_pmu_disable(struct pmu *pmu)
1200 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1202 pmu->pmu_disable(pmu);
1205 void perf_pmu_enable(struct pmu *pmu)
1207 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1209 pmu->pmu_enable(pmu);
1212 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1215 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1216 * perf_event_task_tick() are fully serialized because they're strictly cpu
1217 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1218 * disabled, while perf_event_task_tick is called from IRQ context.
1220 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1222 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1224 lockdep_assert_irqs_disabled();
1226 WARN_ON(!list_empty(&ctx->active_ctx_list));
1228 list_add(&ctx->active_ctx_list, head);
1231 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1233 lockdep_assert_irqs_disabled();
1235 WARN_ON(list_empty(&ctx->active_ctx_list));
1237 list_del_init(&ctx->active_ctx_list);
1240 static void get_ctx(struct perf_event_context *ctx)
1242 refcount_inc(&ctx->refcount);
1245 static void *alloc_task_ctx_data(struct pmu *pmu)
1247 if (pmu->task_ctx_cache)
1248 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1253 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1255 if (pmu->task_ctx_cache && task_ctx_data)
1256 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1259 static void free_ctx(struct rcu_head *head)
1261 struct perf_event_context *ctx;
1263 ctx = container_of(head, struct perf_event_context, rcu_head);
1264 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1268 static void put_ctx(struct perf_event_context *ctx)
1270 if (refcount_dec_and_test(&ctx->refcount)) {
1271 if (ctx->parent_ctx)
1272 put_ctx(ctx->parent_ctx);
1273 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1274 put_task_struct(ctx->task);
1275 call_rcu(&ctx->rcu_head, free_ctx);
1280 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1281 * perf_pmu_migrate_context() we need some magic.
1283 * Those places that change perf_event::ctx will hold both
1284 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1286 * Lock ordering is by mutex address. There are two other sites where
1287 * perf_event_context::mutex nests and those are:
1289 * - perf_event_exit_task_context() [ child , 0 ]
1290 * perf_event_exit_event()
1291 * put_event() [ parent, 1 ]
1293 * - perf_event_init_context() [ parent, 0 ]
1294 * inherit_task_group()
1297 * perf_event_alloc()
1299 * perf_try_init_event() [ child , 1 ]
1301 * While it appears there is an obvious deadlock here -- the parent and child
1302 * nesting levels are inverted between the two. This is in fact safe because
1303 * life-time rules separate them. That is an exiting task cannot fork, and a
1304 * spawning task cannot (yet) exit.
1306 * But remember that that these are parent<->child context relations, and
1307 * migration does not affect children, therefore these two orderings should not
1310 * The change in perf_event::ctx does not affect children (as claimed above)
1311 * because the sys_perf_event_open() case will install a new event and break
1312 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1313 * concerned with cpuctx and that doesn't have children.
1315 * The places that change perf_event::ctx will issue:
1317 * perf_remove_from_context();
1318 * synchronize_rcu();
1319 * perf_install_in_context();
1321 * to affect the change. The remove_from_context() + synchronize_rcu() should
1322 * quiesce the event, after which we can install it in the new location. This
1323 * means that only external vectors (perf_fops, prctl) can perturb the event
1324 * while in transit. Therefore all such accessors should also acquire
1325 * perf_event_context::mutex to serialize against this.
1327 * However; because event->ctx can change while we're waiting to acquire
1328 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1333 * task_struct::perf_event_mutex
1334 * perf_event_context::mutex
1335 * perf_event::child_mutex;
1336 * perf_event_context::lock
1337 * perf_event::mmap_mutex
1339 * perf_addr_filters_head::lock
1343 * cpuctx->mutex / perf_event_context::mutex
1345 static struct perf_event_context *
1346 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1348 struct perf_event_context *ctx;
1352 ctx = READ_ONCE(event->ctx);
1353 if (!refcount_inc_not_zero(&ctx->refcount)) {
1359 mutex_lock_nested(&ctx->mutex, nesting);
1360 if (event->ctx != ctx) {
1361 mutex_unlock(&ctx->mutex);
1369 static inline struct perf_event_context *
1370 perf_event_ctx_lock(struct perf_event *event)
1372 return perf_event_ctx_lock_nested(event, 0);
1375 static void perf_event_ctx_unlock(struct perf_event *event,
1376 struct perf_event_context *ctx)
1378 mutex_unlock(&ctx->mutex);
1383 * This must be done under the ctx->lock, such as to serialize against
1384 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1385 * calling scheduler related locks and ctx->lock nests inside those.
1387 static __must_check struct perf_event_context *
1388 unclone_ctx(struct perf_event_context *ctx)
1390 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1392 lockdep_assert_held(&ctx->lock);
1395 ctx->parent_ctx = NULL;
1401 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1406 * only top level events have the pid namespace they were created in
1409 event = event->parent;
1411 nr = __task_pid_nr_ns(p, type, event->ns);
1412 /* avoid -1 if it is idle thread or runs in another ns */
1413 if (!nr && !pid_alive(p))
1418 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1420 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1423 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1425 return perf_event_pid_type(event, p, PIDTYPE_PID);
1429 * If we inherit events we want to return the parent event id
1432 static u64 primary_event_id(struct perf_event *event)
1437 id = event->parent->id;
1443 * Get the perf_event_context for a task and lock it.
1445 * This has to cope with with the fact that until it is locked,
1446 * the context could get moved to another task.
1448 static struct perf_event_context *
1449 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1451 struct perf_event_context *ctx;
1455 * One of the few rules of preemptible RCU is that one cannot do
1456 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1457 * part of the read side critical section was irqs-enabled -- see
1458 * rcu_read_unlock_special().
1460 * Since ctx->lock nests under rq->lock we must ensure the entire read
1461 * side critical section has interrupts disabled.
1463 local_irq_save(*flags);
1465 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1468 * If this context is a clone of another, it might
1469 * get swapped for another underneath us by
1470 * perf_event_task_sched_out, though the
1471 * rcu_read_lock() protects us from any context
1472 * getting freed. Lock the context and check if it
1473 * got swapped before we could get the lock, and retry
1474 * if so. If we locked the right context, then it
1475 * can't get swapped on us any more.
1477 raw_spin_lock(&ctx->lock);
1478 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1479 raw_spin_unlock(&ctx->lock);
1481 local_irq_restore(*flags);
1485 if (ctx->task == TASK_TOMBSTONE ||
1486 !refcount_inc_not_zero(&ctx->refcount)) {
1487 raw_spin_unlock(&ctx->lock);
1490 WARN_ON_ONCE(ctx->task != task);
1495 local_irq_restore(*flags);
1500 * Get the context for a task and increment its pin_count so it
1501 * can't get swapped to another task. This also increments its
1502 * reference count so that the context can't get freed.
1504 static struct perf_event_context *
1505 perf_pin_task_context(struct task_struct *task, int ctxn)
1507 struct perf_event_context *ctx;
1508 unsigned long flags;
1510 ctx = perf_lock_task_context(task, ctxn, &flags);
1513 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1518 static void perf_unpin_context(struct perf_event_context *ctx)
1520 unsigned long flags;
1522 raw_spin_lock_irqsave(&ctx->lock, flags);
1524 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1528 * Update the record of the current time in a context.
1530 static void update_context_time(struct perf_event_context *ctx)
1532 u64 now = perf_clock();
1534 ctx->time += now - ctx->timestamp;
1535 ctx->timestamp = now;
1538 static u64 perf_event_time(struct perf_event *event)
1540 struct perf_event_context *ctx = event->ctx;
1542 if (is_cgroup_event(event))
1543 return perf_cgroup_event_time(event);
1545 return ctx ? ctx->time : 0;
1548 static enum event_type_t get_event_type(struct perf_event *event)
1550 struct perf_event_context *ctx = event->ctx;
1551 enum event_type_t event_type;
1553 lockdep_assert_held(&ctx->lock);
1556 * It's 'group type', really, because if our group leader is
1557 * pinned, so are we.
1559 if (event->group_leader != event)
1560 event = event->group_leader;
1562 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1564 event_type |= EVENT_CPU;
1570 * Helper function to initialize event group nodes.
1572 static void init_event_group(struct perf_event *event)
1574 RB_CLEAR_NODE(&event->group_node);
1575 event->group_index = 0;
1579 * Extract pinned or flexible groups from the context
1580 * based on event attrs bits.
1582 static struct perf_event_groups *
1583 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1585 if (event->attr.pinned)
1586 return &ctx->pinned_groups;
1588 return &ctx->flexible_groups;
1592 * Helper function to initializes perf_event_group trees.
1594 static void perf_event_groups_init(struct perf_event_groups *groups)
1596 groups->tree = RB_ROOT;
1600 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1602 struct cgroup *cgroup = NULL;
1604 #ifdef CONFIG_CGROUP_PERF
1606 cgroup = event->cgrp->css.cgroup;
1613 * Compare function for event groups;
1615 * Implements complex key that first sorts by CPU and then by virtual index
1616 * which provides ordering when rotating groups for the same CPU.
1618 static __always_inline int
1619 perf_event_groups_cmp(const int left_cpu, const struct cgroup *left_cgroup,
1620 const u64 left_group_index, const struct perf_event *right)
1622 if (left_cpu < right->cpu)
1624 if (left_cpu > right->cpu)
1627 #ifdef CONFIG_CGROUP_PERF
1629 const struct cgroup *right_cgroup = event_cgroup(right);
1631 if (left_cgroup != right_cgroup) {
1634 * Left has no cgroup but right does, no
1635 * cgroups come first.
1639 if (!right_cgroup) {
1641 * Right has no cgroup but left does, no
1642 * cgroups come first.
1646 /* Two dissimilar cgroups, order by id. */
1647 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1655 if (left_group_index < right->group_index)
1657 if (left_group_index > right->group_index)
1663 #define __node_2_pe(node) \
1664 rb_entry((node), struct perf_event, group_node)
1666 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1668 struct perf_event *e = __node_2_pe(a);
1669 return perf_event_groups_cmp(e->cpu, event_cgroup(e), e->group_index,
1670 __node_2_pe(b)) < 0;
1673 struct __group_key {
1675 struct cgroup *cgroup;
1678 static inline int __group_cmp(const void *key, const struct rb_node *node)
1680 const struct __group_key *a = key;
1681 const struct perf_event *b = __node_2_pe(node);
1683 /* partial/subtree match: @cpu, @cgroup; ignore: @group_index */
1684 return perf_event_groups_cmp(a->cpu, a->cgroup, b->group_index, b);
1688 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1689 * key (see perf_event_groups_less). This places it last inside the CPU
1693 perf_event_groups_insert(struct perf_event_groups *groups,
1694 struct perf_event *event)
1696 event->group_index = ++groups->index;
1698 rb_add(&event->group_node, &groups->tree, __group_less);
1702 * Helper function to insert event into the pinned or flexible groups.
1705 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1707 struct perf_event_groups *groups;
1709 groups = get_event_groups(event, ctx);
1710 perf_event_groups_insert(groups, event);
1714 * Delete a group from a tree.
1717 perf_event_groups_delete(struct perf_event_groups *groups,
1718 struct perf_event *event)
1720 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1721 RB_EMPTY_ROOT(&groups->tree));
1723 rb_erase(&event->group_node, &groups->tree);
1724 init_event_group(event);
1728 * Helper function to delete event from its groups.
1731 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1733 struct perf_event_groups *groups;
1735 groups = get_event_groups(event, ctx);
1736 perf_event_groups_delete(groups, event);
1740 * Get the leftmost event in the cpu/cgroup subtree.
1742 static struct perf_event *
1743 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1744 struct cgroup *cgrp)
1746 struct __group_key key = {
1750 struct rb_node *node;
1752 node = rb_find_first(&key, &groups->tree, __group_cmp);
1754 return __node_2_pe(node);
1760 * Like rb_entry_next_safe() for the @cpu subtree.
1762 static struct perf_event *
1763 perf_event_groups_next(struct perf_event *event)
1765 struct __group_key key = {
1767 .cgroup = event_cgroup(event),
1769 struct rb_node *next;
1771 next = rb_next_match(&key, &event->group_node, __group_cmp);
1773 return __node_2_pe(next);
1779 * Iterate through the whole groups tree.
1781 #define perf_event_groups_for_each(event, groups) \
1782 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1783 typeof(*event), group_node); event; \
1784 event = rb_entry_safe(rb_next(&event->group_node), \
1785 typeof(*event), group_node))
1788 * Add an event from the lists for its context.
1789 * Must be called with ctx->mutex and ctx->lock held.
1792 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1794 lockdep_assert_held(&ctx->lock);
1796 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1797 event->attach_state |= PERF_ATTACH_CONTEXT;
1799 event->tstamp = perf_event_time(event);
1802 * If we're a stand alone event or group leader, we go to the context
1803 * list, group events are kept attached to the group so that
1804 * perf_group_detach can, at all times, locate all siblings.
1806 if (event->group_leader == event) {
1807 event->group_caps = event->event_caps;
1808 add_event_to_groups(event, ctx);
1811 list_add_rcu(&event->event_entry, &ctx->event_list);
1813 if (event->attr.inherit_stat)
1816 if (event->state > PERF_EVENT_STATE_OFF)
1817 perf_cgroup_event_enable(event, ctx);
1823 * Initialize event state based on the perf_event_attr::disabled.
1825 static inline void perf_event__state_init(struct perf_event *event)
1827 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1828 PERF_EVENT_STATE_INACTIVE;
1831 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1833 int entry = sizeof(u64); /* value */
1837 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1838 size += sizeof(u64);
1840 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1841 size += sizeof(u64);
1843 if (event->attr.read_format & PERF_FORMAT_ID)
1844 entry += sizeof(u64);
1846 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1848 size += sizeof(u64);
1852 event->read_size = size;
1855 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1857 struct perf_sample_data *data;
1860 if (sample_type & PERF_SAMPLE_IP)
1861 size += sizeof(data->ip);
1863 if (sample_type & PERF_SAMPLE_ADDR)
1864 size += sizeof(data->addr);
1866 if (sample_type & PERF_SAMPLE_PERIOD)
1867 size += sizeof(data->period);
1869 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1870 size += sizeof(data->weight.full);
1872 if (sample_type & PERF_SAMPLE_READ)
1873 size += event->read_size;
1875 if (sample_type & PERF_SAMPLE_DATA_SRC)
1876 size += sizeof(data->data_src.val);
1878 if (sample_type & PERF_SAMPLE_TRANSACTION)
1879 size += sizeof(data->txn);
1881 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1882 size += sizeof(data->phys_addr);
1884 if (sample_type & PERF_SAMPLE_CGROUP)
1885 size += sizeof(data->cgroup);
1887 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1888 size += sizeof(data->data_page_size);
1890 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1891 size += sizeof(data->code_page_size);
1893 event->header_size = size;
1897 * Called at perf_event creation and when events are attached/detached from a
1900 static void perf_event__header_size(struct perf_event *event)
1902 __perf_event_read_size(event,
1903 event->group_leader->nr_siblings);
1904 __perf_event_header_size(event, event->attr.sample_type);
1907 static void perf_event__id_header_size(struct perf_event *event)
1909 struct perf_sample_data *data;
1910 u64 sample_type = event->attr.sample_type;
1913 if (sample_type & PERF_SAMPLE_TID)
1914 size += sizeof(data->tid_entry);
1916 if (sample_type & PERF_SAMPLE_TIME)
1917 size += sizeof(data->time);
1919 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1920 size += sizeof(data->id);
1922 if (sample_type & PERF_SAMPLE_ID)
1923 size += sizeof(data->id);
1925 if (sample_type & PERF_SAMPLE_STREAM_ID)
1926 size += sizeof(data->stream_id);
1928 if (sample_type & PERF_SAMPLE_CPU)
1929 size += sizeof(data->cpu_entry);
1931 event->id_header_size = size;
1934 static bool perf_event_validate_size(struct perf_event *event)
1937 * The values computed here will be over-written when we actually
1940 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1941 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1942 perf_event__id_header_size(event);
1945 * Sum the lot; should not exceed the 64k limit we have on records.
1946 * Conservative limit to allow for callchains and other variable fields.
1948 if (event->read_size + event->header_size +
1949 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1955 static void perf_group_attach(struct perf_event *event)
1957 struct perf_event *group_leader = event->group_leader, *pos;
1959 lockdep_assert_held(&event->ctx->lock);
1962 * We can have double attach due to group movement in perf_event_open.
1964 if (event->attach_state & PERF_ATTACH_GROUP)
1967 event->attach_state |= PERF_ATTACH_GROUP;
1969 if (group_leader == event)
1972 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1974 group_leader->group_caps &= event->event_caps;
1976 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1977 group_leader->nr_siblings++;
1979 perf_event__header_size(group_leader);
1981 for_each_sibling_event(pos, group_leader)
1982 perf_event__header_size(pos);
1986 * Remove an event from the lists for its context.
1987 * Must be called with ctx->mutex and ctx->lock held.
1990 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1992 WARN_ON_ONCE(event->ctx != ctx);
1993 lockdep_assert_held(&ctx->lock);
1996 * We can have double detach due to exit/hot-unplug + close.
1998 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2001 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2004 if (event->attr.inherit_stat)
2007 list_del_rcu(&event->event_entry);
2009 if (event->group_leader == event)
2010 del_event_from_groups(event, ctx);
2013 * If event was in error state, then keep it
2014 * that way, otherwise bogus counts will be
2015 * returned on read(). The only way to get out
2016 * of error state is by explicit re-enabling
2019 if (event->state > PERF_EVENT_STATE_OFF) {
2020 perf_cgroup_event_disable(event, ctx);
2021 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2028 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2030 if (!has_aux(aux_event))
2033 if (!event->pmu->aux_output_match)
2036 return event->pmu->aux_output_match(aux_event);
2039 static void put_event(struct perf_event *event);
2040 static void event_sched_out(struct perf_event *event,
2041 struct perf_cpu_context *cpuctx,
2042 struct perf_event_context *ctx);
2044 static void perf_put_aux_event(struct perf_event *event)
2046 struct perf_event_context *ctx = event->ctx;
2047 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2048 struct perf_event *iter;
2051 * If event uses aux_event tear down the link
2053 if (event->aux_event) {
2054 iter = event->aux_event;
2055 event->aux_event = NULL;
2061 * If the event is an aux_event, tear down all links to
2062 * it from other events.
2064 for_each_sibling_event(iter, event->group_leader) {
2065 if (iter->aux_event != event)
2068 iter->aux_event = NULL;
2072 * If it's ACTIVE, schedule it out and put it into ERROR
2073 * state so that we don't try to schedule it again. Note
2074 * that perf_event_enable() will clear the ERROR status.
2076 event_sched_out(iter, cpuctx, ctx);
2077 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2081 static bool perf_need_aux_event(struct perf_event *event)
2083 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2086 static int perf_get_aux_event(struct perf_event *event,
2087 struct perf_event *group_leader)
2090 * Our group leader must be an aux event if we want to be
2091 * an aux_output. This way, the aux event will precede its
2092 * aux_output events in the group, and therefore will always
2099 * aux_output and aux_sample_size are mutually exclusive.
2101 if (event->attr.aux_output && event->attr.aux_sample_size)
2104 if (event->attr.aux_output &&
2105 !perf_aux_output_match(event, group_leader))
2108 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2111 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2115 * Link aux_outputs to their aux event; this is undone in
2116 * perf_group_detach() by perf_put_aux_event(). When the
2117 * group in torn down, the aux_output events loose their
2118 * link to the aux_event and can't schedule any more.
2120 event->aux_event = group_leader;
2125 static inline struct list_head *get_event_list(struct perf_event *event)
2127 struct perf_event_context *ctx = event->ctx;
2128 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2132 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2133 * cannot exist on their own, schedule them out and move them into the ERROR
2134 * state. Also see _perf_event_enable(), it will not be able to recover
2137 static inline void perf_remove_sibling_event(struct perf_event *event)
2139 struct perf_event_context *ctx = event->ctx;
2140 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2142 event_sched_out(event, cpuctx, ctx);
2143 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2146 static void perf_group_detach(struct perf_event *event)
2148 struct perf_event *leader = event->group_leader;
2149 struct perf_event *sibling, *tmp;
2150 struct perf_event_context *ctx = event->ctx;
2152 lockdep_assert_held(&ctx->lock);
2155 * We can have double detach due to exit/hot-unplug + close.
2157 if (!(event->attach_state & PERF_ATTACH_GROUP))
2160 event->attach_state &= ~PERF_ATTACH_GROUP;
2162 perf_put_aux_event(event);
2165 * If this is a sibling, remove it from its group.
2167 if (leader != event) {
2168 list_del_init(&event->sibling_list);
2169 event->group_leader->nr_siblings--;
2174 * If this was a group event with sibling events then
2175 * upgrade the siblings to singleton events by adding them
2176 * to whatever list we are on.
2178 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2180 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2181 perf_remove_sibling_event(sibling);
2183 sibling->group_leader = sibling;
2184 list_del_init(&sibling->sibling_list);
2186 /* Inherit group flags from the previous leader */
2187 sibling->group_caps = event->group_caps;
2189 if (!RB_EMPTY_NODE(&event->group_node)) {
2190 add_event_to_groups(sibling, event->ctx);
2192 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2193 list_add_tail(&sibling->active_list, get_event_list(sibling));
2196 WARN_ON_ONCE(sibling->ctx != event->ctx);
2200 for_each_sibling_event(tmp, leader)
2201 perf_event__header_size(tmp);
2203 perf_event__header_size(leader);
2206 static bool is_orphaned_event(struct perf_event *event)
2208 return event->state == PERF_EVENT_STATE_DEAD;
2211 static inline int __pmu_filter_match(struct perf_event *event)
2213 struct pmu *pmu = event->pmu;
2214 return pmu->filter_match ? pmu->filter_match(event) : 1;
2218 * Check whether we should attempt to schedule an event group based on
2219 * PMU-specific filtering. An event group can consist of HW and SW events,
2220 * potentially with a SW leader, so we must check all the filters, to
2221 * determine whether a group is schedulable:
2223 static inline int pmu_filter_match(struct perf_event *event)
2225 struct perf_event *sibling;
2227 if (!__pmu_filter_match(event))
2230 for_each_sibling_event(sibling, event) {
2231 if (!__pmu_filter_match(sibling))
2239 event_filter_match(struct perf_event *event)
2241 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2242 perf_cgroup_match(event) && pmu_filter_match(event);
2246 event_sched_out(struct perf_event *event,
2247 struct perf_cpu_context *cpuctx,
2248 struct perf_event_context *ctx)
2250 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2252 WARN_ON_ONCE(event->ctx != ctx);
2253 lockdep_assert_held(&ctx->lock);
2255 if (event->state != PERF_EVENT_STATE_ACTIVE)
2259 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2260 * we can schedule events _OUT_ individually through things like
2261 * __perf_remove_from_context().
2263 list_del_init(&event->active_list);
2265 perf_pmu_disable(event->pmu);
2267 event->pmu->del(event, 0);
2270 if (READ_ONCE(event->pending_disable) >= 0) {
2271 WRITE_ONCE(event->pending_disable, -1);
2272 perf_cgroup_event_disable(event, ctx);
2273 state = PERF_EVENT_STATE_OFF;
2275 perf_event_set_state(event, state);
2277 if (!is_software_event(event))
2278 cpuctx->active_oncpu--;
2279 if (!--ctx->nr_active)
2280 perf_event_ctx_deactivate(ctx);
2281 if (event->attr.freq && event->attr.sample_freq)
2283 if (event->attr.exclusive || !cpuctx->active_oncpu)
2284 cpuctx->exclusive = 0;
2286 perf_pmu_enable(event->pmu);
2290 group_sched_out(struct perf_event *group_event,
2291 struct perf_cpu_context *cpuctx,
2292 struct perf_event_context *ctx)
2294 struct perf_event *event;
2296 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2299 perf_pmu_disable(ctx->pmu);
2301 event_sched_out(group_event, cpuctx, ctx);
2304 * Schedule out siblings (if any):
2306 for_each_sibling_event(event, group_event)
2307 event_sched_out(event, cpuctx, ctx);
2309 perf_pmu_enable(ctx->pmu);
2312 #define DETACH_GROUP 0x01UL
2315 * Cross CPU call to remove a performance event
2317 * We disable the event on the hardware level first. After that we
2318 * remove it from the context list.
2321 __perf_remove_from_context(struct perf_event *event,
2322 struct perf_cpu_context *cpuctx,
2323 struct perf_event_context *ctx,
2326 unsigned long flags = (unsigned long)info;
2328 if (ctx->is_active & EVENT_TIME) {
2329 update_context_time(ctx);
2330 update_cgrp_time_from_cpuctx(cpuctx);
2333 event_sched_out(event, cpuctx, ctx);
2334 if (flags & DETACH_GROUP)
2335 perf_group_detach(event);
2336 list_del_event(event, ctx);
2338 if (!ctx->nr_events && ctx->is_active) {
2340 ctx->rotate_necessary = 0;
2342 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2343 cpuctx->task_ctx = NULL;
2349 * Remove the event from a task's (or a CPU's) list of events.
2351 * If event->ctx is a cloned context, callers must make sure that
2352 * every task struct that event->ctx->task could possibly point to
2353 * remains valid. This is OK when called from perf_release since
2354 * that only calls us on the top-level context, which can't be a clone.
2355 * When called from perf_event_exit_task, it's OK because the
2356 * context has been detached from its task.
2358 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2360 struct perf_event_context *ctx = event->ctx;
2362 lockdep_assert_held(&ctx->mutex);
2364 event_function_call(event, __perf_remove_from_context, (void *)flags);
2367 * The above event_function_call() can NO-OP when it hits
2368 * TASK_TOMBSTONE. In that case we must already have been detached
2369 * from the context (by perf_event_exit_event()) but the grouping
2370 * might still be in-tact.
2372 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2373 if ((flags & DETACH_GROUP) &&
2374 (event->attach_state & PERF_ATTACH_GROUP)) {
2376 * Since in that case we cannot possibly be scheduled, simply
2379 raw_spin_lock_irq(&ctx->lock);
2380 perf_group_detach(event);
2381 raw_spin_unlock_irq(&ctx->lock);
2386 * Cross CPU call to disable a performance event
2388 static void __perf_event_disable(struct perf_event *event,
2389 struct perf_cpu_context *cpuctx,
2390 struct perf_event_context *ctx,
2393 if (event->state < PERF_EVENT_STATE_INACTIVE)
2396 if (ctx->is_active & EVENT_TIME) {
2397 update_context_time(ctx);
2398 update_cgrp_time_from_event(event);
2401 if (event == event->group_leader)
2402 group_sched_out(event, cpuctx, ctx);
2404 event_sched_out(event, cpuctx, ctx);
2406 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2407 perf_cgroup_event_disable(event, ctx);
2413 * If event->ctx is a cloned context, callers must make sure that
2414 * every task struct that event->ctx->task could possibly point to
2415 * remains valid. This condition is satisfied when called through
2416 * perf_event_for_each_child or perf_event_for_each because they
2417 * hold the top-level event's child_mutex, so any descendant that
2418 * goes to exit will block in perf_event_exit_event().
2420 * When called from perf_pending_event it's OK because event->ctx
2421 * is the current context on this CPU and preemption is disabled,
2422 * hence we can't get into perf_event_task_sched_out for this context.
2424 static void _perf_event_disable(struct perf_event *event)
2426 struct perf_event_context *ctx = event->ctx;
2428 raw_spin_lock_irq(&ctx->lock);
2429 if (event->state <= PERF_EVENT_STATE_OFF) {
2430 raw_spin_unlock_irq(&ctx->lock);
2433 raw_spin_unlock_irq(&ctx->lock);
2435 event_function_call(event, __perf_event_disable, NULL);
2438 void perf_event_disable_local(struct perf_event *event)
2440 event_function_local(event, __perf_event_disable, NULL);
2444 * Strictly speaking kernel users cannot create groups and therefore this
2445 * interface does not need the perf_event_ctx_lock() magic.
2447 void perf_event_disable(struct perf_event *event)
2449 struct perf_event_context *ctx;
2451 ctx = perf_event_ctx_lock(event);
2452 _perf_event_disable(event);
2453 perf_event_ctx_unlock(event, ctx);
2455 EXPORT_SYMBOL_GPL(perf_event_disable);
2457 void perf_event_disable_inatomic(struct perf_event *event)
2459 WRITE_ONCE(event->pending_disable, smp_processor_id());
2460 /* can fail, see perf_pending_event_disable() */
2461 irq_work_queue(&event->pending);
2464 static void perf_set_shadow_time(struct perf_event *event,
2465 struct perf_event_context *ctx)
2468 * use the correct time source for the time snapshot
2470 * We could get by without this by leveraging the
2471 * fact that to get to this function, the caller
2472 * has most likely already called update_context_time()
2473 * and update_cgrp_time_xx() and thus both timestamp
2474 * are identical (or very close). Given that tstamp is,
2475 * already adjusted for cgroup, we could say that:
2476 * tstamp - ctx->timestamp
2478 * tstamp - cgrp->timestamp.
2480 * Then, in perf_output_read(), the calculation would
2481 * work with no changes because:
2482 * - event is guaranteed scheduled in
2483 * - no scheduled out in between
2484 * - thus the timestamp would be the same
2486 * But this is a bit hairy.
2488 * So instead, we have an explicit cgroup call to remain
2489 * within the time time source all along. We believe it
2490 * is cleaner and simpler to understand.
2492 if (is_cgroup_event(event))
2493 perf_cgroup_set_shadow_time(event, event->tstamp);
2495 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2498 #define MAX_INTERRUPTS (~0ULL)
2500 static void perf_log_throttle(struct perf_event *event, int enable);
2501 static void perf_log_itrace_start(struct perf_event *event);
2504 event_sched_in(struct perf_event *event,
2505 struct perf_cpu_context *cpuctx,
2506 struct perf_event_context *ctx)
2510 WARN_ON_ONCE(event->ctx != ctx);
2512 lockdep_assert_held(&ctx->lock);
2514 if (event->state <= PERF_EVENT_STATE_OFF)
2517 WRITE_ONCE(event->oncpu, smp_processor_id());
2519 * Order event::oncpu write to happen before the ACTIVE state is
2520 * visible. This allows perf_event_{stop,read}() to observe the correct
2521 * ->oncpu if it sees ACTIVE.
2524 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2527 * Unthrottle events, since we scheduled we might have missed several
2528 * ticks already, also for a heavily scheduling task there is little
2529 * guarantee it'll get a tick in a timely manner.
2531 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2532 perf_log_throttle(event, 1);
2533 event->hw.interrupts = 0;
2536 perf_pmu_disable(event->pmu);
2538 perf_set_shadow_time(event, ctx);
2540 perf_log_itrace_start(event);
2542 if (event->pmu->add(event, PERF_EF_START)) {
2543 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2549 if (!is_software_event(event))
2550 cpuctx->active_oncpu++;
2551 if (!ctx->nr_active++)
2552 perf_event_ctx_activate(ctx);
2553 if (event->attr.freq && event->attr.sample_freq)
2556 if (event->attr.exclusive)
2557 cpuctx->exclusive = 1;
2560 perf_pmu_enable(event->pmu);
2566 group_sched_in(struct perf_event *group_event,
2567 struct perf_cpu_context *cpuctx,
2568 struct perf_event_context *ctx)
2570 struct perf_event *event, *partial_group = NULL;
2571 struct pmu *pmu = ctx->pmu;
2573 if (group_event->state == PERF_EVENT_STATE_OFF)
2576 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2578 if (event_sched_in(group_event, cpuctx, ctx))
2582 * Schedule in siblings as one group (if any):
2584 for_each_sibling_event(event, group_event) {
2585 if (event_sched_in(event, cpuctx, ctx)) {
2586 partial_group = event;
2591 if (!pmu->commit_txn(pmu))
2596 * Groups can be scheduled in as one unit only, so undo any
2597 * partial group before returning:
2598 * The events up to the failed event are scheduled out normally.
2600 for_each_sibling_event(event, group_event) {
2601 if (event == partial_group)
2604 event_sched_out(event, cpuctx, ctx);
2606 event_sched_out(group_event, cpuctx, ctx);
2609 pmu->cancel_txn(pmu);
2614 * Work out whether we can put this event group on the CPU now.
2616 static int group_can_go_on(struct perf_event *event,
2617 struct perf_cpu_context *cpuctx,
2621 * Groups consisting entirely of software events can always go on.
2623 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2626 * If an exclusive group is already on, no other hardware
2629 if (cpuctx->exclusive)
2632 * If this group is exclusive and there are already
2633 * events on the CPU, it can't go on.
2635 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2638 * Otherwise, try to add it if all previous groups were able
2644 static void add_event_to_ctx(struct perf_event *event,
2645 struct perf_event_context *ctx)
2647 list_add_event(event, ctx);
2648 perf_group_attach(event);
2651 static void ctx_sched_out(struct perf_event_context *ctx,
2652 struct perf_cpu_context *cpuctx,
2653 enum event_type_t event_type);
2655 ctx_sched_in(struct perf_event_context *ctx,
2656 struct perf_cpu_context *cpuctx,
2657 enum event_type_t event_type,
2658 struct task_struct *task);
2660 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2661 struct perf_event_context *ctx,
2662 enum event_type_t event_type)
2664 if (!cpuctx->task_ctx)
2667 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2670 ctx_sched_out(ctx, cpuctx, event_type);
2673 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2674 struct perf_event_context *ctx,
2675 struct task_struct *task)
2677 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2679 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2680 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2682 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2686 * We want to maintain the following priority of scheduling:
2687 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2688 * - task pinned (EVENT_PINNED)
2689 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2690 * - task flexible (EVENT_FLEXIBLE).
2692 * In order to avoid unscheduling and scheduling back in everything every
2693 * time an event is added, only do it for the groups of equal priority and
2696 * This can be called after a batch operation on task events, in which case
2697 * event_type is a bit mask of the types of events involved. For CPU events,
2698 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2700 static void ctx_resched(struct perf_cpu_context *cpuctx,
2701 struct perf_event_context *task_ctx,
2702 enum event_type_t event_type)
2704 enum event_type_t ctx_event_type;
2705 bool cpu_event = !!(event_type & EVENT_CPU);
2708 * If pinned groups are involved, flexible groups also need to be
2711 if (event_type & EVENT_PINNED)
2712 event_type |= EVENT_FLEXIBLE;
2714 ctx_event_type = event_type & EVENT_ALL;
2716 perf_pmu_disable(cpuctx->ctx.pmu);
2718 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2721 * Decide which cpu ctx groups to schedule out based on the types
2722 * of events that caused rescheduling:
2723 * - EVENT_CPU: schedule out corresponding groups;
2724 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2725 * - otherwise, do nothing more.
2728 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2729 else if (ctx_event_type & EVENT_PINNED)
2730 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2732 perf_event_sched_in(cpuctx, task_ctx, current);
2733 perf_pmu_enable(cpuctx->ctx.pmu);
2736 void perf_pmu_resched(struct pmu *pmu)
2738 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2739 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2741 perf_ctx_lock(cpuctx, task_ctx);
2742 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2743 perf_ctx_unlock(cpuctx, task_ctx);
2747 * Cross CPU call to install and enable a performance event
2749 * Very similar to remote_function() + event_function() but cannot assume that
2750 * things like ctx->is_active and cpuctx->task_ctx are set.
2752 static int __perf_install_in_context(void *info)
2754 struct perf_event *event = info;
2755 struct perf_event_context *ctx = event->ctx;
2756 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2757 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2758 bool reprogram = true;
2761 raw_spin_lock(&cpuctx->ctx.lock);
2763 raw_spin_lock(&ctx->lock);
2766 reprogram = (ctx->task == current);
2769 * If the task is running, it must be running on this CPU,
2770 * otherwise we cannot reprogram things.
2772 * If its not running, we don't care, ctx->lock will
2773 * serialize against it becoming runnable.
2775 if (task_curr(ctx->task) && !reprogram) {
2780 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2781 } else if (task_ctx) {
2782 raw_spin_lock(&task_ctx->lock);
2785 #ifdef CONFIG_CGROUP_PERF
2786 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2788 * If the current cgroup doesn't match the event's
2789 * cgroup, we should not try to schedule it.
2791 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2792 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2793 event->cgrp->css.cgroup);
2798 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2799 add_event_to_ctx(event, ctx);
2800 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2802 add_event_to_ctx(event, ctx);
2806 perf_ctx_unlock(cpuctx, task_ctx);
2811 static bool exclusive_event_installable(struct perf_event *event,
2812 struct perf_event_context *ctx);
2815 * Attach a performance event to a context.
2817 * Very similar to event_function_call, see comment there.
2820 perf_install_in_context(struct perf_event_context *ctx,
2821 struct perf_event *event,
2824 struct task_struct *task = READ_ONCE(ctx->task);
2826 lockdep_assert_held(&ctx->mutex);
2828 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2830 if (event->cpu != -1)
2834 * Ensures that if we can observe event->ctx, both the event and ctx
2835 * will be 'complete'. See perf_iterate_sb_cpu().
2837 smp_store_release(&event->ctx, ctx);
2840 * perf_event_attr::disabled events will not run and can be initialized
2841 * without IPI. Except when this is the first event for the context, in
2842 * that case we need the magic of the IPI to set ctx->is_active.
2844 * The IOC_ENABLE that is sure to follow the creation of a disabled
2845 * event will issue the IPI and reprogram the hardware.
2847 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2848 raw_spin_lock_irq(&ctx->lock);
2849 if (ctx->task == TASK_TOMBSTONE) {
2850 raw_spin_unlock_irq(&ctx->lock);
2853 add_event_to_ctx(event, ctx);
2854 raw_spin_unlock_irq(&ctx->lock);
2859 cpu_function_call(cpu, __perf_install_in_context, event);
2864 * Should not happen, we validate the ctx is still alive before calling.
2866 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2870 * Installing events is tricky because we cannot rely on ctx->is_active
2871 * to be set in case this is the nr_events 0 -> 1 transition.
2873 * Instead we use task_curr(), which tells us if the task is running.
2874 * However, since we use task_curr() outside of rq::lock, we can race
2875 * against the actual state. This means the result can be wrong.
2877 * If we get a false positive, we retry, this is harmless.
2879 * If we get a false negative, things are complicated. If we are after
2880 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2881 * value must be correct. If we're before, it doesn't matter since
2882 * perf_event_context_sched_in() will program the counter.
2884 * However, this hinges on the remote context switch having observed
2885 * our task->perf_event_ctxp[] store, such that it will in fact take
2886 * ctx::lock in perf_event_context_sched_in().
2888 * We do this by task_function_call(), if the IPI fails to hit the task
2889 * we know any future context switch of task must see the
2890 * perf_event_ctpx[] store.
2894 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2895 * task_cpu() load, such that if the IPI then does not find the task
2896 * running, a future context switch of that task must observe the
2901 if (!task_function_call(task, __perf_install_in_context, event))
2904 raw_spin_lock_irq(&ctx->lock);
2906 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2908 * Cannot happen because we already checked above (which also
2909 * cannot happen), and we hold ctx->mutex, which serializes us
2910 * against perf_event_exit_task_context().
2912 raw_spin_unlock_irq(&ctx->lock);
2916 * If the task is not running, ctx->lock will avoid it becoming so,
2917 * thus we can safely install the event.
2919 if (task_curr(task)) {
2920 raw_spin_unlock_irq(&ctx->lock);
2923 add_event_to_ctx(event, ctx);
2924 raw_spin_unlock_irq(&ctx->lock);
2928 * Cross CPU call to enable a performance event
2930 static void __perf_event_enable(struct perf_event *event,
2931 struct perf_cpu_context *cpuctx,
2932 struct perf_event_context *ctx,
2935 struct perf_event *leader = event->group_leader;
2936 struct perf_event_context *task_ctx;
2938 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2939 event->state <= PERF_EVENT_STATE_ERROR)
2943 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2945 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2946 perf_cgroup_event_enable(event, ctx);
2948 if (!ctx->is_active)
2951 if (!event_filter_match(event)) {
2952 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2957 * If the event is in a group and isn't the group leader,
2958 * then don't put it on unless the group is on.
2960 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2961 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2965 task_ctx = cpuctx->task_ctx;
2967 WARN_ON_ONCE(task_ctx != ctx);
2969 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2975 * If event->ctx is a cloned context, callers must make sure that
2976 * every task struct that event->ctx->task could possibly point to
2977 * remains valid. This condition is satisfied when called through
2978 * perf_event_for_each_child or perf_event_for_each as described
2979 * for perf_event_disable.
2981 static void _perf_event_enable(struct perf_event *event)
2983 struct perf_event_context *ctx = event->ctx;
2985 raw_spin_lock_irq(&ctx->lock);
2986 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2987 event->state < PERF_EVENT_STATE_ERROR) {
2989 raw_spin_unlock_irq(&ctx->lock);
2994 * If the event is in error state, clear that first.
2996 * That way, if we see the event in error state below, we know that it
2997 * has gone back into error state, as distinct from the task having
2998 * been scheduled away before the cross-call arrived.
3000 if (event->state == PERF_EVENT_STATE_ERROR) {
3002 * Detached SIBLING events cannot leave ERROR state.
3004 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3005 event->group_leader == event)
3008 event->state = PERF_EVENT_STATE_OFF;
3010 raw_spin_unlock_irq(&ctx->lock);
3012 event_function_call(event, __perf_event_enable, NULL);
3016 * See perf_event_disable();
3018 void perf_event_enable(struct perf_event *event)
3020 struct perf_event_context *ctx;
3022 ctx = perf_event_ctx_lock(event);
3023 _perf_event_enable(event);
3024 perf_event_ctx_unlock(event, ctx);
3026 EXPORT_SYMBOL_GPL(perf_event_enable);
3028 struct stop_event_data {
3029 struct perf_event *event;
3030 unsigned int restart;
3033 static int __perf_event_stop(void *info)
3035 struct stop_event_data *sd = info;
3036 struct perf_event *event = sd->event;
3038 /* if it's already INACTIVE, do nothing */
3039 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3042 /* matches smp_wmb() in event_sched_in() */
3046 * There is a window with interrupts enabled before we get here,
3047 * so we need to check again lest we try to stop another CPU's event.
3049 if (READ_ONCE(event->oncpu) != smp_processor_id())
3052 event->pmu->stop(event, PERF_EF_UPDATE);
3055 * May race with the actual stop (through perf_pmu_output_stop()),
3056 * but it is only used for events with AUX ring buffer, and such
3057 * events will refuse to restart because of rb::aux_mmap_count==0,
3058 * see comments in perf_aux_output_begin().
3060 * Since this is happening on an event-local CPU, no trace is lost
3064 event->pmu->start(event, 0);
3069 static int perf_event_stop(struct perf_event *event, int restart)
3071 struct stop_event_data sd = {
3078 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3081 /* matches smp_wmb() in event_sched_in() */
3085 * We only want to restart ACTIVE events, so if the event goes
3086 * inactive here (event->oncpu==-1), there's nothing more to do;
3087 * fall through with ret==-ENXIO.
3089 ret = cpu_function_call(READ_ONCE(event->oncpu),
3090 __perf_event_stop, &sd);
3091 } while (ret == -EAGAIN);
3097 * In order to contain the amount of racy and tricky in the address filter
3098 * configuration management, it is a two part process:
3100 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3101 * we update the addresses of corresponding vmas in
3102 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3103 * (p2) when an event is scheduled in (pmu::add), it calls
3104 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3105 * if the generation has changed since the previous call.
3107 * If (p1) happens while the event is active, we restart it to force (p2).
3109 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3110 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3112 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3113 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3115 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3118 void perf_event_addr_filters_sync(struct perf_event *event)
3120 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3122 if (!has_addr_filter(event))
3125 raw_spin_lock(&ifh->lock);
3126 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3127 event->pmu->addr_filters_sync(event);
3128 event->hw.addr_filters_gen = event->addr_filters_gen;
3130 raw_spin_unlock(&ifh->lock);
3132 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3134 static int _perf_event_refresh(struct perf_event *event, int refresh)
3137 * not supported on inherited events
3139 if (event->attr.inherit || !is_sampling_event(event))
3142 atomic_add(refresh, &event->event_limit);
3143 _perf_event_enable(event);
3149 * See perf_event_disable()
3151 int perf_event_refresh(struct perf_event *event, int refresh)
3153 struct perf_event_context *ctx;
3156 ctx = perf_event_ctx_lock(event);
3157 ret = _perf_event_refresh(event, refresh);
3158 perf_event_ctx_unlock(event, ctx);
3162 EXPORT_SYMBOL_GPL(perf_event_refresh);
3164 static int perf_event_modify_breakpoint(struct perf_event *bp,
3165 struct perf_event_attr *attr)
3169 _perf_event_disable(bp);
3171 err = modify_user_hw_breakpoint_check(bp, attr, true);
3173 if (!bp->attr.disabled)
3174 _perf_event_enable(bp);
3179 static int perf_event_modify_attr(struct perf_event *event,
3180 struct perf_event_attr *attr)
3182 if (event->attr.type != attr->type)
3185 switch (event->attr.type) {
3186 case PERF_TYPE_BREAKPOINT:
3187 return perf_event_modify_breakpoint(event, attr);
3189 /* Place holder for future additions. */
3194 static void ctx_sched_out(struct perf_event_context *ctx,
3195 struct perf_cpu_context *cpuctx,
3196 enum event_type_t event_type)
3198 struct perf_event *event, *tmp;
3199 int is_active = ctx->is_active;
3201 lockdep_assert_held(&ctx->lock);
3203 if (likely(!ctx->nr_events)) {
3205 * See __perf_remove_from_context().
3207 WARN_ON_ONCE(ctx->is_active);
3209 WARN_ON_ONCE(cpuctx->task_ctx);
3213 ctx->is_active &= ~event_type;
3214 if (!(ctx->is_active & EVENT_ALL))
3218 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3219 if (!ctx->is_active)
3220 cpuctx->task_ctx = NULL;
3224 * Always update time if it was set; not only when it changes.
3225 * Otherwise we can 'forget' to update time for any but the last
3226 * context we sched out. For example:
3228 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3229 * ctx_sched_out(.event_type = EVENT_PINNED)
3231 * would only update time for the pinned events.
3233 if (is_active & EVENT_TIME) {
3234 /* update (and stop) ctx time */
3235 update_context_time(ctx);
3236 update_cgrp_time_from_cpuctx(cpuctx);
3239 is_active ^= ctx->is_active; /* changed bits */
3241 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3244 perf_pmu_disable(ctx->pmu);
3245 if (is_active & EVENT_PINNED) {
3246 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3247 group_sched_out(event, cpuctx, ctx);
3250 if (is_active & EVENT_FLEXIBLE) {
3251 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3252 group_sched_out(event, cpuctx, ctx);
3255 * Since we cleared EVENT_FLEXIBLE, also clear
3256 * rotate_necessary, is will be reset by
3257 * ctx_flexible_sched_in() when needed.
3259 ctx->rotate_necessary = 0;
3261 perf_pmu_enable(ctx->pmu);
3265 * Test whether two contexts are equivalent, i.e. whether they have both been
3266 * cloned from the same version of the same context.
3268 * Equivalence is measured using a generation number in the context that is
3269 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3270 * and list_del_event().
3272 static int context_equiv(struct perf_event_context *ctx1,
3273 struct perf_event_context *ctx2)
3275 lockdep_assert_held(&ctx1->lock);
3276 lockdep_assert_held(&ctx2->lock);
3278 /* Pinning disables the swap optimization */
3279 if (ctx1->pin_count || ctx2->pin_count)
3282 /* If ctx1 is the parent of ctx2 */
3283 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3286 /* If ctx2 is the parent of ctx1 */
3287 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3291 * If ctx1 and ctx2 have the same parent; we flatten the parent
3292 * hierarchy, see perf_event_init_context().
3294 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3295 ctx1->parent_gen == ctx2->parent_gen)
3302 static void __perf_event_sync_stat(struct perf_event *event,
3303 struct perf_event *next_event)
3307 if (!event->attr.inherit_stat)
3311 * Update the event value, we cannot use perf_event_read()
3312 * because we're in the middle of a context switch and have IRQs
3313 * disabled, which upsets smp_call_function_single(), however
3314 * we know the event must be on the current CPU, therefore we
3315 * don't need to use it.
3317 if (event->state == PERF_EVENT_STATE_ACTIVE)
3318 event->pmu->read(event);
3320 perf_event_update_time(event);
3323 * In order to keep per-task stats reliable we need to flip the event
3324 * values when we flip the contexts.
3326 value = local64_read(&next_event->count);
3327 value = local64_xchg(&event->count, value);
3328 local64_set(&next_event->count, value);
3330 swap(event->total_time_enabled, next_event->total_time_enabled);
3331 swap(event->total_time_running, next_event->total_time_running);
3334 * Since we swizzled the values, update the user visible data too.
3336 perf_event_update_userpage(event);
3337 perf_event_update_userpage(next_event);
3340 static void perf_event_sync_stat(struct perf_event_context *ctx,
3341 struct perf_event_context *next_ctx)
3343 struct perf_event *event, *next_event;
3348 update_context_time(ctx);
3350 event = list_first_entry(&ctx->event_list,
3351 struct perf_event, event_entry);
3353 next_event = list_first_entry(&next_ctx->event_list,
3354 struct perf_event, event_entry);
3356 while (&event->event_entry != &ctx->event_list &&
3357 &next_event->event_entry != &next_ctx->event_list) {
3359 __perf_event_sync_stat(event, next_event);
3361 event = list_next_entry(event, event_entry);
3362 next_event = list_next_entry(next_event, event_entry);
3366 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3367 struct task_struct *next)
3369 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3370 struct perf_event_context *next_ctx;
3371 struct perf_event_context *parent, *next_parent;
3372 struct perf_cpu_context *cpuctx;
3380 cpuctx = __get_cpu_context(ctx);
3381 if (!cpuctx->task_ctx)
3385 next_ctx = next->perf_event_ctxp[ctxn];
3389 parent = rcu_dereference(ctx->parent_ctx);
3390 next_parent = rcu_dereference(next_ctx->parent_ctx);
3392 /* If neither context have a parent context; they cannot be clones. */
3393 if (!parent && !next_parent)
3396 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3398 * Looks like the two contexts are clones, so we might be
3399 * able to optimize the context switch. We lock both
3400 * contexts and check that they are clones under the
3401 * lock (including re-checking that neither has been
3402 * uncloned in the meantime). It doesn't matter which
3403 * order we take the locks because no other cpu could
3404 * be trying to lock both of these tasks.
3406 raw_spin_lock(&ctx->lock);
3407 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3408 if (context_equiv(ctx, next_ctx)) {
3410 WRITE_ONCE(ctx->task, next);
3411 WRITE_ONCE(next_ctx->task, task);
3413 perf_pmu_disable(pmu);
3415 if (cpuctx->sched_cb_usage && pmu->sched_task)
3416 pmu->sched_task(ctx, false);
3419 * PMU specific parts of task perf context can require
3420 * additional synchronization. As an example of such
3421 * synchronization see implementation details of Intel
3422 * LBR call stack data profiling;
3424 if (pmu->swap_task_ctx)
3425 pmu->swap_task_ctx(ctx, next_ctx);
3427 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3429 perf_pmu_enable(pmu);
3432 * RCU_INIT_POINTER here is safe because we've not
3433 * modified the ctx and the above modification of
3434 * ctx->task and ctx->task_ctx_data are immaterial
3435 * since those values are always verified under
3436 * ctx->lock which we're now holding.
3438 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3439 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3443 perf_event_sync_stat(ctx, next_ctx);
3445 raw_spin_unlock(&next_ctx->lock);
3446 raw_spin_unlock(&ctx->lock);
3452 raw_spin_lock(&ctx->lock);
3453 perf_pmu_disable(pmu);
3455 if (cpuctx->sched_cb_usage && pmu->sched_task)
3456 pmu->sched_task(ctx, false);
3457 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3459 perf_pmu_enable(pmu);
3460 raw_spin_unlock(&ctx->lock);
3464 void perf_sched_cb_dec(struct pmu *pmu)
3466 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3468 --cpuctx->sched_cb_usage;
3472 void perf_sched_cb_inc(struct pmu *pmu)
3474 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3476 cpuctx->sched_cb_usage++;
3480 * This function provides the context switch callback to the lower code
3481 * layer. It is invoked ONLY when the context switch callback is enabled.
3483 * This callback is relevant even to per-cpu events; for example multi event
3484 * PEBS requires this to provide PID/TID information. This requires we flush
3485 * all queued PEBS records before we context switch to a new task.
3487 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3491 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3493 if (WARN_ON_ONCE(!pmu->sched_task))
3496 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3497 perf_pmu_disable(pmu);
3499 pmu->sched_task(cpuctx->task_ctx, sched_in);
3501 perf_pmu_enable(pmu);
3502 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3505 static void perf_event_switch(struct task_struct *task,
3506 struct task_struct *next_prev, bool sched_in);
3508 #define for_each_task_context_nr(ctxn) \
3509 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3512 * Called from scheduler to remove the events of the current task,
3513 * with interrupts disabled.
3515 * We stop each event and update the event value in event->count.
3517 * This does not protect us against NMI, but disable()
3518 * sets the disabled bit in the control field of event _before_
3519 * accessing the event control register. If a NMI hits, then it will
3520 * not restart the event.
3522 void __perf_event_task_sched_out(struct task_struct *task,
3523 struct task_struct *next)
3527 if (atomic_read(&nr_switch_events))
3528 perf_event_switch(task, next, false);
3530 for_each_task_context_nr(ctxn)
3531 perf_event_context_sched_out(task, ctxn, next);
3534 * if cgroup events exist on this CPU, then we need
3535 * to check if we have to switch out PMU state.
3536 * cgroup event are system-wide mode only
3538 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3539 perf_cgroup_sched_out(task, next);
3543 * Called with IRQs disabled
3545 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3546 enum event_type_t event_type)
3548 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3551 static bool perf_less_group_idx(const void *l, const void *r)
3553 const struct perf_event *le = *(const struct perf_event **)l;
3554 const struct perf_event *re = *(const struct perf_event **)r;
3556 return le->group_index < re->group_index;
3559 static void swap_ptr(void *l, void *r)
3561 void **lp = l, **rp = r;
3566 static const struct min_heap_callbacks perf_min_heap = {
3567 .elem_size = sizeof(struct perf_event *),
3568 .less = perf_less_group_idx,
3572 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3574 struct perf_event **itrs = heap->data;
3577 itrs[heap->nr] = event;
3582 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3583 struct perf_event_groups *groups, int cpu,
3584 int (*func)(struct perf_event *, void *),
3587 #ifdef CONFIG_CGROUP_PERF
3588 struct cgroup_subsys_state *css = NULL;
3590 /* Space for per CPU and/or any CPU event iterators. */
3591 struct perf_event *itrs[2];
3592 struct min_heap event_heap;
3593 struct perf_event **evt;
3597 event_heap = (struct min_heap){
3598 .data = cpuctx->heap,
3600 .size = cpuctx->heap_size,
3603 lockdep_assert_held(&cpuctx->ctx.lock);
3605 #ifdef CONFIG_CGROUP_PERF
3607 css = &cpuctx->cgrp->css;
3610 event_heap = (struct min_heap){
3613 .size = ARRAY_SIZE(itrs),
3615 /* Events not within a CPU context may be on any CPU. */
3616 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3618 evt = event_heap.data;
3620 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3622 #ifdef CONFIG_CGROUP_PERF
3623 for (; css; css = css->parent)
3624 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3627 min_heapify_all(&event_heap, &perf_min_heap);
3629 while (event_heap.nr) {
3630 ret = func(*evt, data);
3634 *evt = perf_event_groups_next(*evt);
3636 min_heapify(&event_heap, 0, &perf_min_heap);
3638 min_heap_pop(&event_heap, &perf_min_heap);
3644 static int merge_sched_in(struct perf_event *event, void *data)
3646 struct perf_event_context *ctx = event->ctx;
3647 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3648 int *can_add_hw = data;
3650 if (event->state <= PERF_EVENT_STATE_OFF)
3653 if (!event_filter_match(event))
3656 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3657 if (!group_sched_in(event, cpuctx, ctx))
3658 list_add_tail(&event->active_list, get_event_list(event));
3661 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3662 if (event->attr.pinned) {
3663 perf_cgroup_event_disable(event, ctx);
3664 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3668 ctx->rotate_necessary = 1;
3669 perf_mux_hrtimer_restart(cpuctx);
3676 ctx_pinned_sched_in(struct perf_event_context *ctx,
3677 struct perf_cpu_context *cpuctx)
3681 if (ctx != &cpuctx->ctx)
3684 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3686 merge_sched_in, &can_add_hw);
3690 ctx_flexible_sched_in(struct perf_event_context *ctx,
3691 struct perf_cpu_context *cpuctx)
3695 if (ctx != &cpuctx->ctx)
3698 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3700 merge_sched_in, &can_add_hw);
3704 ctx_sched_in(struct perf_event_context *ctx,
3705 struct perf_cpu_context *cpuctx,
3706 enum event_type_t event_type,
3707 struct task_struct *task)
3709 int is_active = ctx->is_active;
3712 lockdep_assert_held(&ctx->lock);
3714 if (likely(!ctx->nr_events))
3717 ctx->is_active |= (event_type | EVENT_TIME);
3720 cpuctx->task_ctx = ctx;
3722 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3725 is_active ^= ctx->is_active; /* changed bits */
3727 if (is_active & EVENT_TIME) {
3728 /* start ctx time */
3730 ctx->timestamp = now;
3731 perf_cgroup_set_timestamp(task, ctx);
3735 * First go through the list and put on any pinned groups
3736 * in order to give them the best chance of going on.
3738 if (is_active & EVENT_PINNED)
3739 ctx_pinned_sched_in(ctx, cpuctx);
3741 /* Then walk through the lower prio flexible groups */
3742 if (is_active & EVENT_FLEXIBLE)
3743 ctx_flexible_sched_in(ctx, cpuctx);
3746 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3747 enum event_type_t event_type,
3748 struct task_struct *task)
3750 struct perf_event_context *ctx = &cpuctx->ctx;
3752 ctx_sched_in(ctx, cpuctx, event_type, task);
3755 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3756 struct task_struct *task)
3758 struct perf_cpu_context *cpuctx;
3759 struct pmu *pmu = ctx->pmu;
3761 cpuctx = __get_cpu_context(ctx);
3762 if (cpuctx->task_ctx == ctx) {
3763 if (cpuctx->sched_cb_usage)
3764 __perf_pmu_sched_task(cpuctx, true);
3768 perf_ctx_lock(cpuctx, ctx);
3770 * We must check ctx->nr_events while holding ctx->lock, such
3771 * that we serialize against perf_install_in_context().
3773 if (!ctx->nr_events)
3776 perf_pmu_disable(pmu);
3778 * We want to keep the following priority order:
3779 * cpu pinned (that don't need to move), task pinned,
3780 * cpu flexible, task flexible.
3782 * However, if task's ctx is not carrying any pinned
3783 * events, no need to flip the cpuctx's events around.
3785 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3786 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3787 perf_event_sched_in(cpuctx, ctx, task);
3789 if (cpuctx->sched_cb_usage && pmu->sched_task)
3790 pmu->sched_task(cpuctx->task_ctx, true);
3792 perf_pmu_enable(pmu);
3795 perf_ctx_unlock(cpuctx, ctx);
3799 * Called from scheduler to add the events of the current task
3800 * with interrupts disabled.
3802 * We restore the event value and then enable it.
3804 * This does not protect us against NMI, but enable()
3805 * sets the enabled bit in the control field of event _before_
3806 * accessing the event control register. If a NMI hits, then it will
3807 * keep the event running.
3809 void __perf_event_task_sched_in(struct task_struct *prev,
3810 struct task_struct *task)
3812 struct perf_event_context *ctx;
3816 * If cgroup events exist on this CPU, then we need to check if we have
3817 * to switch in PMU state; cgroup event are system-wide mode only.
3819 * Since cgroup events are CPU events, we must schedule these in before
3820 * we schedule in the task events.
3822 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3823 perf_cgroup_sched_in(prev, task);
3825 for_each_task_context_nr(ctxn) {
3826 ctx = task->perf_event_ctxp[ctxn];
3830 perf_event_context_sched_in(ctx, task);
3833 if (atomic_read(&nr_switch_events))
3834 perf_event_switch(task, prev, true);
3837 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3839 u64 frequency = event->attr.sample_freq;
3840 u64 sec = NSEC_PER_SEC;
3841 u64 divisor, dividend;
3843 int count_fls, nsec_fls, frequency_fls, sec_fls;
3845 count_fls = fls64(count);
3846 nsec_fls = fls64(nsec);
3847 frequency_fls = fls64(frequency);
3851 * We got @count in @nsec, with a target of sample_freq HZ
3852 * the target period becomes:
3855 * period = -------------------
3856 * @nsec * sample_freq
3861 * Reduce accuracy by one bit such that @a and @b converge
3862 * to a similar magnitude.
3864 #define REDUCE_FLS(a, b) \
3866 if (a##_fls > b##_fls) { \
3876 * Reduce accuracy until either term fits in a u64, then proceed with
3877 * the other, so that finally we can do a u64/u64 division.
3879 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3880 REDUCE_FLS(nsec, frequency);
3881 REDUCE_FLS(sec, count);
3884 if (count_fls + sec_fls > 64) {
3885 divisor = nsec * frequency;
3887 while (count_fls + sec_fls > 64) {
3888 REDUCE_FLS(count, sec);
3892 dividend = count * sec;
3894 dividend = count * sec;
3896 while (nsec_fls + frequency_fls > 64) {
3897 REDUCE_FLS(nsec, frequency);
3901 divisor = nsec * frequency;
3907 return div64_u64(dividend, divisor);
3910 static DEFINE_PER_CPU(int, perf_throttled_count);
3911 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3913 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3915 struct hw_perf_event *hwc = &event->hw;
3916 s64 period, sample_period;
3919 period = perf_calculate_period(event, nsec, count);
3921 delta = (s64)(period - hwc->sample_period);
3922 delta = (delta + 7) / 8; /* low pass filter */
3924 sample_period = hwc->sample_period + delta;
3929 hwc->sample_period = sample_period;
3931 if (local64_read(&hwc->period_left) > 8*sample_period) {
3933 event->pmu->stop(event, PERF_EF_UPDATE);
3935 local64_set(&hwc->period_left, 0);
3938 event->pmu->start(event, PERF_EF_RELOAD);
3943 * combine freq adjustment with unthrottling to avoid two passes over the
3944 * events. At the same time, make sure, having freq events does not change
3945 * the rate of unthrottling as that would introduce bias.
3947 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3950 struct perf_event *event;
3951 struct hw_perf_event *hwc;
3952 u64 now, period = TICK_NSEC;
3956 * only need to iterate over all events iff:
3957 * - context have events in frequency mode (needs freq adjust)
3958 * - there are events to unthrottle on this cpu
3960 if (!(ctx->nr_freq || needs_unthr))
3963 raw_spin_lock(&ctx->lock);
3964 perf_pmu_disable(ctx->pmu);
3966 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3967 if (event->state != PERF_EVENT_STATE_ACTIVE)
3970 if (!event_filter_match(event))
3973 perf_pmu_disable(event->pmu);
3977 if (hwc->interrupts == MAX_INTERRUPTS) {
3978 hwc->interrupts = 0;
3979 perf_log_throttle(event, 1);
3980 event->pmu->start(event, 0);
3983 if (!event->attr.freq || !event->attr.sample_freq)
3987 * stop the event and update event->count
3989 event->pmu->stop(event, PERF_EF_UPDATE);
3991 now = local64_read(&event->count);
3992 delta = now - hwc->freq_count_stamp;
3993 hwc->freq_count_stamp = now;
3997 * reload only if value has changed
3998 * we have stopped the event so tell that
3999 * to perf_adjust_period() to avoid stopping it
4003 perf_adjust_period(event, period, delta, false);
4005 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4007 perf_pmu_enable(event->pmu);
4010 perf_pmu_enable(ctx->pmu);
4011 raw_spin_unlock(&ctx->lock);
4015 * Move @event to the tail of the @ctx's elegible events.
4017 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4020 * Rotate the first entry last of non-pinned groups. Rotation might be
4021 * disabled by the inheritance code.
4023 if (ctx->rotate_disable)
4026 perf_event_groups_delete(&ctx->flexible_groups, event);
4027 perf_event_groups_insert(&ctx->flexible_groups, event);
4030 /* pick an event from the flexible_groups to rotate */
4031 static inline struct perf_event *
4032 ctx_event_to_rotate(struct perf_event_context *ctx)
4034 struct perf_event *event;
4036 /* pick the first active flexible event */
4037 event = list_first_entry_or_null(&ctx->flexible_active,
4038 struct perf_event, active_list);
4040 /* if no active flexible event, pick the first event */
4042 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4043 typeof(*event), group_node);
4047 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4048 * finds there are unschedulable events, it will set it again.
4050 ctx->rotate_necessary = 0;
4055 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4057 struct perf_event *cpu_event = NULL, *task_event = NULL;
4058 struct perf_event_context *task_ctx = NULL;
4059 int cpu_rotate, task_rotate;
4062 * Since we run this from IRQ context, nobody can install new
4063 * events, thus the event count values are stable.
4066 cpu_rotate = cpuctx->ctx.rotate_necessary;
4067 task_ctx = cpuctx->task_ctx;
4068 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4070 if (!(cpu_rotate || task_rotate))
4073 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4074 perf_pmu_disable(cpuctx->ctx.pmu);
4077 task_event = ctx_event_to_rotate(task_ctx);
4079 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4082 * As per the order given at ctx_resched() first 'pop' task flexible
4083 * and then, if needed CPU flexible.
4085 if (task_event || (task_ctx && cpu_event))
4086 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4088 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4091 rotate_ctx(task_ctx, task_event);
4093 rotate_ctx(&cpuctx->ctx, cpu_event);
4095 perf_event_sched_in(cpuctx, task_ctx, current);
4097 perf_pmu_enable(cpuctx->ctx.pmu);
4098 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4103 void perf_event_task_tick(void)
4105 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4106 struct perf_event_context *ctx, *tmp;
4109 lockdep_assert_irqs_disabled();
4111 __this_cpu_inc(perf_throttled_seq);
4112 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4113 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4115 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4116 perf_adjust_freq_unthr_context(ctx, throttled);
4119 static int event_enable_on_exec(struct perf_event *event,
4120 struct perf_event_context *ctx)
4122 if (!event->attr.enable_on_exec)
4125 event->attr.enable_on_exec = 0;
4126 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4129 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4135 * Enable all of a task's events that have been marked enable-on-exec.
4136 * This expects task == current.
4138 static void perf_event_enable_on_exec(int ctxn)
4140 struct perf_event_context *ctx, *clone_ctx = NULL;
4141 enum event_type_t event_type = 0;
4142 struct perf_cpu_context *cpuctx;
4143 struct perf_event *event;
4144 unsigned long flags;
4147 local_irq_save(flags);
4148 ctx = current->perf_event_ctxp[ctxn];
4149 if (!ctx || !ctx->nr_events)
4152 cpuctx = __get_cpu_context(ctx);
4153 perf_ctx_lock(cpuctx, ctx);
4154 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4155 list_for_each_entry(event, &ctx->event_list, event_entry) {
4156 enabled |= event_enable_on_exec(event, ctx);
4157 event_type |= get_event_type(event);
4161 * Unclone and reschedule this context if we enabled any event.
4164 clone_ctx = unclone_ctx(ctx);
4165 ctx_resched(cpuctx, ctx, event_type);
4167 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4169 perf_ctx_unlock(cpuctx, ctx);
4172 local_irq_restore(flags);
4178 struct perf_read_data {
4179 struct perf_event *event;
4184 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4186 u16 local_pkg, event_pkg;
4188 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4189 int local_cpu = smp_processor_id();
4191 event_pkg = topology_physical_package_id(event_cpu);
4192 local_pkg = topology_physical_package_id(local_cpu);
4194 if (event_pkg == local_pkg)
4202 * Cross CPU call to read the hardware event
4204 static void __perf_event_read(void *info)
4206 struct perf_read_data *data = info;
4207 struct perf_event *sub, *event = data->event;
4208 struct perf_event_context *ctx = event->ctx;
4209 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4210 struct pmu *pmu = event->pmu;
4213 * If this is a task context, we need to check whether it is
4214 * the current task context of this cpu. If not it has been
4215 * scheduled out before the smp call arrived. In that case
4216 * event->count would have been updated to a recent sample
4217 * when the event was scheduled out.
4219 if (ctx->task && cpuctx->task_ctx != ctx)
4222 raw_spin_lock(&ctx->lock);
4223 if (ctx->is_active & EVENT_TIME) {
4224 update_context_time(ctx);
4225 update_cgrp_time_from_event(event);
4228 perf_event_update_time(event);
4230 perf_event_update_sibling_time(event);
4232 if (event->state != PERF_EVENT_STATE_ACTIVE)
4241 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4245 for_each_sibling_event(sub, event) {
4246 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4248 * Use sibling's PMU rather than @event's since
4249 * sibling could be on different (eg: software) PMU.
4251 sub->pmu->read(sub);
4255 data->ret = pmu->commit_txn(pmu);
4258 raw_spin_unlock(&ctx->lock);
4261 static inline u64 perf_event_count(struct perf_event *event)
4263 return local64_read(&event->count) + atomic64_read(&event->child_count);
4267 * NMI-safe method to read a local event, that is an event that
4269 * - either for the current task, or for this CPU
4270 * - does not have inherit set, for inherited task events
4271 * will not be local and we cannot read them atomically
4272 * - must not have a pmu::count method
4274 int perf_event_read_local(struct perf_event *event, u64 *value,
4275 u64 *enabled, u64 *running)
4277 unsigned long flags;
4281 * Disabling interrupts avoids all counter scheduling (context
4282 * switches, timer based rotation and IPIs).
4284 local_irq_save(flags);
4287 * It must not be an event with inherit set, we cannot read
4288 * all child counters from atomic context.
4290 if (event->attr.inherit) {
4295 /* If this is a per-task event, it must be for current */
4296 if ((event->attach_state & PERF_ATTACH_TASK) &&
4297 event->hw.target != current) {
4302 /* If this is a per-CPU event, it must be for this CPU */
4303 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4304 event->cpu != smp_processor_id()) {
4309 /* If this is a pinned event it must be running on this CPU */
4310 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4316 * If the event is currently on this CPU, its either a per-task event,
4317 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4320 if (event->oncpu == smp_processor_id())
4321 event->pmu->read(event);
4323 *value = local64_read(&event->count);
4324 if (enabled || running) {
4325 u64 now = event->shadow_ctx_time + perf_clock();
4326 u64 __enabled, __running;
4328 __perf_update_times(event, now, &__enabled, &__running);
4330 *enabled = __enabled;
4332 *running = __running;
4335 local_irq_restore(flags);
4340 static int perf_event_read(struct perf_event *event, bool group)
4342 enum perf_event_state state = READ_ONCE(event->state);
4343 int event_cpu, ret = 0;
4346 * If event is enabled and currently active on a CPU, update the
4347 * value in the event structure:
4350 if (state == PERF_EVENT_STATE_ACTIVE) {
4351 struct perf_read_data data;
4354 * Orders the ->state and ->oncpu loads such that if we see
4355 * ACTIVE we must also see the right ->oncpu.
4357 * Matches the smp_wmb() from event_sched_in().
4361 event_cpu = READ_ONCE(event->oncpu);
4362 if ((unsigned)event_cpu >= nr_cpu_ids)
4365 data = (struct perf_read_data){
4372 event_cpu = __perf_event_read_cpu(event, event_cpu);
4375 * Purposely ignore the smp_call_function_single() return
4378 * If event_cpu isn't a valid CPU it means the event got
4379 * scheduled out and that will have updated the event count.
4381 * Therefore, either way, we'll have an up-to-date event count
4384 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4388 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4389 struct perf_event_context *ctx = event->ctx;
4390 unsigned long flags;
4392 raw_spin_lock_irqsave(&ctx->lock, flags);
4393 state = event->state;
4394 if (state != PERF_EVENT_STATE_INACTIVE) {
4395 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4400 * May read while context is not active (e.g., thread is
4401 * blocked), in that case we cannot update context time
4403 if (ctx->is_active & EVENT_TIME) {
4404 update_context_time(ctx);
4405 update_cgrp_time_from_event(event);
4408 perf_event_update_time(event);
4410 perf_event_update_sibling_time(event);
4411 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4418 * Initialize the perf_event context in a task_struct:
4420 static void __perf_event_init_context(struct perf_event_context *ctx)
4422 raw_spin_lock_init(&ctx->lock);
4423 mutex_init(&ctx->mutex);
4424 INIT_LIST_HEAD(&ctx->active_ctx_list);
4425 perf_event_groups_init(&ctx->pinned_groups);
4426 perf_event_groups_init(&ctx->flexible_groups);
4427 INIT_LIST_HEAD(&ctx->event_list);
4428 INIT_LIST_HEAD(&ctx->pinned_active);
4429 INIT_LIST_HEAD(&ctx->flexible_active);
4430 refcount_set(&ctx->refcount, 1);
4433 static struct perf_event_context *
4434 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4436 struct perf_event_context *ctx;
4438 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4442 __perf_event_init_context(ctx);
4444 ctx->task = get_task_struct(task);
4450 static struct task_struct *
4451 find_lively_task_by_vpid(pid_t vpid)
4453 struct task_struct *task;
4459 task = find_task_by_vpid(vpid);
4461 get_task_struct(task);
4465 return ERR_PTR(-ESRCH);
4471 * Returns a matching context with refcount and pincount.
4473 static struct perf_event_context *
4474 find_get_context(struct pmu *pmu, struct task_struct *task,
4475 struct perf_event *event)
4477 struct perf_event_context *ctx, *clone_ctx = NULL;
4478 struct perf_cpu_context *cpuctx;
4479 void *task_ctx_data = NULL;
4480 unsigned long flags;
4482 int cpu = event->cpu;
4485 /* Must be root to operate on a CPU event: */
4486 err = perf_allow_cpu(&event->attr);
4488 return ERR_PTR(err);
4490 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4499 ctxn = pmu->task_ctx_nr;
4503 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4504 task_ctx_data = alloc_task_ctx_data(pmu);
4505 if (!task_ctx_data) {
4512 ctx = perf_lock_task_context(task, ctxn, &flags);
4514 clone_ctx = unclone_ctx(ctx);
4517 if (task_ctx_data && !ctx->task_ctx_data) {
4518 ctx->task_ctx_data = task_ctx_data;
4519 task_ctx_data = NULL;
4521 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4526 ctx = alloc_perf_context(pmu, task);
4531 if (task_ctx_data) {
4532 ctx->task_ctx_data = task_ctx_data;
4533 task_ctx_data = NULL;
4537 mutex_lock(&task->perf_event_mutex);
4539 * If it has already passed perf_event_exit_task().
4540 * we must see PF_EXITING, it takes this mutex too.
4542 if (task->flags & PF_EXITING)
4544 else if (task->perf_event_ctxp[ctxn])
4549 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4551 mutex_unlock(&task->perf_event_mutex);
4553 if (unlikely(err)) {
4562 free_task_ctx_data(pmu, task_ctx_data);
4566 free_task_ctx_data(pmu, task_ctx_data);
4567 return ERR_PTR(err);
4570 static void perf_event_free_filter(struct perf_event *event);
4571 static void perf_event_free_bpf_prog(struct perf_event *event);
4573 static void free_event_rcu(struct rcu_head *head)
4575 struct perf_event *event;
4577 event = container_of(head, struct perf_event, rcu_head);
4579 put_pid_ns(event->ns);
4580 perf_event_free_filter(event);
4584 static void ring_buffer_attach(struct perf_event *event,
4585 struct perf_buffer *rb);
4587 static void detach_sb_event(struct perf_event *event)
4589 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4591 raw_spin_lock(&pel->lock);
4592 list_del_rcu(&event->sb_list);
4593 raw_spin_unlock(&pel->lock);
4596 static bool is_sb_event(struct perf_event *event)
4598 struct perf_event_attr *attr = &event->attr;
4603 if (event->attach_state & PERF_ATTACH_TASK)
4606 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4607 attr->comm || attr->comm_exec ||
4608 attr->task || attr->ksymbol ||
4609 attr->context_switch || attr->text_poke ||
4615 static void unaccount_pmu_sb_event(struct perf_event *event)
4617 if (is_sb_event(event))
4618 detach_sb_event(event);
4621 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4626 if (is_cgroup_event(event))
4627 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4630 #ifdef CONFIG_NO_HZ_FULL
4631 static DEFINE_SPINLOCK(nr_freq_lock);
4634 static void unaccount_freq_event_nohz(void)
4636 #ifdef CONFIG_NO_HZ_FULL
4637 spin_lock(&nr_freq_lock);
4638 if (atomic_dec_and_test(&nr_freq_events))
4639 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4640 spin_unlock(&nr_freq_lock);
4644 static void unaccount_freq_event(void)
4646 if (tick_nohz_full_enabled())
4647 unaccount_freq_event_nohz();
4649 atomic_dec(&nr_freq_events);
4652 static void unaccount_event(struct perf_event *event)
4659 if (event->attach_state & PERF_ATTACH_TASK)
4661 if (event->attr.mmap || event->attr.mmap_data)
4662 atomic_dec(&nr_mmap_events);
4663 if (event->attr.build_id)
4664 atomic_dec(&nr_build_id_events);
4665 if (event->attr.comm)
4666 atomic_dec(&nr_comm_events);
4667 if (event->attr.namespaces)
4668 atomic_dec(&nr_namespaces_events);
4669 if (event->attr.cgroup)
4670 atomic_dec(&nr_cgroup_events);
4671 if (event->attr.task)
4672 atomic_dec(&nr_task_events);
4673 if (event->attr.freq)
4674 unaccount_freq_event();
4675 if (event->attr.context_switch) {
4677 atomic_dec(&nr_switch_events);
4679 if (is_cgroup_event(event))
4681 if (has_branch_stack(event))
4683 if (event->attr.ksymbol)
4684 atomic_dec(&nr_ksymbol_events);
4685 if (event->attr.bpf_event)
4686 atomic_dec(&nr_bpf_events);
4687 if (event->attr.text_poke)
4688 atomic_dec(&nr_text_poke_events);
4691 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4692 schedule_delayed_work(&perf_sched_work, HZ);
4695 unaccount_event_cpu(event, event->cpu);
4697 unaccount_pmu_sb_event(event);
4700 static void perf_sched_delayed(struct work_struct *work)
4702 mutex_lock(&perf_sched_mutex);
4703 if (atomic_dec_and_test(&perf_sched_count))
4704 static_branch_disable(&perf_sched_events);
4705 mutex_unlock(&perf_sched_mutex);
4709 * The following implement mutual exclusion of events on "exclusive" pmus
4710 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4711 * at a time, so we disallow creating events that might conflict, namely:
4713 * 1) cpu-wide events in the presence of per-task events,
4714 * 2) per-task events in the presence of cpu-wide events,
4715 * 3) two matching events on the same context.
4717 * The former two cases are handled in the allocation path (perf_event_alloc(),
4718 * _free_event()), the latter -- before the first perf_install_in_context().
4720 static int exclusive_event_init(struct perf_event *event)
4722 struct pmu *pmu = event->pmu;
4724 if (!is_exclusive_pmu(pmu))
4728 * Prevent co-existence of per-task and cpu-wide events on the
4729 * same exclusive pmu.
4731 * Negative pmu::exclusive_cnt means there are cpu-wide
4732 * events on this "exclusive" pmu, positive means there are
4735 * Since this is called in perf_event_alloc() path, event::ctx
4736 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4737 * to mean "per-task event", because unlike other attach states it
4738 * never gets cleared.
4740 if (event->attach_state & PERF_ATTACH_TASK) {
4741 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4744 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4751 static void exclusive_event_destroy(struct perf_event *event)
4753 struct pmu *pmu = event->pmu;
4755 if (!is_exclusive_pmu(pmu))
4758 /* see comment in exclusive_event_init() */
4759 if (event->attach_state & PERF_ATTACH_TASK)
4760 atomic_dec(&pmu->exclusive_cnt);
4762 atomic_inc(&pmu->exclusive_cnt);
4765 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4767 if ((e1->pmu == e2->pmu) &&
4768 (e1->cpu == e2->cpu ||
4775 static bool exclusive_event_installable(struct perf_event *event,
4776 struct perf_event_context *ctx)
4778 struct perf_event *iter_event;
4779 struct pmu *pmu = event->pmu;
4781 lockdep_assert_held(&ctx->mutex);
4783 if (!is_exclusive_pmu(pmu))
4786 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4787 if (exclusive_event_match(iter_event, event))
4794 static void perf_addr_filters_splice(struct perf_event *event,
4795 struct list_head *head);
4797 static void _free_event(struct perf_event *event)
4799 irq_work_sync(&event->pending);
4801 unaccount_event(event);
4803 security_perf_event_free(event);
4807 * Can happen when we close an event with re-directed output.
4809 * Since we have a 0 refcount, perf_mmap_close() will skip
4810 * over us; possibly making our ring_buffer_put() the last.
4812 mutex_lock(&event->mmap_mutex);
4813 ring_buffer_attach(event, NULL);
4814 mutex_unlock(&event->mmap_mutex);
4817 if (is_cgroup_event(event))
4818 perf_detach_cgroup(event);
4820 if (!event->parent) {
4821 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4822 put_callchain_buffers();
4825 perf_event_free_bpf_prog(event);
4826 perf_addr_filters_splice(event, NULL);
4827 kfree(event->addr_filter_ranges);
4830 event->destroy(event);
4833 * Must be after ->destroy(), due to uprobe_perf_close() using
4836 if (event->hw.target)
4837 put_task_struct(event->hw.target);
4840 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4841 * all task references must be cleaned up.
4844 put_ctx(event->ctx);
4846 exclusive_event_destroy(event);
4847 module_put(event->pmu->module);
4849 call_rcu(&event->rcu_head, free_event_rcu);
4853 * Used to free events which have a known refcount of 1, such as in error paths
4854 * where the event isn't exposed yet and inherited events.
4856 static void free_event(struct perf_event *event)
4858 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4859 "unexpected event refcount: %ld; ptr=%p\n",
4860 atomic_long_read(&event->refcount), event)) {
4861 /* leak to avoid use-after-free */
4869 * Remove user event from the owner task.
4871 static void perf_remove_from_owner(struct perf_event *event)
4873 struct task_struct *owner;
4877 * Matches the smp_store_release() in perf_event_exit_task(). If we
4878 * observe !owner it means the list deletion is complete and we can
4879 * indeed free this event, otherwise we need to serialize on
4880 * owner->perf_event_mutex.
4882 owner = READ_ONCE(event->owner);
4885 * Since delayed_put_task_struct() also drops the last
4886 * task reference we can safely take a new reference
4887 * while holding the rcu_read_lock().
4889 get_task_struct(owner);
4895 * If we're here through perf_event_exit_task() we're already
4896 * holding ctx->mutex which would be an inversion wrt. the
4897 * normal lock order.
4899 * However we can safely take this lock because its the child
4902 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4905 * We have to re-check the event->owner field, if it is cleared
4906 * we raced with perf_event_exit_task(), acquiring the mutex
4907 * ensured they're done, and we can proceed with freeing the
4911 list_del_init(&event->owner_entry);
4912 smp_store_release(&event->owner, NULL);
4914 mutex_unlock(&owner->perf_event_mutex);
4915 put_task_struct(owner);
4919 static void put_event(struct perf_event *event)
4921 if (!atomic_long_dec_and_test(&event->refcount))
4928 * Kill an event dead; while event:refcount will preserve the event
4929 * object, it will not preserve its functionality. Once the last 'user'
4930 * gives up the object, we'll destroy the thing.
4932 int perf_event_release_kernel(struct perf_event *event)
4934 struct perf_event_context *ctx = event->ctx;
4935 struct perf_event *child, *tmp;
4936 LIST_HEAD(free_list);
4939 * If we got here through err_file: fput(event_file); we will not have
4940 * attached to a context yet.
4943 WARN_ON_ONCE(event->attach_state &
4944 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4948 if (!is_kernel_event(event))
4949 perf_remove_from_owner(event);
4951 ctx = perf_event_ctx_lock(event);
4952 WARN_ON_ONCE(ctx->parent_ctx);
4953 perf_remove_from_context(event, DETACH_GROUP);
4955 raw_spin_lock_irq(&ctx->lock);
4957 * Mark this event as STATE_DEAD, there is no external reference to it
4960 * Anybody acquiring event->child_mutex after the below loop _must_
4961 * also see this, most importantly inherit_event() which will avoid
4962 * placing more children on the list.
4964 * Thus this guarantees that we will in fact observe and kill _ALL_
4967 event->state = PERF_EVENT_STATE_DEAD;
4968 raw_spin_unlock_irq(&ctx->lock);
4970 perf_event_ctx_unlock(event, ctx);
4973 mutex_lock(&event->child_mutex);
4974 list_for_each_entry(child, &event->child_list, child_list) {
4977 * Cannot change, child events are not migrated, see the
4978 * comment with perf_event_ctx_lock_nested().
4980 ctx = READ_ONCE(child->ctx);
4982 * Since child_mutex nests inside ctx::mutex, we must jump
4983 * through hoops. We start by grabbing a reference on the ctx.
4985 * Since the event cannot get freed while we hold the
4986 * child_mutex, the context must also exist and have a !0
4992 * Now that we have a ctx ref, we can drop child_mutex, and
4993 * acquire ctx::mutex without fear of it going away. Then we
4994 * can re-acquire child_mutex.
4996 mutex_unlock(&event->child_mutex);
4997 mutex_lock(&ctx->mutex);
4998 mutex_lock(&event->child_mutex);
5001 * Now that we hold ctx::mutex and child_mutex, revalidate our
5002 * state, if child is still the first entry, it didn't get freed
5003 * and we can continue doing so.
5005 tmp = list_first_entry_or_null(&event->child_list,
5006 struct perf_event, child_list);
5008 perf_remove_from_context(child, DETACH_GROUP);
5009 list_move(&child->child_list, &free_list);
5011 * This matches the refcount bump in inherit_event();
5012 * this can't be the last reference.
5017 mutex_unlock(&event->child_mutex);
5018 mutex_unlock(&ctx->mutex);
5022 mutex_unlock(&event->child_mutex);
5024 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5025 void *var = &child->ctx->refcount;
5027 list_del(&child->child_list);
5031 * Wake any perf_event_free_task() waiting for this event to be
5034 smp_mb(); /* pairs with wait_var_event() */
5039 put_event(event); /* Must be the 'last' reference */
5042 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5045 * Called when the last reference to the file is gone.
5047 static int perf_release(struct inode *inode, struct file *file)
5049 perf_event_release_kernel(file->private_data);
5053 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5055 struct perf_event *child;
5061 mutex_lock(&event->child_mutex);
5063 (void)perf_event_read(event, false);
5064 total += perf_event_count(event);
5066 *enabled += event->total_time_enabled +
5067 atomic64_read(&event->child_total_time_enabled);
5068 *running += event->total_time_running +
5069 atomic64_read(&event->child_total_time_running);
5071 list_for_each_entry(child, &event->child_list, child_list) {
5072 (void)perf_event_read(child, false);
5073 total += perf_event_count(child);
5074 *enabled += child->total_time_enabled;
5075 *running += child->total_time_running;
5077 mutex_unlock(&event->child_mutex);
5082 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5084 struct perf_event_context *ctx;
5087 ctx = perf_event_ctx_lock(event);
5088 count = __perf_event_read_value(event, enabled, running);
5089 perf_event_ctx_unlock(event, ctx);
5093 EXPORT_SYMBOL_GPL(perf_event_read_value);
5095 static int __perf_read_group_add(struct perf_event *leader,
5096 u64 read_format, u64 *values)
5098 struct perf_event_context *ctx = leader->ctx;
5099 struct perf_event *sub;
5100 unsigned long flags;
5101 int n = 1; /* skip @nr */
5104 ret = perf_event_read(leader, true);
5108 raw_spin_lock_irqsave(&ctx->lock, flags);
5111 * Since we co-schedule groups, {enabled,running} times of siblings
5112 * will be identical to those of the leader, so we only publish one
5115 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5116 values[n++] += leader->total_time_enabled +
5117 atomic64_read(&leader->child_total_time_enabled);
5120 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5121 values[n++] += leader->total_time_running +
5122 atomic64_read(&leader->child_total_time_running);
5126 * Write {count,id} tuples for every sibling.
5128 values[n++] += perf_event_count(leader);
5129 if (read_format & PERF_FORMAT_ID)
5130 values[n++] = primary_event_id(leader);
5132 for_each_sibling_event(sub, leader) {
5133 values[n++] += perf_event_count(sub);
5134 if (read_format & PERF_FORMAT_ID)
5135 values[n++] = primary_event_id(sub);
5138 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5142 static int perf_read_group(struct perf_event *event,
5143 u64 read_format, char __user *buf)
5145 struct perf_event *leader = event->group_leader, *child;
5146 struct perf_event_context *ctx = leader->ctx;
5150 lockdep_assert_held(&ctx->mutex);
5152 values = kzalloc(event->read_size, GFP_KERNEL);
5156 values[0] = 1 + leader->nr_siblings;
5159 * By locking the child_mutex of the leader we effectively
5160 * lock the child list of all siblings.. XXX explain how.
5162 mutex_lock(&leader->child_mutex);
5164 ret = __perf_read_group_add(leader, read_format, values);
5168 list_for_each_entry(child, &leader->child_list, child_list) {
5169 ret = __perf_read_group_add(child, read_format, values);
5174 mutex_unlock(&leader->child_mutex);
5176 ret = event->read_size;
5177 if (copy_to_user(buf, values, event->read_size))
5182 mutex_unlock(&leader->child_mutex);
5188 static int perf_read_one(struct perf_event *event,
5189 u64 read_format, char __user *buf)
5191 u64 enabled, running;
5195 values[n++] = __perf_event_read_value(event, &enabled, &running);
5196 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5197 values[n++] = enabled;
5198 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5199 values[n++] = running;
5200 if (read_format & PERF_FORMAT_ID)
5201 values[n++] = primary_event_id(event);
5203 if (copy_to_user(buf, values, n * sizeof(u64)))
5206 return n * sizeof(u64);
5209 static bool is_event_hup(struct perf_event *event)
5213 if (event->state > PERF_EVENT_STATE_EXIT)
5216 mutex_lock(&event->child_mutex);
5217 no_children = list_empty(&event->child_list);
5218 mutex_unlock(&event->child_mutex);
5223 * Read the performance event - simple non blocking version for now
5226 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5228 u64 read_format = event->attr.read_format;
5232 * Return end-of-file for a read on an event that is in
5233 * error state (i.e. because it was pinned but it couldn't be
5234 * scheduled on to the CPU at some point).
5236 if (event->state == PERF_EVENT_STATE_ERROR)
5239 if (count < event->read_size)
5242 WARN_ON_ONCE(event->ctx->parent_ctx);
5243 if (read_format & PERF_FORMAT_GROUP)
5244 ret = perf_read_group(event, read_format, buf);
5246 ret = perf_read_one(event, read_format, buf);
5252 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5254 struct perf_event *event = file->private_data;
5255 struct perf_event_context *ctx;
5258 ret = security_perf_event_read(event);
5262 ctx = perf_event_ctx_lock(event);
5263 ret = __perf_read(event, buf, count);
5264 perf_event_ctx_unlock(event, ctx);
5269 static __poll_t perf_poll(struct file *file, poll_table *wait)
5271 struct perf_event *event = file->private_data;
5272 struct perf_buffer *rb;
5273 __poll_t events = EPOLLHUP;
5275 poll_wait(file, &event->waitq, wait);
5277 if (is_event_hup(event))
5281 * Pin the event->rb by taking event->mmap_mutex; otherwise
5282 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5284 mutex_lock(&event->mmap_mutex);
5287 events = atomic_xchg(&rb->poll, 0);
5288 mutex_unlock(&event->mmap_mutex);
5292 static void _perf_event_reset(struct perf_event *event)
5294 (void)perf_event_read(event, false);
5295 local64_set(&event->count, 0);
5296 perf_event_update_userpage(event);
5299 /* Assume it's not an event with inherit set. */
5300 u64 perf_event_pause(struct perf_event *event, bool reset)
5302 struct perf_event_context *ctx;
5305 ctx = perf_event_ctx_lock(event);
5306 WARN_ON_ONCE(event->attr.inherit);
5307 _perf_event_disable(event);
5308 count = local64_read(&event->count);
5310 local64_set(&event->count, 0);
5311 perf_event_ctx_unlock(event, ctx);
5315 EXPORT_SYMBOL_GPL(perf_event_pause);
5318 * Holding the top-level event's child_mutex means that any
5319 * descendant process that has inherited this event will block
5320 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5321 * task existence requirements of perf_event_enable/disable.
5323 static void perf_event_for_each_child(struct perf_event *event,
5324 void (*func)(struct perf_event *))
5326 struct perf_event *child;
5328 WARN_ON_ONCE(event->ctx->parent_ctx);
5330 mutex_lock(&event->child_mutex);
5332 list_for_each_entry(child, &event->child_list, child_list)
5334 mutex_unlock(&event->child_mutex);
5337 static void perf_event_for_each(struct perf_event *event,
5338 void (*func)(struct perf_event *))
5340 struct perf_event_context *ctx = event->ctx;
5341 struct perf_event *sibling;
5343 lockdep_assert_held(&ctx->mutex);
5345 event = event->group_leader;
5347 perf_event_for_each_child(event, func);
5348 for_each_sibling_event(sibling, event)
5349 perf_event_for_each_child(sibling, func);
5352 static void __perf_event_period(struct perf_event *event,
5353 struct perf_cpu_context *cpuctx,
5354 struct perf_event_context *ctx,
5357 u64 value = *((u64 *)info);
5360 if (event->attr.freq) {
5361 event->attr.sample_freq = value;
5363 event->attr.sample_period = value;
5364 event->hw.sample_period = value;
5367 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5369 perf_pmu_disable(ctx->pmu);
5371 * We could be throttled; unthrottle now to avoid the tick
5372 * trying to unthrottle while we already re-started the event.
5374 if (event->hw.interrupts == MAX_INTERRUPTS) {
5375 event->hw.interrupts = 0;
5376 perf_log_throttle(event, 1);
5378 event->pmu->stop(event, PERF_EF_UPDATE);
5381 local64_set(&event->hw.period_left, 0);
5384 event->pmu->start(event, PERF_EF_RELOAD);
5385 perf_pmu_enable(ctx->pmu);
5389 static int perf_event_check_period(struct perf_event *event, u64 value)
5391 return event->pmu->check_period(event, value);
5394 static int _perf_event_period(struct perf_event *event, u64 value)
5396 if (!is_sampling_event(event))
5402 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5405 if (perf_event_check_period(event, value))
5408 if (!event->attr.freq && (value & (1ULL << 63)))
5411 event_function_call(event, __perf_event_period, &value);
5416 int perf_event_period(struct perf_event *event, u64 value)
5418 struct perf_event_context *ctx;
5421 ctx = perf_event_ctx_lock(event);
5422 ret = _perf_event_period(event, value);
5423 perf_event_ctx_unlock(event, ctx);
5427 EXPORT_SYMBOL_GPL(perf_event_period);
5429 static const struct file_operations perf_fops;
5431 static inline int perf_fget_light(int fd, struct fd *p)
5433 struct fd f = fdget(fd);
5437 if (f.file->f_op != &perf_fops) {
5445 static int perf_event_set_output(struct perf_event *event,
5446 struct perf_event *output_event);
5447 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5448 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5449 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5450 struct perf_event_attr *attr);
5452 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5454 void (*func)(struct perf_event *);
5458 case PERF_EVENT_IOC_ENABLE:
5459 func = _perf_event_enable;
5461 case PERF_EVENT_IOC_DISABLE:
5462 func = _perf_event_disable;
5464 case PERF_EVENT_IOC_RESET:
5465 func = _perf_event_reset;
5468 case PERF_EVENT_IOC_REFRESH:
5469 return _perf_event_refresh(event, arg);
5471 case PERF_EVENT_IOC_PERIOD:
5475 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5478 return _perf_event_period(event, value);
5480 case PERF_EVENT_IOC_ID:
5482 u64 id = primary_event_id(event);
5484 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5489 case PERF_EVENT_IOC_SET_OUTPUT:
5493 struct perf_event *output_event;
5495 ret = perf_fget_light(arg, &output);
5498 output_event = output.file->private_data;
5499 ret = perf_event_set_output(event, output_event);
5502 ret = perf_event_set_output(event, NULL);
5507 case PERF_EVENT_IOC_SET_FILTER:
5508 return perf_event_set_filter(event, (void __user *)arg);
5510 case PERF_EVENT_IOC_SET_BPF:
5511 return perf_event_set_bpf_prog(event, arg);
5513 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5514 struct perf_buffer *rb;
5517 rb = rcu_dereference(event->rb);
5518 if (!rb || !rb->nr_pages) {
5522 rb_toggle_paused(rb, !!arg);
5527 case PERF_EVENT_IOC_QUERY_BPF:
5528 return perf_event_query_prog_array(event, (void __user *)arg);
5530 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5531 struct perf_event_attr new_attr;
5532 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5538 return perf_event_modify_attr(event, &new_attr);
5544 if (flags & PERF_IOC_FLAG_GROUP)
5545 perf_event_for_each(event, func);
5547 perf_event_for_each_child(event, func);
5552 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5554 struct perf_event *event = file->private_data;
5555 struct perf_event_context *ctx;
5558 /* Treat ioctl like writes as it is likely a mutating operation. */
5559 ret = security_perf_event_write(event);
5563 ctx = perf_event_ctx_lock(event);
5564 ret = _perf_ioctl(event, cmd, arg);
5565 perf_event_ctx_unlock(event, ctx);
5570 #ifdef CONFIG_COMPAT
5571 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5574 switch (_IOC_NR(cmd)) {
5575 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5576 case _IOC_NR(PERF_EVENT_IOC_ID):
5577 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5578 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5579 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5580 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5581 cmd &= ~IOCSIZE_MASK;
5582 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5586 return perf_ioctl(file, cmd, arg);
5589 # define perf_compat_ioctl NULL
5592 int perf_event_task_enable(void)
5594 struct perf_event_context *ctx;
5595 struct perf_event *event;
5597 mutex_lock(¤t->perf_event_mutex);
5598 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5599 ctx = perf_event_ctx_lock(event);
5600 perf_event_for_each_child(event, _perf_event_enable);
5601 perf_event_ctx_unlock(event, ctx);
5603 mutex_unlock(¤t->perf_event_mutex);
5608 int perf_event_task_disable(void)
5610 struct perf_event_context *ctx;
5611 struct perf_event *event;
5613 mutex_lock(¤t->perf_event_mutex);
5614 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5615 ctx = perf_event_ctx_lock(event);
5616 perf_event_for_each_child(event, _perf_event_disable);
5617 perf_event_ctx_unlock(event, ctx);
5619 mutex_unlock(¤t->perf_event_mutex);
5624 static int perf_event_index(struct perf_event *event)
5626 if (event->hw.state & PERF_HES_STOPPED)
5629 if (event->state != PERF_EVENT_STATE_ACTIVE)
5632 return event->pmu->event_idx(event);
5635 static void calc_timer_values(struct perf_event *event,
5642 *now = perf_clock();
5643 ctx_time = event->shadow_ctx_time + *now;
5644 __perf_update_times(event, ctx_time, enabled, running);
5647 static void perf_event_init_userpage(struct perf_event *event)
5649 struct perf_event_mmap_page *userpg;
5650 struct perf_buffer *rb;
5653 rb = rcu_dereference(event->rb);
5657 userpg = rb->user_page;
5659 /* Allow new userspace to detect that bit 0 is deprecated */
5660 userpg->cap_bit0_is_deprecated = 1;
5661 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5662 userpg->data_offset = PAGE_SIZE;
5663 userpg->data_size = perf_data_size(rb);
5669 void __weak arch_perf_update_userpage(
5670 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5675 * Callers need to ensure there can be no nesting of this function, otherwise
5676 * the seqlock logic goes bad. We can not serialize this because the arch
5677 * code calls this from NMI context.
5679 void perf_event_update_userpage(struct perf_event *event)
5681 struct perf_event_mmap_page *userpg;
5682 struct perf_buffer *rb;
5683 u64 enabled, running, now;
5686 rb = rcu_dereference(event->rb);
5691 * compute total_time_enabled, total_time_running
5692 * based on snapshot values taken when the event
5693 * was last scheduled in.
5695 * we cannot simply called update_context_time()
5696 * because of locking issue as we can be called in
5699 calc_timer_values(event, &now, &enabled, &running);
5701 userpg = rb->user_page;
5703 * Disable preemption to guarantee consistent time stamps are stored to
5709 userpg->index = perf_event_index(event);
5710 userpg->offset = perf_event_count(event);
5712 userpg->offset -= local64_read(&event->hw.prev_count);
5714 userpg->time_enabled = enabled +
5715 atomic64_read(&event->child_total_time_enabled);
5717 userpg->time_running = running +
5718 atomic64_read(&event->child_total_time_running);
5720 arch_perf_update_userpage(event, userpg, now);
5728 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5730 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5732 struct perf_event *event = vmf->vma->vm_file->private_data;
5733 struct perf_buffer *rb;
5734 vm_fault_t ret = VM_FAULT_SIGBUS;
5736 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5737 if (vmf->pgoff == 0)
5743 rb = rcu_dereference(event->rb);
5747 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5750 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5754 get_page(vmf->page);
5755 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5756 vmf->page->index = vmf->pgoff;
5765 static void ring_buffer_attach(struct perf_event *event,
5766 struct perf_buffer *rb)
5768 struct perf_buffer *old_rb = NULL;
5769 unsigned long flags;
5773 * Should be impossible, we set this when removing
5774 * event->rb_entry and wait/clear when adding event->rb_entry.
5776 WARN_ON_ONCE(event->rcu_pending);
5779 spin_lock_irqsave(&old_rb->event_lock, flags);
5780 list_del_rcu(&event->rb_entry);
5781 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5783 event->rcu_batches = get_state_synchronize_rcu();
5784 event->rcu_pending = 1;
5788 if (event->rcu_pending) {
5789 cond_synchronize_rcu(event->rcu_batches);
5790 event->rcu_pending = 0;
5793 spin_lock_irqsave(&rb->event_lock, flags);
5794 list_add_rcu(&event->rb_entry, &rb->event_list);
5795 spin_unlock_irqrestore(&rb->event_lock, flags);
5799 * Avoid racing with perf_mmap_close(AUX): stop the event
5800 * before swizzling the event::rb pointer; if it's getting
5801 * unmapped, its aux_mmap_count will be 0 and it won't
5802 * restart. See the comment in __perf_pmu_output_stop().
5804 * Data will inevitably be lost when set_output is done in
5805 * mid-air, but then again, whoever does it like this is
5806 * not in for the data anyway.
5809 perf_event_stop(event, 0);
5811 rcu_assign_pointer(event->rb, rb);
5814 ring_buffer_put(old_rb);
5816 * Since we detached before setting the new rb, so that we
5817 * could attach the new rb, we could have missed a wakeup.
5820 wake_up_all(&event->waitq);
5824 static void ring_buffer_wakeup(struct perf_event *event)
5826 struct perf_buffer *rb;
5829 rb = rcu_dereference(event->rb);
5831 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5832 wake_up_all(&event->waitq);
5837 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5839 struct perf_buffer *rb;
5842 rb = rcu_dereference(event->rb);
5844 if (!refcount_inc_not_zero(&rb->refcount))
5852 void ring_buffer_put(struct perf_buffer *rb)
5854 if (!refcount_dec_and_test(&rb->refcount))
5857 WARN_ON_ONCE(!list_empty(&rb->event_list));
5859 call_rcu(&rb->rcu_head, rb_free_rcu);
5862 static void perf_mmap_open(struct vm_area_struct *vma)
5864 struct perf_event *event = vma->vm_file->private_data;
5866 atomic_inc(&event->mmap_count);
5867 atomic_inc(&event->rb->mmap_count);
5870 atomic_inc(&event->rb->aux_mmap_count);
5872 if (event->pmu->event_mapped)
5873 event->pmu->event_mapped(event, vma->vm_mm);
5876 static void perf_pmu_output_stop(struct perf_event *event);
5879 * A buffer can be mmap()ed multiple times; either directly through the same
5880 * event, or through other events by use of perf_event_set_output().
5882 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5883 * the buffer here, where we still have a VM context. This means we need
5884 * to detach all events redirecting to us.
5886 static void perf_mmap_close(struct vm_area_struct *vma)
5888 struct perf_event *event = vma->vm_file->private_data;
5889 struct perf_buffer *rb = ring_buffer_get(event);
5890 struct user_struct *mmap_user = rb->mmap_user;
5891 int mmap_locked = rb->mmap_locked;
5892 unsigned long size = perf_data_size(rb);
5893 bool detach_rest = false;
5895 if (event->pmu->event_unmapped)
5896 event->pmu->event_unmapped(event, vma->vm_mm);
5899 * rb->aux_mmap_count will always drop before rb->mmap_count and
5900 * event->mmap_count, so it is ok to use event->mmap_mutex to
5901 * serialize with perf_mmap here.
5903 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5904 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5906 * Stop all AUX events that are writing to this buffer,
5907 * so that we can free its AUX pages and corresponding PMU
5908 * data. Note that after rb::aux_mmap_count dropped to zero,
5909 * they won't start any more (see perf_aux_output_begin()).
5911 perf_pmu_output_stop(event);
5913 /* now it's safe to free the pages */
5914 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5915 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5917 /* this has to be the last one */
5919 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5921 mutex_unlock(&event->mmap_mutex);
5924 if (atomic_dec_and_test(&rb->mmap_count))
5927 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5930 ring_buffer_attach(event, NULL);
5931 mutex_unlock(&event->mmap_mutex);
5933 /* If there's still other mmap()s of this buffer, we're done. */
5938 * No other mmap()s, detach from all other events that might redirect
5939 * into the now unreachable buffer. Somewhat complicated by the
5940 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5944 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5945 if (!atomic_long_inc_not_zero(&event->refcount)) {
5947 * This event is en-route to free_event() which will
5948 * detach it and remove it from the list.
5954 mutex_lock(&event->mmap_mutex);
5956 * Check we didn't race with perf_event_set_output() which can
5957 * swizzle the rb from under us while we were waiting to
5958 * acquire mmap_mutex.
5960 * If we find a different rb; ignore this event, a next
5961 * iteration will no longer find it on the list. We have to
5962 * still restart the iteration to make sure we're not now
5963 * iterating the wrong list.
5965 if (event->rb == rb)
5966 ring_buffer_attach(event, NULL);
5968 mutex_unlock(&event->mmap_mutex);
5972 * Restart the iteration; either we're on the wrong list or
5973 * destroyed its integrity by doing a deletion.
5980 * It could be there's still a few 0-ref events on the list; they'll
5981 * get cleaned up by free_event() -- they'll also still have their
5982 * ref on the rb and will free it whenever they are done with it.
5984 * Aside from that, this buffer is 'fully' detached and unmapped,
5985 * undo the VM accounting.
5988 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5989 &mmap_user->locked_vm);
5990 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5991 free_uid(mmap_user);
5994 ring_buffer_put(rb); /* could be last */
5997 static const struct vm_operations_struct perf_mmap_vmops = {
5998 .open = perf_mmap_open,
5999 .close = perf_mmap_close, /* non mergeable */
6000 .fault = perf_mmap_fault,
6001 .page_mkwrite = perf_mmap_fault,
6004 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6006 struct perf_event *event = file->private_data;
6007 unsigned long user_locked, user_lock_limit;
6008 struct user_struct *user = current_user();
6009 struct perf_buffer *rb = NULL;
6010 unsigned long locked, lock_limit;
6011 unsigned long vma_size;
6012 unsigned long nr_pages;
6013 long user_extra = 0, extra = 0;
6014 int ret = 0, flags = 0;
6017 * Don't allow mmap() of inherited per-task counters. This would
6018 * create a performance issue due to all children writing to the
6021 if (event->cpu == -1 && event->attr.inherit)
6024 if (!(vma->vm_flags & VM_SHARED))
6027 ret = security_perf_event_read(event);
6031 vma_size = vma->vm_end - vma->vm_start;
6033 if (vma->vm_pgoff == 0) {
6034 nr_pages = (vma_size / PAGE_SIZE) - 1;
6037 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6038 * mapped, all subsequent mappings should have the same size
6039 * and offset. Must be above the normal perf buffer.
6041 u64 aux_offset, aux_size;
6046 nr_pages = vma_size / PAGE_SIZE;
6048 mutex_lock(&event->mmap_mutex);
6055 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6056 aux_size = READ_ONCE(rb->user_page->aux_size);
6058 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6061 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6064 /* already mapped with a different offset */
6065 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6068 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6071 /* already mapped with a different size */
6072 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6075 if (!is_power_of_2(nr_pages))
6078 if (!atomic_inc_not_zero(&rb->mmap_count))
6081 if (rb_has_aux(rb)) {
6082 atomic_inc(&rb->aux_mmap_count);
6087 atomic_set(&rb->aux_mmap_count, 1);
6088 user_extra = nr_pages;
6094 * If we have rb pages ensure they're a power-of-two number, so we
6095 * can do bitmasks instead of modulo.
6097 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6100 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6103 WARN_ON_ONCE(event->ctx->parent_ctx);
6105 mutex_lock(&event->mmap_mutex);
6107 if (event->rb->nr_pages != nr_pages) {
6112 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6114 * Raced against perf_mmap_close() through
6115 * perf_event_set_output(). Try again, hope for better
6118 mutex_unlock(&event->mmap_mutex);
6125 user_extra = nr_pages + 1;
6128 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6131 * Increase the limit linearly with more CPUs:
6133 user_lock_limit *= num_online_cpus();
6135 user_locked = atomic_long_read(&user->locked_vm);
6138 * sysctl_perf_event_mlock may have changed, so that
6139 * user->locked_vm > user_lock_limit
6141 if (user_locked > user_lock_limit)
6142 user_locked = user_lock_limit;
6143 user_locked += user_extra;
6145 if (user_locked > user_lock_limit) {
6147 * charge locked_vm until it hits user_lock_limit;
6148 * charge the rest from pinned_vm
6150 extra = user_locked - user_lock_limit;
6151 user_extra -= extra;
6154 lock_limit = rlimit(RLIMIT_MEMLOCK);
6155 lock_limit >>= PAGE_SHIFT;
6156 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6158 if ((locked > lock_limit) && perf_is_paranoid() &&
6159 !capable(CAP_IPC_LOCK)) {
6164 WARN_ON(!rb && event->rb);
6166 if (vma->vm_flags & VM_WRITE)
6167 flags |= RING_BUFFER_WRITABLE;
6170 rb = rb_alloc(nr_pages,
6171 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6179 atomic_set(&rb->mmap_count, 1);
6180 rb->mmap_user = get_current_user();
6181 rb->mmap_locked = extra;
6183 ring_buffer_attach(event, rb);
6185 perf_event_init_userpage(event);
6186 perf_event_update_userpage(event);
6188 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6189 event->attr.aux_watermark, flags);
6191 rb->aux_mmap_locked = extra;
6196 atomic_long_add(user_extra, &user->locked_vm);
6197 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6199 atomic_inc(&event->mmap_count);
6201 atomic_dec(&rb->mmap_count);
6204 mutex_unlock(&event->mmap_mutex);
6207 * Since pinned accounting is per vm we cannot allow fork() to copy our
6210 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6211 vma->vm_ops = &perf_mmap_vmops;
6213 if (event->pmu->event_mapped)
6214 event->pmu->event_mapped(event, vma->vm_mm);
6219 static int perf_fasync(int fd, struct file *filp, int on)
6221 struct inode *inode = file_inode(filp);
6222 struct perf_event *event = filp->private_data;
6226 retval = fasync_helper(fd, filp, on, &event->fasync);
6227 inode_unlock(inode);
6235 static const struct file_operations perf_fops = {
6236 .llseek = no_llseek,
6237 .release = perf_release,
6240 .unlocked_ioctl = perf_ioctl,
6241 .compat_ioctl = perf_compat_ioctl,
6243 .fasync = perf_fasync,
6249 * If there's data, ensure we set the poll() state and publish everything
6250 * to user-space before waking everybody up.
6253 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6255 /* only the parent has fasync state */
6257 event = event->parent;
6258 return &event->fasync;
6261 void perf_event_wakeup(struct perf_event *event)
6263 ring_buffer_wakeup(event);
6265 if (event->pending_kill) {
6266 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6267 event->pending_kill = 0;
6271 static void perf_pending_event_disable(struct perf_event *event)
6273 int cpu = READ_ONCE(event->pending_disable);
6278 if (cpu == smp_processor_id()) {
6279 WRITE_ONCE(event->pending_disable, -1);
6280 perf_event_disable_local(event);
6287 * perf_event_disable_inatomic()
6288 * @pending_disable = CPU-A;
6292 * @pending_disable = -1;
6295 * perf_event_disable_inatomic()
6296 * @pending_disable = CPU-B;
6297 * irq_work_queue(); // FAILS
6300 * perf_pending_event()
6302 * But the event runs on CPU-B and wants disabling there.
6304 irq_work_queue_on(&event->pending, cpu);
6307 static void perf_pending_event(struct irq_work *entry)
6309 struct perf_event *event = container_of(entry, struct perf_event, pending);
6312 rctx = perf_swevent_get_recursion_context();
6314 * If we 'fail' here, that's OK, it means recursion is already disabled
6315 * and we won't recurse 'further'.
6318 perf_pending_event_disable(event);
6320 if (event->pending_wakeup) {
6321 event->pending_wakeup = 0;
6322 perf_event_wakeup(event);
6326 perf_swevent_put_recursion_context(rctx);
6330 * We assume there is only KVM supporting the callbacks.
6331 * Later on, we might change it to a list if there is
6332 * another virtualization implementation supporting the callbacks.
6334 struct perf_guest_info_callbacks *perf_guest_cbs;
6336 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6338 perf_guest_cbs = cbs;
6341 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6343 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6345 perf_guest_cbs = NULL;
6348 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6351 perf_output_sample_regs(struct perf_output_handle *handle,
6352 struct pt_regs *regs, u64 mask)
6355 DECLARE_BITMAP(_mask, 64);
6357 bitmap_from_u64(_mask, mask);
6358 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6361 val = perf_reg_value(regs, bit);
6362 perf_output_put(handle, val);
6366 static void perf_sample_regs_user(struct perf_regs *regs_user,
6367 struct pt_regs *regs)
6369 if (user_mode(regs)) {
6370 regs_user->abi = perf_reg_abi(current);
6371 regs_user->regs = regs;
6372 } else if (!(current->flags & PF_KTHREAD)) {
6373 perf_get_regs_user(regs_user, regs);
6375 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6376 regs_user->regs = NULL;
6380 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6381 struct pt_regs *regs)
6383 regs_intr->regs = regs;
6384 regs_intr->abi = perf_reg_abi(current);
6389 * Get remaining task size from user stack pointer.
6391 * It'd be better to take stack vma map and limit this more
6392 * precisely, but there's no way to get it safely under interrupt,
6393 * so using TASK_SIZE as limit.
6395 static u64 perf_ustack_task_size(struct pt_regs *regs)
6397 unsigned long addr = perf_user_stack_pointer(regs);
6399 if (!addr || addr >= TASK_SIZE)
6402 return TASK_SIZE - addr;
6406 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6407 struct pt_regs *regs)
6411 /* No regs, no stack pointer, no dump. */
6416 * Check if we fit in with the requested stack size into the:
6418 * If we don't, we limit the size to the TASK_SIZE.
6420 * - remaining sample size
6421 * If we don't, we customize the stack size to
6422 * fit in to the remaining sample size.
6425 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6426 stack_size = min(stack_size, (u16) task_size);
6428 /* Current header size plus static size and dynamic size. */
6429 header_size += 2 * sizeof(u64);
6431 /* Do we fit in with the current stack dump size? */
6432 if ((u16) (header_size + stack_size) < header_size) {
6434 * If we overflow the maximum size for the sample,
6435 * we customize the stack dump size to fit in.
6437 stack_size = USHRT_MAX - header_size - sizeof(u64);
6438 stack_size = round_up(stack_size, sizeof(u64));
6445 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6446 struct pt_regs *regs)
6448 /* Case of a kernel thread, nothing to dump */
6451 perf_output_put(handle, size);
6461 * - the size requested by user or the best one we can fit
6462 * in to the sample max size
6464 * - user stack dump data
6466 * - the actual dumped size
6470 perf_output_put(handle, dump_size);
6473 sp = perf_user_stack_pointer(regs);
6474 fs = force_uaccess_begin();
6475 rem = __output_copy_user(handle, (void *) sp, dump_size);
6476 force_uaccess_end(fs);
6477 dyn_size = dump_size - rem;
6479 perf_output_skip(handle, rem);
6482 perf_output_put(handle, dyn_size);
6486 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6487 struct perf_sample_data *data,
6490 struct perf_event *sampler = event->aux_event;
6491 struct perf_buffer *rb;
6498 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6501 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6504 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6509 * If this is an NMI hit inside sampling code, don't take
6510 * the sample. See also perf_aux_sample_output().
6512 if (READ_ONCE(rb->aux_in_sampling)) {
6515 size = min_t(size_t, size, perf_aux_size(rb));
6516 data->aux_size = ALIGN(size, sizeof(u64));
6518 ring_buffer_put(rb);
6521 return data->aux_size;
6524 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6525 struct perf_event *event,
6526 struct perf_output_handle *handle,
6529 unsigned long flags;
6533 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6534 * paths. If we start calling them in NMI context, they may race with
6535 * the IRQ ones, that is, for example, re-starting an event that's just
6536 * been stopped, which is why we're using a separate callback that
6537 * doesn't change the event state.
6539 * IRQs need to be disabled to prevent IPIs from racing with us.
6541 local_irq_save(flags);
6543 * Guard against NMI hits inside the critical section;
6544 * see also perf_prepare_sample_aux().
6546 WRITE_ONCE(rb->aux_in_sampling, 1);
6549 ret = event->pmu->snapshot_aux(event, handle, size);
6552 WRITE_ONCE(rb->aux_in_sampling, 0);
6553 local_irq_restore(flags);
6558 static void perf_aux_sample_output(struct perf_event *event,
6559 struct perf_output_handle *handle,
6560 struct perf_sample_data *data)
6562 struct perf_event *sampler = event->aux_event;
6563 struct perf_buffer *rb;
6567 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6570 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6574 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6577 * An error here means that perf_output_copy() failed (returned a
6578 * non-zero surplus that it didn't copy), which in its current
6579 * enlightened implementation is not possible. If that changes, we'd
6582 if (WARN_ON_ONCE(size < 0))
6586 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6587 * perf_prepare_sample_aux(), so should not be more than that.
6589 pad = data->aux_size - size;
6590 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6595 perf_output_copy(handle, &zero, pad);
6599 ring_buffer_put(rb);
6602 static void __perf_event_header__init_id(struct perf_event_header *header,
6603 struct perf_sample_data *data,
6604 struct perf_event *event)
6606 u64 sample_type = event->attr.sample_type;
6608 data->type = sample_type;
6609 header->size += event->id_header_size;
6611 if (sample_type & PERF_SAMPLE_TID) {
6612 /* namespace issues */
6613 data->tid_entry.pid = perf_event_pid(event, current);
6614 data->tid_entry.tid = perf_event_tid(event, current);
6617 if (sample_type & PERF_SAMPLE_TIME)
6618 data->time = perf_event_clock(event);
6620 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6621 data->id = primary_event_id(event);
6623 if (sample_type & PERF_SAMPLE_STREAM_ID)
6624 data->stream_id = event->id;
6626 if (sample_type & PERF_SAMPLE_CPU) {
6627 data->cpu_entry.cpu = raw_smp_processor_id();
6628 data->cpu_entry.reserved = 0;
6632 void perf_event_header__init_id(struct perf_event_header *header,
6633 struct perf_sample_data *data,
6634 struct perf_event *event)
6636 if (event->attr.sample_id_all)
6637 __perf_event_header__init_id(header, data, event);
6640 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6641 struct perf_sample_data *data)
6643 u64 sample_type = data->type;
6645 if (sample_type & PERF_SAMPLE_TID)
6646 perf_output_put(handle, data->tid_entry);
6648 if (sample_type & PERF_SAMPLE_TIME)
6649 perf_output_put(handle, data->time);
6651 if (sample_type & PERF_SAMPLE_ID)
6652 perf_output_put(handle, data->id);
6654 if (sample_type & PERF_SAMPLE_STREAM_ID)
6655 perf_output_put(handle, data->stream_id);
6657 if (sample_type & PERF_SAMPLE_CPU)
6658 perf_output_put(handle, data->cpu_entry);
6660 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6661 perf_output_put(handle, data->id);
6664 void perf_event__output_id_sample(struct perf_event *event,
6665 struct perf_output_handle *handle,
6666 struct perf_sample_data *sample)
6668 if (event->attr.sample_id_all)
6669 __perf_event__output_id_sample(handle, sample);
6672 static void perf_output_read_one(struct perf_output_handle *handle,
6673 struct perf_event *event,
6674 u64 enabled, u64 running)
6676 u64 read_format = event->attr.read_format;
6680 values[n++] = perf_event_count(event);
6681 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6682 values[n++] = enabled +
6683 atomic64_read(&event->child_total_time_enabled);
6685 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6686 values[n++] = running +
6687 atomic64_read(&event->child_total_time_running);
6689 if (read_format & PERF_FORMAT_ID)
6690 values[n++] = primary_event_id(event);
6692 __output_copy(handle, values, n * sizeof(u64));
6695 static void perf_output_read_group(struct perf_output_handle *handle,
6696 struct perf_event *event,
6697 u64 enabled, u64 running)
6699 struct perf_event *leader = event->group_leader, *sub;
6700 u64 read_format = event->attr.read_format;
6704 values[n++] = 1 + leader->nr_siblings;
6706 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6707 values[n++] = enabled;
6709 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6710 values[n++] = running;
6712 if ((leader != event) &&
6713 (leader->state == PERF_EVENT_STATE_ACTIVE))
6714 leader->pmu->read(leader);
6716 values[n++] = perf_event_count(leader);
6717 if (read_format & PERF_FORMAT_ID)
6718 values[n++] = primary_event_id(leader);
6720 __output_copy(handle, values, n * sizeof(u64));
6722 for_each_sibling_event(sub, leader) {
6725 if ((sub != event) &&
6726 (sub->state == PERF_EVENT_STATE_ACTIVE))
6727 sub->pmu->read(sub);
6729 values[n++] = perf_event_count(sub);
6730 if (read_format & PERF_FORMAT_ID)
6731 values[n++] = primary_event_id(sub);
6733 __output_copy(handle, values, n * sizeof(u64));
6737 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6738 PERF_FORMAT_TOTAL_TIME_RUNNING)
6741 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6743 * The problem is that its both hard and excessively expensive to iterate the
6744 * child list, not to mention that its impossible to IPI the children running
6745 * on another CPU, from interrupt/NMI context.
6747 static void perf_output_read(struct perf_output_handle *handle,
6748 struct perf_event *event)
6750 u64 enabled = 0, running = 0, now;
6751 u64 read_format = event->attr.read_format;
6754 * compute total_time_enabled, total_time_running
6755 * based on snapshot values taken when the event
6756 * was last scheduled in.
6758 * we cannot simply called update_context_time()
6759 * because of locking issue as we are called in
6762 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6763 calc_timer_values(event, &now, &enabled, &running);
6765 if (event->attr.read_format & PERF_FORMAT_GROUP)
6766 perf_output_read_group(handle, event, enabled, running);
6768 perf_output_read_one(handle, event, enabled, running);
6771 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6773 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6776 void perf_output_sample(struct perf_output_handle *handle,
6777 struct perf_event_header *header,
6778 struct perf_sample_data *data,
6779 struct perf_event *event)
6781 u64 sample_type = data->type;
6783 perf_output_put(handle, *header);
6785 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6786 perf_output_put(handle, data->id);
6788 if (sample_type & PERF_SAMPLE_IP)
6789 perf_output_put(handle, data->ip);
6791 if (sample_type & PERF_SAMPLE_TID)
6792 perf_output_put(handle, data->tid_entry);
6794 if (sample_type & PERF_SAMPLE_TIME)
6795 perf_output_put(handle, data->time);
6797 if (sample_type & PERF_SAMPLE_ADDR)
6798 perf_output_put(handle, data->addr);
6800 if (sample_type & PERF_SAMPLE_ID)
6801 perf_output_put(handle, data->id);
6803 if (sample_type & PERF_SAMPLE_STREAM_ID)
6804 perf_output_put(handle, data->stream_id);
6806 if (sample_type & PERF_SAMPLE_CPU)
6807 perf_output_put(handle, data->cpu_entry);
6809 if (sample_type & PERF_SAMPLE_PERIOD)
6810 perf_output_put(handle, data->period);
6812 if (sample_type & PERF_SAMPLE_READ)
6813 perf_output_read(handle, event);
6815 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6818 size += data->callchain->nr;
6819 size *= sizeof(u64);
6820 __output_copy(handle, data->callchain, size);
6823 if (sample_type & PERF_SAMPLE_RAW) {
6824 struct perf_raw_record *raw = data->raw;
6827 struct perf_raw_frag *frag = &raw->frag;
6829 perf_output_put(handle, raw->size);
6832 __output_custom(handle, frag->copy,
6833 frag->data, frag->size);
6835 __output_copy(handle, frag->data,
6838 if (perf_raw_frag_last(frag))
6843 __output_skip(handle, NULL, frag->pad);
6849 .size = sizeof(u32),
6852 perf_output_put(handle, raw);
6856 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6857 if (data->br_stack) {
6860 size = data->br_stack->nr
6861 * sizeof(struct perf_branch_entry);
6863 perf_output_put(handle, data->br_stack->nr);
6864 if (perf_sample_save_hw_index(event))
6865 perf_output_put(handle, data->br_stack->hw_idx);
6866 perf_output_copy(handle, data->br_stack->entries, size);
6869 * we always store at least the value of nr
6872 perf_output_put(handle, nr);
6876 if (sample_type & PERF_SAMPLE_REGS_USER) {
6877 u64 abi = data->regs_user.abi;
6880 * If there are no regs to dump, notice it through
6881 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6883 perf_output_put(handle, abi);
6886 u64 mask = event->attr.sample_regs_user;
6887 perf_output_sample_regs(handle,
6888 data->regs_user.regs,
6893 if (sample_type & PERF_SAMPLE_STACK_USER) {
6894 perf_output_sample_ustack(handle,
6895 data->stack_user_size,
6896 data->regs_user.regs);
6899 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
6900 perf_output_put(handle, data->weight.full);
6902 if (sample_type & PERF_SAMPLE_DATA_SRC)
6903 perf_output_put(handle, data->data_src.val);
6905 if (sample_type & PERF_SAMPLE_TRANSACTION)
6906 perf_output_put(handle, data->txn);
6908 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6909 u64 abi = data->regs_intr.abi;
6911 * If there are no regs to dump, notice it through
6912 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6914 perf_output_put(handle, abi);
6917 u64 mask = event->attr.sample_regs_intr;
6919 perf_output_sample_regs(handle,
6920 data->regs_intr.regs,
6925 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6926 perf_output_put(handle, data->phys_addr);
6928 if (sample_type & PERF_SAMPLE_CGROUP)
6929 perf_output_put(handle, data->cgroup);
6931 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
6932 perf_output_put(handle, data->data_page_size);
6934 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
6935 perf_output_put(handle, data->code_page_size);
6937 if (sample_type & PERF_SAMPLE_AUX) {
6938 perf_output_put(handle, data->aux_size);
6941 perf_aux_sample_output(event, handle, data);
6944 if (!event->attr.watermark) {
6945 int wakeup_events = event->attr.wakeup_events;
6947 if (wakeup_events) {
6948 struct perf_buffer *rb = handle->rb;
6949 int events = local_inc_return(&rb->events);
6951 if (events >= wakeup_events) {
6952 local_sub(wakeup_events, &rb->events);
6953 local_inc(&rb->wakeup);
6959 static u64 perf_virt_to_phys(u64 virt)
6962 struct page *p = NULL;
6967 if (virt >= TASK_SIZE) {
6968 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6969 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6970 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6971 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6974 * Walking the pages tables for user address.
6975 * Interrupts are disabled, so it prevents any tear down
6976 * of the page tables.
6977 * Try IRQ-safe get_user_page_fast_only first.
6978 * If failed, leave phys_addr as 0.
6980 if (current->mm != NULL) {
6981 pagefault_disable();
6982 if (get_user_page_fast_only(virt, 0, &p))
6983 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6995 * Return the pagetable size of a given virtual address.
6997 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7001 #ifdef CONFIG_HAVE_FAST_GUP
7008 pgdp = pgd_offset(mm, addr);
7009 pgd = READ_ONCE(*pgdp);
7014 return pgd_leaf_size(pgd);
7016 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7017 p4d = READ_ONCE(*p4dp);
7018 if (!p4d_present(p4d))
7022 return p4d_leaf_size(p4d);
7024 pudp = pud_offset_lockless(p4dp, p4d, addr);
7025 pud = READ_ONCE(*pudp);
7026 if (!pud_present(pud))
7030 return pud_leaf_size(pud);
7032 pmdp = pmd_offset_lockless(pudp, pud, addr);
7033 pmd = READ_ONCE(*pmdp);
7034 if (!pmd_present(pmd))
7038 return pmd_leaf_size(pmd);
7040 ptep = pte_offset_map(&pmd, addr);
7041 pte = ptep_get_lockless(ptep);
7042 if (pte_present(pte))
7043 size = pte_leaf_size(pte);
7045 #endif /* CONFIG_HAVE_FAST_GUP */
7050 static u64 perf_get_page_size(unsigned long addr)
7052 struct mm_struct *mm;
7053 unsigned long flags;
7060 * Software page-table walkers must disable IRQs,
7061 * which prevents any tear down of the page tables.
7063 local_irq_save(flags);
7068 * For kernel threads and the like, use init_mm so that
7069 * we can find kernel memory.
7074 size = perf_get_pgtable_size(mm, addr);
7076 local_irq_restore(flags);
7081 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7083 struct perf_callchain_entry *
7084 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7086 bool kernel = !event->attr.exclude_callchain_kernel;
7087 bool user = !event->attr.exclude_callchain_user;
7088 /* Disallow cross-task user callchains. */
7089 bool crosstask = event->ctx->task && event->ctx->task != current;
7090 const u32 max_stack = event->attr.sample_max_stack;
7091 struct perf_callchain_entry *callchain;
7093 if (!kernel && !user)
7094 return &__empty_callchain;
7096 callchain = get_perf_callchain(regs, 0, kernel, user,
7097 max_stack, crosstask, true);
7098 return callchain ?: &__empty_callchain;
7101 void perf_prepare_sample(struct perf_event_header *header,
7102 struct perf_sample_data *data,
7103 struct perf_event *event,
7104 struct pt_regs *regs)
7106 u64 sample_type = event->attr.sample_type;
7108 header->type = PERF_RECORD_SAMPLE;
7109 header->size = sizeof(*header) + event->header_size;
7112 header->misc |= perf_misc_flags(regs);
7114 __perf_event_header__init_id(header, data, event);
7116 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7117 data->ip = perf_instruction_pointer(regs);
7119 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7122 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7123 data->callchain = perf_callchain(event, regs);
7125 size += data->callchain->nr;
7127 header->size += size * sizeof(u64);
7130 if (sample_type & PERF_SAMPLE_RAW) {
7131 struct perf_raw_record *raw = data->raw;
7135 struct perf_raw_frag *frag = &raw->frag;
7140 if (perf_raw_frag_last(frag))
7145 size = round_up(sum + sizeof(u32), sizeof(u64));
7146 raw->size = size - sizeof(u32);
7147 frag->pad = raw->size - sum;
7152 header->size += size;
7155 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7156 int size = sizeof(u64); /* nr */
7157 if (data->br_stack) {
7158 if (perf_sample_save_hw_index(event))
7159 size += sizeof(u64);
7161 size += data->br_stack->nr
7162 * sizeof(struct perf_branch_entry);
7164 header->size += size;
7167 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7168 perf_sample_regs_user(&data->regs_user, regs);
7170 if (sample_type & PERF_SAMPLE_REGS_USER) {
7171 /* regs dump ABI info */
7172 int size = sizeof(u64);
7174 if (data->regs_user.regs) {
7175 u64 mask = event->attr.sample_regs_user;
7176 size += hweight64(mask) * sizeof(u64);
7179 header->size += size;
7182 if (sample_type & PERF_SAMPLE_STACK_USER) {
7184 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7185 * processed as the last one or have additional check added
7186 * in case new sample type is added, because we could eat
7187 * up the rest of the sample size.
7189 u16 stack_size = event->attr.sample_stack_user;
7190 u16 size = sizeof(u64);
7192 stack_size = perf_sample_ustack_size(stack_size, header->size,
7193 data->regs_user.regs);
7196 * If there is something to dump, add space for the dump
7197 * itself and for the field that tells the dynamic size,
7198 * which is how many have been actually dumped.
7201 size += sizeof(u64) + stack_size;
7203 data->stack_user_size = stack_size;
7204 header->size += size;
7207 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7208 /* regs dump ABI info */
7209 int size = sizeof(u64);
7211 perf_sample_regs_intr(&data->regs_intr, regs);
7213 if (data->regs_intr.regs) {
7214 u64 mask = event->attr.sample_regs_intr;
7216 size += hweight64(mask) * sizeof(u64);
7219 header->size += size;
7222 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7223 data->phys_addr = perf_virt_to_phys(data->addr);
7225 #ifdef CONFIG_CGROUP_PERF
7226 if (sample_type & PERF_SAMPLE_CGROUP) {
7227 struct cgroup *cgrp;
7229 /* protected by RCU */
7230 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7231 data->cgroup = cgroup_id(cgrp);
7236 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7237 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7238 * but the value will not dump to the userspace.
7240 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7241 data->data_page_size = perf_get_page_size(data->addr);
7243 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7244 data->code_page_size = perf_get_page_size(data->ip);
7246 if (sample_type & PERF_SAMPLE_AUX) {
7249 header->size += sizeof(u64); /* size */
7252 * Given the 16bit nature of header::size, an AUX sample can
7253 * easily overflow it, what with all the preceding sample bits.
7254 * Make sure this doesn't happen by using up to U16_MAX bytes
7255 * per sample in total (rounded down to 8 byte boundary).
7257 size = min_t(size_t, U16_MAX - header->size,
7258 event->attr.aux_sample_size);
7259 size = rounddown(size, 8);
7260 size = perf_prepare_sample_aux(event, data, size);
7262 WARN_ON_ONCE(size + header->size > U16_MAX);
7263 header->size += size;
7266 * If you're adding more sample types here, you likely need to do
7267 * something about the overflowing header::size, like repurpose the
7268 * lowest 3 bits of size, which should be always zero at the moment.
7269 * This raises a more important question, do we really need 512k sized
7270 * samples and why, so good argumentation is in order for whatever you
7273 WARN_ON_ONCE(header->size & 7);
7276 static __always_inline int
7277 __perf_event_output(struct perf_event *event,
7278 struct perf_sample_data *data,
7279 struct pt_regs *regs,
7280 int (*output_begin)(struct perf_output_handle *,
7281 struct perf_sample_data *,
7282 struct perf_event *,
7285 struct perf_output_handle handle;
7286 struct perf_event_header header;
7289 /* protect the callchain buffers */
7292 perf_prepare_sample(&header, data, event, regs);
7294 err = output_begin(&handle, data, event, header.size);
7298 perf_output_sample(&handle, &header, data, event);
7300 perf_output_end(&handle);
7308 perf_event_output_forward(struct perf_event *event,
7309 struct perf_sample_data *data,
7310 struct pt_regs *regs)
7312 __perf_event_output(event, data, regs, perf_output_begin_forward);
7316 perf_event_output_backward(struct perf_event *event,
7317 struct perf_sample_data *data,
7318 struct pt_regs *regs)
7320 __perf_event_output(event, data, regs, perf_output_begin_backward);
7324 perf_event_output(struct perf_event *event,
7325 struct perf_sample_data *data,
7326 struct pt_regs *regs)
7328 return __perf_event_output(event, data, regs, perf_output_begin);
7335 struct perf_read_event {
7336 struct perf_event_header header;
7343 perf_event_read_event(struct perf_event *event,
7344 struct task_struct *task)
7346 struct perf_output_handle handle;
7347 struct perf_sample_data sample;
7348 struct perf_read_event read_event = {
7350 .type = PERF_RECORD_READ,
7352 .size = sizeof(read_event) + event->read_size,
7354 .pid = perf_event_pid(event, task),
7355 .tid = perf_event_tid(event, task),
7359 perf_event_header__init_id(&read_event.header, &sample, event);
7360 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7364 perf_output_put(&handle, read_event);
7365 perf_output_read(&handle, event);
7366 perf_event__output_id_sample(event, &handle, &sample);
7368 perf_output_end(&handle);
7371 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7374 perf_iterate_ctx(struct perf_event_context *ctx,
7375 perf_iterate_f output,
7376 void *data, bool all)
7378 struct perf_event *event;
7380 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7382 if (event->state < PERF_EVENT_STATE_INACTIVE)
7384 if (!event_filter_match(event))
7388 output(event, data);
7392 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7394 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7395 struct perf_event *event;
7397 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7399 * Skip events that are not fully formed yet; ensure that
7400 * if we observe event->ctx, both event and ctx will be
7401 * complete enough. See perf_install_in_context().
7403 if (!smp_load_acquire(&event->ctx))
7406 if (event->state < PERF_EVENT_STATE_INACTIVE)
7408 if (!event_filter_match(event))
7410 output(event, data);
7415 * Iterate all events that need to receive side-band events.
7417 * For new callers; ensure that account_pmu_sb_event() includes
7418 * your event, otherwise it might not get delivered.
7421 perf_iterate_sb(perf_iterate_f output, void *data,
7422 struct perf_event_context *task_ctx)
7424 struct perf_event_context *ctx;
7431 * If we have task_ctx != NULL we only notify the task context itself.
7432 * The task_ctx is set only for EXIT events before releasing task
7436 perf_iterate_ctx(task_ctx, output, data, false);
7440 perf_iterate_sb_cpu(output, data);
7442 for_each_task_context_nr(ctxn) {
7443 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7445 perf_iterate_ctx(ctx, output, data, false);
7453 * Clear all file-based filters at exec, they'll have to be
7454 * re-instated when/if these objects are mmapped again.
7456 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7458 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7459 struct perf_addr_filter *filter;
7460 unsigned int restart = 0, count = 0;
7461 unsigned long flags;
7463 if (!has_addr_filter(event))
7466 raw_spin_lock_irqsave(&ifh->lock, flags);
7467 list_for_each_entry(filter, &ifh->list, entry) {
7468 if (filter->path.dentry) {
7469 event->addr_filter_ranges[count].start = 0;
7470 event->addr_filter_ranges[count].size = 0;
7478 event->addr_filters_gen++;
7479 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7482 perf_event_stop(event, 1);
7485 void perf_event_exec(void)
7487 struct perf_event_context *ctx;
7491 for_each_task_context_nr(ctxn) {
7492 ctx = current->perf_event_ctxp[ctxn];
7496 perf_event_enable_on_exec(ctxn);
7498 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7504 struct remote_output {
7505 struct perf_buffer *rb;
7509 static void __perf_event_output_stop(struct perf_event *event, void *data)
7511 struct perf_event *parent = event->parent;
7512 struct remote_output *ro = data;
7513 struct perf_buffer *rb = ro->rb;
7514 struct stop_event_data sd = {
7518 if (!has_aux(event))
7525 * In case of inheritance, it will be the parent that links to the
7526 * ring-buffer, but it will be the child that's actually using it.
7528 * We are using event::rb to determine if the event should be stopped,
7529 * however this may race with ring_buffer_attach() (through set_output),
7530 * which will make us skip the event that actually needs to be stopped.
7531 * So ring_buffer_attach() has to stop an aux event before re-assigning
7534 if (rcu_dereference(parent->rb) == rb)
7535 ro->err = __perf_event_stop(&sd);
7538 static int __perf_pmu_output_stop(void *info)
7540 struct perf_event *event = info;
7541 struct pmu *pmu = event->ctx->pmu;
7542 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7543 struct remote_output ro = {
7548 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7549 if (cpuctx->task_ctx)
7550 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7557 static void perf_pmu_output_stop(struct perf_event *event)
7559 struct perf_event *iter;
7564 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7566 * For per-CPU events, we need to make sure that neither they
7567 * nor their children are running; for cpu==-1 events it's
7568 * sufficient to stop the event itself if it's active, since
7569 * it can't have children.
7573 cpu = READ_ONCE(iter->oncpu);
7578 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7579 if (err == -EAGAIN) {
7588 * task tracking -- fork/exit
7590 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7593 struct perf_task_event {
7594 struct task_struct *task;
7595 struct perf_event_context *task_ctx;
7598 struct perf_event_header header;
7608 static int perf_event_task_match(struct perf_event *event)
7610 return event->attr.comm || event->attr.mmap ||
7611 event->attr.mmap2 || event->attr.mmap_data ||
7615 static void perf_event_task_output(struct perf_event *event,
7618 struct perf_task_event *task_event = data;
7619 struct perf_output_handle handle;
7620 struct perf_sample_data sample;
7621 struct task_struct *task = task_event->task;
7622 int ret, size = task_event->event_id.header.size;
7624 if (!perf_event_task_match(event))
7627 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7629 ret = perf_output_begin(&handle, &sample, event,
7630 task_event->event_id.header.size);
7634 task_event->event_id.pid = perf_event_pid(event, task);
7635 task_event->event_id.tid = perf_event_tid(event, task);
7637 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7638 task_event->event_id.ppid = perf_event_pid(event,
7640 task_event->event_id.ptid = perf_event_pid(event,
7642 } else { /* PERF_RECORD_FORK */
7643 task_event->event_id.ppid = perf_event_pid(event, current);
7644 task_event->event_id.ptid = perf_event_tid(event, current);
7647 task_event->event_id.time = perf_event_clock(event);
7649 perf_output_put(&handle, task_event->event_id);
7651 perf_event__output_id_sample(event, &handle, &sample);
7653 perf_output_end(&handle);
7655 task_event->event_id.header.size = size;
7658 static void perf_event_task(struct task_struct *task,
7659 struct perf_event_context *task_ctx,
7662 struct perf_task_event task_event;
7664 if (!atomic_read(&nr_comm_events) &&
7665 !atomic_read(&nr_mmap_events) &&
7666 !atomic_read(&nr_task_events))
7669 task_event = (struct perf_task_event){
7671 .task_ctx = task_ctx,
7674 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7676 .size = sizeof(task_event.event_id),
7686 perf_iterate_sb(perf_event_task_output,
7691 void perf_event_fork(struct task_struct *task)
7693 perf_event_task(task, NULL, 1);
7694 perf_event_namespaces(task);
7701 struct perf_comm_event {
7702 struct task_struct *task;
7707 struct perf_event_header header;
7714 static int perf_event_comm_match(struct perf_event *event)
7716 return event->attr.comm;
7719 static void perf_event_comm_output(struct perf_event *event,
7722 struct perf_comm_event *comm_event = data;
7723 struct perf_output_handle handle;
7724 struct perf_sample_data sample;
7725 int size = comm_event->event_id.header.size;
7728 if (!perf_event_comm_match(event))
7731 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7732 ret = perf_output_begin(&handle, &sample, event,
7733 comm_event->event_id.header.size);
7738 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7739 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7741 perf_output_put(&handle, comm_event->event_id);
7742 __output_copy(&handle, comm_event->comm,
7743 comm_event->comm_size);
7745 perf_event__output_id_sample(event, &handle, &sample);
7747 perf_output_end(&handle);
7749 comm_event->event_id.header.size = size;
7752 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7754 char comm[TASK_COMM_LEN];
7757 memset(comm, 0, sizeof(comm));
7758 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7759 size = ALIGN(strlen(comm)+1, sizeof(u64));
7761 comm_event->comm = comm;
7762 comm_event->comm_size = size;
7764 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7766 perf_iterate_sb(perf_event_comm_output,
7771 void perf_event_comm(struct task_struct *task, bool exec)
7773 struct perf_comm_event comm_event;
7775 if (!atomic_read(&nr_comm_events))
7778 comm_event = (struct perf_comm_event){
7784 .type = PERF_RECORD_COMM,
7785 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7793 perf_event_comm_event(&comm_event);
7797 * namespaces tracking
7800 struct perf_namespaces_event {
7801 struct task_struct *task;
7804 struct perf_event_header header;
7809 struct perf_ns_link_info link_info[NR_NAMESPACES];
7813 static int perf_event_namespaces_match(struct perf_event *event)
7815 return event->attr.namespaces;
7818 static void perf_event_namespaces_output(struct perf_event *event,
7821 struct perf_namespaces_event *namespaces_event = data;
7822 struct perf_output_handle handle;
7823 struct perf_sample_data sample;
7824 u16 header_size = namespaces_event->event_id.header.size;
7827 if (!perf_event_namespaces_match(event))
7830 perf_event_header__init_id(&namespaces_event->event_id.header,
7832 ret = perf_output_begin(&handle, &sample, event,
7833 namespaces_event->event_id.header.size);
7837 namespaces_event->event_id.pid = perf_event_pid(event,
7838 namespaces_event->task);
7839 namespaces_event->event_id.tid = perf_event_tid(event,
7840 namespaces_event->task);
7842 perf_output_put(&handle, namespaces_event->event_id);
7844 perf_event__output_id_sample(event, &handle, &sample);
7846 perf_output_end(&handle);
7848 namespaces_event->event_id.header.size = header_size;
7851 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7852 struct task_struct *task,
7853 const struct proc_ns_operations *ns_ops)
7855 struct path ns_path;
7856 struct inode *ns_inode;
7859 error = ns_get_path(&ns_path, task, ns_ops);
7861 ns_inode = ns_path.dentry->d_inode;
7862 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7863 ns_link_info->ino = ns_inode->i_ino;
7868 void perf_event_namespaces(struct task_struct *task)
7870 struct perf_namespaces_event namespaces_event;
7871 struct perf_ns_link_info *ns_link_info;
7873 if (!atomic_read(&nr_namespaces_events))
7876 namespaces_event = (struct perf_namespaces_event){
7880 .type = PERF_RECORD_NAMESPACES,
7882 .size = sizeof(namespaces_event.event_id),
7886 .nr_namespaces = NR_NAMESPACES,
7887 /* .link_info[NR_NAMESPACES] */
7891 ns_link_info = namespaces_event.event_id.link_info;
7893 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7894 task, &mntns_operations);
7896 #ifdef CONFIG_USER_NS
7897 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7898 task, &userns_operations);
7900 #ifdef CONFIG_NET_NS
7901 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7902 task, &netns_operations);
7904 #ifdef CONFIG_UTS_NS
7905 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7906 task, &utsns_operations);
7908 #ifdef CONFIG_IPC_NS
7909 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7910 task, &ipcns_operations);
7912 #ifdef CONFIG_PID_NS
7913 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7914 task, &pidns_operations);
7916 #ifdef CONFIG_CGROUPS
7917 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7918 task, &cgroupns_operations);
7921 perf_iterate_sb(perf_event_namespaces_output,
7929 #ifdef CONFIG_CGROUP_PERF
7931 struct perf_cgroup_event {
7935 struct perf_event_header header;
7941 static int perf_event_cgroup_match(struct perf_event *event)
7943 return event->attr.cgroup;
7946 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7948 struct perf_cgroup_event *cgroup_event = data;
7949 struct perf_output_handle handle;
7950 struct perf_sample_data sample;
7951 u16 header_size = cgroup_event->event_id.header.size;
7954 if (!perf_event_cgroup_match(event))
7957 perf_event_header__init_id(&cgroup_event->event_id.header,
7959 ret = perf_output_begin(&handle, &sample, event,
7960 cgroup_event->event_id.header.size);
7964 perf_output_put(&handle, cgroup_event->event_id);
7965 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7967 perf_event__output_id_sample(event, &handle, &sample);
7969 perf_output_end(&handle);
7971 cgroup_event->event_id.header.size = header_size;
7974 static void perf_event_cgroup(struct cgroup *cgrp)
7976 struct perf_cgroup_event cgroup_event;
7977 char path_enomem[16] = "//enomem";
7981 if (!atomic_read(&nr_cgroup_events))
7984 cgroup_event = (struct perf_cgroup_event){
7987 .type = PERF_RECORD_CGROUP,
7989 .size = sizeof(cgroup_event.event_id),
7991 .id = cgroup_id(cgrp),
7995 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7996 if (pathname == NULL) {
7997 cgroup_event.path = path_enomem;
7999 /* just to be sure to have enough space for alignment */
8000 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8001 cgroup_event.path = pathname;
8005 * Since our buffer works in 8 byte units we need to align our string
8006 * size to a multiple of 8. However, we must guarantee the tail end is
8007 * zero'd out to avoid leaking random bits to userspace.
8009 size = strlen(cgroup_event.path) + 1;
8010 while (!IS_ALIGNED(size, sizeof(u64)))
8011 cgroup_event.path[size++] = '\0';
8013 cgroup_event.event_id.header.size += size;
8014 cgroup_event.path_size = size;
8016 perf_iterate_sb(perf_event_cgroup_output,
8029 struct perf_mmap_event {
8030 struct vm_area_struct *vma;
8032 const char *file_name;
8038 u8 build_id[BUILD_ID_SIZE_MAX];
8042 struct perf_event_header header;
8052 static int perf_event_mmap_match(struct perf_event *event,
8055 struct perf_mmap_event *mmap_event = data;
8056 struct vm_area_struct *vma = mmap_event->vma;
8057 int executable = vma->vm_flags & VM_EXEC;
8059 return (!executable && event->attr.mmap_data) ||
8060 (executable && (event->attr.mmap || event->attr.mmap2));
8063 static void perf_event_mmap_output(struct perf_event *event,
8066 struct perf_mmap_event *mmap_event = data;
8067 struct perf_output_handle handle;
8068 struct perf_sample_data sample;
8069 int size = mmap_event->event_id.header.size;
8070 u32 type = mmap_event->event_id.header.type;
8074 if (!perf_event_mmap_match(event, data))
8077 if (event->attr.mmap2) {
8078 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8079 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8080 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8081 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8082 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8083 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8084 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8087 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8088 ret = perf_output_begin(&handle, &sample, event,
8089 mmap_event->event_id.header.size);
8093 mmap_event->event_id.pid = perf_event_pid(event, current);
8094 mmap_event->event_id.tid = perf_event_tid(event, current);
8096 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8098 if (event->attr.mmap2 && use_build_id)
8099 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8101 perf_output_put(&handle, mmap_event->event_id);
8103 if (event->attr.mmap2) {
8105 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8107 __output_copy(&handle, size, 4);
8108 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8110 perf_output_put(&handle, mmap_event->maj);
8111 perf_output_put(&handle, mmap_event->min);
8112 perf_output_put(&handle, mmap_event->ino);
8113 perf_output_put(&handle, mmap_event->ino_generation);
8115 perf_output_put(&handle, mmap_event->prot);
8116 perf_output_put(&handle, mmap_event->flags);
8119 __output_copy(&handle, mmap_event->file_name,
8120 mmap_event->file_size);
8122 perf_event__output_id_sample(event, &handle, &sample);
8124 perf_output_end(&handle);
8126 mmap_event->event_id.header.size = size;
8127 mmap_event->event_id.header.type = type;
8130 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8132 struct vm_area_struct *vma = mmap_event->vma;
8133 struct file *file = vma->vm_file;
8134 int maj = 0, min = 0;
8135 u64 ino = 0, gen = 0;
8136 u32 prot = 0, flags = 0;
8142 if (vma->vm_flags & VM_READ)
8144 if (vma->vm_flags & VM_WRITE)
8146 if (vma->vm_flags & VM_EXEC)
8149 if (vma->vm_flags & VM_MAYSHARE)
8152 flags = MAP_PRIVATE;
8154 if (vma->vm_flags & VM_DENYWRITE)
8155 flags |= MAP_DENYWRITE;
8156 if (vma->vm_flags & VM_MAYEXEC)
8157 flags |= MAP_EXECUTABLE;
8158 if (vma->vm_flags & VM_LOCKED)
8159 flags |= MAP_LOCKED;
8160 if (is_vm_hugetlb_page(vma))
8161 flags |= MAP_HUGETLB;
8164 struct inode *inode;
8167 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8173 * d_path() works from the end of the rb backwards, so we
8174 * need to add enough zero bytes after the string to handle
8175 * the 64bit alignment we do later.
8177 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8182 inode = file_inode(vma->vm_file);
8183 dev = inode->i_sb->s_dev;
8185 gen = inode->i_generation;
8191 if (vma->vm_ops && vma->vm_ops->name) {
8192 name = (char *) vma->vm_ops->name(vma);
8197 name = (char *)arch_vma_name(vma);
8201 if (vma->vm_start <= vma->vm_mm->start_brk &&
8202 vma->vm_end >= vma->vm_mm->brk) {
8206 if (vma->vm_start <= vma->vm_mm->start_stack &&
8207 vma->vm_end >= vma->vm_mm->start_stack) {
8217 strlcpy(tmp, name, sizeof(tmp));
8221 * Since our buffer works in 8 byte units we need to align our string
8222 * size to a multiple of 8. However, we must guarantee the tail end is
8223 * zero'd out to avoid leaking random bits to userspace.
8225 size = strlen(name)+1;
8226 while (!IS_ALIGNED(size, sizeof(u64)))
8227 name[size++] = '\0';
8229 mmap_event->file_name = name;
8230 mmap_event->file_size = size;
8231 mmap_event->maj = maj;
8232 mmap_event->min = min;
8233 mmap_event->ino = ino;
8234 mmap_event->ino_generation = gen;
8235 mmap_event->prot = prot;
8236 mmap_event->flags = flags;
8238 if (!(vma->vm_flags & VM_EXEC))
8239 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8241 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8243 if (atomic_read(&nr_build_id_events))
8244 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8246 perf_iterate_sb(perf_event_mmap_output,
8254 * Check whether inode and address range match filter criteria.
8256 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8257 struct file *file, unsigned long offset,
8260 /* d_inode(NULL) won't be equal to any mapped user-space file */
8261 if (!filter->path.dentry)
8264 if (d_inode(filter->path.dentry) != file_inode(file))
8267 if (filter->offset > offset + size)
8270 if (filter->offset + filter->size < offset)
8276 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8277 struct vm_area_struct *vma,
8278 struct perf_addr_filter_range *fr)
8280 unsigned long vma_size = vma->vm_end - vma->vm_start;
8281 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8282 struct file *file = vma->vm_file;
8284 if (!perf_addr_filter_match(filter, file, off, vma_size))
8287 if (filter->offset < off) {
8288 fr->start = vma->vm_start;
8289 fr->size = min(vma_size, filter->size - (off - filter->offset));
8291 fr->start = vma->vm_start + filter->offset - off;
8292 fr->size = min(vma->vm_end - fr->start, filter->size);
8298 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8300 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8301 struct vm_area_struct *vma = data;
8302 struct perf_addr_filter *filter;
8303 unsigned int restart = 0, count = 0;
8304 unsigned long flags;
8306 if (!has_addr_filter(event))
8312 raw_spin_lock_irqsave(&ifh->lock, flags);
8313 list_for_each_entry(filter, &ifh->list, entry) {
8314 if (perf_addr_filter_vma_adjust(filter, vma,
8315 &event->addr_filter_ranges[count]))
8322 event->addr_filters_gen++;
8323 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8326 perf_event_stop(event, 1);
8330 * Adjust all task's events' filters to the new vma
8332 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8334 struct perf_event_context *ctx;
8338 * Data tracing isn't supported yet and as such there is no need
8339 * to keep track of anything that isn't related to executable code:
8341 if (!(vma->vm_flags & VM_EXEC))
8345 for_each_task_context_nr(ctxn) {
8346 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8350 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8355 void perf_event_mmap(struct vm_area_struct *vma)
8357 struct perf_mmap_event mmap_event;
8359 if (!atomic_read(&nr_mmap_events))
8362 mmap_event = (struct perf_mmap_event){
8368 .type = PERF_RECORD_MMAP,
8369 .misc = PERF_RECORD_MISC_USER,
8374 .start = vma->vm_start,
8375 .len = vma->vm_end - vma->vm_start,
8376 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8378 /* .maj (attr_mmap2 only) */
8379 /* .min (attr_mmap2 only) */
8380 /* .ino (attr_mmap2 only) */
8381 /* .ino_generation (attr_mmap2 only) */
8382 /* .prot (attr_mmap2 only) */
8383 /* .flags (attr_mmap2 only) */
8386 perf_addr_filters_adjust(vma);
8387 perf_event_mmap_event(&mmap_event);
8390 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8391 unsigned long size, u64 flags)
8393 struct perf_output_handle handle;
8394 struct perf_sample_data sample;
8395 struct perf_aux_event {
8396 struct perf_event_header header;
8402 .type = PERF_RECORD_AUX,
8404 .size = sizeof(rec),
8412 perf_event_header__init_id(&rec.header, &sample, event);
8413 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8418 perf_output_put(&handle, rec);
8419 perf_event__output_id_sample(event, &handle, &sample);
8421 perf_output_end(&handle);
8425 * Lost/dropped samples logging
8427 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8429 struct perf_output_handle handle;
8430 struct perf_sample_data sample;
8434 struct perf_event_header header;
8436 } lost_samples_event = {
8438 .type = PERF_RECORD_LOST_SAMPLES,
8440 .size = sizeof(lost_samples_event),
8445 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8447 ret = perf_output_begin(&handle, &sample, event,
8448 lost_samples_event.header.size);
8452 perf_output_put(&handle, lost_samples_event);
8453 perf_event__output_id_sample(event, &handle, &sample);
8454 perf_output_end(&handle);
8458 * context_switch tracking
8461 struct perf_switch_event {
8462 struct task_struct *task;
8463 struct task_struct *next_prev;
8466 struct perf_event_header header;
8472 static int perf_event_switch_match(struct perf_event *event)
8474 return event->attr.context_switch;
8477 static void perf_event_switch_output(struct perf_event *event, void *data)
8479 struct perf_switch_event *se = data;
8480 struct perf_output_handle handle;
8481 struct perf_sample_data sample;
8484 if (!perf_event_switch_match(event))
8487 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8488 if (event->ctx->task) {
8489 se->event_id.header.type = PERF_RECORD_SWITCH;
8490 se->event_id.header.size = sizeof(se->event_id.header);
8492 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8493 se->event_id.header.size = sizeof(se->event_id);
8494 se->event_id.next_prev_pid =
8495 perf_event_pid(event, se->next_prev);
8496 se->event_id.next_prev_tid =
8497 perf_event_tid(event, se->next_prev);
8500 perf_event_header__init_id(&se->event_id.header, &sample, event);
8502 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8506 if (event->ctx->task)
8507 perf_output_put(&handle, se->event_id.header);
8509 perf_output_put(&handle, se->event_id);
8511 perf_event__output_id_sample(event, &handle, &sample);
8513 perf_output_end(&handle);
8516 static void perf_event_switch(struct task_struct *task,
8517 struct task_struct *next_prev, bool sched_in)
8519 struct perf_switch_event switch_event;
8521 /* N.B. caller checks nr_switch_events != 0 */
8523 switch_event = (struct perf_switch_event){
8525 .next_prev = next_prev,
8529 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8532 /* .next_prev_pid */
8533 /* .next_prev_tid */
8537 if (!sched_in && task->state == TASK_RUNNING)
8538 switch_event.event_id.header.misc |=
8539 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8541 perf_iterate_sb(perf_event_switch_output,
8547 * IRQ throttle logging
8550 static void perf_log_throttle(struct perf_event *event, int enable)
8552 struct perf_output_handle handle;
8553 struct perf_sample_data sample;
8557 struct perf_event_header header;
8561 } throttle_event = {
8563 .type = PERF_RECORD_THROTTLE,
8565 .size = sizeof(throttle_event),
8567 .time = perf_event_clock(event),
8568 .id = primary_event_id(event),
8569 .stream_id = event->id,
8573 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8575 perf_event_header__init_id(&throttle_event.header, &sample, event);
8577 ret = perf_output_begin(&handle, &sample, event,
8578 throttle_event.header.size);
8582 perf_output_put(&handle, throttle_event);
8583 perf_event__output_id_sample(event, &handle, &sample);
8584 perf_output_end(&handle);
8588 * ksymbol register/unregister tracking
8591 struct perf_ksymbol_event {
8595 struct perf_event_header header;
8603 static int perf_event_ksymbol_match(struct perf_event *event)
8605 return event->attr.ksymbol;
8608 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8610 struct perf_ksymbol_event *ksymbol_event = data;
8611 struct perf_output_handle handle;
8612 struct perf_sample_data sample;
8615 if (!perf_event_ksymbol_match(event))
8618 perf_event_header__init_id(&ksymbol_event->event_id.header,
8620 ret = perf_output_begin(&handle, &sample, event,
8621 ksymbol_event->event_id.header.size);
8625 perf_output_put(&handle, ksymbol_event->event_id);
8626 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8627 perf_event__output_id_sample(event, &handle, &sample);
8629 perf_output_end(&handle);
8632 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8635 struct perf_ksymbol_event ksymbol_event;
8636 char name[KSYM_NAME_LEN];
8640 if (!atomic_read(&nr_ksymbol_events))
8643 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8644 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8647 strlcpy(name, sym, KSYM_NAME_LEN);
8648 name_len = strlen(name) + 1;
8649 while (!IS_ALIGNED(name_len, sizeof(u64)))
8650 name[name_len++] = '\0';
8651 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8654 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8656 ksymbol_event = (struct perf_ksymbol_event){
8658 .name_len = name_len,
8661 .type = PERF_RECORD_KSYMBOL,
8662 .size = sizeof(ksymbol_event.event_id) +
8667 .ksym_type = ksym_type,
8672 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8675 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8679 * bpf program load/unload tracking
8682 struct perf_bpf_event {
8683 struct bpf_prog *prog;
8685 struct perf_event_header header;
8689 u8 tag[BPF_TAG_SIZE];
8693 static int perf_event_bpf_match(struct perf_event *event)
8695 return event->attr.bpf_event;
8698 static void perf_event_bpf_output(struct perf_event *event, void *data)
8700 struct perf_bpf_event *bpf_event = data;
8701 struct perf_output_handle handle;
8702 struct perf_sample_data sample;
8705 if (!perf_event_bpf_match(event))
8708 perf_event_header__init_id(&bpf_event->event_id.header,
8710 ret = perf_output_begin(&handle, data, event,
8711 bpf_event->event_id.header.size);
8715 perf_output_put(&handle, bpf_event->event_id);
8716 perf_event__output_id_sample(event, &handle, &sample);
8718 perf_output_end(&handle);
8721 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8722 enum perf_bpf_event_type type)
8724 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8727 if (prog->aux->func_cnt == 0) {
8728 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8729 (u64)(unsigned long)prog->bpf_func,
8730 prog->jited_len, unregister,
8731 prog->aux->ksym.name);
8733 for (i = 0; i < prog->aux->func_cnt; i++) {
8734 struct bpf_prog *subprog = prog->aux->func[i];
8737 PERF_RECORD_KSYMBOL_TYPE_BPF,
8738 (u64)(unsigned long)subprog->bpf_func,
8739 subprog->jited_len, unregister,
8740 prog->aux->ksym.name);
8745 void perf_event_bpf_event(struct bpf_prog *prog,
8746 enum perf_bpf_event_type type,
8749 struct perf_bpf_event bpf_event;
8751 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8752 type >= PERF_BPF_EVENT_MAX)
8756 case PERF_BPF_EVENT_PROG_LOAD:
8757 case PERF_BPF_EVENT_PROG_UNLOAD:
8758 if (atomic_read(&nr_ksymbol_events))
8759 perf_event_bpf_emit_ksymbols(prog, type);
8765 if (!atomic_read(&nr_bpf_events))
8768 bpf_event = (struct perf_bpf_event){
8772 .type = PERF_RECORD_BPF_EVENT,
8773 .size = sizeof(bpf_event.event_id),
8777 .id = prog->aux->id,
8781 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8783 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8784 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8787 struct perf_text_poke_event {
8788 const void *old_bytes;
8789 const void *new_bytes;
8795 struct perf_event_header header;
8801 static int perf_event_text_poke_match(struct perf_event *event)
8803 return event->attr.text_poke;
8806 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8808 struct perf_text_poke_event *text_poke_event = data;
8809 struct perf_output_handle handle;
8810 struct perf_sample_data sample;
8814 if (!perf_event_text_poke_match(event))
8817 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8819 ret = perf_output_begin(&handle, &sample, event,
8820 text_poke_event->event_id.header.size);
8824 perf_output_put(&handle, text_poke_event->event_id);
8825 perf_output_put(&handle, text_poke_event->old_len);
8826 perf_output_put(&handle, text_poke_event->new_len);
8828 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8829 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8831 if (text_poke_event->pad)
8832 __output_copy(&handle, &padding, text_poke_event->pad);
8834 perf_event__output_id_sample(event, &handle, &sample);
8836 perf_output_end(&handle);
8839 void perf_event_text_poke(const void *addr, const void *old_bytes,
8840 size_t old_len, const void *new_bytes, size_t new_len)
8842 struct perf_text_poke_event text_poke_event;
8845 if (!atomic_read(&nr_text_poke_events))
8848 tot = sizeof(text_poke_event.old_len) + old_len;
8849 tot += sizeof(text_poke_event.new_len) + new_len;
8850 pad = ALIGN(tot, sizeof(u64)) - tot;
8852 text_poke_event = (struct perf_text_poke_event){
8853 .old_bytes = old_bytes,
8854 .new_bytes = new_bytes,
8860 .type = PERF_RECORD_TEXT_POKE,
8861 .misc = PERF_RECORD_MISC_KERNEL,
8862 .size = sizeof(text_poke_event.event_id) + tot + pad,
8864 .addr = (unsigned long)addr,
8868 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8871 void perf_event_itrace_started(struct perf_event *event)
8873 event->attach_state |= PERF_ATTACH_ITRACE;
8876 static void perf_log_itrace_start(struct perf_event *event)
8878 struct perf_output_handle handle;
8879 struct perf_sample_data sample;
8880 struct perf_aux_event {
8881 struct perf_event_header header;
8888 event = event->parent;
8890 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8891 event->attach_state & PERF_ATTACH_ITRACE)
8894 rec.header.type = PERF_RECORD_ITRACE_START;
8895 rec.header.misc = 0;
8896 rec.header.size = sizeof(rec);
8897 rec.pid = perf_event_pid(event, current);
8898 rec.tid = perf_event_tid(event, current);
8900 perf_event_header__init_id(&rec.header, &sample, event);
8901 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8906 perf_output_put(&handle, rec);
8907 perf_event__output_id_sample(event, &handle, &sample);
8909 perf_output_end(&handle);
8913 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8915 struct hw_perf_event *hwc = &event->hw;
8919 seq = __this_cpu_read(perf_throttled_seq);
8920 if (seq != hwc->interrupts_seq) {
8921 hwc->interrupts_seq = seq;
8922 hwc->interrupts = 1;
8925 if (unlikely(throttle
8926 && hwc->interrupts >= max_samples_per_tick)) {
8927 __this_cpu_inc(perf_throttled_count);
8928 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8929 hwc->interrupts = MAX_INTERRUPTS;
8930 perf_log_throttle(event, 0);
8935 if (event->attr.freq) {
8936 u64 now = perf_clock();
8937 s64 delta = now - hwc->freq_time_stamp;
8939 hwc->freq_time_stamp = now;
8941 if (delta > 0 && delta < 2*TICK_NSEC)
8942 perf_adjust_period(event, delta, hwc->last_period, true);
8948 int perf_event_account_interrupt(struct perf_event *event)
8950 return __perf_event_account_interrupt(event, 1);
8954 * Generic event overflow handling, sampling.
8957 static int __perf_event_overflow(struct perf_event *event,
8958 int throttle, struct perf_sample_data *data,
8959 struct pt_regs *regs)
8961 int events = atomic_read(&event->event_limit);
8965 * Non-sampling counters might still use the PMI to fold short
8966 * hardware counters, ignore those.
8968 if (unlikely(!is_sampling_event(event)))
8971 ret = __perf_event_account_interrupt(event, throttle);
8974 * XXX event_limit might not quite work as expected on inherited
8978 event->pending_kill = POLL_IN;
8979 if (events && atomic_dec_and_test(&event->event_limit)) {
8981 event->pending_kill = POLL_HUP;
8983 perf_event_disable_inatomic(event);
8986 READ_ONCE(event->overflow_handler)(event, data, regs);
8988 if (*perf_event_fasync(event) && event->pending_kill) {
8989 event->pending_wakeup = 1;
8990 irq_work_queue(&event->pending);
8996 int perf_event_overflow(struct perf_event *event,
8997 struct perf_sample_data *data,
8998 struct pt_regs *regs)
9000 return __perf_event_overflow(event, 1, data, regs);
9004 * Generic software event infrastructure
9007 struct swevent_htable {
9008 struct swevent_hlist *swevent_hlist;
9009 struct mutex hlist_mutex;
9012 /* Recursion avoidance in each contexts */
9013 int recursion[PERF_NR_CONTEXTS];
9016 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9019 * We directly increment event->count and keep a second value in
9020 * event->hw.period_left to count intervals. This period event
9021 * is kept in the range [-sample_period, 0] so that we can use the
9025 u64 perf_swevent_set_period(struct perf_event *event)
9027 struct hw_perf_event *hwc = &event->hw;
9028 u64 period = hwc->last_period;
9032 hwc->last_period = hwc->sample_period;
9035 old = val = local64_read(&hwc->period_left);
9039 nr = div64_u64(period + val, period);
9040 offset = nr * period;
9042 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9048 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9049 struct perf_sample_data *data,
9050 struct pt_regs *regs)
9052 struct hw_perf_event *hwc = &event->hw;
9056 overflow = perf_swevent_set_period(event);
9058 if (hwc->interrupts == MAX_INTERRUPTS)
9061 for (; overflow; overflow--) {
9062 if (__perf_event_overflow(event, throttle,
9065 * We inhibit the overflow from happening when
9066 * hwc->interrupts == MAX_INTERRUPTS.
9074 static void perf_swevent_event(struct perf_event *event, u64 nr,
9075 struct perf_sample_data *data,
9076 struct pt_regs *regs)
9078 struct hw_perf_event *hwc = &event->hw;
9080 local64_add(nr, &event->count);
9085 if (!is_sampling_event(event))
9088 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9090 return perf_swevent_overflow(event, 1, data, regs);
9092 data->period = event->hw.last_period;
9094 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9095 return perf_swevent_overflow(event, 1, data, regs);
9097 if (local64_add_negative(nr, &hwc->period_left))
9100 perf_swevent_overflow(event, 0, data, regs);
9103 static int perf_exclude_event(struct perf_event *event,
9104 struct pt_regs *regs)
9106 if (event->hw.state & PERF_HES_STOPPED)
9110 if (event->attr.exclude_user && user_mode(regs))
9113 if (event->attr.exclude_kernel && !user_mode(regs))
9120 static int perf_swevent_match(struct perf_event *event,
9121 enum perf_type_id type,
9123 struct perf_sample_data *data,
9124 struct pt_regs *regs)
9126 if (event->attr.type != type)
9129 if (event->attr.config != event_id)
9132 if (perf_exclude_event(event, regs))
9138 static inline u64 swevent_hash(u64 type, u32 event_id)
9140 u64 val = event_id | (type << 32);
9142 return hash_64(val, SWEVENT_HLIST_BITS);
9145 static inline struct hlist_head *
9146 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9148 u64 hash = swevent_hash(type, event_id);
9150 return &hlist->heads[hash];
9153 /* For the read side: events when they trigger */
9154 static inline struct hlist_head *
9155 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9157 struct swevent_hlist *hlist;
9159 hlist = rcu_dereference(swhash->swevent_hlist);
9163 return __find_swevent_head(hlist, type, event_id);
9166 /* For the event head insertion and removal in the hlist */
9167 static inline struct hlist_head *
9168 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9170 struct swevent_hlist *hlist;
9171 u32 event_id = event->attr.config;
9172 u64 type = event->attr.type;
9175 * Event scheduling is always serialized against hlist allocation
9176 * and release. Which makes the protected version suitable here.
9177 * The context lock guarantees that.
9179 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9180 lockdep_is_held(&event->ctx->lock));
9184 return __find_swevent_head(hlist, type, event_id);
9187 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9189 struct perf_sample_data *data,
9190 struct pt_regs *regs)
9192 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9193 struct perf_event *event;
9194 struct hlist_head *head;
9197 head = find_swevent_head_rcu(swhash, type, event_id);
9201 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9202 if (perf_swevent_match(event, type, event_id, data, regs))
9203 perf_swevent_event(event, nr, data, regs);
9209 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9211 int perf_swevent_get_recursion_context(void)
9213 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9215 return get_recursion_context(swhash->recursion);
9217 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9219 void perf_swevent_put_recursion_context(int rctx)
9221 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9223 put_recursion_context(swhash->recursion, rctx);
9226 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9228 struct perf_sample_data data;
9230 if (WARN_ON_ONCE(!regs))
9233 perf_sample_data_init(&data, addr, 0);
9234 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9237 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9241 preempt_disable_notrace();
9242 rctx = perf_swevent_get_recursion_context();
9243 if (unlikely(rctx < 0))
9246 ___perf_sw_event(event_id, nr, regs, addr);
9248 perf_swevent_put_recursion_context(rctx);
9250 preempt_enable_notrace();
9253 static void perf_swevent_read(struct perf_event *event)
9257 static int perf_swevent_add(struct perf_event *event, int flags)
9259 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9260 struct hw_perf_event *hwc = &event->hw;
9261 struct hlist_head *head;
9263 if (is_sampling_event(event)) {
9264 hwc->last_period = hwc->sample_period;
9265 perf_swevent_set_period(event);
9268 hwc->state = !(flags & PERF_EF_START);
9270 head = find_swevent_head(swhash, event);
9271 if (WARN_ON_ONCE(!head))
9274 hlist_add_head_rcu(&event->hlist_entry, head);
9275 perf_event_update_userpage(event);
9280 static void perf_swevent_del(struct perf_event *event, int flags)
9282 hlist_del_rcu(&event->hlist_entry);
9285 static void perf_swevent_start(struct perf_event *event, int flags)
9287 event->hw.state = 0;
9290 static void perf_swevent_stop(struct perf_event *event, int flags)
9292 event->hw.state = PERF_HES_STOPPED;
9295 /* Deref the hlist from the update side */
9296 static inline struct swevent_hlist *
9297 swevent_hlist_deref(struct swevent_htable *swhash)
9299 return rcu_dereference_protected(swhash->swevent_hlist,
9300 lockdep_is_held(&swhash->hlist_mutex));
9303 static void swevent_hlist_release(struct swevent_htable *swhash)
9305 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9310 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9311 kfree_rcu(hlist, rcu_head);
9314 static void swevent_hlist_put_cpu(int cpu)
9316 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9318 mutex_lock(&swhash->hlist_mutex);
9320 if (!--swhash->hlist_refcount)
9321 swevent_hlist_release(swhash);
9323 mutex_unlock(&swhash->hlist_mutex);
9326 static void swevent_hlist_put(void)
9330 for_each_possible_cpu(cpu)
9331 swevent_hlist_put_cpu(cpu);
9334 static int swevent_hlist_get_cpu(int cpu)
9336 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9339 mutex_lock(&swhash->hlist_mutex);
9340 if (!swevent_hlist_deref(swhash) &&
9341 cpumask_test_cpu(cpu, perf_online_mask)) {
9342 struct swevent_hlist *hlist;
9344 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9349 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9351 swhash->hlist_refcount++;
9353 mutex_unlock(&swhash->hlist_mutex);
9358 static int swevent_hlist_get(void)
9360 int err, cpu, failed_cpu;
9362 mutex_lock(&pmus_lock);
9363 for_each_possible_cpu(cpu) {
9364 err = swevent_hlist_get_cpu(cpu);
9370 mutex_unlock(&pmus_lock);
9373 for_each_possible_cpu(cpu) {
9374 if (cpu == failed_cpu)
9376 swevent_hlist_put_cpu(cpu);
9378 mutex_unlock(&pmus_lock);
9382 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9384 static void sw_perf_event_destroy(struct perf_event *event)
9386 u64 event_id = event->attr.config;
9388 WARN_ON(event->parent);
9390 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9391 swevent_hlist_put();
9394 static int perf_swevent_init(struct perf_event *event)
9396 u64 event_id = event->attr.config;
9398 if (event->attr.type != PERF_TYPE_SOFTWARE)
9402 * no branch sampling for software events
9404 if (has_branch_stack(event))
9408 case PERF_COUNT_SW_CPU_CLOCK:
9409 case PERF_COUNT_SW_TASK_CLOCK:
9416 if (event_id >= PERF_COUNT_SW_MAX)
9419 if (!event->parent) {
9422 err = swevent_hlist_get();
9426 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9427 event->destroy = sw_perf_event_destroy;
9433 static struct pmu perf_swevent = {
9434 .task_ctx_nr = perf_sw_context,
9436 .capabilities = PERF_PMU_CAP_NO_NMI,
9438 .event_init = perf_swevent_init,
9439 .add = perf_swevent_add,
9440 .del = perf_swevent_del,
9441 .start = perf_swevent_start,
9442 .stop = perf_swevent_stop,
9443 .read = perf_swevent_read,
9446 #ifdef CONFIG_EVENT_TRACING
9448 static int perf_tp_filter_match(struct perf_event *event,
9449 struct perf_sample_data *data)
9451 void *record = data->raw->frag.data;
9453 /* only top level events have filters set */
9455 event = event->parent;
9457 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9462 static int perf_tp_event_match(struct perf_event *event,
9463 struct perf_sample_data *data,
9464 struct pt_regs *regs)
9466 if (event->hw.state & PERF_HES_STOPPED)
9469 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9471 if (event->attr.exclude_kernel && !user_mode(regs))
9474 if (!perf_tp_filter_match(event, data))
9480 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9481 struct trace_event_call *call, u64 count,
9482 struct pt_regs *regs, struct hlist_head *head,
9483 struct task_struct *task)
9485 if (bpf_prog_array_valid(call)) {
9486 *(struct pt_regs **)raw_data = regs;
9487 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9488 perf_swevent_put_recursion_context(rctx);
9492 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9495 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9497 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9498 struct pt_regs *regs, struct hlist_head *head, int rctx,
9499 struct task_struct *task)
9501 struct perf_sample_data data;
9502 struct perf_event *event;
9504 struct perf_raw_record raw = {
9511 perf_sample_data_init(&data, 0, 0);
9514 perf_trace_buf_update(record, event_type);
9516 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9517 if (perf_tp_event_match(event, &data, regs))
9518 perf_swevent_event(event, count, &data, regs);
9522 * If we got specified a target task, also iterate its context and
9523 * deliver this event there too.
9525 if (task && task != current) {
9526 struct perf_event_context *ctx;
9527 struct trace_entry *entry = record;
9530 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9534 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9535 if (event->cpu != smp_processor_id())
9537 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9539 if (event->attr.config != entry->type)
9541 if (perf_tp_event_match(event, &data, regs))
9542 perf_swevent_event(event, count, &data, regs);
9548 perf_swevent_put_recursion_context(rctx);
9550 EXPORT_SYMBOL_GPL(perf_tp_event);
9552 static void tp_perf_event_destroy(struct perf_event *event)
9554 perf_trace_destroy(event);
9557 static int perf_tp_event_init(struct perf_event *event)
9561 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9565 * no branch sampling for tracepoint events
9567 if (has_branch_stack(event))
9570 err = perf_trace_init(event);
9574 event->destroy = tp_perf_event_destroy;
9579 static struct pmu perf_tracepoint = {
9580 .task_ctx_nr = perf_sw_context,
9582 .event_init = perf_tp_event_init,
9583 .add = perf_trace_add,
9584 .del = perf_trace_del,
9585 .start = perf_swevent_start,
9586 .stop = perf_swevent_stop,
9587 .read = perf_swevent_read,
9590 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9592 * Flags in config, used by dynamic PMU kprobe and uprobe
9593 * The flags should match following PMU_FORMAT_ATTR().
9595 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9596 * if not set, create kprobe/uprobe
9598 * The following values specify a reference counter (or semaphore in the
9599 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9600 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9602 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9603 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9605 enum perf_probe_config {
9606 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9607 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9608 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9611 PMU_FORMAT_ATTR(retprobe, "config:0");
9614 #ifdef CONFIG_KPROBE_EVENTS
9615 static struct attribute *kprobe_attrs[] = {
9616 &format_attr_retprobe.attr,
9620 static struct attribute_group kprobe_format_group = {
9622 .attrs = kprobe_attrs,
9625 static const struct attribute_group *kprobe_attr_groups[] = {
9626 &kprobe_format_group,
9630 static int perf_kprobe_event_init(struct perf_event *event);
9631 static struct pmu perf_kprobe = {
9632 .task_ctx_nr = perf_sw_context,
9633 .event_init = perf_kprobe_event_init,
9634 .add = perf_trace_add,
9635 .del = perf_trace_del,
9636 .start = perf_swevent_start,
9637 .stop = perf_swevent_stop,
9638 .read = perf_swevent_read,
9639 .attr_groups = kprobe_attr_groups,
9642 static int perf_kprobe_event_init(struct perf_event *event)
9647 if (event->attr.type != perf_kprobe.type)
9650 if (!perfmon_capable())
9654 * no branch sampling for probe events
9656 if (has_branch_stack(event))
9659 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9660 err = perf_kprobe_init(event, is_retprobe);
9664 event->destroy = perf_kprobe_destroy;
9668 #endif /* CONFIG_KPROBE_EVENTS */
9670 #ifdef CONFIG_UPROBE_EVENTS
9671 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9673 static struct attribute *uprobe_attrs[] = {
9674 &format_attr_retprobe.attr,
9675 &format_attr_ref_ctr_offset.attr,
9679 static struct attribute_group uprobe_format_group = {
9681 .attrs = uprobe_attrs,
9684 static const struct attribute_group *uprobe_attr_groups[] = {
9685 &uprobe_format_group,
9689 static int perf_uprobe_event_init(struct perf_event *event);
9690 static struct pmu perf_uprobe = {
9691 .task_ctx_nr = perf_sw_context,
9692 .event_init = perf_uprobe_event_init,
9693 .add = perf_trace_add,
9694 .del = perf_trace_del,
9695 .start = perf_swevent_start,
9696 .stop = perf_swevent_stop,
9697 .read = perf_swevent_read,
9698 .attr_groups = uprobe_attr_groups,
9701 static int perf_uprobe_event_init(struct perf_event *event)
9704 unsigned long ref_ctr_offset;
9707 if (event->attr.type != perf_uprobe.type)
9710 if (!perfmon_capable())
9714 * no branch sampling for probe events
9716 if (has_branch_stack(event))
9719 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9720 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9721 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9725 event->destroy = perf_uprobe_destroy;
9729 #endif /* CONFIG_UPROBE_EVENTS */
9731 static inline void perf_tp_register(void)
9733 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9734 #ifdef CONFIG_KPROBE_EVENTS
9735 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9737 #ifdef CONFIG_UPROBE_EVENTS
9738 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9742 static void perf_event_free_filter(struct perf_event *event)
9744 ftrace_profile_free_filter(event);
9747 #ifdef CONFIG_BPF_SYSCALL
9748 static void bpf_overflow_handler(struct perf_event *event,
9749 struct perf_sample_data *data,
9750 struct pt_regs *regs)
9752 struct bpf_perf_event_data_kern ctx = {
9758 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9759 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9762 ret = BPF_PROG_RUN(event->prog, &ctx);
9765 __this_cpu_dec(bpf_prog_active);
9769 event->orig_overflow_handler(event, data, regs);
9772 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9774 struct bpf_prog *prog;
9776 if (event->overflow_handler_context)
9777 /* hw breakpoint or kernel counter */
9783 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9785 return PTR_ERR(prog);
9787 if (event->attr.precise_ip &&
9788 prog->call_get_stack &&
9789 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9790 event->attr.exclude_callchain_kernel ||
9791 event->attr.exclude_callchain_user)) {
9793 * On perf_event with precise_ip, calling bpf_get_stack()
9794 * may trigger unwinder warnings and occasional crashes.
9795 * bpf_get_[stack|stackid] works around this issue by using
9796 * callchain attached to perf_sample_data. If the
9797 * perf_event does not full (kernel and user) callchain
9798 * attached to perf_sample_data, do not allow attaching BPF
9799 * program that calls bpf_get_[stack|stackid].
9806 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9807 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9811 static void perf_event_free_bpf_handler(struct perf_event *event)
9813 struct bpf_prog *prog = event->prog;
9818 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9823 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9827 static void perf_event_free_bpf_handler(struct perf_event *event)
9833 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9834 * with perf_event_open()
9836 static inline bool perf_event_is_tracing(struct perf_event *event)
9838 if (event->pmu == &perf_tracepoint)
9840 #ifdef CONFIG_KPROBE_EVENTS
9841 if (event->pmu == &perf_kprobe)
9844 #ifdef CONFIG_UPROBE_EVENTS
9845 if (event->pmu == &perf_uprobe)
9851 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9853 bool is_kprobe, is_tracepoint, is_syscall_tp;
9854 struct bpf_prog *prog;
9857 if (!perf_event_is_tracing(event))
9858 return perf_event_set_bpf_handler(event, prog_fd);
9860 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9861 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9862 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9863 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9864 /* bpf programs can only be attached to u/kprobe or tracepoint */
9867 prog = bpf_prog_get(prog_fd);
9869 return PTR_ERR(prog);
9871 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9872 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9873 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9874 /* valid fd, but invalid bpf program type */
9879 /* Kprobe override only works for kprobes, not uprobes. */
9880 if (prog->kprobe_override &&
9881 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9886 if (is_tracepoint || is_syscall_tp) {
9887 int off = trace_event_get_offsets(event->tp_event);
9889 if (prog->aux->max_ctx_offset > off) {
9895 ret = perf_event_attach_bpf_prog(event, prog);
9901 static void perf_event_free_bpf_prog(struct perf_event *event)
9903 if (!perf_event_is_tracing(event)) {
9904 perf_event_free_bpf_handler(event);
9907 perf_event_detach_bpf_prog(event);
9912 static inline void perf_tp_register(void)
9916 static void perf_event_free_filter(struct perf_event *event)
9920 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9925 static void perf_event_free_bpf_prog(struct perf_event *event)
9928 #endif /* CONFIG_EVENT_TRACING */
9930 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9931 void perf_bp_event(struct perf_event *bp, void *data)
9933 struct perf_sample_data sample;
9934 struct pt_regs *regs = data;
9936 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9938 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9939 perf_swevent_event(bp, 1, &sample, regs);
9944 * Allocate a new address filter
9946 static struct perf_addr_filter *
9947 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9949 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9950 struct perf_addr_filter *filter;
9952 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9956 INIT_LIST_HEAD(&filter->entry);
9957 list_add_tail(&filter->entry, filters);
9962 static void free_filters_list(struct list_head *filters)
9964 struct perf_addr_filter *filter, *iter;
9966 list_for_each_entry_safe(filter, iter, filters, entry) {
9967 path_put(&filter->path);
9968 list_del(&filter->entry);
9974 * Free existing address filters and optionally install new ones
9976 static void perf_addr_filters_splice(struct perf_event *event,
9977 struct list_head *head)
9979 unsigned long flags;
9982 if (!has_addr_filter(event))
9985 /* don't bother with children, they don't have their own filters */
9989 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9991 list_splice_init(&event->addr_filters.list, &list);
9993 list_splice(head, &event->addr_filters.list);
9995 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9997 free_filters_list(&list);
10001 * Scan through mm's vmas and see if one of them matches the
10002 * @filter; if so, adjust filter's address range.
10003 * Called with mm::mmap_lock down for reading.
10005 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10006 struct mm_struct *mm,
10007 struct perf_addr_filter_range *fr)
10009 struct vm_area_struct *vma;
10011 for (vma = mm->mmap; vma; vma = vma->vm_next) {
10015 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10021 * Update event's address range filters based on the
10022 * task's existing mappings, if any.
10024 static void perf_event_addr_filters_apply(struct perf_event *event)
10026 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10027 struct task_struct *task = READ_ONCE(event->ctx->task);
10028 struct perf_addr_filter *filter;
10029 struct mm_struct *mm = NULL;
10030 unsigned int count = 0;
10031 unsigned long flags;
10034 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10035 * will stop on the parent's child_mutex that our caller is also holding
10037 if (task == TASK_TOMBSTONE)
10040 if (ifh->nr_file_filters) {
10041 mm = get_task_mm(event->ctx->task);
10045 mmap_read_lock(mm);
10048 raw_spin_lock_irqsave(&ifh->lock, flags);
10049 list_for_each_entry(filter, &ifh->list, entry) {
10050 if (filter->path.dentry) {
10052 * Adjust base offset if the filter is associated to a
10053 * binary that needs to be mapped:
10055 event->addr_filter_ranges[count].start = 0;
10056 event->addr_filter_ranges[count].size = 0;
10058 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10060 event->addr_filter_ranges[count].start = filter->offset;
10061 event->addr_filter_ranges[count].size = filter->size;
10067 event->addr_filters_gen++;
10068 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10070 if (ifh->nr_file_filters) {
10071 mmap_read_unlock(mm);
10077 perf_event_stop(event, 1);
10081 * Address range filtering: limiting the data to certain
10082 * instruction address ranges. Filters are ioctl()ed to us from
10083 * userspace as ascii strings.
10085 * Filter string format:
10087 * ACTION RANGE_SPEC
10088 * where ACTION is one of the
10089 * * "filter": limit the trace to this region
10090 * * "start": start tracing from this address
10091 * * "stop": stop tracing at this address/region;
10093 * * for kernel addresses: <start address>[/<size>]
10094 * * for object files: <start address>[/<size>]@</path/to/object/file>
10096 * if <size> is not specified or is zero, the range is treated as a single
10097 * address; not valid for ACTION=="filter".
10111 IF_STATE_ACTION = 0,
10116 static const match_table_t if_tokens = {
10117 { IF_ACT_FILTER, "filter" },
10118 { IF_ACT_START, "start" },
10119 { IF_ACT_STOP, "stop" },
10120 { IF_SRC_FILE, "%u/%u@%s" },
10121 { IF_SRC_KERNEL, "%u/%u" },
10122 { IF_SRC_FILEADDR, "%u@%s" },
10123 { IF_SRC_KERNELADDR, "%u" },
10124 { IF_ACT_NONE, NULL },
10128 * Address filter string parser
10131 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10132 struct list_head *filters)
10134 struct perf_addr_filter *filter = NULL;
10135 char *start, *orig, *filename = NULL;
10136 substring_t args[MAX_OPT_ARGS];
10137 int state = IF_STATE_ACTION, token;
10138 unsigned int kernel = 0;
10141 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10145 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10146 static const enum perf_addr_filter_action_t actions[] = {
10147 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10148 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10149 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10156 /* filter definition begins */
10157 if (state == IF_STATE_ACTION) {
10158 filter = perf_addr_filter_new(event, filters);
10163 token = match_token(start, if_tokens, args);
10165 case IF_ACT_FILTER:
10168 if (state != IF_STATE_ACTION)
10171 filter->action = actions[token];
10172 state = IF_STATE_SOURCE;
10175 case IF_SRC_KERNELADDR:
10176 case IF_SRC_KERNEL:
10180 case IF_SRC_FILEADDR:
10182 if (state != IF_STATE_SOURCE)
10186 ret = kstrtoul(args[0].from, 0, &filter->offset);
10190 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10192 ret = kstrtoul(args[1].from, 0, &filter->size);
10197 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10198 int fpos = token == IF_SRC_FILE ? 2 : 1;
10201 filename = match_strdup(&args[fpos]);
10208 state = IF_STATE_END;
10216 * Filter definition is fully parsed, validate and install it.
10217 * Make sure that it doesn't contradict itself or the event's
10220 if (state == IF_STATE_END) {
10222 if (kernel && event->attr.exclude_kernel)
10226 * ACTION "filter" must have a non-zero length region
10229 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10238 * For now, we only support file-based filters
10239 * in per-task events; doing so for CPU-wide
10240 * events requires additional context switching
10241 * trickery, since same object code will be
10242 * mapped at different virtual addresses in
10243 * different processes.
10246 if (!event->ctx->task)
10249 /* look up the path and grab its inode */
10250 ret = kern_path(filename, LOOKUP_FOLLOW,
10256 if (!filter->path.dentry ||
10257 !S_ISREG(d_inode(filter->path.dentry)
10261 event->addr_filters.nr_file_filters++;
10264 /* ready to consume more filters */
10265 state = IF_STATE_ACTION;
10270 if (state != IF_STATE_ACTION)
10280 free_filters_list(filters);
10287 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10289 LIST_HEAD(filters);
10293 * Since this is called in perf_ioctl() path, we're already holding
10296 lockdep_assert_held(&event->ctx->mutex);
10298 if (WARN_ON_ONCE(event->parent))
10301 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10303 goto fail_clear_files;
10305 ret = event->pmu->addr_filters_validate(&filters);
10307 goto fail_free_filters;
10309 /* remove existing filters, if any */
10310 perf_addr_filters_splice(event, &filters);
10312 /* install new filters */
10313 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10318 free_filters_list(&filters);
10321 event->addr_filters.nr_file_filters = 0;
10326 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10331 filter_str = strndup_user(arg, PAGE_SIZE);
10332 if (IS_ERR(filter_str))
10333 return PTR_ERR(filter_str);
10335 #ifdef CONFIG_EVENT_TRACING
10336 if (perf_event_is_tracing(event)) {
10337 struct perf_event_context *ctx = event->ctx;
10340 * Beware, here be dragons!!
10342 * the tracepoint muck will deadlock against ctx->mutex, but
10343 * the tracepoint stuff does not actually need it. So
10344 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10345 * already have a reference on ctx.
10347 * This can result in event getting moved to a different ctx,
10348 * but that does not affect the tracepoint state.
10350 mutex_unlock(&ctx->mutex);
10351 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10352 mutex_lock(&ctx->mutex);
10355 if (has_addr_filter(event))
10356 ret = perf_event_set_addr_filter(event, filter_str);
10363 * hrtimer based swevent callback
10366 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10368 enum hrtimer_restart ret = HRTIMER_RESTART;
10369 struct perf_sample_data data;
10370 struct pt_regs *regs;
10371 struct perf_event *event;
10374 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10376 if (event->state != PERF_EVENT_STATE_ACTIVE)
10377 return HRTIMER_NORESTART;
10379 event->pmu->read(event);
10381 perf_sample_data_init(&data, 0, event->hw.last_period);
10382 regs = get_irq_regs();
10384 if (regs && !perf_exclude_event(event, regs)) {
10385 if (!(event->attr.exclude_idle && is_idle_task(current)))
10386 if (__perf_event_overflow(event, 1, &data, regs))
10387 ret = HRTIMER_NORESTART;
10390 period = max_t(u64, 10000, event->hw.sample_period);
10391 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10396 static void perf_swevent_start_hrtimer(struct perf_event *event)
10398 struct hw_perf_event *hwc = &event->hw;
10401 if (!is_sampling_event(event))
10404 period = local64_read(&hwc->period_left);
10409 local64_set(&hwc->period_left, 0);
10411 period = max_t(u64, 10000, hwc->sample_period);
10413 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10414 HRTIMER_MODE_REL_PINNED_HARD);
10417 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10419 struct hw_perf_event *hwc = &event->hw;
10421 if (is_sampling_event(event)) {
10422 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10423 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10425 hrtimer_cancel(&hwc->hrtimer);
10429 static void perf_swevent_init_hrtimer(struct perf_event *event)
10431 struct hw_perf_event *hwc = &event->hw;
10433 if (!is_sampling_event(event))
10436 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10437 hwc->hrtimer.function = perf_swevent_hrtimer;
10440 * Since hrtimers have a fixed rate, we can do a static freq->period
10441 * mapping and avoid the whole period adjust feedback stuff.
10443 if (event->attr.freq) {
10444 long freq = event->attr.sample_freq;
10446 event->attr.sample_period = NSEC_PER_SEC / freq;
10447 hwc->sample_period = event->attr.sample_period;
10448 local64_set(&hwc->period_left, hwc->sample_period);
10449 hwc->last_period = hwc->sample_period;
10450 event->attr.freq = 0;
10455 * Software event: cpu wall time clock
10458 static void cpu_clock_event_update(struct perf_event *event)
10463 now = local_clock();
10464 prev = local64_xchg(&event->hw.prev_count, now);
10465 local64_add(now - prev, &event->count);
10468 static void cpu_clock_event_start(struct perf_event *event, int flags)
10470 local64_set(&event->hw.prev_count, local_clock());
10471 perf_swevent_start_hrtimer(event);
10474 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10476 perf_swevent_cancel_hrtimer(event);
10477 cpu_clock_event_update(event);
10480 static int cpu_clock_event_add(struct perf_event *event, int flags)
10482 if (flags & PERF_EF_START)
10483 cpu_clock_event_start(event, flags);
10484 perf_event_update_userpage(event);
10489 static void cpu_clock_event_del(struct perf_event *event, int flags)
10491 cpu_clock_event_stop(event, flags);
10494 static void cpu_clock_event_read(struct perf_event *event)
10496 cpu_clock_event_update(event);
10499 static int cpu_clock_event_init(struct perf_event *event)
10501 if (event->attr.type != PERF_TYPE_SOFTWARE)
10504 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10508 * no branch sampling for software events
10510 if (has_branch_stack(event))
10511 return -EOPNOTSUPP;
10513 perf_swevent_init_hrtimer(event);
10518 static struct pmu perf_cpu_clock = {
10519 .task_ctx_nr = perf_sw_context,
10521 .capabilities = PERF_PMU_CAP_NO_NMI,
10523 .event_init = cpu_clock_event_init,
10524 .add = cpu_clock_event_add,
10525 .del = cpu_clock_event_del,
10526 .start = cpu_clock_event_start,
10527 .stop = cpu_clock_event_stop,
10528 .read = cpu_clock_event_read,
10532 * Software event: task time clock
10535 static void task_clock_event_update(struct perf_event *event, u64 now)
10540 prev = local64_xchg(&event->hw.prev_count, now);
10541 delta = now - prev;
10542 local64_add(delta, &event->count);
10545 static void task_clock_event_start(struct perf_event *event, int flags)
10547 local64_set(&event->hw.prev_count, event->ctx->time);
10548 perf_swevent_start_hrtimer(event);
10551 static void task_clock_event_stop(struct perf_event *event, int flags)
10553 perf_swevent_cancel_hrtimer(event);
10554 task_clock_event_update(event, event->ctx->time);
10557 static int task_clock_event_add(struct perf_event *event, int flags)
10559 if (flags & PERF_EF_START)
10560 task_clock_event_start(event, flags);
10561 perf_event_update_userpage(event);
10566 static void task_clock_event_del(struct perf_event *event, int flags)
10568 task_clock_event_stop(event, PERF_EF_UPDATE);
10571 static void task_clock_event_read(struct perf_event *event)
10573 u64 now = perf_clock();
10574 u64 delta = now - event->ctx->timestamp;
10575 u64 time = event->ctx->time + delta;
10577 task_clock_event_update(event, time);
10580 static int task_clock_event_init(struct perf_event *event)
10582 if (event->attr.type != PERF_TYPE_SOFTWARE)
10585 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10589 * no branch sampling for software events
10591 if (has_branch_stack(event))
10592 return -EOPNOTSUPP;
10594 perf_swevent_init_hrtimer(event);
10599 static struct pmu perf_task_clock = {
10600 .task_ctx_nr = perf_sw_context,
10602 .capabilities = PERF_PMU_CAP_NO_NMI,
10604 .event_init = task_clock_event_init,
10605 .add = task_clock_event_add,
10606 .del = task_clock_event_del,
10607 .start = task_clock_event_start,
10608 .stop = task_clock_event_stop,
10609 .read = task_clock_event_read,
10612 static void perf_pmu_nop_void(struct pmu *pmu)
10616 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10620 static int perf_pmu_nop_int(struct pmu *pmu)
10625 static int perf_event_nop_int(struct perf_event *event, u64 value)
10630 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10632 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10634 __this_cpu_write(nop_txn_flags, flags);
10636 if (flags & ~PERF_PMU_TXN_ADD)
10639 perf_pmu_disable(pmu);
10642 static int perf_pmu_commit_txn(struct pmu *pmu)
10644 unsigned int flags = __this_cpu_read(nop_txn_flags);
10646 __this_cpu_write(nop_txn_flags, 0);
10648 if (flags & ~PERF_PMU_TXN_ADD)
10651 perf_pmu_enable(pmu);
10655 static void perf_pmu_cancel_txn(struct pmu *pmu)
10657 unsigned int flags = __this_cpu_read(nop_txn_flags);
10659 __this_cpu_write(nop_txn_flags, 0);
10661 if (flags & ~PERF_PMU_TXN_ADD)
10664 perf_pmu_enable(pmu);
10667 static int perf_event_idx_default(struct perf_event *event)
10673 * Ensures all contexts with the same task_ctx_nr have the same
10674 * pmu_cpu_context too.
10676 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10683 list_for_each_entry(pmu, &pmus, entry) {
10684 if (pmu->task_ctx_nr == ctxn)
10685 return pmu->pmu_cpu_context;
10691 static void free_pmu_context(struct pmu *pmu)
10694 * Static contexts such as perf_sw_context have a global lifetime
10695 * and may be shared between different PMUs. Avoid freeing them
10696 * when a single PMU is going away.
10698 if (pmu->task_ctx_nr > perf_invalid_context)
10701 free_percpu(pmu->pmu_cpu_context);
10705 * Let userspace know that this PMU supports address range filtering:
10707 static ssize_t nr_addr_filters_show(struct device *dev,
10708 struct device_attribute *attr,
10711 struct pmu *pmu = dev_get_drvdata(dev);
10713 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10715 DEVICE_ATTR_RO(nr_addr_filters);
10717 static struct idr pmu_idr;
10720 type_show(struct device *dev, struct device_attribute *attr, char *page)
10722 struct pmu *pmu = dev_get_drvdata(dev);
10724 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10726 static DEVICE_ATTR_RO(type);
10729 perf_event_mux_interval_ms_show(struct device *dev,
10730 struct device_attribute *attr,
10733 struct pmu *pmu = dev_get_drvdata(dev);
10735 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10738 static DEFINE_MUTEX(mux_interval_mutex);
10741 perf_event_mux_interval_ms_store(struct device *dev,
10742 struct device_attribute *attr,
10743 const char *buf, size_t count)
10745 struct pmu *pmu = dev_get_drvdata(dev);
10746 int timer, cpu, ret;
10748 ret = kstrtoint(buf, 0, &timer);
10755 /* same value, noting to do */
10756 if (timer == pmu->hrtimer_interval_ms)
10759 mutex_lock(&mux_interval_mutex);
10760 pmu->hrtimer_interval_ms = timer;
10762 /* update all cpuctx for this PMU */
10764 for_each_online_cpu(cpu) {
10765 struct perf_cpu_context *cpuctx;
10766 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10767 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10769 cpu_function_call(cpu,
10770 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10772 cpus_read_unlock();
10773 mutex_unlock(&mux_interval_mutex);
10777 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10779 static struct attribute *pmu_dev_attrs[] = {
10780 &dev_attr_type.attr,
10781 &dev_attr_perf_event_mux_interval_ms.attr,
10784 ATTRIBUTE_GROUPS(pmu_dev);
10786 static int pmu_bus_running;
10787 static struct bus_type pmu_bus = {
10788 .name = "event_source",
10789 .dev_groups = pmu_dev_groups,
10792 static void pmu_dev_release(struct device *dev)
10797 static int pmu_dev_alloc(struct pmu *pmu)
10801 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10805 pmu->dev->groups = pmu->attr_groups;
10806 device_initialize(pmu->dev);
10807 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10811 dev_set_drvdata(pmu->dev, pmu);
10812 pmu->dev->bus = &pmu_bus;
10813 pmu->dev->release = pmu_dev_release;
10814 ret = device_add(pmu->dev);
10818 /* For PMUs with address filters, throw in an extra attribute: */
10819 if (pmu->nr_addr_filters)
10820 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10825 if (pmu->attr_update)
10826 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10835 device_del(pmu->dev);
10838 put_device(pmu->dev);
10842 static struct lock_class_key cpuctx_mutex;
10843 static struct lock_class_key cpuctx_lock;
10845 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10847 int cpu, ret, max = PERF_TYPE_MAX;
10849 mutex_lock(&pmus_lock);
10851 pmu->pmu_disable_count = alloc_percpu(int);
10852 if (!pmu->pmu_disable_count)
10860 if (type != PERF_TYPE_SOFTWARE) {
10864 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10868 WARN_ON(type >= 0 && ret != type);
10874 if (pmu_bus_running) {
10875 ret = pmu_dev_alloc(pmu);
10881 if (pmu->task_ctx_nr == perf_hw_context) {
10882 static int hw_context_taken = 0;
10885 * Other than systems with heterogeneous CPUs, it never makes
10886 * sense for two PMUs to share perf_hw_context. PMUs which are
10887 * uncore must use perf_invalid_context.
10889 if (WARN_ON_ONCE(hw_context_taken &&
10890 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10891 pmu->task_ctx_nr = perf_invalid_context;
10893 hw_context_taken = 1;
10896 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10897 if (pmu->pmu_cpu_context)
10898 goto got_cpu_context;
10901 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10902 if (!pmu->pmu_cpu_context)
10905 for_each_possible_cpu(cpu) {
10906 struct perf_cpu_context *cpuctx;
10908 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10909 __perf_event_init_context(&cpuctx->ctx);
10910 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10911 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10912 cpuctx->ctx.pmu = pmu;
10913 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10915 __perf_mux_hrtimer_init(cpuctx, cpu);
10917 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10918 cpuctx->heap = cpuctx->heap_default;
10922 if (!pmu->start_txn) {
10923 if (pmu->pmu_enable) {
10925 * If we have pmu_enable/pmu_disable calls, install
10926 * transaction stubs that use that to try and batch
10927 * hardware accesses.
10929 pmu->start_txn = perf_pmu_start_txn;
10930 pmu->commit_txn = perf_pmu_commit_txn;
10931 pmu->cancel_txn = perf_pmu_cancel_txn;
10933 pmu->start_txn = perf_pmu_nop_txn;
10934 pmu->commit_txn = perf_pmu_nop_int;
10935 pmu->cancel_txn = perf_pmu_nop_void;
10939 if (!pmu->pmu_enable) {
10940 pmu->pmu_enable = perf_pmu_nop_void;
10941 pmu->pmu_disable = perf_pmu_nop_void;
10944 if (!pmu->check_period)
10945 pmu->check_period = perf_event_nop_int;
10947 if (!pmu->event_idx)
10948 pmu->event_idx = perf_event_idx_default;
10951 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10952 * since these cannot be in the IDR. This way the linear search
10953 * is fast, provided a valid software event is provided.
10955 if (type == PERF_TYPE_SOFTWARE || !name)
10956 list_add_rcu(&pmu->entry, &pmus);
10958 list_add_tail_rcu(&pmu->entry, &pmus);
10960 atomic_set(&pmu->exclusive_cnt, 0);
10963 mutex_unlock(&pmus_lock);
10968 device_del(pmu->dev);
10969 put_device(pmu->dev);
10972 if (pmu->type != PERF_TYPE_SOFTWARE)
10973 idr_remove(&pmu_idr, pmu->type);
10976 free_percpu(pmu->pmu_disable_count);
10979 EXPORT_SYMBOL_GPL(perf_pmu_register);
10981 void perf_pmu_unregister(struct pmu *pmu)
10983 mutex_lock(&pmus_lock);
10984 list_del_rcu(&pmu->entry);
10987 * We dereference the pmu list under both SRCU and regular RCU, so
10988 * synchronize against both of those.
10990 synchronize_srcu(&pmus_srcu);
10993 free_percpu(pmu->pmu_disable_count);
10994 if (pmu->type != PERF_TYPE_SOFTWARE)
10995 idr_remove(&pmu_idr, pmu->type);
10996 if (pmu_bus_running) {
10997 if (pmu->nr_addr_filters)
10998 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10999 device_del(pmu->dev);
11000 put_device(pmu->dev);
11002 free_pmu_context(pmu);
11003 mutex_unlock(&pmus_lock);
11005 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11007 static inline bool has_extended_regs(struct perf_event *event)
11009 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11010 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11013 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11015 struct perf_event_context *ctx = NULL;
11018 if (!try_module_get(pmu->module))
11022 * A number of pmu->event_init() methods iterate the sibling_list to,
11023 * for example, validate if the group fits on the PMU. Therefore,
11024 * if this is a sibling event, acquire the ctx->mutex to protect
11025 * the sibling_list.
11027 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11029 * This ctx->mutex can nest when we're called through
11030 * inheritance. See the perf_event_ctx_lock_nested() comment.
11032 ctx = perf_event_ctx_lock_nested(event->group_leader,
11033 SINGLE_DEPTH_NESTING);
11038 ret = pmu->event_init(event);
11041 perf_event_ctx_unlock(event->group_leader, ctx);
11044 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11045 has_extended_regs(event))
11048 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11049 event_has_any_exclude_flag(event))
11052 if (ret && event->destroy)
11053 event->destroy(event);
11057 module_put(pmu->module);
11062 static struct pmu *perf_init_event(struct perf_event *event)
11064 int idx, type, ret;
11067 idx = srcu_read_lock(&pmus_srcu);
11069 /* Try parent's PMU first: */
11070 if (event->parent && event->parent->pmu) {
11071 pmu = event->parent->pmu;
11072 ret = perf_try_init_event(pmu, event);
11078 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11079 * are often aliases for PERF_TYPE_RAW.
11081 type = event->attr.type;
11082 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11083 type = PERF_TYPE_RAW;
11087 pmu = idr_find(&pmu_idr, type);
11090 ret = perf_try_init_event(pmu, event);
11091 if (ret == -ENOENT && event->attr.type != type) {
11092 type = event->attr.type;
11097 pmu = ERR_PTR(ret);
11102 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11103 ret = perf_try_init_event(pmu, event);
11107 if (ret != -ENOENT) {
11108 pmu = ERR_PTR(ret);
11112 pmu = ERR_PTR(-ENOENT);
11114 srcu_read_unlock(&pmus_srcu, idx);
11119 static void attach_sb_event(struct perf_event *event)
11121 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11123 raw_spin_lock(&pel->lock);
11124 list_add_rcu(&event->sb_list, &pel->list);
11125 raw_spin_unlock(&pel->lock);
11129 * We keep a list of all !task (and therefore per-cpu) events
11130 * that need to receive side-band records.
11132 * This avoids having to scan all the various PMU per-cpu contexts
11133 * looking for them.
11135 static void account_pmu_sb_event(struct perf_event *event)
11137 if (is_sb_event(event))
11138 attach_sb_event(event);
11141 static void account_event_cpu(struct perf_event *event, int cpu)
11146 if (is_cgroup_event(event))
11147 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11150 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11151 static void account_freq_event_nohz(void)
11153 #ifdef CONFIG_NO_HZ_FULL
11154 /* Lock so we don't race with concurrent unaccount */
11155 spin_lock(&nr_freq_lock);
11156 if (atomic_inc_return(&nr_freq_events) == 1)
11157 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11158 spin_unlock(&nr_freq_lock);
11162 static void account_freq_event(void)
11164 if (tick_nohz_full_enabled())
11165 account_freq_event_nohz();
11167 atomic_inc(&nr_freq_events);
11171 static void account_event(struct perf_event *event)
11178 if (event->attach_state & PERF_ATTACH_TASK)
11180 if (event->attr.mmap || event->attr.mmap_data)
11181 atomic_inc(&nr_mmap_events);
11182 if (event->attr.build_id)
11183 atomic_inc(&nr_build_id_events);
11184 if (event->attr.comm)
11185 atomic_inc(&nr_comm_events);
11186 if (event->attr.namespaces)
11187 atomic_inc(&nr_namespaces_events);
11188 if (event->attr.cgroup)
11189 atomic_inc(&nr_cgroup_events);
11190 if (event->attr.task)
11191 atomic_inc(&nr_task_events);
11192 if (event->attr.freq)
11193 account_freq_event();
11194 if (event->attr.context_switch) {
11195 atomic_inc(&nr_switch_events);
11198 if (has_branch_stack(event))
11200 if (is_cgroup_event(event))
11202 if (event->attr.ksymbol)
11203 atomic_inc(&nr_ksymbol_events);
11204 if (event->attr.bpf_event)
11205 atomic_inc(&nr_bpf_events);
11206 if (event->attr.text_poke)
11207 atomic_inc(&nr_text_poke_events);
11211 * We need the mutex here because static_branch_enable()
11212 * must complete *before* the perf_sched_count increment
11215 if (atomic_inc_not_zero(&perf_sched_count))
11218 mutex_lock(&perf_sched_mutex);
11219 if (!atomic_read(&perf_sched_count)) {
11220 static_branch_enable(&perf_sched_events);
11222 * Guarantee that all CPUs observe they key change and
11223 * call the perf scheduling hooks before proceeding to
11224 * install events that need them.
11229 * Now that we have waited for the sync_sched(), allow further
11230 * increments to by-pass the mutex.
11232 atomic_inc(&perf_sched_count);
11233 mutex_unlock(&perf_sched_mutex);
11237 account_event_cpu(event, event->cpu);
11239 account_pmu_sb_event(event);
11243 * Allocate and initialize an event structure
11245 static struct perf_event *
11246 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11247 struct task_struct *task,
11248 struct perf_event *group_leader,
11249 struct perf_event *parent_event,
11250 perf_overflow_handler_t overflow_handler,
11251 void *context, int cgroup_fd)
11254 struct perf_event *event;
11255 struct hw_perf_event *hwc;
11256 long err = -EINVAL;
11258 if ((unsigned)cpu >= nr_cpu_ids) {
11259 if (!task || cpu != -1)
11260 return ERR_PTR(-EINVAL);
11263 event = kzalloc(sizeof(*event), GFP_KERNEL);
11265 return ERR_PTR(-ENOMEM);
11268 * Single events are their own group leaders, with an
11269 * empty sibling list:
11272 group_leader = event;
11274 mutex_init(&event->child_mutex);
11275 INIT_LIST_HEAD(&event->child_list);
11277 INIT_LIST_HEAD(&event->event_entry);
11278 INIT_LIST_HEAD(&event->sibling_list);
11279 INIT_LIST_HEAD(&event->active_list);
11280 init_event_group(event);
11281 INIT_LIST_HEAD(&event->rb_entry);
11282 INIT_LIST_HEAD(&event->active_entry);
11283 INIT_LIST_HEAD(&event->addr_filters.list);
11284 INIT_HLIST_NODE(&event->hlist_entry);
11287 init_waitqueue_head(&event->waitq);
11288 event->pending_disable = -1;
11289 init_irq_work(&event->pending, perf_pending_event);
11291 mutex_init(&event->mmap_mutex);
11292 raw_spin_lock_init(&event->addr_filters.lock);
11294 atomic_long_set(&event->refcount, 1);
11296 event->attr = *attr;
11297 event->group_leader = group_leader;
11301 event->parent = parent_event;
11303 event->ns = get_pid_ns(task_active_pid_ns(current));
11304 event->id = atomic64_inc_return(&perf_event_id);
11306 event->state = PERF_EVENT_STATE_INACTIVE;
11309 event->attach_state = PERF_ATTACH_TASK;
11311 * XXX pmu::event_init needs to know what task to account to
11312 * and we cannot use the ctx information because we need the
11313 * pmu before we get a ctx.
11315 event->hw.target = get_task_struct(task);
11318 event->clock = &local_clock;
11320 event->clock = parent_event->clock;
11322 if (!overflow_handler && parent_event) {
11323 overflow_handler = parent_event->overflow_handler;
11324 context = parent_event->overflow_handler_context;
11325 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11326 if (overflow_handler == bpf_overflow_handler) {
11327 struct bpf_prog *prog = parent_event->prog;
11329 bpf_prog_inc(prog);
11330 event->prog = prog;
11331 event->orig_overflow_handler =
11332 parent_event->orig_overflow_handler;
11337 if (overflow_handler) {
11338 event->overflow_handler = overflow_handler;
11339 event->overflow_handler_context = context;
11340 } else if (is_write_backward(event)){
11341 event->overflow_handler = perf_event_output_backward;
11342 event->overflow_handler_context = NULL;
11344 event->overflow_handler = perf_event_output_forward;
11345 event->overflow_handler_context = NULL;
11348 perf_event__state_init(event);
11353 hwc->sample_period = attr->sample_period;
11354 if (attr->freq && attr->sample_freq)
11355 hwc->sample_period = 1;
11356 hwc->last_period = hwc->sample_period;
11358 local64_set(&hwc->period_left, hwc->sample_period);
11361 * We currently do not support PERF_SAMPLE_READ on inherited events.
11362 * See perf_output_read().
11364 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11367 if (!has_branch_stack(event))
11368 event->attr.branch_sample_type = 0;
11370 pmu = perf_init_event(event);
11372 err = PTR_ERR(pmu);
11377 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11378 * be different on other CPUs in the uncore mask.
11380 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11385 if (event->attr.aux_output &&
11386 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11391 if (cgroup_fd != -1) {
11392 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11397 err = exclusive_event_init(event);
11401 if (has_addr_filter(event)) {
11402 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11403 sizeof(struct perf_addr_filter_range),
11405 if (!event->addr_filter_ranges) {
11411 * Clone the parent's vma offsets: they are valid until exec()
11412 * even if the mm is not shared with the parent.
11414 if (event->parent) {
11415 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11417 raw_spin_lock_irq(&ifh->lock);
11418 memcpy(event->addr_filter_ranges,
11419 event->parent->addr_filter_ranges,
11420 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11421 raw_spin_unlock_irq(&ifh->lock);
11424 /* force hw sync on the address filters */
11425 event->addr_filters_gen = 1;
11428 if (!event->parent) {
11429 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11430 err = get_callchain_buffers(attr->sample_max_stack);
11432 goto err_addr_filters;
11436 err = security_perf_event_alloc(event);
11438 goto err_callchain_buffer;
11440 /* symmetric to unaccount_event() in _free_event() */
11441 account_event(event);
11445 err_callchain_buffer:
11446 if (!event->parent) {
11447 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11448 put_callchain_buffers();
11451 kfree(event->addr_filter_ranges);
11454 exclusive_event_destroy(event);
11457 if (is_cgroup_event(event))
11458 perf_detach_cgroup(event);
11459 if (event->destroy)
11460 event->destroy(event);
11461 module_put(pmu->module);
11464 put_pid_ns(event->ns);
11465 if (event->hw.target)
11466 put_task_struct(event->hw.target);
11469 return ERR_PTR(err);
11472 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11473 struct perf_event_attr *attr)
11478 /* Zero the full structure, so that a short copy will be nice. */
11479 memset(attr, 0, sizeof(*attr));
11481 ret = get_user(size, &uattr->size);
11485 /* ABI compatibility quirk: */
11487 size = PERF_ATTR_SIZE_VER0;
11488 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11491 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11500 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11503 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11506 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11509 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11510 u64 mask = attr->branch_sample_type;
11512 /* only using defined bits */
11513 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11516 /* at least one branch bit must be set */
11517 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11520 /* propagate priv level, when not set for branch */
11521 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11523 /* exclude_kernel checked on syscall entry */
11524 if (!attr->exclude_kernel)
11525 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11527 if (!attr->exclude_user)
11528 mask |= PERF_SAMPLE_BRANCH_USER;
11530 if (!attr->exclude_hv)
11531 mask |= PERF_SAMPLE_BRANCH_HV;
11533 * adjust user setting (for HW filter setup)
11535 attr->branch_sample_type = mask;
11537 /* privileged levels capture (kernel, hv): check permissions */
11538 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11539 ret = perf_allow_kernel(attr);
11545 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11546 ret = perf_reg_validate(attr->sample_regs_user);
11551 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11552 if (!arch_perf_have_user_stack_dump())
11556 * We have __u32 type for the size, but so far
11557 * we can only use __u16 as maximum due to the
11558 * __u16 sample size limit.
11560 if (attr->sample_stack_user >= USHRT_MAX)
11562 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11566 if (!attr->sample_max_stack)
11567 attr->sample_max_stack = sysctl_perf_event_max_stack;
11569 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11570 ret = perf_reg_validate(attr->sample_regs_intr);
11572 #ifndef CONFIG_CGROUP_PERF
11573 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11576 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
11577 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
11584 put_user(sizeof(*attr), &uattr->size);
11590 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11592 struct perf_buffer *rb = NULL;
11598 /* don't allow circular references */
11599 if (event == output_event)
11603 * Don't allow cross-cpu buffers
11605 if (output_event->cpu != event->cpu)
11609 * If its not a per-cpu rb, it must be the same task.
11611 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11615 * Mixing clocks in the same buffer is trouble you don't need.
11617 if (output_event->clock != event->clock)
11621 * Either writing ring buffer from beginning or from end.
11622 * Mixing is not allowed.
11624 if (is_write_backward(output_event) != is_write_backward(event))
11628 * If both events generate aux data, they must be on the same PMU
11630 if (has_aux(event) && has_aux(output_event) &&
11631 event->pmu != output_event->pmu)
11635 mutex_lock(&event->mmap_mutex);
11636 /* Can't redirect output if we've got an active mmap() */
11637 if (atomic_read(&event->mmap_count))
11640 if (output_event) {
11641 /* get the rb we want to redirect to */
11642 rb = ring_buffer_get(output_event);
11647 ring_buffer_attach(event, rb);
11651 mutex_unlock(&event->mmap_mutex);
11657 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11663 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11666 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11668 bool nmi_safe = false;
11671 case CLOCK_MONOTONIC:
11672 event->clock = &ktime_get_mono_fast_ns;
11676 case CLOCK_MONOTONIC_RAW:
11677 event->clock = &ktime_get_raw_fast_ns;
11681 case CLOCK_REALTIME:
11682 event->clock = &ktime_get_real_ns;
11685 case CLOCK_BOOTTIME:
11686 event->clock = &ktime_get_boottime_ns;
11690 event->clock = &ktime_get_clocktai_ns;
11697 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11704 * Variation on perf_event_ctx_lock_nested(), except we take two context
11707 static struct perf_event_context *
11708 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11709 struct perf_event_context *ctx)
11711 struct perf_event_context *gctx;
11715 gctx = READ_ONCE(group_leader->ctx);
11716 if (!refcount_inc_not_zero(&gctx->refcount)) {
11722 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11724 if (group_leader->ctx != gctx) {
11725 mutex_unlock(&ctx->mutex);
11726 mutex_unlock(&gctx->mutex);
11735 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11737 * @attr_uptr: event_id type attributes for monitoring/sampling
11740 * @group_fd: group leader event fd
11742 SYSCALL_DEFINE5(perf_event_open,
11743 struct perf_event_attr __user *, attr_uptr,
11744 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11746 struct perf_event *group_leader = NULL, *output_event = NULL;
11747 struct perf_event *event, *sibling;
11748 struct perf_event_attr attr;
11749 struct perf_event_context *ctx, *gctx;
11750 struct file *event_file = NULL;
11751 struct fd group = {NULL, 0};
11752 struct task_struct *task = NULL;
11755 int move_group = 0;
11757 int f_flags = O_RDWR;
11758 int cgroup_fd = -1;
11760 /* for future expandability... */
11761 if (flags & ~PERF_FLAG_ALL)
11764 /* Do we allow access to perf_event_open(2) ? */
11765 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11769 err = perf_copy_attr(attr_uptr, &attr);
11773 if (!attr.exclude_kernel) {
11774 err = perf_allow_kernel(&attr);
11779 if (attr.namespaces) {
11780 if (!perfmon_capable())
11785 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11788 if (attr.sample_period & (1ULL << 63))
11792 /* Only privileged users can get physical addresses */
11793 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11794 err = perf_allow_kernel(&attr);
11799 err = security_locked_down(LOCKDOWN_PERF);
11800 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11801 /* REGS_INTR can leak data, lockdown must prevent this */
11807 * In cgroup mode, the pid argument is used to pass the fd
11808 * opened to the cgroup directory in cgroupfs. The cpu argument
11809 * designates the cpu on which to monitor threads from that
11812 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11815 if (flags & PERF_FLAG_FD_CLOEXEC)
11816 f_flags |= O_CLOEXEC;
11818 event_fd = get_unused_fd_flags(f_flags);
11822 if (group_fd != -1) {
11823 err = perf_fget_light(group_fd, &group);
11826 group_leader = group.file->private_data;
11827 if (flags & PERF_FLAG_FD_OUTPUT)
11828 output_event = group_leader;
11829 if (flags & PERF_FLAG_FD_NO_GROUP)
11830 group_leader = NULL;
11833 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11834 task = find_lively_task_by_vpid(pid);
11835 if (IS_ERR(task)) {
11836 err = PTR_ERR(task);
11841 if (task && group_leader &&
11842 group_leader->attr.inherit != attr.inherit) {
11847 if (flags & PERF_FLAG_PID_CGROUP)
11850 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11851 NULL, NULL, cgroup_fd);
11852 if (IS_ERR(event)) {
11853 err = PTR_ERR(event);
11857 if (is_sampling_event(event)) {
11858 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11865 * Special case software events and allow them to be part of
11866 * any hardware group.
11870 if (attr.use_clockid) {
11871 err = perf_event_set_clock(event, attr.clockid);
11876 if (pmu->task_ctx_nr == perf_sw_context)
11877 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11879 if (group_leader) {
11880 if (is_software_event(event) &&
11881 !in_software_context(group_leader)) {
11883 * If the event is a sw event, but the group_leader
11884 * is on hw context.
11886 * Allow the addition of software events to hw
11887 * groups, this is safe because software events
11888 * never fail to schedule.
11890 pmu = group_leader->ctx->pmu;
11891 } else if (!is_software_event(event) &&
11892 is_software_event(group_leader) &&
11893 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11895 * In case the group is a pure software group, and we
11896 * try to add a hardware event, move the whole group to
11897 * the hardware context.
11904 * Get the target context (task or percpu):
11906 ctx = find_get_context(pmu, task, event);
11908 err = PTR_ERR(ctx);
11913 * Look up the group leader (we will attach this event to it):
11915 if (group_leader) {
11919 * Do not allow a recursive hierarchy (this new sibling
11920 * becoming part of another group-sibling):
11922 if (group_leader->group_leader != group_leader)
11925 /* All events in a group should have the same clock */
11926 if (group_leader->clock != event->clock)
11930 * Make sure we're both events for the same CPU;
11931 * grouping events for different CPUs is broken; since
11932 * you can never concurrently schedule them anyhow.
11934 if (group_leader->cpu != event->cpu)
11938 * Make sure we're both on the same task, or both
11941 if (group_leader->ctx->task != ctx->task)
11945 * Do not allow to attach to a group in a different task
11946 * or CPU context. If we're moving SW events, we'll fix
11947 * this up later, so allow that.
11949 if (!move_group && group_leader->ctx != ctx)
11953 * Only a group leader can be exclusive or pinned
11955 if (attr.exclusive || attr.pinned)
11959 if (output_event) {
11960 err = perf_event_set_output(event, output_event);
11965 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11967 if (IS_ERR(event_file)) {
11968 err = PTR_ERR(event_file);
11974 err = down_read_interruptible(&task->signal->exec_update_lock);
11979 * Preserve ptrace permission check for backwards compatibility.
11981 * We must hold exec_update_lock across this and any potential
11982 * perf_install_in_context() call for this new event to
11983 * serialize against exec() altering our credentials (and the
11984 * perf_event_exit_task() that could imply).
11987 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11992 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11994 if (gctx->task == TASK_TOMBSTONE) {
12000 * Check if we raced against another sys_perf_event_open() call
12001 * moving the software group underneath us.
12003 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12005 * If someone moved the group out from under us, check
12006 * if this new event wound up on the same ctx, if so
12007 * its the regular !move_group case, otherwise fail.
12013 perf_event_ctx_unlock(group_leader, gctx);
12019 * Failure to create exclusive events returns -EBUSY.
12022 if (!exclusive_event_installable(group_leader, ctx))
12025 for_each_sibling_event(sibling, group_leader) {
12026 if (!exclusive_event_installable(sibling, ctx))
12030 mutex_lock(&ctx->mutex);
12033 if (ctx->task == TASK_TOMBSTONE) {
12038 if (!perf_event_validate_size(event)) {
12045 * Check if the @cpu we're creating an event for is online.
12047 * We use the perf_cpu_context::ctx::mutex to serialize against
12048 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12050 struct perf_cpu_context *cpuctx =
12051 container_of(ctx, struct perf_cpu_context, ctx);
12053 if (!cpuctx->online) {
12059 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12065 * Must be under the same ctx::mutex as perf_install_in_context(),
12066 * because we need to serialize with concurrent event creation.
12068 if (!exclusive_event_installable(event, ctx)) {
12073 WARN_ON_ONCE(ctx->parent_ctx);
12076 * This is the point on no return; we cannot fail hereafter. This is
12077 * where we start modifying current state.
12082 * See perf_event_ctx_lock() for comments on the details
12083 * of swizzling perf_event::ctx.
12085 perf_remove_from_context(group_leader, 0);
12088 for_each_sibling_event(sibling, group_leader) {
12089 perf_remove_from_context(sibling, 0);
12094 * Wait for everybody to stop referencing the events through
12095 * the old lists, before installing it on new lists.
12100 * Install the group siblings before the group leader.
12102 * Because a group leader will try and install the entire group
12103 * (through the sibling list, which is still in-tact), we can
12104 * end up with siblings installed in the wrong context.
12106 * By installing siblings first we NO-OP because they're not
12107 * reachable through the group lists.
12109 for_each_sibling_event(sibling, group_leader) {
12110 perf_event__state_init(sibling);
12111 perf_install_in_context(ctx, sibling, sibling->cpu);
12116 * Removing from the context ends up with disabled
12117 * event. What we want here is event in the initial
12118 * startup state, ready to be add into new context.
12120 perf_event__state_init(group_leader);
12121 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12126 * Precalculate sample_data sizes; do while holding ctx::mutex such
12127 * that we're serialized against further additions and before
12128 * perf_install_in_context() which is the point the event is active and
12129 * can use these values.
12131 perf_event__header_size(event);
12132 perf_event__id_header_size(event);
12134 event->owner = current;
12136 perf_install_in_context(ctx, event, event->cpu);
12137 perf_unpin_context(ctx);
12140 perf_event_ctx_unlock(group_leader, gctx);
12141 mutex_unlock(&ctx->mutex);
12144 up_read(&task->signal->exec_update_lock);
12145 put_task_struct(task);
12148 mutex_lock(¤t->perf_event_mutex);
12149 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12150 mutex_unlock(¤t->perf_event_mutex);
12153 * Drop the reference on the group_event after placing the
12154 * new event on the sibling_list. This ensures destruction
12155 * of the group leader will find the pointer to itself in
12156 * perf_group_detach().
12159 fd_install(event_fd, event_file);
12164 perf_event_ctx_unlock(group_leader, gctx);
12165 mutex_unlock(&ctx->mutex);
12168 up_read(&task->signal->exec_update_lock);
12172 perf_unpin_context(ctx);
12176 * If event_file is set, the fput() above will have called ->release()
12177 * and that will take care of freeing the event.
12183 put_task_struct(task);
12187 put_unused_fd(event_fd);
12192 * perf_event_create_kernel_counter
12194 * @attr: attributes of the counter to create
12195 * @cpu: cpu in which the counter is bound
12196 * @task: task to profile (NULL for percpu)
12198 struct perf_event *
12199 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12200 struct task_struct *task,
12201 perf_overflow_handler_t overflow_handler,
12204 struct perf_event_context *ctx;
12205 struct perf_event *event;
12209 * Grouping is not supported for kernel events, neither is 'AUX',
12210 * make sure the caller's intentions are adjusted.
12212 if (attr->aux_output)
12213 return ERR_PTR(-EINVAL);
12215 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12216 overflow_handler, context, -1);
12217 if (IS_ERR(event)) {
12218 err = PTR_ERR(event);
12222 /* Mark owner so we could distinguish it from user events. */
12223 event->owner = TASK_TOMBSTONE;
12226 * Get the target context (task or percpu):
12228 ctx = find_get_context(event->pmu, task, event);
12230 err = PTR_ERR(ctx);
12234 WARN_ON_ONCE(ctx->parent_ctx);
12235 mutex_lock(&ctx->mutex);
12236 if (ctx->task == TASK_TOMBSTONE) {
12243 * Check if the @cpu we're creating an event for is online.
12245 * We use the perf_cpu_context::ctx::mutex to serialize against
12246 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12248 struct perf_cpu_context *cpuctx =
12249 container_of(ctx, struct perf_cpu_context, ctx);
12250 if (!cpuctx->online) {
12256 if (!exclusive_event_installable(event, ctx)) {
12261 perf_install_in_context(ctx, event, event->cpu);
12262 perf_unpin_context(ctx);
12263 mutex_unlock(&ctx->mutex);
12268 mutex_unlock(&ctx->mutex);
12269 perf_unpin_context(ctx);
12274 return ERR_PTR(err);
12276 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12278 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12280 struct perf_event_context *src_ctx;
12281 struct perf_event_context *dst_ctx;
12282 struct perf_event *event, *tmp;
12285 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12286 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12289 * See perf_event_ctx_lock() for comments on the details
12290 * of swizzling perf_event::ctx.
12292 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12293 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12295 perf_remove_from_context(event, 0);
12296 unaccount_event_cpu(event, src_cpu);
12298 list_add(&event->migrate_entry, &events);
12302 * Wait for the events to quiesce before re-instating them.
12307 * Re-instate events in 2 passes.
12309 * Skip over group leaders and only install siblings on this first
12310 * pass, siblings will not get enabled without a leader, however a
12311 * leader will enable its siblings, even if those are still on the old
12314 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12315 if (event->group_leader == event)
12318 list_del(&event->migrate_entry);
12319 if (event->state >= PERF_EVENT_STATE_OFF)
12320 event->state = PERF_EVENT_STATE_INACTIVE;
12321 account_event_cpu(event, dst_cpu);
12322 perf_install_in_context(dst_ctx, event, dst_cpu);
12327 * Once all the siblings are setup properly, install the group leaders
12330 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12331 list_del(&event->migrate_entry);
12332 if (event->state >= PERF_EVENT_STATE_OFF)
12333 event->state = PERF_EVENT_STATE_INACTIVE;
12334 account_event_cpu(event, dst_cpu);
12335 perf_install_in_context(dst_ctx, event, dst_cpu);
12338 mutex_unlock(&dst_ctx->mutex);
12339 mutex_unlock(&src_ctx->mutex);
12341 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12343 static void sync_child_event(struct perf_event *child_event,
12344 struct task_struct *child)
12346 struct perf_event *parent_event = child_event->parent;
12349 if (child_event->attr.inherit_stat)
12350 perf_event_read_event(child_event, child);
12352 child_val = perf_event_count(child_event);
12355 * Add back the child's count to the parent's count:
12357 atomic64_add(child_val, &parent_event->child_count);
12358 atomic64_add(child_event->total_time_enabled,
12359 &parent_event->child_total_time_enabled);
12360 atomic64_add(child_event->total_time_running,
12361 &parent_event->child_total_time_running);
12365 perf_event_exit_event(struct perf_event *child_event,
12366 struct perf_event_context *child_ctx,
12367 struct task_struct *child)
12369 struct perf_event *parent_event = child_event->parent;
12372 * Do not destroy the 'original' grouping; because of the context
12373 * switch optimization the original events could've ended up in a
12374 * random child task.
12376 * If we were to destroy the original group, all group related
12377 * operations would cease to function properly after this random
12380 * Do destroy all inherited groups, we don't care about those
12381 * and being thorough is better.
12383 raw_spin_lock_irq(&child_ctx->lock);
12384 WARN_ON_ONCE(child_ctx->is_active);
12387 perf_group_detach(child_event);
12388 list_del_event(child_event, child_ctx);
12389 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12390 raw_spin_unlock_irq(&child_ctx->lock);
12393 * Parent events are governed by their filedesc, retain them.
12395 if (!parent_event) {
12396 perf_event_wakeup(child_event);
12400 * Child events can be cleaned up.
12403 sync_child_event(child_event, child);
12406 * Remove this event from the parent's list
12408 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12409 mutex_lock(&parent_event->child_mutex);
12410 list_del_init(&child_event->child_list);
12411 mutex_unlock(&parent_event->child_mutex);
12414 * Kick perf_poll() for is_event_hup().
12416 perf_event_wakeup(parent_event);
12417 free_event(child_event);
12418 put_event(parent_event);
12421 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12423 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12424 struct perf_event *child_event, *next;
12426 WARN_ON_ONCE(child != current);
12428 child_ctx = perf_pin_task_context(child, ctxn);
12433 * In order to reduce the amount of tricky in ctx tear-down, we hold
12434 * ctx::mutex over the entire thing. This serializes against almost
12435 * everything that wants to access the ctx.
12437 * The exception is sys_perf_event_open() /
12438 * perf_event_create_kernel_count() which does find_get_context()
12439 * without ctx::mutex (it cannot because of the move_group double mutex
12440 * lock thing). See the comments in perf_install_in_context().
12442 mutex_lock(&child_ctx->mutex);
12445 * In a single ctx::lock section, de-schedule the events and detach the
12446 * context from the task such that we cannot ever get it scheduled back
12449 raw_spin_lock_irq(&child_ctx->lock);
12450 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12453 * Now that the context is inactive, destroy the task <-> ctx relation
12454 * and mark the context dead.
12456 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12457 put_ctx(child_ctx); /* cannot be last */
12458 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12459 put_task_struct(current); /* cannot be last */
12461 clone_ctx = unclone_ctx(child_ctx);
12462 raw_spin_unlock_irq(&child_ctx->lock);
12465 put_ctx(clone_ctx);
12468 * Report the task dead after unscheduling the events so that we
12469 * won't get any samples after PERF_RECORD_EXIT. We can however still
12470 * get a few PERF_RECORD_READ events.
12472 perf_event_task(child, child_ctx, 0);
12474 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12475 perf_event_exit_event(child_event, child_ctx, child);
12477 mutex_unlock(&child_ctx->mutex);
12479 put_ctx(child_ctx);
12483 * When a child task exits, feed back event values to parent events.
12485 * Can be called with exec_update_lock held when called from
12486 * setup_new_exec().
12488 void perf_event_exit_task(struct task_struct *child)
12490 struct perf_event *event, *tmp;
12493 mutex_lock(&child->perf_event_mutex);
12494 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12496 list_del_init(&event->owner_entry);
12499 * Ensure the list deletion is visible before we clear
12500 * the owner, closes a race against perf_release() where
12501 * we need to serialize on the owner->perf_event_mutex.
12503 smp_store_release(&event->owner, NULL);
12505 mutex_unlock(&child->perf_event_mutex);
12507 for_each_task_context_nr(ctxn)
12508 perf_event_exit_task_context(child, ctxn);
12511 * The perf_event_exit_task_context calls perf_event_task
12512 * with child's task_ctx, which generates EXIT events for
12513 * child contexts and sets child->perf_event_ctxp[] to NULL.
12514 * At this point we need to send EXIT events to cpu contexts.
12516 perf_event_task(child, NULL, 0);
12519 static void perf_free_event(struct perf_event *event,
12520 struct perf_event_context *ctx)
12522 struct perf_event *parent = event->parent;
12524 if (WARN_ON_ONCE(!parent))
12527 mutex_lock(&parent->child_mutex);
12528 list_del_init(&event->child_list);
12529 mutex_unlock(&parent->child_mutex);
12533 raw_spin_lock_irq(&ctx->lock);
12534 perf_group_detach(event);
12535 list_del_event(event, ctx);
12536 raw_spin_unlock_irq(&ctx->lock);
12541 * Free a context as created by inheritance by perf_event_init_task() below,
12542 * used by fork() in case of fail.
12544 * Even though the task has never lived, the context and events have been
12545 * exposed through the child_list, so we must take care tearing it all down.
12547 void perf_event_free_task(struct task_struct *task)
12549 struct perf_event_context *ctx;
12550 struct perf_event *event, *tmp;
12553 for_each_task_context_nr(ctxn) {
12554 ctx = task->perf_event_ctxp[ctxn];
12558 mutex_lock(&ctx->mutex);
12559 raw_spin_lock_irq(&ctx->lock);
12561 * Destroy the task <-> ctx relation and mark the context dead.
12563 * This is important because even though the task hasn't been
12564 * exposed yet the context has been (through child_list).
12566 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12567 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12568 put_task_struct(task); /* cannot be last */
12569 raw_spin_unlock_irq(&ctx->lock);
12571 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12572 perf_free_event(event, ctx);
12574 mutex_unlock(&ctx->mutex);
12577 * perf_event_release_kernel() could've stolen some of our
12578 * child events and still have them on its free_list. In that
12579 * case we must wait for these events to have been freed (in
12580 * particular all their references to this task must've been
12583 * Without this copy_process() will unconditionally free this
12584 * task (irrespective of its reference count) and
12585 * _free_event()'s put_task_struct(event->hw.target) will be a
12588 * Wait for all events to drop their context reference.
12590 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12591 put_ctx(ctx); /* must be last */
12595 void perf_event_delayed_put(struct task_struct *task)
12599 for_each_task_context_nr(ctxn)
12600 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12603 struct file *perf_event_get(unsigned int fd)
12605 struct file *file = fget(fd);
12607 return ERR_PTR(-EBADF);
12609 if (file->f_op != &perf_fops) {
12611 return ERR_PTR(-EBADF);
12617 const struct perf_event *perf_get_event(struct file *file)
12619 if (file->f_op != &perf_fops)
12620 return ERR_PTR(-EINVAL);
12622 return file->private_data;
12625 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12628 return ERR_PTR(-EINVAL);
12630 return &event->attr;
12634 * Inherit an event from parent task to child task.
12637 * - valid pointer on success
12638 * - NULL for orphaned events
12639 * - IS_ERR() on error
12641 static struct perf_event *
12642 inherit_event(struct perf_event *parent_event,
12643 struct task_struct *parent,
12644 struct perf_event_context *parent_ctx,
12645 struct task_struct *child,
12646 struct perf_event *group_leader,
12647 struct perf_event_context *child_ctx)
12649 enum perf_event_state parent_state = parent_event->state;
12650 struct perf_event *child_event;
12651 unsigned long flags;
12654 * Instead of creating recursive hierarchies of events,
12655 * we link inherited events back to the original parent,
12656 * which has a filp for sure, which we use as the reference
12659 if (parent_event->parent)
12660 parent_event = parent_event->parent;
12662 child_event = perf_event_alloc(&parent_event->attr,
12665 group_leader, parent_event,
12667 if (IS_ERR(child_event))
12668 return child_event;
12671 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12672 !child_ctx->task_ctx_data) {
12673 struct pmu *pmu = child_event->pmu;
12675 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12676 if (!child_ctx->task_ctx_data) {
12677 free_event(child_event);
12678 return ERR_PTR(-ENOMEM);
12683 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12684 * must be under the same lock in order to serialize against
12685 * perf_event_release_kernel(), such that either we must observe
12686 * is_orphaned_event() or they will observe us on the child_list.
12688 mutex_lock(&parent_event->child_mutex);
12689 if (is_orphaned_event(parent_event) ||
12690 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12691 mutex_unlock(&parent_event->child_mutex);
12692 /* task_ctx_data is freed with child_ctx */
12693 free_event(child_event);
12697 get_ctx(child_ctx);
12700 * Make the child state follow the state of the parent event,
12701 * not its attr.disabled bit. We hold the parent's mutex,
12702 * so we won't race with perf_event_{en, dis}able_family.
12704 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12705 child_event->state = PERF_EVENT_STATE_INACTIVE;
12707 child_event->state = PERF_EVENT_STATE_OFF;
12709 if (parent_event->attr.freq) {
12710 u64 sample_period = parent_event->hw.sample_period;
12711 struct hw_perf_event *hwc = &child_event->hw;
12713 hwc->sample_period = sample_period;
12714 hwc->last_period = sample_period;
12716 local64_set(&hwc->period_left, sample_period);
12719 child_event->ctx = child_ctx;
12720 child_event->overflow_handler = parent_event->overflow_handler;
12721 child_event->overflow_handler_context
12722 = parent_event->overflow_handler_context;
12725 * Precalculate sample_data sizes
12727 perf_event__header_size(child_event);
12728 perf_event__id_header_size(child_event);
12731 * Link it up in the child's context:
12733 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12734 add_event_to_ctx(child_event, child_ctx);
12735 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12738 * Link this into the parent event's child list
12740 list_add_tail(&child_event->child_list, &parent_event->child_list);
12741 mutex_unlock(&parent_event->child_mutex);
12743 return child_event;
12747 * Inherits an event group.
12749 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12750 * This matches with perf_event_release_kernel() removing all child events.
12756 static int inherit_group(struct perf_event *parent_event,
12757 struct task_struct *parent,
12758 struct perf_event_context *parent_ctx,
12759 struct task_struct *child,
12760 struct perf_event_context *child_ctx)
12762 struct perf_event *leader;
12763 struct perf_event *sub;
12764 struct perf_event *child_ctr;
12766 leader = inherit_event(parent_event, parent, parent_ctx,
12767 child, NULL, child_ctx);
12768 if (IS_ERR(leader))
12769 return PTR_ERR(leader);
12771 * @leader can be NULL here because of is_orphaned_event(). In this
12772 * case inherit_event() will create individual events, similar to what
12773 * perf_group_detach() would do anyway.
12775 for_each_sibling_event(sub, parent_event) {
12776 child_ctr = inherit_event(sub, parent, parent_ctx,
12777 child, leader, child_ctx);
12778 if (IS_ERR(child_ctr))
12779 return PTR_ERR(child_ctr);
12781 if (sub->aux_event == parent_event && child_ctr &&
12782 !perf_get_aux_event(child_ctr, leader))
12789 * Creates the child task context and tries to inherit the event-group.
12791 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12792 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12793 * consistent with perf_event_release_kernel() removing all child events.
12800 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12801 struct perf_event_context *parent_ctx,
12802 struct task_struct *child, int ctxn,
12803 int *inherited_all)
12806 struct perf_event_context *child_ctx;
12808 if (!event->attr.inherit) {
12809 *inherited_all = 0;
12813 child_ctx = child->perf_event_ctxp[ctxn];
12816 * This is executed from the parent task context, so
12817 * inherit events that have been marked for cloning.
12818 * First allocate and initialize a context for the
12821 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12825 child->perf_event_ctxp[ctxn] = child_ctx;
12828 ret = inherit_group(event, parent, parent_ctx,
12832 *inherited_all = 0;
12838 * Initialize the perf_event context in task_struct
12840 static int perf_event_init_context(struct task_struct *child, int ctxn)
12842 struct perf_event_context *child_ctx, *parent_ctx;
12843 struct perf_event_context *cloned_ctx;
12844 struct perf_event *event;
12845 struct task_struct *parent = current;
12846 int inherited_all = 1;
12847 unsigned long flags;
12850 if (likely(!parent->perf_event_ctxp[ctxn]))
12854 * If the parent's context is a clone, pin it so it won't get
12855 * swapped under us.
12857 parent_ctx = perf_pin_task_context(parent, ctxn);
12862 * No need to check if parent_ctx != NULL here; since we saw
12863 * it non-NULL earlier, the only reason for it to become NULL
12864 * is if we exit, and since we're currently in the middle of
12865 * a fork we can't be exiting at the same time.
12869 * Lock the parent list. No need to lock the child - not PID
12870 * hashed yet and not running, so nobody can access it.
12872 mutex_lock(&parent_ctx->mutex);
12875 * We dont have to disable NMIs - we are only looking at
12876 * the list, not manipulating it:
12878 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12879 ret = inherit_task_group(event, parent, parent_ctx,
12880 child, ctxn, &inherited_all);
12886 * We can't hold ctx->lock when iterating the ->flexible_group list due
12887 * to allocations, but we need to prevent rotation because
12888 * rotate_ctx() will change the list from interrupt context.
12890 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12891 parent_ctx->rotate_disable = 1;
12892 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12894 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12895 ret = inherit_task_group(event, parent, parent_ctx,
12896 child, ctxn, &inherited_all);
12901 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12902 parent_ctx->rotate_disable = 0;
12904 child_ctx = child->perf_event_ctxp[ctxn];
12906 if (child_ctx && inherited_all) {
12908 * Mark the child context as a clone of the parent
12909 * context, or of whatever the parent is a clone of.
12911 * Note that if the parent is a clone, the holding of
12912 * parent_ctx->lock avoids it from being uncloned.
12914 cloned_ctx = parent_ctx->parent_ctx;
12916 child_ctx->parent_ctx = cloned_ctx;
12917 child_ctx->parent_gen = parent_ctx->parent_gen;
12919 child_ctx->parent_ctx = parent_ctx;
12920 child_ctx->parent_gen = parent_ctx->generation;
12922 get_ctx(child_ctx->parent_ctx);
12925 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12927 mutex_unlock(&parent_ctx->mutex);
12929 perf_unpin_context(parent_ctx);
12930 put_ctx(parent_ctx);
12936 * Initialize the perf_event context in task_struct
12938 int perf_event_init_task(struct task_struct *child)
12942 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12943 mutex_init(&child->perf_event_mutex);
12944 INIT_LIST_HEAD(&child->perf_event_list);
12946 for_each_task_context_nr(ctxn) {
12947 ret = perf_event_init_context(child, ctxn);
12949 perf_event_free_task(child);
12957 static void __init perf_event_init_all_cpus(void)
12959 struct swevent_htable *swhash;
12962 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12964 for_each_possible_cpu(cpu) {
12965 swhash = &per_cpu(swevent_htable, cpu);
12966 mutex_init(&swhash->hlist_mutex);
12967 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12969 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12970 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12972 #ifdef CONFIG_CGROUP_PERF
12973 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12978 static void perf_swevent_init_cpu(unsigned int cpu)
12980 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12982 mutex_lock(&swhash->hlist_mutex);
12983 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12984 struct swevent_hlist *hlist;
12986 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12988 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12990 mutex_unlock(&swhash->hlist_mutex);
12993 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12994 static void __perf_event_exit_context(void *__info)
12996 struct perf_event_context *ctx = __info;
12997 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12998 struct perf_event *event;
13000 raw_spin_lock(&ctx->lock);
13001 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13002 list_for_each_entry(event, &ctx->event_list, event_entry)
13003 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13004 raw_spin_unlock(&ctx->lock);
13007 static void perf_event_exit_cpu_context(int cpu)
13009 struct perf_cpu_context *cpuctx;
13010 struct perf_event_context *ctx;
13013 mutex_lock(&pmus_lock);
13014 list_for_each_entry(pmu, &pmus, entry) {
13015 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13016 ctx = &cpuctx->ctx;
13018 mutex_lock(&ctx->mutex);
13019 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13020 cpuctx->online = 0;
13021 mutex_unlock(&ctx->mutex);
13023 cpumask_clear_cpu(cpu, perf_online_mask);
13024 mutex_unlock(&pmus_lock);
13028 static void perf_event_exit_cpu_context(int cpu) { }
13032 int perf_event_init_cpu(unsigned int cpu)
13034 struct perf_cpu_context *cpuctx;
13035 struct perf_event_context *ctx;
13038 perf_swevent_init_cpu(cpu);
13040 mutex_lock(&pmus_lock);
13041 cpumask_set_cpu(cpu, perf_online_mask);
13042 list_for_each_entry(pmu, &pmus, entry) {
13043 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13044 ctx = &cpuctx->ctx;
13046 mutex_lock(&ctx->mutex);
13047 cpuctx->online = 1;
13048 mutex_unlock(&ctx->mutex);
13050 mutex_unlock(&pmus_lock);
13055 int perf_event_exit_cpu(unsigned int cpu)
13057 perf_event_exit_cpu_context(cpu);
13062 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13066 for_each_online_cpu(cpu)
13067 perf_event_exit_cpu(cpu);
13073 * Run the perf reboot notifier at the very last possible moment so that
13074 * the generic watchdog code runs as long as possible.
13076 static struct notifier_block perf_reboot_notifier = {
13077 .notifier_call = perf_reboot,
13078 .priority = INT_MIN,
13081 void __init perf_event_init(void)
13085 idr_init(&pmu_idr);
13087 perf_event_init_all_cpus();
13088 init_srcu_struct(&pmus_srcu);
13089 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13090 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13091 perf_pmu_register(&perf_task_clock, NULL, -1);
13092 perf_tp_register();
13093 perf_event_init_cpu(smp_processor_id());
13094 register_reboot_notifier(&perf_reboot_notifier);
13096 ret = init_hw_breakpoint();
13097 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13100 * Build time assertion that we keep the data_head at the intended
13101 * location. IOW, validation we got the __reserved[] size right.
13103 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13107 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13110 struct perf_pmu_events_attr *pmu_attr =
13111 container_of(attr, struct perf_pmu_events_attr, attr);
13113 if (pmu_attr->event_str)
13114 return sprintf(page, "%s\n", pmu_attr->event_str);
13118 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13120 static int __init perf_event_sysfs_init(void)
13125 mutex_lock(&pmus_lock);
13127 ret = bus_register(&pmu_bus);
13131 list_for_each_entry(pmu, &pmus, entry) {
13132 if (!pmu->name || pmu->type < 0)
13135 ret = pmu_dev_alloc(pmu);
13136 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13138 pmu_bus_running = 1;
13142 mutex_unlock(&pmus_lock);
13146 device_initcall(perf_event_sysfs_init);
13148 #ifdef CONFIG_CGROUP_PERF
13149 static struct cgroup_subsys_state *
13150 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13152 struct perf_cgroup *jc;
13154 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13156 return ERR_PTR(-ENOMEM);
13158 jc->info = alloc_percpu(struct perf_cgroup_info);
13161 return ERR_PTR(-ENOMEM);
13167 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13169 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13171 free_percpu(jc->info);
13175 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13177 perf_event_cgroup(css->cgroup);
13181 static int __perf_cgroup_move(void *info)
13183 struct task_struct *task = info;
13185 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13190 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13192 struct task_struct *task;
13193 struct cgroup_subsys_state *css;
13195 cgroup_taskset_for_each(task, css, tset)
13196 task_function_call(task, __perf_cgroup_move, task);
13199 struct cgroup_subsys perf_event_cgrp_subsys = {
13200 .css_alloc = perf_cgroup_css_alloc,
13201 .css_free = perf_cgroup_css_free,
13202 .css_online = perf_cgroup_css_online,
13203 .attach = perf_cgroup_attach,
13205 * Implicitly enable on dfl hierarchy so that perf events can
13206 * always be filtered by cgroup2 path as long as perf_event
13207 * controller is not mounted on a legacy hierarchy.
13209 .implicit_on_dfl = true,
13212 #endif /* CONFIG_CGROUP_PERF */