perf/core: Fix a memory leak in perf_event_parse_addr_filter()
[linux/fpc-iii.git] / kernel / events / core.c
blob98a603098f23ed9e41dac3d15cbe1b513a68a962
1 // SPDX-License-Identifier: GPL-2.0
2 /*
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>
9 */
11 #include <linux/fs.h>
12 #include <linux/mm.h>
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>
55 #include "internal.h"
57 #include <asm/irq_regs.h>
59 typedef int (*remote_function_f)(void *);
61 struct remote_function_call {
62 struct task_struct *p;
63 remote_function_f func;
64 void *info;
65 int ret;
68 static void remote_function(void *data)
70 struct remote_function_call *tfc = data;
71 struct task_struct *p = tfc->p;
73 if (p) {
74 /* -EAGAIN */
75 if (task_cpu(p) != smp_processor_id())
76 return;
79 * Now that we're on right CPU with IRQs disabled, we can test
80 * if we hit the right task without races.
83 tfc->ret = -ESRCH; /* No such (running) process */
84 if (p != current)
85 return;
88 tfc->ret = tfc->func(tfc->info);
91 /**
92 * task_function_call - call a function on the cpu on which a task runs
93 * @p: the task to evaluate
94 * @func: the function to be called
95 * @info: the function call argument
97 * Calls the function @func when the task is currently running. This might
98 * be on the current CPU, which just calls the function directly. This will
99 * retry due to any failures in smp_call_function_single(), such as if the
100 * task_cpu() goes offline concurrently.
102 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
104 static int
105 task_function_call(struct task_struct *p, remote_function_f func, void *info)
107 struct remote_function_call data = {
108 .p = p,
109 .func = func,
110 .info = info,
111 .ret = -EAGAIN,
113 int ret;
115 for (;;) {
116 ret = smp_call_function_single(task_cpu(p), remote_function,
117 &data, 1);
118 if (!ret)
119 ret = data.ret;
121 if (ret != -EAGAIN)
122 break;
124 cond_resched();
127 return ret;
131 * cpu_function_call - call a function on the cpu
132 * @func: the function to be called
133 * @info: the function call argument
135 * Calls the function @func on the remote cpu.
137 * returns: @func return value or -ENXIO when the cpu is offline
139 static int cpu_function_call(int cpu, remote_function_f func, void *info)
141 struct remote_function_call data = {
142 .p = NULL,
143 .func = func,
144 .info = info,
145 .ret = -ENXIO, /* No such CPU */
148 smp_call_function_single(cpu, remote_function, &data, 1);
150 return data.ret;
153 static inline struct perf_cpu_context *
154 __get_cpu_context(struct perf_event_context *ctx)
156 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
159 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
160 struct perf_event_context *ctx)
162 raw_spin_lock(&cpuctx->ctx.lock);
163 if (ctx)
164 raw_spin_lock(&ctx->lock);
167 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
168 struct perf_event_context *ctx)
170 if (ctx)
171 raw_spin_unlock(&ctx->lock);
172 raw_spin_unlock(&cpuctx->ctx.lock);
175 #define TASK_TOMBSTONE ((void *)-1L)
177 static bool is_kernel_event(struct perf_event *event)
179 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
183 * On task ctx scheduling...
185 * When !ctx->nr_events a task context will not be scheduled. This means
186 * we can disable the scheduler hooks (for performance) without leaving
187 * pending task ctx state.
189 * This however results in two special cases:
191 * - removing the last event from a task ctx; this is relatively straight
192 * forward and is done in __perf_remove_from_context.
194 * - adding the first event to a task ctx; this is tricky because we cannot
195 * rely on ctx->is_active and therefore cannot use event_function_call().
196 * See perf_install_in_context().
198 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
201 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
202 struct perf_event_context *, void *);
204 struct event_function_struct {
205 struct perf_event *event;
206 event_f func;
207 void *data;
210 static int event_function(void *info)
212 struct event_function_struct *efs = info;
213 struct perf_event *event = efs->event;
214 struct perf_event_context *ctx = event->ctx;
215 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
216 struct perf_event_context *task_ctx = cpuctx->task_ctx;
217 int ret = 0;
219 lockdep_assert_irqs_disabled();
221 perf_ctx_lock(cpuctx, task_ctx);
223 * Since we do the IPI call without holding ctx->lock things can have
224 * changed, double check we hit the task we set out to hit.
226 if (ctx->task) {
227 if (ctx->task != current) {
228 ret = -ESRCH;
229 goto unlock;
233 * We only use event_function_call() on established contexts,
234 * and event_function() is only ever called when active (or
235 * rather, we'll have bailed in task_function_call() or the
236 * above ctx->task != current test), therefore we must have
237 * ctx->is_active here.
239 WARN_ON_ONCE(!ctx->is_active);
241 * And since we have ctx->is_active, cpuctx->task_ctx must
242 * match.
244 WARN_ON_ONCE(task_ctx != ctx);
245 } else {
246 WARN_ON_ONCE(&cpuctx->ctx != ctx);
249 efs->func(event, cpuctx, ctx, efs->data);
250 unlock:
251 perf_ctx_unlock(cpuctx, task_ctx);
253 return ret;
256 static void event_function_call(struct perf_event *event, event_f func, void *data)
258 struct perf_event_context *ctx = event->ctx;
259 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
260 struct event_function_struct efs = {
261 .event = event,
262 .func = func,
263 .data = data,
266 if (!event->parent) {
268 * If this is a !child event, we must hold ctx::mutex to
269 * stabilize the the event->ctx relation. See
270 * perf_event_ctx_lock().
272 lockdep_assert_held(&ctx->mutex);
275 if (!task) {
276 cpu_function_call(event->cpu, event_function, &efs);
277 return;
280 if (task == TASK_TOMBSTONE)
281 return;
283 again:
284 if (!task_function_call(task, event_function, &efs))
285 return;
287 raw_spin_lock_irq(&ctx->lock);
289 * Reload the task pointer, it might have been changed by
290 * a concurrent perf_event_context_sched_out().
292 task = ctx->task;
293 if (task == TASK_TOMBSTONE) {
294 raw_spin_unlock_irq(&ctx->lock);
295 return;
297 if (ctx->is_active) {
298 raw_spin_unlock_irq(&ctx->lock);
299 goto again;
301 func(event, NULL, ctx, data);
302 raw_spin_unlock_irq(&ctx->lock);
306 * Similar to event_function_call() + event_function(), but hard assumes IRQs
307 * are already disabled and we're on the right CPU.
309 static void event_function_local(struct perf_event *event, event_f func, void *data)
311 struct perf_event_context *ctx = event->ctx;
312 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
313 struct task_struct *task = READ_ONCE(ctx->task);
314 struct perf_event_context *task_ctx = NULL;
316 lockdep_assert_irqs_disabled();
318 if (task) {
319 if (task == TASK_TOMBSTONE)
320 return;
322 task_ctx = ctx;
325 perf_ctx_lock(cpuctx, task_ctx);
327 task = ctx->task;
328 if (task == TASK_TOMBSTONE)
329 goto unlock;
331 if (task) {
333 * We must be either inactive or active and the right task,
334 * otherwise we're screwed, since we cannot IPI to somewhere
335 * else.
337 if (ctx->is_active) {
338 if (WARN_ON_ONCE(task != current))
339 goto unlock;
341 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
342 goto unlock;
344 } else {
345 WARN_ON_ONCE(&cpuctx->ctx != ctx);
348 func(event, cpuctx, ctx, data);
349 unlock:
350 perf_ctx_unlock(cpuctx, task_ctx);
353 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
354 PERF_FLAG_FD_OUTPUT |\
355 PERF_FLAG_PID_CGROUP |\
356 PERF_FLAG_FD_CLOEXEC)
359 * branch priv levels that need permission checks
361 #define PERF_SAMPLE_BRANCH_PERM_PLM \
362 (PERF_SAMPLE_BRANCH_KERNEL |\
363 PERF_SAMPLE_BRANCH_HV)
365 enum event_type_t {
366 EVENT_FLEXIBLE = 0x1,
367 EVENT_PINNED = 0x2,
368 EVENT_TIME = 0x4,
369 /* see ctx_resched() for details */
370 EVENT_CPU = 0x8,
371 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
375 * perf_sched_events : >0 events exist
376 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
379 static void perf_sched_delayed(struct work_struct *work);
380 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
381 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
382 static DEFINE_MUTEX(perf_sched_mutex);
383 static atomic_t perf_sched_count;
385 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
386 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
387 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
389 static atomic_t nr_mmap_events __read_mostly;
390 static atomic_t nr_comm_events __read_mostly;
391 static atomic_t nr_namespaces_events __read_mostly;
392 static atomic_t nr_task_events __read_mostly;
393 static atomic_t nr_freq_events __read_mostly;
394 static atomic_t nr_switch_events __read_mostly;
395 static atomic_t nr_ksymbol_events __read_mostly;
396 static atomic_t nr_bpf_events __read_mostly;
397 static atomic_t nr_cgroup_events __read_mostly;
398 static atomic_t nr_text_poke_events __read_mostly;
400 static LIST_HEAD(pmus);
401 static DEFINE_MUTEX(pmus_lock);
402 static struct srcu_struct pmus_srcu;
403 static cpumask_var_t perf_online_mask;
406 * perf event paranoia level:
407 * -1 - not paranoid at all
408 * 0 - disallow raw tracepoint access for unpriv
409 * 1 - disallow cpu events for unpriv
410 * 2 - disallow kernel profiling for unpriv
412 int sysctl_perf_event_paranoid __read_mostly = 2;
414 /* Minimum for 512 kiB + 1 user control page */
415 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
418 * max perf event sample rate
420 #define DEFAULT_MAX_SAMPLE_RATE 100000
421 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
422 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
424 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
426 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
427 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
429 static int perf_sample_allowed_ns __read_mostly =
430 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
432 static void update_perf_cpu_limits(void)
434 u64 tmp = perf_sample_period_ns;
436 tmp *= sysctl_perf_cpu_time_max_percent;
437 tmp = div_u64(tmp, 100);
438 if (!tmp)
439 tmp = 1;
441 WRITE_ONCE(perf_sample_allowed_ns, tmp);
444 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
446 int perf_proc_update_handler(struct ctl_table *table, int write,
447 void *buffer, size_t *lenp, loff_t *ppos)
449 int ret;
450 int perf_cpu = sysctl_perf_cpu_time_max_percent;
452 * If throttling is disabled don't allow the write:
454 if (write && (perf_cpu == 100 || perf_cpu == 0))
455 return -EINVAL;
457 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
458 if (ret || !write)
459 return ret;
461 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
462 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
463 update_perf_cpu_limits();
465 return 0;
468 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
470 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
471 void *buffer, size_t *lenp, loff_t *ppos)
473 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
475 if (ret || !write)
476 return ret;
478 if (sysctl_perf_cpu_time_max_percent == 100 ||
479 sysctl_perf_cpu_time_max_percent == 0) {
480 printk(KERN_WARNING
481 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
482 WRITE_ONCE(perf_sample_allowed_ns, 0);
483 } else {
484 update_perf_cpu_limits();
487 return 0;
491 * perf samples are done in some very critical code paths (NMIs).
492 * If they take too much CPU time, the system can lock up and not
493 * get any real work done. This will drop the sample rate when
494 * we detect that events are taking too long.
496 #define NR_ACCUMULATED_SAMPLES 128
497 static DEFINE_PER_CPU(u64, running_sample_length);
499 static u64 __report_avg;
500 static u64 __report_allowed;
502 static void perf_duration_warn(struct irq_work *w)
504 printk_ratelimited(KERN_INFO
505 "perf: interrupt took too long (%lld > %lld), lowering "
506 "kernel.perf_event_max_sample_rate to %d\n",
507 __report_avg, __report_allowed,
508 sysctl_perf_event_sample_rate);
511 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
513 void perf_sample_event_took(u64 sample_len_ns)
515 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
516 u64 running_len;
517 u64 avg_len;
518 u32 max;
520 if (max_len == 0)
521 return;
523 /* Decay the counter by 1 average sample. */
524 running_len = __this_cpu_read(running_sample_length);
525 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
526 running_len += sample_len_ns;
527 __this_cpu_write(running_sample_length, running_len);
530 * Note: this will be biased artifically low until we have
531 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
532 * from having to maintain a count.
534 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
535 if (avg_len <= max_len)
536 return;
538 __report_avg = avg_len;
539 __report_allowed = max_len;
542 * Compute a throttle threshold 25% below the current duration.
544 avg_len += avg_len / 4;
545 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
546 if (avg_len < max)
547 max /= (u32)avg_len;
548 else
549 max = 1;
551 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
552 WRITE_ONCE(max_samples_per_tick, max);
554 sysctl_perf_event_sample_rate = max * HZ;
555 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
557 if (!irq_work_queue(&perf_duration_work)) {
558 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
559 "kernel.perf_event_max_sample_rate to %d\n",
560 __report_avg, __report_allowed,
561 sysctl_perf_event_sample_rate);
565 static atomic64_t perf_event_id;
567 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
568 enum event_type_t event_type);
570 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
571 enum event_type_t event_type,
572 struct task_struct *task);
574 static void update_context_time(struct perf_event_context *ctx);
575 static u64 perf_event_time(struct perf_event *event);
577 void __weak perf_event_print_debug(void) { }
579 extern __weak const char *perf_pmu_name(void)
581 return "pmu";
584 static inline u64 perf_clock(void)
586 return local_clock();
589 static inline u64 perf_event_clock(struct perf_event *event)
591 return event->clock();
595 * State based event timekeeping...
597 * The basic idea is to use event->state to determine which (if any) time
598 * fields to increment with the current delta. This means we only need to
599 * update timestamps when we change state or when they are explicitly requested
600 * (read).
602 * Event groups make things a little more complicated, but not terribly so. The
603 * rules for a group are that if the group leader is OFF the entire group is
604 * OFF, irrespecive of what the group member states are. This results in
605 * __perf_effective_state().
607 * A futher ramification is that when a group leader flips between OFF and
608 * !OFF, we need to update all group member times.
611 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
612 * need to make sure the relevant context time is updated before we try and
613 * update our timestamps.
616 static __always_inline enum perf_event_state
617 __perf_effective_state(struct perf_event *event)
619 struct perf_event *leader = event->group_leader;
621 if (leader->state <= PERF_EVENT_STATE_OFF)
622 return leader->state;
624 return event->state;
627 static __always_inline void
628 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
630 enum perf_event_state state = __perf_effective_state(event);
631 u64 delta = now - event->tstamp;
633 *enabled = event->total_time_enabled;
634 if (state >= PERF_EVENT_STATE_INACTIVE)
635 *enabled += delta;
637 *running = event->total_time_running;
638 if (state >= PERF_EVENT_STATE_ACTIVE)
639 *running += delta;
642 static void perf_event_update_time(struct perf_event *event)
644 u64 now = perf_event_time(event);
646 __perf_update_times(event, now, &event->total_time_enabled,
647 &event->total_time_running);
648 event->tstamp = now;
651 static void perf_event_update_sibling_time(struct perf_event *leader)
653 struct perf_event *sibling;
655 for_each_sibling_event(sibling, leader)
656 perf_event_update_time(sibling);
659 static void
660 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
662 if (event->state == state)
663 return;
665 perf_event_update_time(event);
667 * If a group leader gets enabled/disabled all its siblings
668 * are affected too.
670 if ((event->state < 0) ^ (state < 0))
671 perf_event_update_sibling_time(event);
673 WRITE_ONCE(event->state, state);
676 #ifdef CONFIG_CGROUP_PERF
678 static inline bool
679 perf_cgroup_match(struct perf_event *event)
681 struct perf_event_context *ctx = event->ctx;
682 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
684 /* @event doesn't care about cgroup */
685 if (!event->cgrp)
686 return true;
688 /* wants specific cgroup scope but @cpuctx isn't associated with any */
689 if (!cpuctx->cgrp)
690 return false;
693 * Cgroup scoping is recursive. An event enabled for a cgroup is
694 * also enabled for all its descendant cgroups. If @cpuctx's
695 * cgroup is a descendant of @event's (the test covers identity
696 * case), it's a match.
698 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
699 event->cgrp->css.cgroup);
702 static inline void perf_detach_cgroup(struct perf_event *event)
704 css_put(&event->cgrp->css);
705 event->cgrp = NULL;
708 static inline int is_cgroup_event(struct perf_event *event)
710 return event->cgrp != NULL;
713 static inline u64 perf_cgroup_event_time(struct perf_event *event)
715 struct perf_cgroup_info *t;
717 t = per_cpu_ptr(event->cgrp->info, event->cpu);
718 return t->time;
721 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
723 struct perf_cgroup_info *info;
724 u64 now;
726 now = perf_clock();
728 info = this_cpu_ptr(cgrp->info);
730 info->time += now - info->timestamp;
731 info->timestamp = now;
734 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
736 struct perf_cgroup *cgrp = cpuctx->cgrp;
737 struct cgroup_subsys_state *css;
739 if (cgrp) {
740 for (css = &cgrp->css; css; css = css->parent) {
741 cgrp = container_of(css, struct perf_cgroup, css);
742 __update_cgrp_time(cgrp);
747 static inline void update_cgrp_time_from_event(struct perf_event *event)
749 struct perf_cgroup *cgrp;
752 * ensure we access cgroup data only when needed and
753 * when we know the cgroup is pinned (css_get)
755 if (!is_cgroup_event(event))
756 return;
758 cgrp = perf_cgroup_from_task(current, event->ctx);
760 * Do not update time when cgroup is not active
762 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
763 __update_cgrp_time(event->cgrp);
766 static inline void
767 perf_cgroup_set_timestamp(struct task_struct *task,
768 struct perf_event_context *ctx)
770 struct perf_cgroup *cgrp;
771 struct perf_cgroup_info *info;
772 struct cgroup_subsys_state *css;
775 * ctx->lock held by caller
776 * ensure we do not access cgroup data
777 * unless we have the cgroup pinned (css_get)
779 if (!task || !ctx->nr_cgroups)
780 return;
782 cgrp = perf_cgroup_from_task(task, ctx);
784 for (css = &cgrp->css; css; css = css->parent) {
785 cgrp = container_of(css, struct perf_cgroup, css);
786 info = this_cpu_ptr(cgrp->info);
787 info->timestamp = ctx->timestamp;
791 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
793 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
794 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
797 * reschedule events based on the cgroup constraint of task.
799 * mode SWOUT : schedule out everything
800 * mode SWIN : schedule in based on cgroup for next
802 static void perf_cgroup_switch(struct task_struct *task, int mode)
804 struct perf_cpu_context *cpuctx;
805 struct list_head *list;
806 unsigned long flags;
809 * Disable interrupts and preemption to avoid this CPU's
810 * cgrp_cpuctx_entry to change under us.
812 local_irq_save(flags);
814 list = this_cpu_ptr(&cgrp_cpuctx_list);
815 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
816 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
818 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
819 perf_pmu_disable(cpuctx->ctx.pmu);
821 if (mode & PERF_CGROUP_SWOUT) {
822 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
824 * must not be done before ctxswout due
825 * to event_filter_match() in event_sched_out()
827 cpuctx->cgrp = NULL;
830 if (mode & PERF_CGROUP_SWIN) {
831 WARN_ON_ONCE(cpuctx->cgrp);
833 * set cgrp before ctxsw in to allow
834 * event_filter_match() to not have to pass
835 * task around
836 * we pass the cpuctx->ctx to perf_cgroup_from_task()
837 * because cgorup events are only per-cpu
839 cpuctx->cgrp = perf_cgroup_from_task(task,
840 &cpuctx->ctx);
841 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
843 perf_pmu_enable(cpuctx->ctx.pmu);
844 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
847 local_irq_restore(flags);
850 static inline void perf_cgroup_sched_out(struct task_struct *task,
851 struct task_struct *next)
853 struct perf_cgroup *cgrp1;
854 struct perf_cgroup *cgrp2 = NULL;
856 rcu_read_lock();
858 * we come here when we know perf_cgroup_events > 0
859 * we do not need to pass the ctx here because we know
860 * we are holding the rcu lock
862 cgrp1 = perf_cgroup_from_task(task, NULL);
863 cgrp2 = perf_cgroup_from_task(next, NULL);
866 * only schedule out current cgroup events if we know
867 * that we are switching to a different cgroup. Otherwise,
868 * do no touch the cgroup events.
870 if (cgrp1 != cgrp2)
871 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
873 rcu_read_unlock();
876 static inline void perf_cgroup_sched_in(struct task_struct *prev,
877 struct task_struct *task)
879 struct perf_cgroup *cgrp1;
880 struct perf_cgroup *cgrp2 = NULL;
882 rcu_read_lock();
884 * we come here when we know perf_cgroup_events > 0
885 * we do not need to pass the ctx here because we know
886 * we are holding the rcu lock
888 cgrp1 = perf_cgroup_from_task(task, NULL);
889 cgrp2 = perf_cgroup_from_task(prev, NULL);
892 * only need to schedule in cgroup events if we are changing
893 * cgroup during ctxsw. Cgroup events were not scheduled
894 * out of ctxsw out if that was not the case.
896 if (cgrp1 != cgrp2)
897 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
899 rcu_read_unlock();
902 static int perf_cgroup_ensure_storage(struct perf_event *event,
903 struct cgroup_subsys_state *css)
905 struct perf_cpu_context *cpuctx;
906 struct perf_event **storage;
907 int cpu, heap_size, ret = 0;
910 * Allow storage to have sufficent space for an iterator for each
911 * possibly nested cgroup plus an iterator for events with no cgroup.
913 for (heap_size = 1; css; css = css->parent)
914 heap_size++;
916 for_each_possible_cpu(cpu) {
917 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
918 if (heap_size <= cpuctx->heap_size)
919 continue;
921 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
922 GFP_KERNEL, cpu_to_node(cpu));
923 if (!storage) {
924 ret = -ENOMEM;
925 break;
928 raw_spin_lock_irq(&cpuctx->ctx.lock);
929 if (cpuctx->heap_size < heap_size) {
930 swap(cpuctx->heap, storage);
931 if (storage == cpuctx->heap_default)
932 storage = NULL;
933 cpuctx->heap_size = heap_size;
935 raw_spin_unlock_irq(&cpuctx->ctx.lock);
937 kfree(storage);
940 return ret;
943 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
944 struct perf_event_attr *attr,
945 struct perf_event *group_leader)
947 struct perf_cgroup *cgrp;
948 struct cgroup_subsys_state *css;
949 struct fd f = fdget(fd);
950 int ret = 0;
952 if (!f.file)
953 return -EBADF;
955 css = css_tryget_online_from_dir(f.file->f_path.dentry,
956 &perf_event_cgrp_subsys);
957 if (IS_ERR(css)) {
958 ret = PTR_ERR(css);
959 goto out;
962 ret = perf_cgroup_ensure_storage(event, css);
963 if (ret)
964 goto out;
966 cgrp = container_of(css, struct perf_cgroup, css);
967 event->cgrp = cgrp;
970 * all events in a group must monitor
971 * the same cgroup because a task belongs
972 * to only one perf cgroup at a time
974 if (group_leader && group_leader->cgrp != cgrp) {
975 perf_detach_cgroup(event);
976 ret = -EINVAL;
978 out:
979 fdput(f);
980 return ret;
983 static inline void
984 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
986 struct perf_cgroup_info *t;
987 t = per_cpu_ptr(event->cgrp->info, event->cpu);
988 event->shadow_ctx_time = now - t->timestamp;
991 static inline void
992 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
994 struct perf_cpu_context *cpuctx;
996 if (!is_cgroup_event(event))
997 return;
1000 * Because cgroup events are always per-cpu events,
1001 * @ctx == &cpuctx->ctx.
1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1006 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1007 * matching the event's cgroup, we must do this for every new event,
1008 * because if the first would mismatch, the second would not try again
1009 * and we would leave cpuctx->cgrp unset.
1011 if (ctx->is_active && !cpuctx->cgrp) {
1012 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1014 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1015 cpuctx->cgrp = cgrp;
1018 if (ctx->nr_cgroups++)
1019 return;
1021 list_add(&cpuctx->cgrp_cpuctx_entry,
1022 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1025 static inline void
1026 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1028 struct perf_cpu_context *cpuctx;
1030 if (!is_cgroup_event(event))
1031 return;
1034 * Because cgroup events are always per-cpu events,
1035 * @ctx == &cpuctx->ctx.
1037 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1039 if (--ctx->nr_cgroups)
1040 return;
1042 if (ctx->is_active && cpuctx->cgrp)
1043 cpuctx->cgrp = NULL;
1045 list_del(&cpuctx->cgrp_cpuctx_entry);
1048 #else /* !CONFIG_CGROUP_PERF */
1050 static inline bool
1051 perf_cgroup_match(struct perf_event *event)
1053 return true;
1056 static inline void perf_detach_cgroup(struct perf_event *event)
1059 static inline int is_cgroup_event(struct perf_event *event)
1061 return 0;
1064 static inline void update_cgrp_time_from_event(struct perf_event *event)
1068 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1072 static inline void perf_cgroup_sched_out(struct task_struct *task,
1073 struct task_struct *next)
1077 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1078 struct task_struct *task)
1082 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1083 struct perf_event_attr *attr,
1084 struct perf_event *group_leader)
1086 return -EINVAL;
1089 static inline void
1090 perf_cgroup_set_timestamp(struct task_struct *task,
1091 struct perf_event_context *ctx)
1095 static inline void
1096 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1100 static inline void
1101 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1105 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1107 return 0;
1110 static inline void
1111 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1115 static inline void
1116 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1119 #endif
1122 * set default to be dependent on timer tick just
1123 * like original code
1125 #define PERF_CPU_HRTIMER (1000 / HZ)
1127 * function must be called with interrupts disabled
1129 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1131 struct perf_cpu_context *cpuctx;
1132 bool rotations;
1134 lockdep_assert_irqs_disabled();
1136 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1137 rotations = perf_rotate_context(cpuctx);
1139 raw_spin_lock(&cpuctx->hrtimer_lock);
1140 if (rotations)
1141 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1142 else
1143 cpuctx->hrtimer_active = 0;
1144 raw_spin_unlock(&cpuctx->hrtimer_lock);
1146 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1149 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1151 struct hrtimer *timer = &cpuctx->hrtimer;
1152 struct pmu *pmu = cpuctx->ctx.pmu;
1153 u64 interval;
1155 /* no multiplexing needed for SW PMU */
1156 if (pmu->task_ctx_nr == perf_sw_context)
1157 return;
1160 * check default is sane, if not set then force to
1161 * default interval (1/tick)
1163 interval = pmu->hrtimer_interval_ms;
1164 if (interval < 1)
1165 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1167 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1169 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1170 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1171 timer->function = perf_mux_hrtimer_handler;
1174 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1176 struct hrtimer *timer = &cpuctx->hrtimer;
1177 struct pmu *pmu = cpuctx->ctx.pmu;
1178 unsigned long flags;
1180 /* not for SW PMU */
1181 if (pmu->task_ctx_nr == perf_sw_context)
1182 return 0;
1184 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1185 if (!cpuctx->hrtimer_active) {
1186 cpuctx->hrtimer_active = 1;
1187 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1188 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1190 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1192 return 0;
1195 void perf_pmu_disable(struct pmu *pmu)
1197 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1198 if (!(*count)++)
1199 pmu->pmu_disable(pmu);
1202 void perf_pmu_enable(struct pmu *pmu)
1204 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1205 if (!--(*count))
1206 pmu->pmu_enable(pmu);
1209 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1212 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1213 * perf_event_task_tick() are fully serialized because they're strictly cpu
1214 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1215 * disabled, while perf_event_task_tick is called from IRQ context.
1217 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1219 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1221 lockdep_assert_irqs_disabled();
1223 WARN_ON(!list_empty(&ctx->active_ctx_list));
1225 list_add(&ctx->active_ctx_list, head);
1228 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1230 lockdep_assert_irqs_disabled();
1232 WARN_ON(list_empty(&ctx->active_ctx_list));
1234 list_del_init(&ctx->active_ctx_list);
1237 static void get_ctx(struct perf_event_context *ctx)
1239 refcount_inc(&ctx->refcount);
1242 static void *alloc_task_ctx_data(struct pmu *pmu)
1244 if (pmu->task_ctx_cache)
1245 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1247 return NULL;
1250 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1252 if (pmu->task_ctx_cache && task_ctx_data)
1253 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1256 static void free_ctx(struct rcu_head *head)
1258 struct perf_event_context *ctx;
1260 ctx = container_of(head, struct perf_event_context, rcu_head);
1261 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1262 kfree(ctx);
1265 static void put_ctx(struct perf_event_context *ctx)
1267 if (refcount_dec_and_test(&ctx->refcount)) {
1268 if (ctx->parent_ctx)
1269 put_ctx(ctx->parent_ctx);
1270 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1271 put_task_struct(ctx->task);
1272 call_rcu(&ctx->rcu_head, free_ctx);
1277 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1278 * perf_pmu_migrate_context() we need some magic.
1280 * Those places that change perf_event::ctx will hold both
1281 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1283 * Lock ordering is by mutex address. There are two other sites where
1284 * perf_event_context::mutex nests and those are:
1286 * - perf_event_exit_task_context() [ child , 0 ]
1287 * perf_event_exit_event()
1288 * put_event() [ parent, 1 ]
1290 * - perf_event_init_context() [ parent, 0 ]
1291 * inherit_task_group()
1292 * inherit_group()
1293 * inherit_event()
1294 * perf_event_alloc()
1295 * perf_init_event()
1296 * perf_try_init_event() [ child , 1 ]
1298 * While it appears there is an obvious deadlock here -- the parent and child
1299 * nesting levels are inverted between the two. This is in fact safe because
1300 * life-time rules separate them. That is an exiting task cannot fork, and a
1301 * spawning task cannot (yet) exit.
1303 * But remember that that these are parent<->child context relations, and
1304 * migration does not affect children, therefore these two orderings should not
1305 * interact.
1307 * The change in perf_event::ctx does not affect children (as claimed above)
1308 * because the sys_perf_event_open() case will install a new event and break
1309 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1310 * concerned with cpuctx and that doesn't have children.
1312 * The places that change perf_event::ctx will issue:
1314 * perf_remove_from_context();
1315 * synchronize_rcu();
1316 * perf_install_in_context();
1318 * to affect the change. The remove_from_context() + synchronize_rcu() should
1319 * quiesce the event, after which we can install it in the new location. This
1320 * means that only external vectors (perf_fops, prctl) can perturb the event
1321 * while in transit. Therefore all such accessors should also acquire
1322 * perf_event_context::mutex to serialize against this.
1324 * However; because event->ctx can change while we're waiting to acquire
1325 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1326 * function.
1328 * Lock order:
1329 * exec_update_mutex
1330 * task_struct::perf_event_mutex
1331 * perf_event_context::mutex
1332 * perf_event::child_mutex;
1333 * perf_event_context::lock
1334 * perf_event::mmap_mutex
1335 * mmap_lock
1336 * perf_addr_filters_head::lock
1338 * cpu_hotplug_lock
1339 * pmus_lock
1340 * cpuctx->mutex / perf_event_context::mutex
1342 static struct perf_event_context *
1343 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1345 struct perf_event_context *ctx;
1347 again:
1348 rcu_read_lock();
1349 ctx = READ_ONCE(event->ctx);
1350 if (!refcount_inc_not_zero(&ctx->refcount)) {
1351 rcu_read_unlock();
1352 goto again;
1354 rcu_read_unlock();
1356 mutex_lock_nested(&ctx->mutex, nesting);
1357 if (event->ctx != ctx) {
1358 mutex_unlock(&ctx->mutex);
1359 put_ctx(ctx);
1360 goto again;
1363 return ctx;
1366 static inline struct perf_event_context *
1367 perf_event_ctx_lock(struct perf_event *event)
1369 return perf_event_ctx_lock_nested(event, 0);
1372 static void perf_event_ctx_unlock(struct perf_event *event,
1373 struct perf_event_context *ctx)
1375 mutex_unlock(&ctx->mutex);
1376 put_ctx(ctx);
1380 * This must be done under the ctx->lock, such as to serialize against
1381 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1382 * calling scheduler related locks and ctx->lock nests inside those.
1384 static __must_check struct perf_event_context *
1385 unclone_ctx(struct perf_event_context *ctx)
1387 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1389 lockdep_assert_held(&ctx->lock);
1391 if (parent_ctx)
1392 ctx->parent_ctx = NULL;
1393 ctx->generation++;
1395 return parent_ctx;
1398 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1399 enum pid_type type)
1401 u32 nr;
1403 * only top level events have the pid namespace they were created in
1405 if (event->parent)
1406 event = event->parent;
1408 nr = __task_pid_nr_ns(p, type, event->ns);
1409 /* avoid -1 if it is idle thread or runs in another ns */
1410 if (!nr && !pid_alive(p))
1411 nr = -1;
1412 return nr;
1415 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1417 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1420 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1422 return perf_event_pid_type(event, p, PIDTYPE_PID);
1426 * If we inherit events we want to return the parent event id
1427 * to userspace.
1429 static u64 primary_event_id(struct perf_event *event)
1431 u64 id = event->id;
1433 if (event->parent)
1434 id = event->parent->id;
1436 return id;
1440 * Get the perf_event_context for a task and lock it.
1442 * This has to cope with with the fact that until it is locked,
1443 * the context could get moved to another task.
1445 static struct perf_event_context *
1446 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1448 struct perf_event_context *ctx;
1450 retry:
1452 * One of the few rules of preemptible RCU is that one cannot do
1453 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1454 * part of the read side critical section was irqs-enabled -- see
1455 * rcu_read_unlock_special().
1457 * Since ctx->lock nests under rq->lock we must ensure the entire read
1458 * side critical section has interrupts disabled.
1460 local_irq_save(*flags);
1461 rcu_read_lock();
1462 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1463 if (ctx) {
1465 * If this context is a clone of another, it might
1466 * get swapped for another underneath us by
1467 * perf_event_task_sched_out, though the
1468 * rcu_read_lock() protects us from any context
1469 * getting freed. Lock the context and check if it
1470 * got swapped before we could get the lock, and retry
1471 * if so. If we locked the right context, then it
1472 * can't get swapped on us any more.
1474 raw_spin_lock(&ctx->lock);
1475 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1476 raw_spin_unlock(&ctx->lock);
1477 rcu_read_unlock();
1478 local_irq_restore(*flags);
1479 goto retry;
1482 if (ctx->task == TASK_TOMBSTONE ||
1483 !refcount_inc_not_zero(&ctx->refcount)) {
1484 raw_spin_unlock(&ctx->lock);
1485 ctx = NULL;
1486 } else {
1487 WARN_ON_ONCE(ctx->task != task);
1490 rcu_read_unlock();
1491 if (!ctx)
1492 local_irq_restore(*flags);
1493 return ctx;
1497 * Get the context for a task and increment its pin_count so it
1498 * can't get swapped to another task. This also increments its
1499 * reference count so that the context can't get freed.
1501 static struct perf_event_context *
1502 perf_pin_task_context(struct task_struct *task, int ctxn)
1504 struct perf_event_context *ctx;
1505 unsigned long flags;
1507 ctx = perf_lock_task_context(task, ctxn, &flags);
1508 if (ctx) {
1509 ++ctx->pin_count;
1510 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1512 return ctx;
1515 static void perf_unpin_context(struct perf_event_context *ctx)
1517 unsigned long flags;
1519 raw_spin_lock_irqsave(&ctx->lock, flags);
1520 --ctx->pin_count;
1521 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1525 * Update the record of the current time in a context.
1527 static void update_context_time(struct perf_event_context *ctx)
1529 u64 now = perf_clock();
1531 ctx->time += now - ctx->timestamp;
1532 ctx->timestamp = now;
1535 static u64 perf_event_time(struct perf_event *event)
1537 struct perf_event_context *ctx = event->ctx;
1539 if (is_cgroup_event(event))
1540 return perf_cgroup_event_time(event);
1542 return ctx ? ctx->time : 0;
1545 static enum event_type_t get_event_type(struct perf_event *event)
1547 struct perf_event_context *ctx = event->ctx;
1548 enum event_type_t event_type;
1550 lockdep_assert_held(&ctx->lock);
1553 * It's 'group type', really, because if our group leader is
1554 * pinned, so are we.
1556 if (event->group_leader != event)
1557 event = event->group_leader;
1559 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1560 if (!ctx->task)
1561 event_type |= EVENT_CPU;
1563 return event_type;
1567 * Helper function to initialize event group nodes.
1569 static void init_event_group(struct perf_event *event)
1571 RB_CLEAR_NODE(&event->group_node);
1572 event->group_index = 0;
1576 * Extract pinned or flexible groups from the context
1577 * based on event attrs bits.
1579 static struct perf_event_groups *
1580 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1582 if (event->attr.pinned)
1583 return &ctx->pinned_groups;
1584 else
1585 return &ctx->flexible_groups;
1589 * Helper function to initializes perf_event_group trees.
1591 static void perf_event_groups_init(struct perf_event_groups *groups)
1593 groups->tree = RB_ROOT;
1594 groups->index = 0;
1598 * Compare function for event groups;
1600 * Implements complex key that first sorts by CPU and then by virtual index
1601 * which provides ordering when rotating groups for the same CPU.
1603 static bool
1604 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1606 if (left->cpu < right->cpu)
1607 return true;
1608 if (left->cpu > right->cpu)
1609 return false;
1611 #ifdef CONFIG_CGROUP_PERF
1612 if (left->cgrp != right->cgrp) {
1613 if (!left->cgrp || !left->cgrp->css.cgroup) {
1615 * Left has no cgroup but right does, no cgroups come
1616 * first.
1618 return true;
1620 if (!right->cgrp || !right->cgrp->css.cgroup) {
1622 * Right has no cgroup but left does, no cgroups come
1623 * first.
1625 return false;
1627 /* Two dissimilar cgroups, order by id. */
1628 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1629 return true;
1631 return false;
1633 #endif
1635 if (left->group_index < right->group_index)
1636 return true;
1637 if (left->group_index > right->group_index)
1638 return false;
1640 return false;
1644 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1645 * key (see perf_event_groups_less). This places it last inside the CPU
1646 * subtree.
1648 static void
1649 perf_event_groups_insert(struct perf_event_groups *groups,
1650 struct perf_event *event)
1652 struct perf_event *node_event;
1653 struct rb_node *parent;
1654 struct rb_node **node;
1656 event->group_index = ++groups->index;
1658 node = &groups->tree.rb_node;
1659 parent = *node;
1661 while (*node) {
1662 parent = *node;
1663 node_event = container_of(*node, struct perf_event, group_node);
1665 if (perf_event_groups_less(event, node_event))
1666 node = &parent->rb_left;
1667 else
1668 node = &parent->rb_right;
1671 rb_link_node(&event->group_node, parent, node);
1672 rb_insert_color(&event->group_node, &groups->tree);
1676 * Helper function to insert event into the pinned or flexible groups.
1678 static void
1679 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1681 struct perf_event_groups *groups;
1683 groups = get_event_groups(event, ctx);
1684 perf_event_groups_insert(groups, event);
1688 * Delete a group from a tree.
1690 static void
1691 perf_event_groups_delete(struct perf_event_groups *groups,
1692 struct perf_event *event)
1694 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1695 RB_EMPTY_ROOT(&groups->tree));
1697 rb_erase(&event->group_node, &groups->tree);
1698 init_event_group(event);
1702 * Helper function to delete event from its groups.
1704 static void
1705 del_event_from_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_delete(groups, event);
1714 * Get the leftmost event in the cpu/cgroup subtree.
1716 static struct perf_event *
1717 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1718 struct cgroup *cgrp)
1720 struct perf_event *node_event = NULL, *match = NULL;
1721 struct rb_node *node = groups->tree.rb_node;
1722 #ifdef CONFIG_CGROUP_PERF
1723 u64 node_cgrp_id, cgrp_id = 0;
1725 if (cgrp)
1726 cgrp_id = cgrp->kn->id;
1727 #endif
1729 while (node) {
1730 node_event = container_of(node, struct perf_event, group_node);
1732 if (cpu < node_event->cpu) {
1733 node = node->rb_left;
1734 continue;
1736 if (cpu > node_event->cpu) {
1737 node = node->rb_right;
1738 continue;
1740 #ifdef CONFIG_CGROUP_PERF
1741 node_cgrp_id = 0;
1742 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1743 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1745 if (cgrp_id < node_cgrp_id) {
1746 node = node->rb_left;
1747 continue;
1749 if (cgrp_id > node_cgrp_id) {
1750 node = node->rb_right;
1751 continue;
1753 #endif
1754 match = node_event;
1755 node = node->rb_left;
1758 return match;
1762 * Like rb_entry_next_safe() for the @cpu subtree.
1764 static struct perf_event *
1765 perf_event_groups_next(struct perf_event *event)
1767 struct perf_event *next;
1768 #ifdef CONFIG_CGROUP_PERF
1769 u64 curr_cgrp_id = 0;
1770 u64 next_cgrp_id = 0;
1771 #endif
1773 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1774 if (next == NULL || next->cpu != event->cpu)
1775 return NULL;
1777 #ifdef CONFIG_CGROUP_PERF
1778 if (event->cgrp && event->cgrp->css.cgroup)
1779 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1781 if (next->cgrp && next->cgrp->css.cgroup)
1782 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1784 if (curr_cgrp_id != next_cgrp_id)
1785 return NULL;
1786 #endif
1787 return next;
1791 * Iterate through the whole groups tree.
1793 #define perf_event_groups_for_each(event, groups) \
1794 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1795 typeof(*event), group_node); event; \
1796 event = rb_entry_safe(rb_next(&event->group_node), \
1797 typeof(*event), group_node))
1800 * Add an event from the lists for its context.
1801 * Must be called with ctx->mutex and ctx->lock held.
1803 static void
1804 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1806 lockdep_assert_held(&ctx->lock);
1808 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1809 event->attach_state |= PERF_ATTACH_CONTEXT;
1811 event->tstamp = perf_event_time(event);
1814 * If we're a stand alone event or group leader, we go to the context
1815 * list, group events are kept attached to the group so that
1816 * perf_group_detach can, at all times, locate all siblings.
1818 if (event->group_leader == event) {
1819 event->group_caps = event->event_caps;
1820 add_event_to_groups(event, ctx);
1823 list_add_rcu(&event->event_entry, &ctx->event_list);
1824 ctx->nr_events++;
1825 if (event->attr.inherit_stat)
1826 ctx->nr_stat++;
1828 if (event->state > PERF_EVENT_STATE_OFF)
1829 perf_cgroup_event_enable(event, ctx);
1831 ctx->generation++;
1835 * Initialize event state based on the perf_event_attr::disabled.
1837 static inline void perf_event__state_init(struct perf_event *event)
1839 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1840 PERF_EVENT_STATE_INACTIVE;
1843 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1845 int entry = sizeof(u64); /* value */
1846 int size = 0;
1847 int nr = 1;
1849 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1850 size += sizeof(u64);
1852 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1853 size += sizeof(u64);
1855 if (event->attr.read_format & PERF_FORMAT_ID)
1856 entry += sizeof(u64);
1858 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1859 nr += nr_siblings;
1860 size += sizeof(u64);
1863 size += entry * nr;
1864 event->read_size = size;
1867 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1869 struct perf_sample_data *data;
1870 u16 size = 0;
1872 if (sample_type & PERF_SAMPLE_IP)
1873 size += sizeof(data->ip);
1875 if (sample_type & PERF_SAMPLE_ADDR)
1876 size += sizeof(data->addr);
1878 if (sample_type & PERF_SAMPLE_PERIOD)
1879 size += sizeof(data->period);
1881 if (sample_type & PERF_SAMPLE_WEIGHT)
1882 size += sizeof(data->weight);
1884 if (sample_type & PERF_SAMPLE_READ)
1885 size += event->read_size;
1887 if (sample_type & PERF_SAMPLE_DATA_SRC)
1888 size += sizeof(data->data_src.val);
1890 if (sample_type & PERF_SAMPLE_TRANSACTION)
1891 size += sizeof(data->txn);
1893 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1894 size += sizeof(data->phys_addr);
1896 if (sample_type & PERF_SAMPLE_CGROUP)
1897 size += sizeof(data->cgroup);
1899 event->header_size = size;
1903 * Called at perf_event creation and when events are attached/detached from a
1904 * group.
1906 static void perf_event__header_size(struct perf_event *event)
1908 __perf_event_read_size(event,
1909 event->group_leader->nr_siblings);
1910 __perf_event_header_size(event, event->attr.sample_type);
1913 static void perf_event__id_header_size(struct perf_event *event)
1915 struct perf_sample_data *data;
1916 u64 sample_type = event->attr.sample_type;
1917 u16 size = 0;
1919 if (sample_type & PERF_SAMPLE_TID)
1920 size += sizeof(data->tid_entry);
1922 if (sample_type & PERF_SAMPLE_TIME)
1923 size += sizeof(data->time);
1925 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1926 size += sizeof(data->id);
1928 if (sample_type & PERF_SAMPLE_ID)
1929 size += sizeof(data->id);
1931 if (sample_type & PERF_SAMPLE_STREAM_ID)
1932 size += sizeof(data->stream_id);
1934 if (sample_type & PERF_SAMPLE_CPU)
1935 size += sizeof(data->cpu_entry);
1937 event->id_header_size = size;
1940 static bool perf_event_validate_size(struct perf_event *event)
1943 * The values computed here will be over-written when we actually
1944 * attach the event.
1946 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1947 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1948 perf_event__id_header_size(event);
1951 * Sum the lot; should not exceed the 64k limit we have on records.
1952 * Conservative limit to allow for callchains and other variable fields.
1954 if (event->read_size + event->header_size +
1955 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1956 return false;
1958 return true;
1961 static void perf_group_attach(struct perf_event *event)
1963 struct perf_event *group_leader = event->group_leader, *pos;
1965 lockdep_assert_held(&event->ctx->lock);
1968 * We can have double attach due to group movement in perf_event_open.
1970 if (event->attach_state & PERF_ATTACH_GROUP)
1971 return;
1973 event->attach_state |= PERF_ATTACH_GROUP;
1975 if (group_leader == event)
1976 return;
1978 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1980 group_leader->group_caps &= event->event_caps;
1982 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1983 group_leader->nr_siblings++;
1985 perf_event__header_size(group_leader);
1987 for_each_sibling_event(pos, group_leader)
1988 perf_event__header_size(pos);
1992 * Remove an event from the lists for its context.
1993 * Must be called with ctx->mutex and ctx->lock held.
1995 static void
1996 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1998 WARN_ON_ONCE(event->ctx != ctx);
1999 lockdep_assert_held(&ctx->lock);
2002 * We can have double detach due to exit/hot-unplug + close.
2004 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2005 return;
2007 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2009 ctx->nr_events--;
2010 if (event->attr.inherit_stat)
2011 ctx->nr_stat--;
2013 list_del_rcu(&event->event_entry);
2015 if (event->group_leader == event)
2016 del_event_from_groups(event, ctx);
2019 * If event was in error state, then keep it
2020 * that way, otherwise bogus counts will be
2021 * returned on read(). The only way to get out
2022 * of error state is by explicit re-enabling
2023 * of the event
2025 if (event->state > PERF_EVENT_STATE_OFF) {
2026 perf_cgroup_event_disable(event, ctx);
2027 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2030 ctx->generation++;
2033 static int
2034 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2036 if (!has_aux(aux_event))
2037 return 0;
2039 if (!event->pmu->aux_output_match)
2040 return 0;
2042 return event->pmu->aux_output_match(aux_event);
2045 static void put_event(struct perf_event *event);
2046 static void event_sched_out(struct perf_event *event,
2047 struct perf_cpu_context *cpuctx,
2048 struct perf_event_context *ctx);
2050 static void perf_put_aux_event(struct perf_event *event)
2052 struct perf_event_context *ctx = event->ctx;
2053 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2054 struct perf_event *iter;
2057 * If event uses aux_event tear down the link
2059 if (event->aux_event) {
2060 iter = event->aux_event;
2061 event->aux_event = NULL;
2062 put_event(iter);
2063 return;
2067 * If the event is an aux_event, tear down all links to
2068 * it from other events.
2070 for_each_sibling_event(iter, event->group_leader) {
2071 if (iter->aux_event != event)
2072 continue;
2074 iter->aux_event = NULL;
2075 put_event(event);
2078 * If it's ACTIVE, schedule it out and put it into ERROR
2079 * state so that we don't try to schedule it again. Note
2080 * that perf_event_enable() will clear the ERROR status.
2082 event_sched_out(iter, cpuctx, ctx);
2083 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2087 static bool perf_need_aux_event(struct perf_event *event)
2089 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2092 static int perf_get_aux_event(struct perf_event *event,
2093 struct perf_event *group_leader)
2096 * Our group leader must be an aux event if we want to be
2097 * an aux_output. This way, the aux event will precede its
2098 * aux_output events in the group, and therefore will always
2099 * schedule first.
2101 if (!group_leader)
2102 return 0;
2105 * aux_output and aux_sample_size are mutually exclusive.
2107 if (event->attr.aux_output && event->attr.aux_sample_size)
2108 return 0;
2110 if (event->attr.aux_output &&
2111 !perf_aux_output_match(event, group_leader))
2112 return 0;
2114 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2115 return 0;
2117 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2118 return 0;
2121 * Link aux_outputs to their aux event; this is undone in
2122 * perf_group_detach() by perf_put_aux_event(). When the
2123 * group in torn down, the aux_output events loose their
2124 * link to the aux_event and can't schedule any more.
2126 event->aux_event = group_leader;
2128 return 1;
2131 static inline struct list_head *get_event_list(struct perf_event *event)
2133 struct perf_event_context *ctx = event->ctx;
2134 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2137 static void perf_group_detach(struct perf_event *event)
2139 struct perf_event *sibling, *tmp;
2140 struct perf_event_context *ctx = event->ctx;
2142 lockdep_assert_held(&ctx->lock);
2145 * We can have double detach due to exit/hot-unplug + close.
2147 if (!(event->attach_state & PERF_ATTACH_GROUP))
2148 return;
2150 event->attach_state &= ~PERF_ATTACH_GROUP;
2152 perf_put_aux_event(event);
2155 * If this is a sibling, remove it from its group.
2157 if (event->group_leader != event) {
2158 list_del_init(&event->sibling_list);
2159 event->group_leader->nr_siblings--;
2160 goto out;
2164 * If this was a group event with sibling events then
2165 * upgrade the siblings to singleton events by adding them
2166 * to whatever list we are on.
2168 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2170 sibling->group_leader = sibling;
2171 list_del_init(&sibling->sibling_list);
2173 /* Inherit group flags from the previous leader */
2174 sibling->group_caps = event->group_caps;
2176 if (!RB_EMPTY_NODE(&event->group_node)) {
2177 add_event_to_groups(sibling, event->ctx);
2179 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2180 list_add_tail(&sibling->active_list, get_event_list(sibling));
2183 WARN_ON_ONCE(sibling->ctx != event->ctx);
2186 out:
2187 perf_event__header_size(event->group_leader);
2189 for_each_sibling_event(tmp, event->group_leader)
2190 perf_event__header_size(tmp);
2193 static bool is_orphaned_event(struct perf_event *event)
2195 return event->state == PERF_EVENT_STATE_DEAD;
2198 static inline int __pmu_filter_match(struct perf_event *event)
2200 struct pmu *pmu = event->pmu;
2201 return pmu->filter_match ? pmu->filter_match(event) : 1;
2205 * Check whether we should attempt to schedule an event group based on
2206 * PMU-specific filtering. An event group can consist of HW and SW events,
2207 * potentially with a SW leader, so we must check all the filters, to
2208 * determine whether a group is schedulable:
2210 static inline int pmu_filter_match(struct perf_event *event)
2212 struct perf_event *sibling;
2214 if (!__pmu_filter_match(event))
2215 return 0;
2217 for_each_sibling_event(sibling, event) {
2218 if (!__pmu_filter_match(sibling))
2219 return 0;
2222 return 1;
2225 static inline int
2226 event_filter_match(struct perf_event *event)
2228 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2229 perf_cgroup_match(event) && pmu_filter_match(event);
2232 static void
2233 event_sched_out(struct perf_event *event,
2234 struct perf_cpu_context *cpuctx,
2235 struct perf_event_context *ctx)
2237 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2239 WARN_ON_ONCE(event->ctx != ctx);
2240 lockdep_assert_held(&ctx->lock);
2242 if (event->state != PERF_EVENT_STATE_ACTIVE)
2243 return;
2246 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2247 * we can schedule events _OUT_ individually through things like
2248 * __perf_remove_from_context().
2250 list_del_init(&event->active_list);
2252 perf_pmu_disable(event->pmu);
2254 event->pmu->del(event, 0);
2255 event->oncpu = -1;
2257 if (READ_ONCE(event->pending_disable) >= 0) {
2258 WRITE_ONCE(event->pending_disable, -1);
2259 perf_cgroup_event_disable(event, ctx);
2260 state = PERF_EVENT_STATE_OFF;
2262 perf_event_set_state(event, state);
2264 if (!is_software_event(event))
2265 cpuctx->active_oncpu--;
2266 if (!--ctx->nr_active)
2267 perf_event_ctx_deactivate(ctx);
2268 if (event->attr.freq && event->attr.sample_freq)
2269 ctx->nr_freq--;
2270 if (event->attr.exclusive || !cpuctx->active_oncpu)
2271 cpuctx->exclusive = 0;
2273 perf_pmu_enable(event->pmu);
2276 static void
2277 group_sched_out(struct perf_event *group_event,
2278 struct perf_cpu_context *cpuctx,
2279 struct perf_event_context *ctx)
2281 struct perf_event *event;
2283 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2284 return;
2286 perf_pmu_disable(ctx->pmu);
2288 event_sched_out(group_event, cpuctx, ctx);
2291 * Schedule out siblings (if any):
2293 for_each_sibling_event(event, group_event)
2294 event_sched_out(event, cpuctx, ctx);
2296 perf_pmu_enable(ctx->pmu);
2298 if (group_event->attr.exclusive)
2299 cpuctx->exclusive = 0;
2302 #define DETACH_GROUP 0x01UL
2305 * Cross CPU call to remove a performance event
2307 * We disable the event on the hardware level first. After that we
2308 * remove it from the context list.
2310 static void
2311 __perf_remove_from_context(struct perf_event *event,
2312 struct perf_cpu_context *cpuctx,
2313 struct perf_event_context *ctx,
2314 void *info)
2316 unsigned long flags = (unsigned long)info;
2318 if (ctx->is_active & EVENT_TIME) {
2319 update_context_time(ctx);
2320 update_cgrp_time_from_cpuctx(cpuctx);
2323 event_sched_out(event, cpuctx, ctx);
2324 if (flags & DETACH_GROUP)
2325 perf_group_detach(event);
2326 list_del_event(event, ctx);
2328 if (!ctx->nr_events && ctx->is_active) {
2329 ctx->is_active = 0;
2330 ctx->rotate_necessary = 0;
2331 if (ctx->task) {
2332 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2333 cpuctx->task_ctx = NULL;
2339 * Remove the event from a task's (or a CPU's) list of events.
2341 * If event->ctx is a cloned context, callers must make sure that
2342 * every task struct that event->ctx->task could possibly point to
2343 * remains valid. This is OK when called from perf_release since
2344 * that only calls us on the top-level context, which can't be a clone.
2345 * When called from perf_event_exit_task, it's OK because the
2346 * context has been detached from its task.
2348 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2350 struct perf_event_context *ctx = event->ctx;
2352 lockdep_assert_held(&ctx->mutex);
2354 event_function_call(event, __perf_remove_from_context, (void *)flags);
2357 * The above event_function_call() can NO-OP when it hits
2358 * TASK_TOMBSTONE. In that case we must already have been detached
2359 * from the context (by perf_event_exit_event()) but the grouping
2360 * might still be in-tact.
2362 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2363 if ((flags & DETACH_GROUP) &&
2364 (event->attach_state & PERF_ATTACH_GROUP)) {
2366 * Since in that case we cannot possibly be scheduled, simply
2367 * detach now.
2369 raw_spin_lock_irq(&ctx->lock);
2370 perf_group_detach(event);
2371 raw_spin_unlock_irq(&ctx->lock);
2376 * Cross CPU call to disable a performance event
2378 static void __perf_event_disable(struct perf_event *event,
2379 struct perf_cpu_context *cpuctx,
2380 struct perf_event_context *ctx,
2381 void *info)
2383 if (event->state < PERF_EVENT_STATE_INACTIVE)
2384 return;
2386 if (ctx->is_active & EVENT_TIME) {
2387 update_context_time(ctx);
2388 update_cgrp_time_from_event(event);
2391 if (event == event->group_leader)
2392 group_sched_out(event, cpuctx, ctx);
2393 else
2394 event_sched_out(event, cpuctx, ctx);
2396 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2397 perf_cgroup_event_disable(event, ctx);
2401 * Disable an event.
2403 * If event->ctx is a cloned context, callers must make sure that
2404 * every task struct that event->ctx->task could possibly point to
2405 * remains valid. This condition is satisfied when called through
2406 * perf_event_for_each_child or perf_event_for_each because they
2407 * hold the top-level event's child_mutex, so any descendant that
2408 * goes to exit will block in perf_event_exit_event().
2410 * When called from perf_pending_event it's OK because event->ctx
2411 * is the current context on this CPU and preemption is disabled,
2412 * hence we can't get into perf_event_task_sched_out for this context.
2414 static void _perf_event_disable(struct perf_event *event)
2416 struct perf_event_context *ctx = event->ctx;
2418 raw_spin_lock_irq(&ctx->lock);
2419 if (event->state <= PERF_EVENT_STATE_OFF) {
2420 raw_spin_unlock_irq(&ctx->lock);
2421 return;
2423 raw_spin_unlock_irq(&ctx->lock);
2425 event_function_call(event, __perf_event_disable, NULL);
2428 void perf_event_disable_local(struct perf_event *event)
2430 event_function_local(event, __perf_event_disable, NULL);
2434 * Strictly speaking kernel users cannot create groups and therefore this
2435 * interface does not need the perf_event_ctx_lock() magic.
2437 void perf_event_disable(struct perf_event *event)
2439 struct perf_event_context *ctx;
2441 ctx = perf_event_ctx_lock(event);
2442 _perf_event_disable(event);
2443 perf_event_ctx_unlock(event, ctx);
2445 EXPORT_SYMBOL_GPL(perf_event_disable);
2447 void perf_event_disable_inatomic(struct perf_event *event)
2449 WRITE_ONCE(event->pending_disable, smp_processor_id());
2450 /* can fail, see perf_pending_event_disable() */
2451 irq_work_queue(&event->pending);
2454 static void perf_set_shadow_time(struct perf_event *event,
2455 struct perf_event_context *ctx)
2458 * use the correct time source for the time snapshot
2460 * We could get by without this by leveraging the
2461 * fact that to get to this function, the caller
2462 * has most likely already called update_context_time()
2463 * and update_cgrp_time_xx() and thus both timestamp
2464 * are identical (or very close). Given that tstamp is,
2465 * already adjusted for cgroup, we could say that:
2466 * tstamp - ctx->timestamp
2467 * is equivalent to
2468 * tstamp - cgrp->timestamp.
2470 * Then, in perf_output_read(), the calculation would
2471 * work with no changes because:
2472 * - event is guaranteed scheduled in
2473 * - no scheduled out in between
2474 * - thus the timestamp would be the same
2476 * But this is a bit hairy.
2478 * So instead, we have an explicit cgroup call to remain
2479 * within the time time source all along. We believe it
2480 * is cleaner and simpler to understand.
2482 if (is_cgroup_event(event))
2483 perf_cgroup_set_shadow_time(event, event->tstamp);
2484 else
2485 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2488 #define MAX_INTERRUPTS (~0ULL)
2490 static void perf_log_throttle(struct perf_event *event, int enable);
2491 static void perf_log_itrace_start(struct perf_event *event);
2493 static int
2494 event_sched_in(struct perf_event *event,
2495 struct perf_cpu_context *cpuctx,
2496 struct perf_event_context *ctx)
2498 int ret = 0;
2500 WARN_ON_ONCE(event->ctx != ctx);
2502 lockdep_assert_held(&ctx->lock);
2504 if (event->state <= PERF_EVENT_STATE_OFF)
2505 return 0;
2507 WRITE_ONCE(event->oncpu, smp_processor_id());
2509 * Order event::oncpu write to happen before the ACTIVE state is
2510 * visible. This allows perf_event_{stop,read}() to observe the correct
2511 * ->oncpu if it sees ACTIVE.
2513 smp_wmb();
2514 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2517 * Unthrottle events, since we scheduled we might have missed several
2518 * ticks already, also for a heavily scheduling task there is little
2519 * guarantee it'll get a tick in a timely manner.
2521 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2522 perf_log_throttle(event, 1);
2523 event->hw.interrupts = 0;
2526 perf_pmu_disable(event->pmu);
2528 perf_set_shadow_time(event, ctx);
2530 perf_log_itrace_start(event);
2532 if (event->pmu->add(event, PERF_EF_START)) {
2533 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2534 event->oncpu = -1;
2535 ret = -EAGAIN;
2536 goto out;
2539 if (!is_software_event(event))
2540 cpuctx->active_oncpu++;
2541 if (!ctx->nr_active++)
2542 perf_event_ctx_activate(ctx);
2543 if (event->attr.freq && event->attr.sample_freq)
2544 ctx->nr_freq++;
2546 if (event->attr.exclusive)
2547 cpuctx->exclusive = 1;
2549 out:
2550 perf_pmu_enable(event->pmu);
2552 return ret;
2555 static int
2556 group_sched_in(struct perf_event *group_event,
2557 struct perf_cpu_context *cpuctx,
2558 struct perf_event_context *ctx)
2560 struct perf_event *event, *partial_group = NULL;
2561 struct pmu *pmu = ctx->pmu;
2563 if (group_event->state == PERF_EVENT_STATE_OFF)
2564 return 0;
2566 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2568 if (event_sched_in(group_event, cpuctx, ctx)) {
2569 pmu->cancel_txn(pmu);
2570 perf_mux_hrtimer_restart(cpuctx);
2571 return -EAGAIN;
2575 * Schedule in siblings as one group (if any):
2577 for_each_sibling_event(event, group_event) {
2578 if (event_sched_in(event, cpuctx, ctx)) {
2579 partial_group = event;
2580 goto group_error;
2584 if (!pmu->commit_txn(pmu))
2585 return 0;
2587 group_error:
2589 * Groups can be scheduled in as one unit only, so undo any
2590 * partial group before returning:
2591 * The events up to the failed event are scheduled out normally.
2593 for_each_sibling_event(event, group_event) {
2594 if (event == partial_group)
2595 break;
2597 event_sched_out(event, cpuctx, ctx);
2599 event_sched_out(group_event, cpuctx, ctx);
2601 pmu->cancel_txn(pmu);
2603 perf_mux_hrtimer_restart(cpuctx);
2605 return -EAGAIN;
2609 * Work out whether we can put this event group on the CPU now.
2611 static int group_can_go_on(struct perf_event *event,
2612 struct perf_cpu_context *cpuctx,
2613 int can_add_hw)
2616 * Groups consisting entirely of software events can always go on.
2618 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2619 return 1;
2621 * If an exclusive group is already on, no other hardware
2622 * events can go on.
2624 if (cpuctx->exclusive)
2625 return 0;
2627 * If this group is exclusive and there are already
2628 * events on the CPU, it can't go on.
2630 if (event->attr.exclusive && cpuctx->active_oncpu)
2631 return 0;
2633 * Otherwise, try to add it if all previous groups were able
2634 * to go on.
2636 return can_add_hw;
2639 static void add_event_to_ctx(struct perf_event *event,
2640 struct perf_event_context *ctx)
2642 list_add_event(event, ctx);
2643 perf_group_attach(event);
2646 static void ctx_sched_out(struct perf_event_context *ctx,
2647 struct perf_cpu_context *cpuctx,
2648 enum event_type_t event_type);
2649 static void
2650 ctx_sched_in(struct perf_event_context *ctx,
2651 struct perf_cpu_context *cpuctx,
2652 enum event_type_t event_type,
2653 struct task_struct *task);
2655 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2656 struct perf_event_context *ctx,
2657 enum event_type_t event_type)
2659 if (!cpuctx->task_ctx)
2660 return;
2662 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2663 return;
2665 ctx_sched_out(ctx, cpuctx, event_type);
2668 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2669 struct perf_event_context *ctx,
2670 struct task_struct *task)
2672 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2673 if (ctx)
2674 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2675 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2676 if (ctx)
2677 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2681 * We want to maintain the following priority of scheduling:
2682 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2683 * - task pinned (EVENT_PINNED)
2684 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2685 * - task flexible (EVENT_FLEXIBLE).
2687 * In order to avoid unscheduling and scheduling back in everything every
2688 * time an event is added, only do it for the groups of equal priority and
2689 * below.
2691 * This can be called after a batch operation on task events, in which case
2692 * event_type is a bit mask of the types of events involved. For CPU events,
2693 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2695 static void ctx_resched(struct perf_cpu_context *cpuctx,
2696 struct perf_event_context *task_ctx,
2697 enum event_type_t event_type)
2699 enum event_type_t ctx_event_type;
2700 bool cpu_event = !!(event_type & EVENT_CPU);
2703 * If pinned groups are involved, flexible groups also need to be
2704 * scheduled out.
2706 if (event_type & EVENT_PINNED)
2707 event_type |= EVENT_FLEXIBLE;
2709 ctx_event_type = event_type & EVENT_ALL;
2711 perf_pmu_disable(cpuctx->ctx.pmu);
2712 if (task_ctx)
2713 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2716 * Decide which cpu ctx groups to schedule out based on the types
2717 * of events that caused rescheduling:
2718 * - EVENT_CPU: schedule out corresponding groups;
2719 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2720 * - otherwise, do nothing more.
2722 if (cpu_event)
2723 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2724 else if (ctx_event_type & EVENT_PINNED)
2725 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2727 perf_event_sched_in(cpuctx, task_ctx, current);
2728 perf_pmu_enable(cpuctx->ctx.pmu);
2731 void perf_pmu_resched(struct pmu *pmu)
2733 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2734 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2736 perf_ctx_lock(cpuctx, task_ctx);
2737 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2738 perf_ctx_unlock(cpuctx, task_ctx);
2742 * Cross CPU call to install and enable a performance event
2744 * Very similar to remote_function() + event_function() but cannot assume that
2745 * things like ctx->is_active and cpuctx->task_ctx are set.
2747 static int __perf_install_in_context(void *info)
2749 struct perf_event *event = info;
2750 struct perf_event_context *ctx = event->ctx;
2751 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2752 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2753 bool reprogram = true;
2754 int ret = 0;
2756 raw_spin_lock(&cpuctx->ctx.lock);
2757 if (ctx->task) {
2758 raw_spin_lock(&ctx->lock);
2759 task_ctx = ctx;
2761 reprogram = (ctx->task == current);
2764 * If the task is running, it must be running on this CPU,
2765 * otherwise we cannot reprogram things.
2767 * If its not running, we don't care, ctx->lock will
2768 * serialize against it becoming runnable.
2770 if (task_curr(ctx->task) && !reprogram) {
2771 ret = -ESRCH;
2772 goto unlock;
2775 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2776 } else if (task_ctx) {
2777 raw_spin_lock(&task_ctx->lock);
2780 #ifdef CONFIG_CGROUP_PERF
2781 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2783 * If the current cgroup doesn't match the event's
2784 * cgroup, we should not try to schedule it.
2786 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2787 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2788 event->cgrp->css.cgroup);
2790 #endif
2792 if (reprogram) {
2793 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2794 add_event_to_ctx(event, ctx);
2795 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2796 } else {
2797 add_event_to_ctx(event, ctx);
2800 unlock:
2801 perf_ctx_unlock(cpuctx, task_ctx);
2803 return ret;
2806 static bool exclusive_event_installable(struct perf_event *event,
2807 struct perf_event_context *ctx);
2810 * Attach a performance event to a context.
2812 * Very similar to event_function_call, see comment there.
2814 static void
2815 perf_install_in_context(struct perf_event_context *ctx,
2816 struct perf_event *event,
2817 int cpu)
2819 struct task_struct *task = READ_ONCE(ctx->task);
2821 lockdep_assert_held(&ctx->mutex);
2823 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2825 if (event->cpu != -1)
2826 event->cpu = cpu;
2829 * Ensures that if we can observe event->ctx, both the event and ctx
2830 * will be 'complete'. See perf_iterate_sb_cpu().
2832 smp_store_release(&event->ctx, ctx);
2835 * perf_event_attr::disabled events will not run and can be initialized
2836 * without IPI. Except when this is the first event for the context, in
2837 * that case we need the magic of the IPI to set ctx->is_active.
2839 * The IOC_ENABLE that is sure to follow the creation of a disabled
2840 * event will issue the IPI and reprogram the hardware.
2842 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2843 raw_spin_lock_irq(&ctx->lock);
2844 if (ctx->task == TASK_TOMBSTONE) {
2845 raw_spin_unlock_irq(&ctx->lock);
2846 return;
2848 add_event_to_ctx(event, ctx);
2849 raw_spin_unlock_irq(&ctx->lock);
2850 return;
2853 if (!task) {
2854 cpu_function_call(cpu, __perf_install_in_context, event);
2855 return;
2859 * Should not happen, we validate the ctx is still alive before calling.
2861 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2862 return;
2865 * Installing events is tricky because we cannot rely on ctx->is_active
2866 * to be set in case this is the nr_events 0 -> 1 transition.
2868 * Instead we use task_curr(), which tells us if the task is running.
2869 * However, since we use task_curr() outside of rq::lock, we can race
2870 * against the actual state. This means the result can be wrong.
2872 * If we get a false positive, we retry, this is harmless.
2874 * If we get a false negative, things are complicated. If we are after
2875 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2876 * value must be correct. If we're before, it doesn't matter since
2877 * perf_event_context_sched_in() will program the counter.
2879 * However, this hinges on the remote context switch having observed
2880 * our task->perf_event_ctxp[] store, such that it will in fact take
2881 * ctx::lock in perf_event_context_sched_in().
2883 * We do this by task_function_call(), if the IPI fails to hit the task
2884 * we know any future context switch of task must see the
2885 * perf_event_ctpx[] store.
2889 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2890 * task_cpu() load, such that if the IPI then does not find the task
2891 * running, a future context switch of that task must observe the
2892 * store.
2894 smp_mb();
2895 again:
2896 if (!task_function_call(task, __perf_install_in_context, event))
2897 return;
2899 raw_spin_lock_irq(&ctx->lock);
2900 task = ctx->task;
2901 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2903 * Cannot happen because we already checked above (which also
2904 * cannot happen), and we hold ctx->mutex, which serializes us
2905 * against perf_event_exit_task_context().
2907 raw_spin_unlock_irq(&ctx->lock);
2908 return;
2911 * If the task is not running, ctx->lock will avoid it becoming so,
2912 * thus we can safely install the event.
2914 if (task_curr(task)) {
2915 raw_spin_unlock_irq(&ctx->lock);
2916 goto again;
2918 add_event_to_ctx(event, ctx);
2919 raw_spin_unlock_irq(&ctx->lock);
2923 * Cross CPU call to enable a performance event
2925 static void __perf_event_enable(struct perf_event *event,
2926 struct perf_cpu_context *cpuctx,
2927 struct perf_event_context *ctx,
2928 void *info)
2930 struct perf_event *leader = event->group_leader;
2931 struct perf_event_context *task_ctx;
2933 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2934 event->state <= PERF_EVENT_STATE_ERROR)
2935 return;
2937 if (ctx->is_active)
2938 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2940 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2941 perf_cgroup_event_enable(event, ctx);
2943 if (!ctx->is_active)
2944 return;
2946 if (!event_filter_match(event)) {
2947 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2948 return;
2952 * If the event is in a group and isn't the group leader,
2953 * then don't put it on unless the group is on.
2955 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2956 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2957 return;
2960 task_ctx = cpuctx->task_ctx;
2961 if (ctx->task)
2962 WARN_ON_ONCE(task_ctx != ctx);
2964 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2968 * Enable an event.
2970 * If event->ctx is a cloned context, callers must make sure that
2971 * every task struct that event->ctx->task could possibly point to
2972 * remains valid. This condition is satisfied when called through
2973 * perf_event_for_each_child or perf_event_for_each as described
2974 * for perf_event_disable.
2976 static void _perf_event_enable(struct perf_event *event)
2978 struct perf_event_context *ctx = event->ctx;
2980 raw_spin_lock_irq(&ctx->lock);
2981 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2982 event->state < PERF_EVENT_STATE_ERROR) {
2983 raw_spin_unlock_irq(&ctx->lock);
2984 return;
2988 * If the event is in error state, clear that first.
2990 * That way, if we see the event in error state below, we know that it
2991 * has gone back into error state, as distinct from the task having
2992 * been scheduled away before the cross-call arrived.
2994 if (event->state == PERF_EVENT_STATE_ERROR)
2995 event->state = PERF_EVENT_STATE_OFF;
2996 raw_spin_unlock_irq(&ctx->lock);
2998 event_function_call(event, __perf_event_enable, NULL);
3002 * See perf_event_disable();
3004 void perf_event_enable(struct perf_event *event)
3006 struct perf_event_context *ctx;
3008 ctx = perf_event_ctx_lock(event);
3009 _perf_event_enable(event);
3010 perf_event_ctx_unlock(event, ctx);
3012 EXPORT_SYMBOL_GPL(perf_event_enable);
3014 struct stop_event_data {
3015 struct perf_event *event;
3016 unsigned int restart;
3019 static int __perf_event_stop(void *info)
3021 struct stop_event_data *sd = info;
3022 struct perf_event *event = sd->event;
3024 /* if it's already INACTIVE, do nothing */
3025 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3026 return 0;
3028 /* matches smp_wmb() in event_sched_in() */
3029 smp_rmb();
3032 * There is a window with interrupts enabled before we get here,
3033 * so we need to check again lest we try to stop another CPU's event.
3035 if (READ_ONCE(event->oncpu) != smp_processor_id())
3036 return -EAGAIN;
3038 event->pmu->stop(event, PERF_EF_UPDATE);
3041 * May race with the actual stop (through perf_pmu_output_stop()),
3042 * but it is only used for events with AUX ring buffer, and such
3043 * events will refuse to restart because of rb::aux_mmap_count==0,
3044 * see comments in perf_aux_output_begin().
3046 * Since this is happening on an event-local CPU, no trace is lost
3047 * while restarting.
3049 if (sd->restart)
3050 event->pmu->start(event, 0);
3052 return 0;
3055 static int perf_event_stop(struct perf_event *event, int restart)
3057 struct stop_event_data sd = {
3058 .event = event,
3059 .restart = restart,
3061 int ret = 0;
3063 do {
3064 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3065 return 0;
3067 /* matches smp_wmb() in event_sched_in() */
3068 smp_rmb();
3071 * We only want to restart ACTIVE events, so if the event goes
3072 * inactive here (event->oncpu==-1), there's nothing more to do;
3073 * fall through with ret==-ENXIO.
3075 ret = cpu_function_call(READ_ONCE(event->oncpu),
3076 __perf_event_stop, &sd);
3077 } while (ret == -EAGAIN);
3079 return ret;
3083 * In order to contain the amount of racy and tricky in the address filter
3084 * configuration management, it is a two part process:
3086 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3087 * we update the addresses of corresponding vmas in
3088 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3089 * (p2) when an event is scheduled in (pmu::add), it calls
3090 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3091 * if the generation has changed since the previous call.
3093 * If (p1) happens while the event is active, we restart it to force (p2).
3095 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3096 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3097 * ioctl;
3098 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3099 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3100 * for reading;
3101 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3102 * of exec.
3104 void perf_event_addr_filters_sync(struct perf_event *event)
3106 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3108 if (!has_addr_filter(event))
3109 return;
3111 raw_spin_lock(&ifh->lock);
3112 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3113 event->pmu->addr_filters_sync(event);
3114 event->hw.addr_filters_gen = event->addr_filters_gen;
3116 raw_spin_unlock(&ifh->lock);
3118 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3120 static int _perf_event_refresh(struct perf_event *event, int refresh)
3123 * not supported on inherited events
3125 if (event->attr.inherit || !is_sampling_event(event))
3126 return -EINVAL;
3128 atomic_add(refresh, &event->event_limit);
3129 _perf_event_enable(event);
3131 return 0;
3135 * See perf_event_disable()
3137 int perf_event_refresh(struct perf_event *event, int refresh)
3139 struct perf_event_context *ctx;
3140 int ret;
3142 ctx = perf_event_ctx_lock(event);
3143 ret = _perf_event_refresh(event, refresh);
3144 perf_event_ctx_unlock(event, ctx);
3146 return ret;
3148 EXPORT_SYMBOL_GPL(perf_event_refresh);
3150 static int perf_event_modify_breakpoint(struct perf_event *bp,
3151 struct perf_event_attr *attr)
3153 int err;
3155 _perf_event_disable(bp);
3157 err = modify_user_hw_breakpoint_check(bp, attr, true);
3159 if (!bp->attr.disabled)
3160 _perf_event_enable(bp);
3162 return err;
3165 static int perf_event_modify_attr(struct perf_event *event,
3166 struct perf_event_attr *attr)
3168 if (event->attr.type != attr->type)
3169 return -EINVAL;
3171 switch (event->attr.type) {
3172 case PERF_TYPE_BREAKPOINT:
3173 return perf_event_modify_breakpoint(event, attr);
3174 default:
3175 /* Place holder for future additions. */
3176 return -EOPNOTSUPP;
3180 static void ctx_sched_out(struct perf_event_context *ctx,
3181 struct perf_cpu_context *cpuctx,
3182 enum event_type_t event_type)
3184 struct perf_event *event, *tmp;
3185 int is_active = ctx->is_active;
3187 lockdep_assert_held(&ctx->lock);
3189 if (likely(!ctx->nr_events)) {
3191 * See __perf_remove_from_context().
3193 WARN_ON_ONCE(ctx->is_active);
3194 if (ctx->task)
3195 WARN_ON_ONCE(cpuctx->task_ctx);
3196 return;
3199 ctx->is_active &= ~event_type;
3200 if (!(ctx->is_active & EVENT_ALL))
3201 ctx->is_active = 0;
3203 if (ctx->task) {
3204 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3205 if (!ctx->is_active)
3206 cpuctx->task_ctx = NULL;
3210 * Always update time if it was set; not only when it changes.
3211 * Otherwise we can 'forget' to update time for any but the last
3212 * context we sched out. For example:
3214 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3215 * ctx_sched_out(.event_type = EVENT_PINNED)
3217 * would only update time for the pinned events.
3219 if (is_active & EVENT_TIME) {
3220 /* update (and stop) ctx time */
3221 update_context_time(ctx);
3222 update_cgrp_time_from_cpuctx(cpuctx);
3225 is_active ^= ctx->is_active; /* changed bits */
3227 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3228 return;
3230 perf_pmu_disable(ctx->pmu);
3231 if (is_active & EVENT_PINNED) {
3232 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3233 group_sched_out(event, cpuctx, ctx);
3236 if (is_active & EVENT_FLEXIBLE) {
3237 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3238 group_sched_out(event, cpuctx, ctx);
3241 * Since we cleared EVENT_FLEXIBLE, also clear
3242 * rotate_necessary, is will be reset by
3243 * ctx_flexible_sched_in() when needed.
3245 ctx->rotate_necessary = 0;
3247 perf_pmu_enable(ctx->pmu);
3251 * Test whether two contexts are equivalent, i.e. whether they have both been
3252 * cloned from the same version of the same context.
3254 * Equivalence is measured using a generation number in the context that is
3255 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3256 * and list_del_event().
3258 static int context_equiv(struct perf_event_context *ctx1,
3259 struct perf_event_context *ctx2)
3261 lockdep_assert_held(&ctx1->lock);
3262 lockdep_assert_held(&ctx2->lock);
3264 /* Pinning disables the swap optimization */
3265 if (ctx1->pin_count || ctx2->pin_count)
3266 return 0;
3268 /* If ctx1 is the parent of ctx2 */
3269 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3270 return 1;
3272 /* If ctx2 is the parent of ctx1 */
3273 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3274 return 1;
3277 * If ctx1 and ctx2 have the same parent; we flatten the parent
3278 * hierarchy, see perf_event_init_context().
3280 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3281 ctx1->parent_gen == ctx2->parent_gen)
3282 return 1;
3284 /* Unmatched */
3285 return 0;
3288 static void __perf_event_sync_stat(struct perf_event *event,
3289 struct perf_event *next_event)
3291 u64 value;
3293 if (!event->attr.inherit_stat)
3294 return;
3297 * Update the event value, we cannot use perf_event_read()
3298 * because we're in the middle of a context switch and have IRQs
3299 * disabled, which upsets smp_call_function_single(), however
3300 * we know the event must be on the current CPU, therefore we
3301 * don't need to use it.
3303 if (event->state == PERF_EVENT_STATE_ACTIVE)
3304 event->pmu->read(event);
3306 perf_event_update_time(event);
3309 * In order to keep per-task stats reliable we need to flip the event
3310 * values when we flip the contexts.
3312 value = local64_read(&next_event->count);
3313 value = local64_xchg(&event->count, value);
3314 local64_set(&next_event->count, value);
3316 swap(event->total_time_enabled, next_event->total_time_enabled);
3317 swap(event->total_time_running, next_event->total_time_running);
3320 * Since we swizzled the values, update the user visible data too.
3322 perf_event_update_userpage(event);
3323 perf_event_update_userpage(next_event);
3326 static void perf_event_sync_stat(struct perf_event_context *ctx,
3327 struct perf_event_context *next_ctx)
3329 struct perf_event *event, *next_event;
3331 if (!ctx->nr_stat)
3332 return;
3334 update_context_time(ctx);
3336 event = list_first_entry(&ctx->event_list,
3337 struct perf_event, event_entry);
3339 next_event = list_first_entry(&next_ctx->event_list,
3340 struct perf_event, event_entry);
3342 while (&event->event_entry != &ctx->event_list &&
3343 &next_event->event_entry != &next_ctx->event_list) {
3345 __perf_event_sync_stat(event, next_event);
3347 event = list_next_entry(event, event_entry);
3348 next_event = list_next_entry(next_event, event_entry);
3352 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3353 struct task_struct *next)
3355 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3356 struct perf_event_context *next_ctx;
3357 struct perf_event_context *parent, *next_parent;
3358 struct perf_cpu_context *cpuctx;
3359 int do_switch = 1;
3361 if (likely(!ctx))
3362 return;
3364 cpuctx = __get_cpu_context(ctx);
3365 if (!cpuctx->task_ctx)
3366 return;
3368 rcu_read_lock();
3369 next_ctx = next->perf_event_ctxp[ctxn];
3370 if (!next_ctx)
3371 goto unlock;
3373 parent = rcu_dereference(ctx->parent_ctx);
3374 next_parent = rcu_dereference(next_ctx->parent_ctx);
3376 /* If neither context have a parent context; they cannot be clones. */
3377 if (!parent && !next_parent)
3378 goto unlock;
3380 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3382 * Looks like the two contexts are clones, so we might be
3383 * able to optimize the context switch. We lock both
3384 * contexts and check that they are clones under the
3385 * lock (including re-checking that neither has been
3386 * uncloned in the meantime). It doesn't matter which
3387 * order we take the locks because no other cpu could
3388 * be trying to lock both of these tasks.
3390 raw_spin_lock(&ctx->lock);
3391 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3392 if (context_equiv(ctx, next_ctx)) {
3393 struct pmu *pmu = ctx->pmu;
3395 WRITE_ONCE(ctx->task, next);
3396 WRITE_ONCE(next_ctx->task, task);
3399 * PMU specific parts of task perf context can require
3400 * additional synchronization. As an example of such
3401 * synchronization see implementation details of Intel
3402 * LBR call stack data profiling;
3404 if (pmu->swap_task_ctx)
3405 pmu->swap_task_ctx(ctx, next_ctx);
3406 else
3407 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3410 * RCU_INIT_POINTER here is safe because we've not
3411 * modified the ctx and the above modification of
3412 * ctx->task and ctx->task_ctx_data are immaterial
3413 * since those values are always verified under
3414 * ctx->lock which we're now holding.
3416 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3417 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3419 do_switch = 0;
3421 perf_event_sync_stat(ctx, next_ctx);
3423 raw_spin_unlock(&next_ctx->lock);
3424 raw_spin_unlock(&ctx->lock);
3426 unlock:
3427 rcu_read_unlock();
3429 if (do_switch) {
3430 raw_spin_lock(&ctx->lock);
3431 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3432 raw_spin_unlock(&ctx->lock);
3436 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3438 void perf_sched_cb_dec(struct pmu *pmu)
3440 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3442 this_cpu_dec(perf_sched_cb_usages);
3444 if (!--cpuctx->sched_cb_usage)
3445 list_del(&cpuctx->sched_cb_entry);
3449 void perf_sched_cb_inc(struct pmu *pmu)
3451 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3453 if (!cpuctx->sched_cb_usage++)
3454 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3456 this_cpu_inc(perf_sched_cb_usages);
3460 * This function provides the context switch callback to the lower code
3461 * layer. It is invoked ONLY when the context switch callback is enabled.
3463 * This callback is relevant even to per-cpu events; for example multi event
3464 * PEBS requires this to provide PID/TID information. This requires we flush
3465 * all queued PEBS records before we context switch to a new task.
3467 static void perf_pmu_sched_task(struct task_struct *prev,
3468 struct task_struct *next,
3469 bool sched_in)
3471 struct perf_cpu_context *cpuctx;
3472 struct pmu *pmu;
3474 if (prev == next)
3475 return;
3477 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3478 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3480 if (WARN_ON_ONCE(!pmu->sched_task))
3481 continue;
3483 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3484 perf_pmu_disable(pmu);
3486 pmu->sched_task(cpuctx->task_ctx, sched_in);
3488 perf_pmu_enable(pmu);
3489 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3493 static void perf_event_switch(struct task_struct *task,
3494 struct task_struct *next_prev, bool sched_in);
3496 #define for_each_task_context_nr(ctxn) \
3497 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3500 * Called from scheduler to remove the events of the current task,
3501 * with interrupts disabled.
3503 * We stop each event and update the event value in event->count.
3505 * This does not protect us against NMI, but disable()
3506 * sets the disabled bit in the control field of event _before_
3507 * accessing the event control register. If a NMI hits, then it will
3508 * not restart the event.
3510 void __perf_event_task_sched_out(struct task_struct *task,
3511 struct task_struct *next)
3513 int ctxn;
3515 if (__this_cpu_read(perf_sched_cb_usages))
3516 perf_pmu_sched_task(task, next, false);
3518 if (atomic_read(&nr_switch_events))
3519 perf_event_switch(task, next, false);
3521 for_each_task_context_nr(ctxn)
3522 perf_event_context_sched_out(task, ctxn, next);
3525 * if cgroup events exist on this CPU, then we need
3526 * to check if we have to switch out PMU state.
3527 * cgroup event are system-wide mode only
3529 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3530 perf_cgroup_sched_out(task, next);
3534 * Called with IRQs disabled
3536 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3537 enum event_type_t event_type)
3539 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3542 static bool perf_less_group_idx(const void *l, const void *r)
3544 const struct perf_event *le = *(const struct perf_event **)l;
3545 const struct perf_event *re = *(const struct perf_event **)r;
3547 return le->group_index < re->group_index;
3550 static void swap_ptr(void *l, void *r)
3552 void **lp = l, **rp = r;
3554 swap(*lp, *rp);
3557 static const struct min_heap_callbacks perf_min_heap = {
3558 .elem_size = sizeof(struct perf_event *),
3559 .less = perf_less_group_idx,
3560 .swp = swap_ptr,
3563 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3565 struct perf_event **itrs = heap->data;
3567 if (event) {
3568 itrs[heap->nr] = event;
3569 heap->nr++;
3573 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3574 struct perf_event_groups *groups, int cpu,
3575 int (*func)(struct perf_event *, void *),
3576 void *data)
3578 #ifdef CONFIG_CGROUP_PERF
3579 struct cgroup_subsys_state *css = NULL;
3580 #endif
3581 /* Space for per CPU and/or any CPU event iterators. */
3582 struct perf_event *itrs[2];
3583 struct min_heap event_heap;
3584 struct perf_event **evt;
3585 int ret;
3587 if (cpuctx) {
3588 event_heap = (struct min_heap){
3589 .data = cpuctx->heap,
3590 .nr = 0,
3591 .size = cpuctx->heap_size,
3594 lockdep_assert_held(&cpuctx->ctx.lock);
3596 #ifdef CONFIG_CGROUP_PERF
3597 if (cpuctx->cgrp)
3598 css = &cpuctx->cgrp->css;
3599 #endif
3600 } else {
3601 event_heap = (struct min_heap){
3602 .data = itrs,
3603 .nr = 0,
3604 .size = ARRAY_SIZE(itrs),
3606 /* Events not within a CPU context may be on any CPU. */
3607 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3609 evt = event_heap.data;
3611 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3613 #ifdef CONFIG_CGROUP_PERF
3614 for (; css; css = css->parent)
3615 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3616 #endif
3618 min_heapify_all(&event_heap, &perf_min_heap);
3620 while (event_heap.nr) {
3621 ret = func(*evt, data);
3622 if (ret)
3623 return ret;
3625 *evt = perf_event_groups_next(*evt);
3626 if (*evt)
3627 min_heapify(&event_heap, 0, &perf_min_heap);
3628 else
3629 min_heap_pop(&event_heap, &perf_min_heap);
3632 return 0;
3635 static int merge_sched_in(struct perf_event *event, void *data)
3637 struct perf_event_context *ctx = event->ctx;
3638 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3639 int *can_add_hw = data;
3641 if (event->state <= PERF_EVENT_STATE_OFF)
3642 return 0;
3644 if (!event_filter_match(event))
3645 return 0;
3647 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3648 if (!group_sched_in(event, cpuctx, ctx))
3649 list_add_tail(&event->active_list, get_event_list(event));
3652 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3653 if (event->attr.pinned) {
3654 perf_cgroup_event_disable(event, ctx);
3655 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3658 *can_add_hw = 0;
3659 ctx->rotate_necessary = 1;
3662 return 0;
3665 static void
3666 ctx_pinned_sched_in(struct perf_event_context *ctx,
3667 struct perf_cpu_context *cpuctx)
3669 int can_add_hw = 1;
3671 if (ctx != &cpuctx->ctx)
3672 cpuctx = NULL;
3674 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3675 smp_processor_id(),
3676 merge_sched_in, &can_add_hw);
3679 static void
3680 ctx_flexible_sched_in(struct perf_event_context *ctx,
3681 struct perf_cpu_context *cpuctx)
3683 int can_add_hw = 1;
3685 if (ctx != &cpuctx->ctx)
3686 cpuctx = NULL;
3688 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3689 smp_processor_id(),
3690 merge_sched_in, &can_add_hw);
3693 static void
3694 ctx_sched_in(struct perf_event_context *ctx,
3695 struct perf_cpu_context *cpuctx,
3696 enum event_type_t event_type,
3697 struct task_struct *task)
3699 int is_active = ctx->is_active;
3700 u64 now;
3702 lockdep_assert_held(&ctx->lock);
3704 if (likely(!ctx->nr_events))
3705 return;
3707 ctx->is_active |= (event_type | EVENT_TIME);
3708 if (ctx->task) {
3709 if (!is_active)
3710 cpuctx->task_ctx = ctx;
3711 else
3712 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3715 is_active ^= ctx->is_active; /* changed bits */
3717 if (is_active & EVENT_TIME) {
3718 /* start ctx time */
3719 now = perf_clock();
3720 ctx->timestamp = now;
3721 perf_cgroup_set_timestamp(task, ctx);
3725 * First go through the list and put on any pinned groups
3726 * in order to give them the best chance of going on.
3728 if (is_active & EVENT_PINNED)
3729 ctx_pinned_sched_in(ctx, cpuctx);
3731 /* Then walk through the lower prio flexible groups */
3732 if (is_active & EVENT_FLEXIBLE)
3733 ctx_flexible_sched_in(ctx, cpuctx);
3736 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3737 enum event_type_t event_type,
3738 struct task_struct *task)
3740 struct perf_event_context *ctx = &cpuctx->ctx;
3742 ctx_sched_in(ctx, cpuctx, event_type, task);
3745 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3746 struct task_struct *task)
3748 struct perf_cpu_context *cpuctx;
3750 cpuctx = __get_cpu_context(ctx);
3751 if (cpuctx->task_ctx == ctx)
3752 return;
3754 perf_ctx_lock(cpuctx, ctx);
3756 * We must check ctx->nr_events while holding ctx->lock, such
3757 * that we serialize against perf_install_in_context().
3759 if (!ctx->nr_events)
3760 goto unlock;
3762 perf_pmu_disable(ctx->pmu);
3764 * We want to keep the following priority order:
3765 * cpu pinned (that don't need to move), task pinned,
3766 * cpu flexible, task flexible.
3768 * However, if task's ctx is not carrying any pinned
3769 * events, no need to flip the cpuctx's events around.
3771 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3772 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3773 perf_event_sched_in(cpuctx, ctx, task);
3774 perf_pmu_enable(ctx->pmu);
3776 unlock:
3777 perf_ctx_unlock(cpuctx, ctx);
3781 * Called from scheduler to add the events of the current task
3782 * with interrupts disabled.
3784 * We restore the event value and then enable it.
3786 * This does not protect us against NMI, but enable()
3787 * sets the enabled bit in the control field of event _before_
3788 * accessing the event control register. If a NMI hits, then it will
3789 * keep the event running.
3791 void __perf_event_task_sched_in(struct task_struct *prev,
3792 struct task_struct *task)
3794 struct perf_event_context *ctx;
3795 int ctxn;
3798 * If cgroup events exist on this CPU, then we need to check if we have
3799 * to switch in PMU state; cgroup event are system-wide mode only.
3801 * Since cgroup events are CPU events, we must schedule these in before
3802 * we schedule in the task events.
3804 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3805 perf_cgroup_sched_in(prev, task);
3807 for_each_task_context_nr(ctxn) {
3808 ctx = task->perf_event_ctxp[ctxn];
3809 if (likely(!ctx))
3810 continue;
3812 perf_event_context_sched_in(ctx, task);
3815 if (atomic_read(&nr_switch_events))
3816 perf_event_switch(task, prev, true);
3818 if (__this_cpu_read(perf_sched_cb_usages))
3819 perf_pmu_sched_task(prev, task, true);
3822 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3824 u64 frequency = event->attr.sample_freq;
3825 u64 sec = NSEC_PER_SEC;
3826 u64 divisor, dividend;
3828 int count_fls, nsec_fls, frequency_fls, sec_fls;
3830 count_fls = fls64(count);
3831 nsec_fls = fls64(nsec);
3832 frequency_fls = fls64(frequency);
3833 sec_fls = 30;
3836 * We got @count in @nsec, with a target of sample_freq HZ
3837 * the target period becomes:
3839 * @count * 10^9
3840 * period = -------------------
3841 * @nsec * sample_freq
3846 * Reduce accuracy by one bit such that @a and @b converge
3847 * to a similar magnitude.
3849 #define REDUCE_FLS(a, b) \
3850 do { \
3851 if (a##_fls > b##_fls) { \
3852 a >>= 1; \
3853 a##_fls--; \
3854 } else { \
3855 b >>= 1; \
3856 b##_fls--; \
3858 } while (0)
3861 * Reduce accuracy until either term fits in a u64, then proceed with
3862 * the other, so that finally we can do a u64/u64 division.
3864 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3865 REDUCE_FLS(nsec, frequency);
3866 REDUCE_FLS(sec, count);
3869 if (count_fls + sec_fls > 64) {
3870 divisor = nsec * frequency;
3872 while (count_fls + sec_fls > 64) {
3873 REDUCE_FLS(count, sec);
3874 divisor >>= 1;
3877 dividend = count * sec;
3878 } else {
3879 dividend = count * sec;
3881 while (nsec_fls + frequency_fls > 64) {
3882 REDUCE_FLS(nsec, frequency);
3883 dividend >>= 1;
3886 divisor = nsec * frequency;
3889 if (!divisor)
3890 return dividend;
3892 return div64_u64(dividend, divisor);
3895 static DEFINE_PER_CPU(int, perf_throttled_count);
3896 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3898 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3900 struct hw_perf_event *hwc = &event->hw;
3901 s64 period, sample_period;
3902 s64 delta;
3904 period = perf_calculate_period(event, nsec, count);
3906 delta = (s64)(period - hwc->sample_period);
3907 delta = (delta + 7) / 8; /* low pass filter */
3909 sample_period = hwc->sample_period + delta;
3911 if (!sample_period)
3912 sample_period = 1;
3914 hwc->sample_period = sample_period;
3916 if (local64_read(&hwc->period_left) > 8*sample_period) {
3917 if (disable)
3918 event->pmu->stop(event, PERF_EF_UPDATE);
3920 local64_set(&hwc->period_left, 0);
3922 if (disable)
3923 event->pmu->start(event, PERF_EF_RELOAD);
3928 * combine freq adjustment with unthrottling to avoid two passes over the
3929 * events. At the same time, make sure, having freq events does not change
3930 * the rate of unthrottling as that would introduce bias.
3932 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3933 int needs_unthr)
3935 struct perf_event *event;
3936 struct hw_perf_event *hwc;
3937 u64 now, period = TICK_NSEC;
3938 s64 delta;
3941 * only need to iterate over all events iff:
3942 * - context have events in frequency mode (needs freq adjust)
3943 * - there are events to unthrottle on this cpu
3945 if (!(ctx->nr_freq || needs_unthr))
3946 return;
3948 raw_spin_lock(&ctx->lock);
3949 perf_pmu_disable(ctx->pmu);
3951 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3952 if (event->state != PERF_EVENT_STATE_ACTIVE)
3953 continue;
3955 if (!event_filter_match(event))
3956 continue;
3958 perf_pmu_disable(event->pmu);
3960 hwc = &event->hw;
3962 if (hwc->interrupts == MAX_INTERRUPTS) {
3963 hwc->interrupts = 0;
3964 perf_log_throttle(event, 1);
3965 event->pmu->start(event, 0);
3968 if (!event->attr.freq || !event->attr.sample_freq)
3969 goto next;
3972 * stop the event and update event->count
3974 event->pmu->stop(event, PERF_EF_UPDATE);
3976 now = local64_read(&event->count);
3977 delta = now - hwc->freq_count_stamp;
3978 hwc->freq_count_stamp = now;
3981 * restart the event
3982 * reload only if value has changed
3983 * we have stopped the event so tell that
3984 * to perf_adjust_period() to avoid stopping it
3985 * twice.
3987 if (delta > 0)
3988 perf_adjust_period(event, period, delta, false);
3990 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3991 next:
3992 perf_pmu_enable(event->pmu);
3995 perf_pmu_enable(ctx->pmu);
3996 raw_spin_unlock(&ctx->lock);
4000 * Move @event to the tail of the @ctx's elegible events.
4002 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4005 * Rotate the first entry last of non-pinned groups. Rotation might be
4006 * disabled by the inheritance code.
4008 if (ctx->rotate_disable)
4009 return;
4011 perf_event_groups_delete(&ctx->flexible_groups, event);
4012 perf_event_groups_insert(&ctx->flexible_groups, event);
4015 /* pick an event from the flexible_groups to rotate */
4016 static inline struct perf_event *
4017 ctx_event_to_rotate(struct perf_event_context *ctx)
4019 struct perf_event *event;
4021 /* pick the first active flexible event */
4022 event = list_first_entry_or_null(&ctx->flexible_active,
4023 struct perf_event, active_list);
4025 /* if no active flexible event, pick the first event */
4026 if (!event) {
4027 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4028 typeof(*event), group_node);
4032 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4033 * finds there are unschedulable events, it will set it again.
4035 ctx->rotate_necessary = 0;
4037 return event;
4040 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4042 struct perf_event *cpu_event = NULL, *task_event = NULL;
4043 struct perf_event_context *task_ctx = NULL;
4044 int cpu_rotate, task_rotate;
4047 * Since we run this from IRQ context, nobody can install new
4048 * events, thus the event count values are stable.
4051 cpu_rotate = cpuctx->ctx.rotate_necessary;
4052 task_ctx = cpuctx->task_ctx;
4053 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4055 if (!(cpu_rotate || task_rotate))
4056 return false;
4058 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4059 perf_pmu_disable(cpuctx->ctx.pmu);
4061 if (task_rotate)
4062 task_event = ctx_event_to_rotate(task_ctx);
4063 if (cpu_rotate)
4064 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4067 * As per the order given at ctx_resched() first 'pop' task flexible
4068 * and then, if needed CPU flexible.
4070 if (task_event || (task_ctx && cpu_event))
4071 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4072 if (cpu_event)
4073 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4075 if (task_event)
4076 rotate_ctx(task_ctx, task_event);
4077 if (cpu_event)
4078 rotate_ctx(&cpuctx->ctx, cpu_event);
4080 perf_event_sched_in(cpuctx, task_ctx, current);
4082 perf_pmu_enable(cpuctx->ctx.pmu);
4083 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4085 return true;
4088 void perf_event_task_tick(void)
4090 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4091 struct perf_event_context *ctx, *tmp;
4092 int throttled;
4094 lockdep_assert_irqs_disabled();
4096 __this_cpu_inc(perf_throttled_seq);
4097 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4098 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4100 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4101 perf_adjust_freq_unthr_context(ctx, throttled);
4104 static int event_enable_on_exec(struct perf_event *event,
4105 struct perf_event_context *ctx)
4107 if (!event->attr.enable_on_exec)
4108 return 0;
4110 event->attr.enable_on_exec = 0;
4111 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4112 return 0;
4114 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4116 return 1;
4120 * Enable all of a task's events that have been marked enable-on-exec.
4121 * This expects task == current.
4123 static void perf_event_enable_on_exec(int ctxn)
4125 struct perf_event_context *ctx, *clone_ctx = NULL;
4126 enum event_type_t event_type = 0;
4127 struct perf_cpu_context *cpuctx;
4128 struct perf_event *event;
4129 unsigned long flags;
4130 int enabled = 0;
4132 local_irq_save(flags);
4133 ctx = current->perf_event_ctxp[ctxn];
4134 if (!ctx || !ctx->nr_events)
4135 goto out;
4137 cpuctx = __get_cpu_context(ctx);
4138 perf_ctx_lock(cpuctx, ctx);
4139 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4140 list_for_each_entry(event, &ctx->event_list, event_entry) {
4141 enabled |= event_enable_on_exec(event, ctx);
4142 event_type |= get_event_type(event);
4146 * Unclone and reschedule this context if we enabled any event.
4148 if (enabled) {
4149 clone_ctx = unclone_ctx(ctx);
4150 ctx_resched(cpuctx, ctx, event_type);
4151 } else {
4152 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4154 perf_ctx_unlock(cpuctx, ctx);
4156 out:
4157 local_irq_restore(flags);
4159 if (clone_ctx)
4160 put_ctx(clone_ctx);
4163 struct perf_read_data {
4164 struct perf_event *event;
4165 bool group;
4166 int ret;
4169 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4171 u16 local_pkg, event_pkg;
4173 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4174 int local_cpu = smp_processor_id();
4176 event_pkg = topology_physical_package_id(event_cpu);
4177 local_pkg = topology_physical_package_id(local_cpu);
4179 if (event_pkg == local_pkg)
4180 return local_cpu;
4183 return event_cpu;
4187 * Cross CPU call to read the hardware event
4189 static void __perf_event_read(void *info)
4191 struct perf_read_data *data = info;
4192 struct perf_event *sub, *event = data->event;
4193 struct perf_event_context *ctx = event->ctx;
4194 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4195 struct pmu *pmu = event->pmu;
4198 * If this is a task context, we need to check whether it is
4199 * the current task context of this cpu. If not it has been
4200 * scheduled out before the smp call arrived. In that case
4201 * event->count would have been updated to a recent sample
4202 * when the event was scheduled out.
4204 if (ctx->task && cpuctx->task_ctx != ctx)
4205 return;
4207 raw_spin_lock(&ctx->lock);
4208 if (ctx->is_active & EVENT_TIME) {
4209 update_context_time(ctx);
4210 update_cgrp_time_from_event(event);
4213 perf_event_update_time(event);
4214 if (data->group)
4215 perf_event_update_sibling_time(event);
4217 if (event->state != PERF_EVENT_STATE_ACTIVE)
4218 goto unlock;
4220 if (!data->group) {
4221 pmu->read(event);
4222 data->ret = 0;
4223 goto unlock;
4226 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4228 pmu->read(event);
4230 for_each_sibling_event(sub, event) {
4231 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4233 * Use sibling's PMU rather than @event's since
4234 * sibling could be on different (eg: software) PMU.
4236 sub->pmu->read(sub);
4240 data->ret = pmu->commit_txn(pmu);
4242 unlock:
4243 raw_spin_unlock(&ctx->lock);
4246 static inline u64 perf_event_count(struct perf_event *event)
4248 return local64_read(&event->count) + atomic64_read(&event->child_count);
4252 * NMI-safe method to read a local event, that is an event that
4253 * is:
4254 * - either for the current task, or for this CPU
4255 * - does not have inherit set, for inherited task events
4256 * will not be local and we cannot read them atomically
4257 * - must not have a pmu::count method
4259 int perf_event_read_local(struct perf_event *event, u64 *value,
4260 u64 *enabled, u64 *running)
4262 unsigned long flags;
4263 int ret = 0;
4266 * Disabling interrupts avoids all counter scheduling (context
4267 * switches, timer based rotation and IPIs).
4269 local_irq_save(flags);
4272 * It must not be an event with inherit set, we cannot read
4273 * all child counters from atomic context.
4275 if (event->attr.inherit) {
4276 ret = -EOPNOTSUPP;
4277 goto out;
4280 /* If this is a per-task event, it must be for current */
4281 if ((event->attach_state & PERF_ATTACH_TASK) &&
4282 event->hw.target != current) {
4283 ret = -EINVAL;
4284 goto out;
4287 /* If this is a per-CPU event, it must be for this CPU */
4288 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4289 event->cpu != smp_processor_id()) {
4290 ret = -EINVAL;
4291 goto out;
4294 /* If this is a pinned event it must be running on this CPU */
4295 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4296 ret = -EBUSY;
4297 goto out;
4301 * If the event is currently on this CPU, its either a per-task event,
4302 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4303 * oncpu == -1).
4305 if (event->oncpu == smp_processor_id())
4306 event->pmu->read(event);
4308 *value = local64_read(&event->count);
4309 if (enabled || running) {
4310 u64 now = event->shadow_ctx_time + perf_clock();
4311 u64 __enabled, __running;
4313 __perf_update_times(event, now, &__enabled, &__running);
4314 if (enabled)
4315 *enabled = __enabled;
4316 if (running)
4317 *running = __running;
4319 out:
4320 local_irq_restore(flags);
4322 return ret;
4325 static int perf_event_read(struct perf_event *event, bool group)
4327 enum perf_event_state state = READ_ONCE(event->state);
4328 int event_cpu, ret = 0;
4331 * If event is enabled and currently active on a CPU, update the
4332 * value in the event structure:
4334 again:
4335 if (state == PERF_EVENT_STATE_ACTIVE) {
4336 struct perf_read_data data;
4339 * Orders the ->state and ->oncpu loads such that if we see
4340 * ACTIVE we must also see the right ->oncpu.
4342 * Matches the smp_wmb() from event_sched_in().
4344 smp_rmb();
4346 event_cpu = READ_ONCE(event->oncpu);
4347 if ((unsigned)event_cpu >= nr_cpu_ids)
4348 return 0;
4350 data = (struct perf_read_data){
4351 .event = event,
4352 .group = group,
4353 .ret = 0,
4356 preempt_disable();
4357 event_cpu = __perf_event_read_cpu(event, event_cpu);
4360 * Purposely ignore the smp_call_function_single() return
4361 * value.
4363 * If event_cpu isn't a valid CPU it means the event got
4364 * scheduled out and that will have updated the event count.
4366 * Therefore, either way, we'll have an up-to-date event count
4367 * after this.
4369 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4370 preempt_enable();
4371 ret = data.ret;
4373 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4374 struct perf_event_context *ctx = event->ctx;
4375 unsigned long flags;
4377 raw_spin_lock_irqsave(&ctx->lock, flags);
4378 state = event->state;
4379 if (state != PERF_EVENT_STATE_INACTIVE) {
4380 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4381 goto again;
4385 * May read while context is not active (e.g., thread is
4386 * blocked), in that case we cannot update context time
4388 if (ctx->is_active & EVENT_TIME) {
4389 update_context_time(ctx);
4390 update_cgrp_time_from_event(event);
4393 perf_event_update_time(event);
4394 if (group)
4395 perf_event_update_sibling_time(event);
4396 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4399 return ret;
4403 * Initialize the perf_event context in a task_struct:
4405 static void __perf_event_init_context(struct perf_event_context *ctx)
4407 raw_spin_lock_init(&ctx->lock);
4408 mutex_init(&ctx->mutex);
4409 INIT_LIST_HEAD(&ctx->active_ctx_list);
4410 perf_event_groups_init(&ctx->pinned_groups);
4411 perf_event_groups_init(&ctx->flexible_groups);
4412 INIT_LIST_HEAD(&ctx->event_list);
4413 INIT_LIST_HEAD(&ctx->pinned_active);
4414 INIT_LIST_HEAD(&ctx->flexible_active);
4415 refcount_set(&ctx->refcount, 1);
4418 static struct perf_event_context *
4419 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4421 struct perf_event_context *ctx;
4423 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4424 if (!ctx)
4425 return NULL;
4427 __perf_event_init_context(ctx);
4428 if (task)
4429 ctx->task = get_task_struct(task);
4430 ctx->pmu = pmu;
4432 return ctx;
4435 static struct task_struct *
4436 find_lively_task_by_vpid(pid_t vpid)
4438 struct task_struct *task;
4440 rcu_read_lock();
4441 if (!vpid)
4442 task = current;
4443 else
4444 task = find_task_by_vpid(vpid);
4445 if (task)
4446 get_task_struct(task);
4447 rcu_read_unlock();
4449 if (!task)
4450 return ERR_PTR(-ESRCH);
4452 return task;
4456 * Returns a matching context with refcount and pincount.
4458 static struct perf_event_context *
4459 find_get_context(struct pmu *pmu, struct task_struct *task,
4460 struct perf_event *event)
4462 struct perf_event_context *ctx, *clone_ctx = NULL;
4463 struct perf_cpu_context *cpuctx;
4464 void *task_ctx_data = NULL;
4465 unsigned long flags;
4466 int ctxn, err;
4467 int cpu = event->cpu;
4469 if (!task) {
4470 /* Must be root to operate on a CPU event: */
4471 err = perf_allow_cpu(&event->attr);
4472 if (err)
4473 return ERR_PTR(err);
4475 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4476 ctx = &cpuctx->ctx;
4477 get_ctx(ctx);
4478 ++ctx->pin_count;
4480 return ctx;
4483 err = -EINVAL;
4484 ctxn = pmu->task_ctx_nr;
4485 if (ctxn < 0)
4486 goto errout;
4488 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4489 task_ctx_data = alloc_task_ctx_data(pmu);
4490 if (!task_ctx_data) {
4491 err = -ENOMEM;
4492 goto errout;
4496 retry:
4497 ctx = perf_lock_task_context(task, ctxn, &flags);
4498 if (ctx) {
4499 clone_ctx = unclone_ctx(ctx);
4500 ++ctx->pin_count;
4502 if (task_ctx_data && !ctx->task_ctx_data) {
4503 ctx->task_ctx_data = task_ctx_data;
4504 task_ctx_data = NULL;
4506 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4508 if (clone_ctx)
4509 put_ctx(clone_ctx);
4510 } else {
4511 ctx = alloc_perf_context(pmu, task);
4512 err = -ENOMEM;
4513 if (!ctx)
4514 goto errout;
4516 if (task_ctx_data) {
4517 ctx->task_ctx_data = task_ctx_data;
4518 task_ctx_data = NULL;
4521 err = 0;
4522 mutex_lock(&task->perf_event_mutex);
4524 * If it has already passed perf_event_exit_task().
4525 * we must see PF_EXITING, it takes this mutex too.
4527 if (task->flags & PF_EXITING)
4528 err = -ESRCH;
4529 else if (task->perf_event_ctxp[ctxn])
4530 err = -EAGAIN;
4531 else {
4532 get_ctx(ctx);
4533 ++ctx->pin_count;
4534 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4536 mutex_unlock(&task->perf_event_mutex);
4538 if (unlikely(err)) {
4539 put_ctx(ctx);
4541 if (err == -EAGAIN)
4542 goto retry;
4543 goto errout;
4547 free_task_ctx_data(pmu, task_ctx_data);
4548 return ctx;
4550 errout:
4551 free_task_ctx_data(pmu, task_ctx_data);
4552 return ERR_PTR(err);
4555 static void perf_event_free_filter(struct perf_event *event);
4556 static void perf_event_free_bpf_prog(struct perf_event *event);
4558 static void free_event_rcu(struct rcu_head *head)
4560 struct perf_event *event;
4562 event = container_of(head, struct perf_event, rcu_head);
4563 if (event->ns)
4564 put_pid_ns(event->ns);
4565 perf_event_free_filter(event);
4566 kfree(event);
4569 static void ring_buffer_attach(struct perf_event *event,
4570 struct perf_buffer *rb);
4572 static void detach_sb_event(struct perf_event *event)
4574 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4576 raw_spin_lock(&pel->lock);
4577 list_del_rcu(&event->sb_list);
4578 raw_spin_unlock(&pel->lock);
4581 static bool is_sb_event(struct perf_event *event)
4583 struct perf_event_attr *attr = &event->attr;
4585 if (event->parent)
4586 return false;
4588 if (event->attach_state & PERF_ATTACH_TASK)
4589 return false;
4591 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4592 attr->comm || attr->comm_exec ||
4593 attr->task || attr->ksymbol ||
4594 attr->context_switch || attr->text_poke ||
4595 attr->bpf_event)
4596 return true;
4597 return false;
4600 static void unaccount_pmu_sb_event(struct perf_event *event)
4602 if (is_sb_event(event))
4603 detach_sb_event(event);
4606 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4608 if (event->parent)
4609 return;
4611 if (is_cgroup_event(event))
4612 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4615 #ifdef CONFIG_NO_HZ_FULL
4616 static DEFINE_SPINLOCK(nr_freq_lock);
4617 #endif
4619 static void unaccount_freq_event_nohz(void)
4621 #ifdef CONFIG_NO_HZ_FULL
4622 spin_lock(&nr_freq_lock);
4623 if (atomic_dec_and_test(&nr_freq_events))
4624 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4625 spin_unlock(&nr_freq_lock);
4626 #endif
4629 static void unaccount_freq_event(void)
4631 if (tick_nohz_full_enabled())
4632 unaccount_freq_event_nohz();
4633 else
4634 atomic_dec(&nr_freq_events);
4637 static void unaccount_event(struct perf_event *event)
4639 bool dec = false;
4641 if (event->parent)
4642 return;
4644 if (event->attach_state & PERF_ATTACH_TASK)
4645 dec = true;
4646 if (event->attr.mmap || event->attr.mmap_data)
4647 atomic_dec(&nr_mmap_events);
4648 if (event->attr.comm)
4649 atomic_dec(&nr_comm_events);
4650 if (event->attr.namespaces)
4651 atomic_dec(&nr_namespaces_events);
4652 if (event->attr.cgroup)
4653 atomic_dec(&nr_cgroup_events);
4654 if (event->attr.task)
4655 atomic_dec(&nr_task_events);
4656 if (event->attr.freq)
4657 unaccount_freq_event();
4658 if (event->attr.context_switch) {
4659 dec = true;
4660 atomic_dec(&nr_switch_events);
4662 if (is_cgroup_event(event))
4663 dec = true;
4664 if (has_branch_stack(event))
4665 dec = true;
4666 if (event->attr.ksymbol)
4667 atomic_dec(&nr_ksymbol_events);
4668 if (event->attr.bpf_event)
4669 atomic_dec(&nr_bpf_events);
4670 if (event->attr.text_poke)
4671 atomic_dec(&nr_text_poke_events);
4673 if (dec) {
4674 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4675 schedule_delayed_work(&perf_sched_work, HZ);
4678 unaccount_event_cpu(event, event->cpu);
4680 unaccount_pmu_sb_event(event);
4683 static void perf_sched_delayed(struct work_struct *work)
4685 mutex_lock(&perf_sched_mutex);
4686 if (atomic_dec_and_test(&perf_sched_count))
4687 static_branch_disable(&perf_sched_events);
4688 mutex_unlock(&perf_sched_mutex);
4692 * The following implement mutual exclusion of events on "exclusive" pmus
4693 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4694 * at a time, so we disallow creating events that might conflict, namely:
4696 * 1) cpu-wide events in the presence of per-task events,
4697 * 2) per-task events in the presence of cpu-wide events,
4698 * 3) two matching events on the same context.
4700 * The former two cases are handled in the allocation path (perf_event_alloc(),
4701 * _free_event()), the latter -- before the first perf_install_in_context().
4703 static int exclusive_event_init(struct perf_event *event)
4705 struct pmu *pmu = event->pmu;
4707 if (!is_exclusive_pmu(pmu))
4708 return 0;
4711 * Prevent co-existence of per-task and cpu-wide events on the
4712 * same exclusive pmu.
4714 * Negative pmu::exclusive_cnt means there are cpu-wide
4715 * events on this "exclusive" pmu, positive means there are
4716 * per-task events.
4718 * Since this is called in perf_event_alloc() path, event::ctx
4719 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4720 * to mean "per-task event", because unlike other attach states it
4721 * never gets cleared.
4723 if (event->attach_state & PERF_ATTACH_TASK) {
4724 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4725 return -EBUSY;
4726 } else {
4727 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4728 return -EBUSY;
4731 return 0;
4734 static void exclusive_event_destroy(struct perf_event *event)
4736 struct pmu *pmu = event->pmu;
4738 if (!is_exclusive_pmu(pmu))
4739 return;
4741 /* see comment in exclusive_event_init() */
4742 if (event->attach_state & PERF_ATTACH_TASK)
4743 atomic_dec(&pmu->exclusive_cnt);
4744 else
4745 atomic_inc(&pmu->exclusive_cnt);
4748 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4750 if ((e1->pmu == e2->pmu) &&
4751 (e1->cpu == e2->cpu ||
4752 e1->cpu == -1 ||
4753 e2->cpu == -1))
4754 return true;
4755 return false;
4758 static bool exclusive_event_installable(struct perf_event *event,
4759 struct perf_event_context *ctx)
4761 struct perf_event *iter_event;
4762 struct pmu *pmu = event->pmu;
4764 lockdep_assert_held(&ctx->mutex);
4766 if (!is_exclusive_pmu(pmu))
4767 return true;
4769 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4770 if (exclusive_event_match(iter_event, event))
4771 return false;
4774 return true;
4777 static void perf_addr_filters_splice(struct perf_event *event,
4778 struct list_head *head);
4780 static void _free_event(struct perf_event *event)
4782 irq_work_sync(&event->pending);
4784 unaccount_event(event);
4786 security_perf_event_free(event);
4788 if (event->rb) {
4790 * Can happen when we close an event with re-directed output.
4792 * Since we have a 0 refcount, perf_mmap_close() will skip
4793 * over us; possibly making our ring_buffer_put() the last.
4795 mutex_lock(&event->mmap_mutex);
4796 ring_buffer_attach(event, NULL);
4797 mutex_unlock(&event->mmap_mutex);
4800 if (is_cgroup_event(event))
4801 perf_detach_cgroup(event);
4803 if (!event->parent) {
4804 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4805 put_callchain_buffers();
4808 perf_event_free_bpf_prog(event);
4809 perf_addr_filters_splice(event, NULL);
4810 kfree(event->addr_filter_ranges);
4812 if (event->destroy)
4813 event->destroy(event);
4816 * Must be after ->destroy(), due to uprobe_perf_close() using
4817 * hw.target.
4819 if (event->hw.target)
4820 put_task_struct(event->hw.target);
4823 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4824 * all task references must be cleaned up.
4826 if (event->ctx)
4827 put_ctx(event->ctx);
4829 exclusive_event_destroy(event);
4830 module_put(event->pmu->module);
4832 call_rcu(&event->rcu_head, free_event_rcu);
4836 * Used to free events which have a known refcount of 1, such as in error paths
4837 * where the event isn't exposed yet and inherited events.
4839 static void free_event(struct perf_event *event)
4841 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4842 "unexpected event refcount: %ld; ptr=%p\n",
4843 atomic_long_read(&event->refcount), event)) {
4844 /* leak to avoid use-after-free */
4845 return;
4848 _free_event(event);
4852 * Remove user event from the owner task.
4854 static void perf_remove_from_owner(struct perf_event *event)
4856 struct task_struct *owner;
4858 rcu_read_lock();
4860 * Matches the smp_store_release() in perf_event_exit_task(). If we
4861 * observe !owner it means the list deletion is complete and we can
4862 * indeed free this event, otherwise we need to serialize on
4863 * owner->perf_event_mutex.
4865 owner = READ_ONCE(event->owner);
4866 if (owner) {
4868 * Since delayed_put_task_struct() also drops the last
4869 * task reference we can safely take a new reference
4870 * while holding the rcu_read_lock().
4872 get_task_struct(owner);
4874 rcu_read_unlock();
4876 if (owner) {
4878 * If we're here through perf_event_exit_task() we're already
4879 * holding ctx->mutex which would be an inversion wrt. the
4880 * normal lock order.
4882 * However we can safely take this lock because its the child
4883 * ctx->mutex.
4885 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4888 * We have to re-check the event->owner field, if it is cleared
4889 * we raced with perf_event_exit_task(), acquiring the mutex
4890 * ensured they're done, and we can proceed with freeing the
4891 * event.
4893 if (event->owner) {
4894 list_del_init(&event->owner_entry);
4895 smp_store_release(&event->owner, NULL);
4897 mutex_unlock(&owner->perf_event_mutex);
4898 put_task_struct(owner);
4902 static void put_event(struct perf_event *event)
4904 if (!atomic_long_dec_and_test(&event->refcount))
4905 return;
4907 _free_event(event);
4911 * Kill an event dead; while event:refcount will preserve the event
4912 * object, it will not preserve its functionality. Once the last 'user'
4913 * gives up the object, we'll destroy the thing.
4915 int perf_event_release_kernel(struct perf_event *event)
4917 struct perf_event_context *ctx = event->ctx;
4918 struct perf_event *child, *tmp;
4919 LIST_HEAD(free_list);
4922 * If we got here through err_file: fput(event_file); we will not have
4923 * attached to a context yet.
4925 if (!ctx) {
4926 WARN_ON_ONCE(event->attach_state &
4927 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4928 goto no_ctx;
4931 if (!is_kernel_event(event))
4932 perf_remove_from_owner(event);
4934 ctx = perf_event_ctx_lock(event);
4935 WARN_ON_ONCE(ctx->parent_ctx);
4936 perf_remove_from_context(event, DETACH_GROUP);
4938 raw_spin_lock_irq(&ctx->lock);
4940 * Mark this event as STATE_DEAD, there is no external reference to it
4941 * anymore.
4943 * Anybody acquiring event->child_mutex after the below loop _must_
4944 * also see this, most importantly inherit_event() which will avoid
4945 * placing more children on the list.
4947 * Thus this guarantees that we will in fact observe and kill _ALL_
4948 * child events.
4950 event->state = PERF_EVENT_STATE_DEAD;
4951 raw_spin_unlock_irq(&ctx->lock);
4953 perf_event_ctx_unlock(event, ctx);
4955 again:
4956 mutex_lock(&event->child_mutex);
4957 list_for_each_entry(child, &event->child_list, child_list) {
4960 * Cannot change, child events are not migrated, see the
4961 * comment with perf_event_ctx_lock_nested().
4963 ctx = READ_ONCE(child->ctx);
4965 * Since child_mutex nests inside ctx::mutex, we must jump
4966 * through hoops. We start by grabbing a reference on the ctx.
4968 * Since the event cannot get freed while we hold the
4969 * child_mutex, the context must also exist and have a !0
4970 * reference count.
4972 get_ctx(ctx);
4975 * Now that we have a ctx ref, we can drop child_mutex, and
4976 * acquire ctx::mutex without fear of it going away. Then we
4977 * can re-acquire child_mutex.
4979 mutex_unlock(&event->child_mutex);
4980 mutex_lock(&ctx->mutex);
4981 mutex_lock(&event->child_mutex);
4984 * Now that we hold ctx::mutex and child_mutex, revalidate our
4985 * state, if child is still the first entry, it didn't get freed
4986 * and we can continue doing so.
4988 tmp = list_first_entry_or_null(&event->child_list,
4989 struct perf_event, child_list);
4990 if (tmp == child) {
4991 perf_remove_from_context(child, DETACH_GROUP);
4992 list_move(&child->child_list, &free_list);
4994 * This matches the refcount bump in inherit_event();
4995 * this can't be the last reference.
4997 put_event(event);
5000 mutex_unlock(&event->child_mutex);
5001 mutex_unlock(&ctx->mutex);
5002 put_ctx(ctx);
5003 goto again;
5005 mutex_unlock(&event->child_mutex);
5007 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5008 void *var = &child->ctx->refcount;
5010 list_del(&child->child_list);
5011 free_event(child);
5014 * Wake any perf_event_free_task() waiting for this event to be
5015 * freed.
5017 smp_mb(); /* pairs with wait_var_event() */
5018 wake_up_var(var);
5021 no_ctx:
5022 put_event(event); /* Must be the 'last' reference */
5023 return 0;
5025 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5028 * Called when the last reference to the file is gone.
5030 static int perf_release(struct inode *inode, struct file *file)
5032 perf_event_release_kernel(file->private_data);
5033 return 0;
5036 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5038 struct perf_event *child;
5039 u64 total = 0;
5041 *enabled = 0;
5042 *running = 0;
5044 mutex_lock(&event->child_mutex);
5046 (void)perf_event_read(event, false);
5047 total += perf_event_count(event);
5049 *enabled += event->total_time_enabled +
5050 atomic64_read(&event->child_total_time_enabled);
5051 *running += event->total_time_running +
5052 atomic64_read(&event->child_total_time_running);
5054 list_for_each_entry(child, &event->child_list, child_list) {
5055 (void)perf_event_read(child, false);
5056 total += perf_event_count(child);
5057 *enabled += child->total_time_enabled;
5058 *running += child->total_time_running;
5060 mutex_unlock(&event->child_mutex);
5062 return total;
5065 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5067 struct perf_event_context *ctx;
5068 u64 count;
5070 ctx = perf_event_ctx_lock(event);
5071 count = __perf_event_read_value(event, enabled, running);
5072 perf_event_ctx_unlock(event, ctx);
5074 return count;
5076 EXPORT_SYMBOL_GPL(perf_event_read_value);
5078 static int __perf_read_group_add(struct perf_event *leader,
5079 u64 read_format, u64 *values)
5081 struct perf_event_context *ctx = leader->ctx;
5082 struct perf_event *sub;
5083 unsigned long flags;
5084 int n = 1; /* skip @nr */
5085 int ret;
5087 ret = perf_event_read(leader, true);
5088 if (ret)
5089 return ret;
5091 raw_spin_lock_irqsave(&ctx->lock, flags);
5094 * Since we co-schedule groups, {enabled,running} times of siblings
5095 * will be identical to those of the leader, so we only publish one
5096 * set.
5098 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5099 values[n++] += leader->total_time_enabled +
5100 atomic64_read(&leader->child_total_time_enabled);
5103 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5104 values[n++] += leader->total_time_running +
5105 atomic64_read(&leader->child_total_time_running);
5109 * Write {count,id} tuples for every sibling.
5111 values[n++] += perf_event_count(leader);
5112 if (read_format & PERF_FORMAT_ID)
5113 values[n++] = primary_event_id(leader);
5115 for_each_sibling_event(sub, leader) {
5116 values[n++] += perf_event_count(sub);
5117 if (read_format & PERF_FORMAT_ID)
5118 values[n++] = primary_event_id(sub);
5121 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5122 return 0;
5125 static int perf_read_group(struct perf_event *event,
5126 u64 read_format, char __user *buf)
5128 struct perf_event *leader = event->group_leader, *child;
5129 struct perf_event_context *ctx = leader->ctx;
5130 int ret;
5131 u64 *values;
5133 lockdep_assert_held(&ctx->mutex);
5135 values = kzalloc(event->read_size, GFP_KERNEL);
5136 if (!values)
5137 return -ENOMEM;
5139 values[0] = 1 + leader->nr_siblings;
5142 * By locking the child_mutex of the leader we effectively
5143 * lock the child list of all siblings.. XXX explain how.
5145 mutex_lock(&leader->child_mutex);
5147 ret = __perf_read_group_add(leader, read_format, values);
5148 if (ret)
5149 goto unlock;
5151 list_for_each_entry(child, &leader->child_list, child_list) {
5152 ret = __perf_read_group_add(child, read_format, values);
5153 if (ret)
5154 goto unlock;
5157 mutex_unlock(&leader->child_mutex);
5159 ret = event->read_size;
5160 if (copy_to_user(buf, values, event->read_size))
5161 ret = -EFAULT;
5162 goto out;
5164 unlock:
5165 mutex_unlock(&leader->child_mutex);
5166 out:
5167 kfree(values);
5168 return ret;
5171 static int perf_read_one(struct perf_event *event,
5172 u64 read_format, char __user *buf)
5174 u64 enabled, running;
5175 u64 values[4];
5176 int n = 0;
5178 values[n++] = __perf_event_read_value(event, &enabled, &running);
5179 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5180 values[n++] = enabled;
5181 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5182 values[n++] = running;
5183 if (read_format & PERF_FORMAT_ID)
5184 values[n++] = primary_event_id(event);
5186 if (copy_to_user(buf, values, n * sizeof(u64)))
5187 return -EFAULT;
5189 return n * sizeof(u64);
5192 static bool is_event_hup(struct perf_event *event)
5194 bool no_children;
5196 if (event->state > PERF_EVENT_STATE_EXIT)
5197 return false;
5199 mutex_lock(&event->child_mutex);
5200 no_children = list_empty(&event->child_list);
5201 mutex_unlock(&event->child_mutex);
5202 return no_children;
5206 * Read the performance event - simple non blocking version for now
5208 static ssize_t
5209 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5211 u64 read_format = event->attr.read_format;
5212 int ret;
5215 * Return end-of-file for a read on an event that is in
5216 * error state (i.e. because it was pinned but it couldn't be
5217 * scheduled on to the CPU at some point).
5219 if (event->state == PERF_EVENT_STATE_ERROR)
5220 return 0;
5222 if (count < event->read_size)
5223 return -ENOSPC;
5225 WARN_ON_ONCE(event->ctx->parent_ctx);
5226 if (read_format & PERF_FORMAT_GROUP)
5227 ret = perf_read_group(event, read_format, buf);
5228 else
5229 ret = perf_read_one(event, read_format, buf);
5231 return ret;
5234 static ssize_t
5235 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5237 struct perf_event *event = file->private_data;
5238 struct perf_event_context *ctx;
5239 int ret;
5241 ret = security_perf_event_read(event);
5242 if (ret)
5243 return ret;
5245 ctx = perf_event_ctx_lock(event);
5246 ret = __perf_read(event, buf, count);
5247 perf_event_ctx_unlock(event, ctx);
5249 return ret;
5252 static __poll_t perf_poll(struct file *file, poll_table *wait)
5254 struct perf_event *event = file->private_data;
5255 struct perf_buffer *rb;
5256 __poll_t events = EPOLLHUP;
5258 poll_wait(file, &event->waitq, wait);
5260 if (is_event_hup(event))
5261 return events;
5264 * Pin the event->rb by taking event->mmap_mutex; otherwise
5265 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5267 mutex_lock(&event->mmap_mutex);
5268 rb = event->rb;
5269 if (rb)
5270 events = atomic_xchg(&rb->poll, 0);
5271 mutex_unlock(&event->mmap_mutex);
5272 return events;
5275 static void _perf_event_reset(struct perf_event *event)
5277 (void)perf_event_read(event, false);
5278 local64_set(&event->count, 0);
5279 perf_event_update_userpage(event);
5282 /* Assume it's not an event with inherit set. */
5283 u64 perf_event_pause(struct perf_event *event, bool reset)
5285 struct perf_event_context *ctx;
5286 u64 count;
5288 ctx = perf_event_ctx_lock(event);
5289 WARN_ON_ONCE(event->attr.inherit);
5290 _perf_event_disable(event);
5291 count = local64_read(&event->count);
5292 if (reset)
5293 local64_set(&event->count, 0);
5294 perf_event_ctx_unlock(event, ctx);
5296 return count;
5298 EXPORT_SYMBOL_GPL(perf_event_pause);
5301 * Holding the top-level event's child_mutex means that any
5302 * descendant process that has inherited this event will block
5303 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5304 * task existence requirements of perf_event_enable/disable.
5306 static void perf_event_for_each_child(struct perf_event *event,
5307 void (*func)(struct perf_event *))
5309 struct perf_event *child;
5311 WARN_ON_ONCE(event->ctx->parent_ctx);
5313 mutex_lock(&event->child_mutex);
5314 func(event);
5315 list_for_each_entry(child, &event->child_list, child_list)
5316 func(child);
5317 mutex_unlock(&event->child_mutex);
5320 static void perf_event_for_each(struct perf_event *event,
5321 void (*func)(struct perf_event *))
5323 struct perf_event_context *ctx = event->ctx;
5324 struct perf_event *sibling;
5326 lockdep_assert_held(&ctx->mutex);
5328 event = event->group_leader;
5330 perf_event_for_each_child(event, func);
5331 for_each_sibling_event(sibling, event)
5332 perf_event_for_each_child(sibling, func);
5335 static void __perf_event_period(struct perf_event *event,
5336 struct perf_cpu_context *cpuctx,
5337 struct perf_event_context *ctx,
5338 void *info)
5340 u64 value = *((u64 *)info);
5341 bool active;
5343 if (event->attr.freq) {
5344 event->attr.sample_freq = value;
5345 } else {
5346 event->attr.sample_period = value;
5347 event->hw.sample_period = value;
5350 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5351 if (active) {
5352 perf_pmu_disable(ctx->pmu);
5354 * We could be throttled; unthrottle now to avoid the tick
5355 * trying to unthrottle while we already re-started the event.
5357 if (event->hw.interrupts == MAX_INTERRUPTS) {
5358 event->hw.interrupts = 0;
5359 perf_log_throttle(event, 1);
5361 event->pmu->stop(event, PERF_EF_UPDATE);
5364 local64_set(&event->hw.period_left, 0);
5366 if (active) {
5367 event->pmu->start(event, PERF_EF_RELOAD);
5368 perf_pmu_enable(ctx->pmu);
5372 static int perf_event_check_period(struct perf_event *event, u64 value)
5374 return event->pmu->check_period(event, value);
5377 static int _perf_event_period(struct perf_event *event, u64 value)
5379 if (!is_sampling_event(event))
5380 return -EINVAL;
5382 if (!value)
5383 return -EINVAL;
5385 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5386 return -EINVAL;
5388 if (perf_event_check_period(event, value))
5389 return -EINVAL;
5391 if (!event->attr.freq && (value & (1ULL << 63)))
5392 return -EINVAL;
5394 event_function_call(event, __perf_event_period, &value);
5396 return 0;
5399 int perf_event_period(struct perf_event *event, u64 value)
5401 struct perf_event_context *ctx;
5402 int ret;
5404 ctx = perf_event_ctx_lock(event);
5405 ret = _perf_event_period(event, value);
5406 perf_event_ctx_unlock(event, ctx);
5408 return ret;
5410 EXPORT_SYMBOL_GPL(perf_event_period);
5412 static const struct file_operations perf_fops;
5414 static inline int perf_fget_light(int fd, struct fd *p)
5416 struct fd f = fdget(fd);
5417 if (!f.file)
5418 return -EBADF;
5420 if (f.file->f_op != &perf_fops) {
5421 fdput(f);
5422 return -EBADF;
5424 *p = f;
5425 return 0;
5428 static int perf_event_set_output(struct perf_event *event,
5429 struct perf_event *output_event);
5430 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5431 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5432 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5433 struct perf_event_attr *attr);
5435 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5437 void (*func)(struct perf_event *);
5438 u32 flags = arg;
5440 switch (cmd) {
5441 case PERF_EVENT_IOC_ENABLE:
5442 func = _perf_event_enable;
5443 break;
5444 case PERF_EVENT_IOC_DISABLE:
5445 func = _perf_event_disable;
5446 break;
5447 case PERF_EVENT_IOC_RESET:
5448 func = _perf_event_reset;
5449 break;
5451 case PERF_EVENT_IOC_REFRESH:
5452 return _perf_event_refresh(event, arg);
5454 case PERF_EVENT_IOC_PERIOD:
5456 u64 value;
5458 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5459 return -EFAULT;
5461 return _perf_event_period(event, value);
5463 case PERF_EVENT_IOC_ID:
5465 u64 id = primary_event_id(event);
5467 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5468 return -EFAULT;
5469 return 0;
5472 case PERF_EVENT_IOC_SET_OUTPUT:
5474 int ret;
5475 if (arg != -1) {
5476 struct perf_event *output_event;
5477 struct fd output;
5478 ret = perf_fget_light(arg, &output);
5479 if (ret)
5480 return ret;
5481 output_event = output.file->private_data;
5482 ret = perf_event_set_output(event, output_event);
5483 fdput(output);
5484 } else {
5485 ret = perf_event_set_output(event, NULL);
5487 return ret;
5490 case PERF_EVENT_IOC_SET_FILTER:
5491 return perf_event_set_filter(event, (void __user *)arg);
5493 case PERF_EVENT_IOC_SET_BPF:
5494 return perf_event_set_bpf_prog(event, arg);
5496 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5497 struct perf_buffer *rb;
5499 rcu_read_lock();
5500 rb = rcu_dereference(event->rb);
5501 if (!rb || !rb->nr_pages) {
5502 rcu_read_unlock();
5503 return -EINVAL;
5505 rb_toggle_paused(rb, !!arg);
5506 rcu_read_unlock();
5507 return 0;
5510 case PERF_EVENT_IOC_QUERY_BPF:
5511 return perf_event_query_prog_array(event, (void __user *)arg);
5513 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5514 struct perf_event_attr new_attr;
5515 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5516 &new_attr);
5518 if (err)
5519 return err;
5521 return perf_event_modify_attr(event, &new_attr);
5523 default:
5524 return -ENOTTY;
5527 if (flags & PERF_IOC_FLAG_GROUP)
5528 perf_event_for_each(event, func);
5529 else
5530 perf_event_for_each_child(event, func);
5532 return 0;
5535 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5537 struct perf_event *event = file->private_data;
5538 struct perf_event_context *ctx;
5539 long ret;
5541 /* Treat ioctl like writes as it is likely a mutating operation. */
5542 ret = security_perf_event_write(event);
5543 if (ret)
5544 return ret;
5546 ctx = perf_event_ctx_lock(event);
5547 ret = _perf_ioctl(event, cmd, arg);
5548 perf_event_ctx_unlock(event, ctx);
5550 return ret;
5553 #ifdef CONFIG_COMPAT
5554 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5555 unsigned long arg)
5557 switch (_IOC_NR(cmd)) {
5558 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5559 case _IOC_NR(PERF_EVENT_IOC_ID):
5560 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5561 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5562 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5563 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5564 cmd &= ~IOCSIZE_MASK;
5565 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5567 break;
5569 return perf_ioctl(file, cmd, arg);
5571 #else
5572 # define perf_compat_ioctl NULL
5573 #endif
5575 int perf_event_task_enable(void)
5577 struct perf_event_context *ctx;
5578 struct perf_event *event;
5580 mutex_lock(&current->perf_event_mutex);
5581 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5582 ctx = perf_event_ctx_lock(event);
5583 perf_event_for_each_child(event, _perf_event_enable);
5584 perf_event_ctx_unlock(event, ctx);
5586 mutex_unlock(&current->perf_event_mutex);
5588 return 0;
5591 int perf_event_task_disable(void)
5593 struct perf_event_context *ctx;
5594 struct perf_event *event;
5596 mutex_lock(&current->perf_event_mutex);
5597 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5598 ctx = perf_event_ctx_lock(event);
5599 perf_event_for_each_child(event, _perf_event_disable);
5600 perf_event_ctx_unlock(event, ctx);
5602 mutex_unlock(&current->perf_event_mutex);
5604 return 0;
5607 static int perf_event_index(struct perf_event *event)
5609 if (event->hw.state & PERF_HES_STOPPED)
5610 return 0;
5612 if (event->state != PERF_EVENT_STATE_ACTIVE)
5613 return 0;
5615 return event->pmu->event_idx(event);
5618 static void calc_timer_values(struct perf_event *event,
5619 u64 *now,
5620 u64 *enabled,
5621 u64 *running)
5623 u64 ctx_time;
5625 *now = perf_clock();
5626 ctx_time = event->shadow_ctx_time + *now;
5627 __perf_update_times(event, ctx_time, enabled, running);
5630 static void perf_event_init_userpage(struct perf_event *event)
5632 struct perf_event_mmap_page *userpg;
5633 struct perf_buffer *rb;
5635 rcu_read_lock();
5636 rb = rcu_dereference(event->rb);
5637 if (!rb)
5638 goto unlock;
5640 userpg = rb->user_page;
5642 /* Allow new userspace to detect that bit 0 is deprecated */
5643 userpg->cap_bit0_is_deprecated = 1;
5644 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5645 userpg->data_offset = PAGE_SIZE;
5646 userpg->data_size = perf_data_size(rb);
5648 unlock:
5649 rcu_read_unlock();
5652 void __weak arch_perf_update_userpage(
5653 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5658 * Callers need to ensure there can be no nesting of this function, otherwise
5659 * the seqlock logic goes bad. We can not serialize this because the arch
5660 * code calls this from NMI context.
5662 void perf_event_update_userpage(struct perf_event *event)
5664 struct perf_event_mmap_page *userpg;
5665 struct perf_buffer *rb;
5666 u64 enabled, running, now;
5668 rcu_read_lock();
5669 rb = rcu_dereference(event->rb);
5670 if (!rb)
5671 goto unlock;
5674 * compute total_time_enabled, total_time_running
5675 * based on snapshot values taken when the event
5676 * was last scheduled in.
5678 * we cannot simply called update_context_time()
5679 * because of locking issue as we can be called in
5680 * NMI context
5682 calc_timer_values(event, &now, &enabled, &running);
5684 userpg = rb->user_page;
5686 * Disable preemption to guarantee consistent time stamps are stored to
5687 * the user page.
5689 preempt_disable();
5690 ++userpg->lock;
5691 barrier();
5692 userpg->index = perf_event_index(event);
5693 userpg->offset = perf_event_count(event);
5694 if (userpg->index)
5695 userpg->offset -= local64_read(&event->hw.prev_count);
5697 userpg->time_enabled = enabled +
5698 atomic64_read(&event->child_total_time_enabled);
5700 userpg->time_running = running +
5701 atomic64_read(&event->child_total_time_running);
5703 arch_perf_update_userpage(event, userpg, now);
5705 barrier();
5706 ++userpg->lock;
5707 preempt_enable();
5708 unlock:
5709 rcu_read_unlock();
5711 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5713 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5715 struct perf_event *event = vmf->vma->vm_file->private_data;
5716 struct perf_buffer *rb;
5717 vm_fault_t ret = VM_FAULT_SIGBUS;
5719 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5720 if (vmf->pgoff == 0)
5721 ret = 0;
5722 return ret;
5725 rcu_read_lock();
5726 rb = rcu_dereference(event->rb);
5727 if (!rb)
5728 goto unlock;
5730 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5731 goto unlock;
5733 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5734 if (!vmf->page)
5735 goto unlock;
5737 get_page(vmf->page);
5738 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5739 vmf->page->index = vmf->pgoff;
5741 ret = 0;
5742 unlock:
5743 rcu_read_unlock();
5745 return ret;
5748 static void ring_buffer_attach(struct perf_event *event,
5749 struct perf_buffer *rb)
5751 struct perf_buffer *old_rb = NULL;
5752 unsigned long flags;
5754 if (event->rb) {
5756 * Should be impossible, we set this when removing
5757 * event->rb_entry and wait/clear when adding event->rb_entry.
5759 WARN_ON_ONCE(event->rcu_pending);
5761 old_rb = event->rb;
5762 spin_lock_irqsave(&old_rb->event_lock, flags);
5763 list_del_rcu(&event->rb_entry);
5764 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5766 event->rcu_batches = get_state_synchronize_rcu();
5767 event->rcu_pending = 1;
5770 if (rb) {
5771 if (event->rcu_pending) {
5772 cond_synchronize_rcu(event->rcu_batches);
5773 event->rcu_pending = 0;
5776 spin_lock_irqsave(&rb->event_lock, flags);
5777 list_add_rcu(&event->rb_entry, &rb->event_list);
5778 spin_unlock_irqrestore(&rb->event_lock, flags);
5782 * Avoid racing with perf_mmap_close(AUX): stop the event
5783 * before swizzling the event::rb pointer; if it's getting
5784 * unmapped, its aux_mmap_count will be 0 and it won't
5785 * restart. See the comment in __perf_pmu_output_stop().
5787 * Data will inevitably be lost when set_output is done in
5788 * mid-air, but then again, whoever does it like this is
5789 * not in for the data anyway.
5791 if (has_aux(event))
5792 perf_event_stop(event, 0);
5794 rcu_assign_pointer(event->rb, rb);
5796 if (old_rb) {
5797 ring_buffer_put(old_rb);
5799 * Since we detached before setting the new rb, so that we
5800 * could attach the new rb, we could have missed a wakeup.
5801 * Provide it now.
5803 wake_up_all(&event->waitq);
5807 static void ring_buffer_wakeup(struct perf_event *event)
5809 struct perf_buffer *rb;
5811 rcu_read_lock();
5812 rb = rcu_dereference(event->rb);
5813 if (rb) {
5814 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5815 wake_up_all(&event->waitq);
5817 rcu_read_unlock();
5820 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5822 struct perf_buffer *rb;
5824 rcu_read_lock();
5825 rb = rcu_dereference(event->rb);
5826 if (rb) {
5827 if (!refcount_inc_not_zero(&rb->refcount))
5828 rb = NULL;
5830 rcu_read_unlock();
5832 return rb;
5835 void ring_buffer_put(struct perf_buffer *rb)
5837 if (!refcount_dec_and_test(&rb->refcount))
5838 return;
5840 WARN_ON_ONCE(!list_empty(&rb->event_list));
5842 call_rcu(&rb->rcu_head, rb_free_rcu);
5845 static void perf_mmap_open(struct vm_area_struct *vma)
5847 struct perf_event *event = vma->vm_file->private_data;
5849 atomic_inc(&event->mmap_count);
5850 atomic_inc(&event->rb->mmap_count);
5852 if (vma->vm_pgoff)
5853 atomic_inc(&event->rb->aux_mmap_count);
5855 if (event->pmu->event_mapped)
5856 event->pmu->event_mapped(event, vma->vm_mm);
5859 static void perf_pmu_output_stop(struct perf_event *event);
5862 * A buffer can be mmap()ed multiple times; either directly through the same
5863 * event, or through other events by use of perf_event_set_output().
5865 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5866 * the buffer here, where we still have a VM context. This means we need
5867 * to detach all events redirecting to us.
5869 static void perf_mmap_close(struct vm_area_struct *vma)
5871 struct perf_event *event = vma->vm_file->private_data;
5872 struct perf_buffer *rb = ring_buffer_get(event);
5873 struct user_struct *mmap_user = rb->mmap_user;
5874 int mmap_locked = rb->mmap_locked;
5875 unsigned long size = perf_data_size(rb);
5876 bool detach_rest = false;
5878 if (event->pmu->event_unmapped)
5879 event->pmu->event_unmapped(event, vma->vm_mm);
5882 * rb->aux_mmap_count will always drop before rb->mmap_count and
5883 * event->mmap_count, so it is ok to use event->mmap_mutex to
5884 * serialize with perf_mmap here.
5886 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5887 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5889 * Stop all AUX events that are writing to this buffer,
5890 * so that we can free its AUX pages and corresponding PMU
5891 * data. Note that after rb::aux_mmap_count dropped to zero,
5892 * they won't start any more (see perf_aux_output_begin()).
5894 perf_pmu_output_stop(event);
5896 /* now it's safe to free the pages */
5897 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5898 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5900 /* this has to be the last one */
5901 rb_free_aux(rb);
5902 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5904 mutex_unlock(&event->mmap_mutex);
5907 if (atomic_dec_and_test(&rb->mmap_count))
5908 detach_rest = true;
5910 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5911 goto out_put;
5913 ring_buffer_attach(event, NULL);
5914 mutex_unlock(&event->mmap_mutex);
5916 /* If there's still other mmap()s of this buffer, we're done. */
5917 if (!detach_rest)
5918 goto out_put;
5921 * No other mmap()s, detach from all other events that might redirect
5922 * into the now unreachable buffer. Somewhat complicated by the
5923 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5925 again:
5926 rcu_read_lock();
5927 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5928 if (!atomic_long_inc_not_zero(&event->refcount)) {
5930 * This event is en-route to free_event() which will
5931 * detach it and remove it from the list.
5933 continue;
5935 rcu_read_unlock();
5937 mutex_lock(&event->mmap_mutex);
5939 * Check we didn't race with perf_event_set_output() which can
5940 * swizzle the rb from under us while we were waiting to
5941 * acquire mmap_mutex.
5943 * If we find a different rb; ignore this event, a next
5944 * iteration will no longer find it on the list. We have to
5945 * still restart the iteration to make sure we're not now
5946 * iterating the wrong list.
5948 if (event->rb == rb)
5949 ring_buffer_attach(event, NULL);
5951 mutex_unlock(&event->mmap_mutex);
5952 put_event(event);
5955 * Restart the iteration; either we're on the wrong list or
5956 * destroyed its integrity by doing a deletion.
5958 goto again;
5960 rcu_read_unlock();
5963 * It could be there's still a few 0-ref events on the list; they'll
5964 * get cleaned up by free_event() -- they'll also still have their
5965 * ref on the rb and will free it whenever they are done with it.
5967 * Aside from that, this buffer is 'fully' detached and unmapped,
5968 * undo the VM accounting.
5971 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5972 &mmap_user->locked_vm);
5973 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5974 free_uid(mmap_user);
5976 out_put:
5977 ring_buffer_put(rb); /* could be last */
5980 static const struct vm_operations_struct perf_mmap_vmops = {
5981 .open = perf_mmap_open,
5982 .close = perf_mmap_close, /* non mergeable */
5983 .fault = perf_mmap_fault,
5984 .page_mkwrite = perf_mmap_fault,
5987 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5989 struct perf_event *event = file->private_data;
5990 unsigned long user_locked, user_lock_limit;
5991 struct user_struct *user = current_user();
5992 struct perf_buffer *rb = NULL;
5993 unsigned long locked, lock_limit;
5994 unsigned long vma_size;
5995 unsigned long nr_pages;
5996 long user_extra = 0, extra = 0;
5997 int ret = 0, flags = 0;
6000 * Don't allow mmap() of inherited per-task counters. This would
6001 * create a performance issue due to all children writing to the
6002 * same rb.
6004 if (event->cpu == -1 && event->attr.inherit)
6005 return -EINVAL;
6007 if (!(vma->vm_flags & VM_SHARED))
6008 return -EINVAL;
6010 ret = security_perf_event_read(event);
6011 if (ret)
6012 return ret;
6014 vma_size = vma->vm_end - vma->vm_start;
6016 if (vma->vm_pgoff == 0) {
6017 nr_pages = (vma_size / PAGE_SIZE) - 1;
6018 } else {
6020 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6021 * mapped, all subsequent mappings should have the same size
6022 * and offset. Must be above the normal perf buffer.
6024 u64 aux_offset, aux_size;
6026 if (!event->rb)
6027 return -EINVAL;
6029 nr_pages = vma_size / PAGE_SIZE;
6031 mutex_lock(&event->mmap_mutex);
6032 ret = -EINVAL;
6034 rb = event->rb;
6035 if (!rb)
6036 goto aux_unlock;
6038 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6039 aux_size = READ_ONCE(rb->user_page->aux_size);
6041 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6042 goto aux_unlock;
6044 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6045 goto aux_unlock;
6047 /* already mapped with a different offset */
6048 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6049 goto aux_unlock;
6051 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6052 goto aux_unlock;
6054 /* already mapped with a different size */
6055 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6056 goto aux_unlock;
6058 if (!is_power_of_2(nr_pages))
6059 goto aux_unlock;
6061 if (!atomic_inc_not_zero(&rb->mmap_count))
6062 goto aux_unlock;
6064 if (rb_has_aux(rb)) {
6065 atomic_inc(&rb->aux_mmap_count);
6066 ret = 0;
6067 goto unlock;
6070 atomic_set(&rb->aux_mmap_count, 1);
6071 user_extra = nr_pages;
6073 goto accounting;
6077 * If we have rb pages ensure they're a power-of-two number, so we
6078 * can do bitmasks instead of modulo.
6080 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6081 return -EINVAL;
6083 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6084 return -EINVAL;
6086 WARN_ON_ONCE(event->ctx->parent_ctx);
6087 again:
6088 mutex_lock(&event->mmap_mutex);
6089 if (event->rb) {
6090 if (event->rb->nr_pages != nr_pages) {
6091 ret = -EINVAL;
6092 goto unlock;
6095 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6097 * Raced against perf_mmap_close() through
6098 * perf_event_set_output(). Try again, hope for better
6099 * luck.
6101 mutex_unlock(&event->mmap_mutex);
6102 goto again;
6105 goto unlock;
6108 user_extra = nr_pages + 1;
6110 accounting:
6111 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6114 * Increase the limit linearly with more CPUs:
6116 user_lock_limit *= num_online_cpus();
6118 user_locked = atomic_long_read(&user->locked_vm);
6121 * sysctl_perf_event_mlock may have changed, so that
6122 * user->locked_vm > user_lock_limit
6124 if (user_locked > user_lock_limit)
6125 user_locked = user_lock_limit;
6126 user_locked += user_extra;
6128 if (user_locked > user_lock_limit) {
6130 * charge locked_vm until it hits user_lock_limit;
6131 * charge the rest from pinned_vm
6133 extra = user_locked - user_lock_limit;
6134 user_extra -= extra;
6137 lock_limit = rlimit(RLIMIT_MEMLOCK);
6138 lock_limit >>= PAGE_SHIFT;
6139 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6141 if ((locked > lock_limit) && perf_is_paranoid() &&
6142 !capable(CAP_IPC_LOCK)) {
6143 ret = -EPERM;
6144 goto unlock;
6147 WARN_ON(!rb && event->rb);
6149 if (vma->vm_flags & VM_WRITE)
6150 flags |= RING_BUFFER_WRITABLE;
6152 if (!rb) {
6153 rb = rb_alloc(nr_pages,
6154 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6155 event->cpu, flags);
6157 if (!rb) {
6158 ret = -ENOMEM;
6159 goto unlock;
6162 atomic_set(&rb->mmap_count, 1);
6163 rb->mmap_user = get_current_user();
6164 rb->mmap_locked = extra;
6166 ring_buffer_attach(event, rb);
6168 perf_event_init_userpage(event);
6169 perf_event_update_userpage(event);
6170 } else {
6171 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6172 event->attr.aux_watermark, flags);
6173 if (!ret)
6174 rb->aux_mmap_locked = extra;
6177 unlock:
6178 if (!ret) {
6179 atomic_long_add(user_extra, &user->locked_vm);
6180 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6182 atomic_inc(&event->mmap_count);
6183 } else if (rb) {
6184 atomic_dec(&rb->mmap_count);
6186 aux_unlock:
6187 mutex_unlock(&event->mmap_mutex);
6190 * Since pinned accounting is per vm we cannot allow fork() to copy our
6191 * vma.
6193 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6194 vma->vm_ops = &perf_mmap_vmops;
6196 if (event->pmu->event_mapped)
6197 event->pmu->event_mapped(event, vma->vm_mm);
6199 return ret;
6202 static int perf_fasync(int fd, struct file *filp, int on)
6204 struct inode *inode = file_inode(filp);
6205 struct perf_event *event = filp->private_data;
6206 int retval;
6208 inode_lock(inode);
6209 retval = fasync_helper(fd, filp, on, &event->fasync);
6210 inode_unlock(inode);
6212 if (retval < 0)
6213 return retval;
6215 return 0;
6218 static const struct file_operations perf_fops = {
6219 .llseek = no_llseek,
6220 .release = perf_release,
6221 .read = perf_read,
6222 .poll = perf_poll,
6223 .unlocked_ioctl = perf_ioctl,
6224 .compat_ioctl = perf_compat_ioctl,
6225 .mmap = perf_mmap,
6226 .fasync = perf_fasync,
6230 * Perf event wakeup
6232 * If there's data, ensure we set the poll() state and publish everything
6233 * to user-space before waking everybody up.
6236 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6238 /* only the parent has fasync state */
6239 if (event->parent)
6240 event = event->parent;
6241 return &event->fasync;
6244 void perf_event_wakeup(struct perf_event *event)
6246 ring_buffer_wakeup(event);
6248 if (event->pending_kill) {
6249 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6250 event->pending_kill = 0;
6254 static void perf_pending_event_disable(struct perf_event *event)
6256 int cpu = READ_ONCE(event->pending_disable);
6258 if (cpu < 0)
6259 return;
6261 if (cpu == smp_processor_id()) {
6262 WRITE_ONCE(event->pending_disable, -1);
6263 perf_event_disable_local(event);
6264 return;
6268 * CPU-A CPU-B
6270 * perf_event_disable_inatomic()
6271 * @pending_disable = CPU-A;
6272 * irq_work_queue();
6274 * sched-out
6275 * @pending_disable = -1;
6277 * sched-in
6278 * perf_event_disable_inatomic()
6279 * @pending_disable = CPU-B;
6280 * irq_work_queue(); // FAILS
6282 * irq_work_run()
6283 * perf_pending_event()
6285 * But the event runs on CPU-B and wants disabling there.
6287 irq_work_queue_on(&event->pending, cpu);
6290 static void perf_pending_event(struct irq_work *entry)
6292 struct perf_event *event = container_of(entry, struct perf_event, pending);
6293 int rctx;
6295 rctx = perf_swevent_get_recursion_context();
6297 * If we 'fail' here, that's OK, it means recursion is already disabled
6298 * and we won't recurse 'further'.
6301 perf_pending_event_disable(event);
6303 if (event->pending_wakeup) {
6304 event->pending_wakeup = 0;
6305 perf_event_wakeup(event);
6308 if (rctx >= 0)
6309 perf_swevent_put_recursion_context(rctx);
6313 * We assume there is only KVM supporting the callbacks.
6314 * Later on, we might change it to a list if there is
6315 * another virtualization implementation supporting the callbacks.
6317 struct perf_guest_info_callbacks *perf_guest_cbs;
6319 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6321 perf_guest_cbs = cbs;
6322 return 0;
6324 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6326 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6328 perf_guest_cbs = NULL;
6329 return 0;
6331 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6333 static void
6334 perf_output_sample_regs(struct perf_output_handle *handle,
6335 struct pt_regs *regs, u64 mask)
6337 int bit;
6338 DECLARE_BITMAP(_mask, 64);
6340 bitmap_from_u64(_mask, mask);
6341 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6342 u64 val;
6344 val = perf_reg_value(regs, bit);
6345 perf_output_put(handle, val);
6349 static void perf_sample_regs_user(struct perf_regs *regs_user,
6350 struct pt_regs *regs,
6351 struct pt_regs *regs_user_copy)
6353 if (user_mode(regs)) {
6354 regs_user->abi = perf_reg_abi(current);
6355 regs_user->regs = regs;
6356 } else if (!(current->flags & PF_KTHREAD)) {
6357 perf_get_regs_user(regs_user, regs, regs_user_copy);
6358 } else {
6359 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6360 regs_user->regs = NULL;
6364 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6365 struct pt_regs *regs)
6367 regs_intr->regs = regs;
6368 regs_intr->abi = perf_reg_abi(current);
6373 * Get remaining task size from user stack pointer.
6375 * It'd be better to take stack vma map and limit this more
6376 * precisely, but there's no way to get it safely under interrupt,
6377 * so using TASK_SIZE as limit.
6379 static u64 perf_ustack_task_size(struct pt_regs *regs)
6381 unsigned long addr = perf_user_stack_pointer(regs);
6383 if (!addr || addr >= TASK_SIZE)
6384 return 0;
6386 return TASK_SIZE - addr;
6389 static u16
6390 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6391 struct pt_regs *regs)
6393 u64 task_size;
6395 /* No regs, no stack pointer, no dump. */
6396 if (!regs)
6397 return 0;
6400 * Check if we fit in with the requested stack size into the:
6401 * - TASK_SIZE
6402 * If we don't, we limit the size to the TASK_SIZE.
6404 * - remaining sample size
6405 * If we don't, we customize the stack size to
6406 * fit in to the remaining sample size.
6409 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6410 stack_size = min(stack_size, (u16) task_size);
6412 /* Current header size plus static size and dynamic size. */
6413 header_size += 2 * sizeof(u64);
6415 /* Do we fit in with the current stack dump size? */
6416 if ((u16) (header_size + stack_size) < header_size) {
6418 * If we overflow the maximum size for the sample,
6419 * we customize the stack dump size to fit in.
6421 stack_size = USHRT_MAX - header_size - sizeof(u64);
6422 stack_size = round_up(stack_size, sizeof(u64));
6425 return stack_size;
6428 static void
6429 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6430 struct pt_regs *regs)
6432 /* Case of a kernel thread, nothing to dump */
6433 if (!regs) {
6434 u64 size = 0;
6435 perf_output_put(handle, size);
6436 } else {
6437 unsigned long sp;
6438 unsigned int rem;
6439 u64 dyn_size;
6440 mm_segment_t fs;
6443 * We dump:
6444 * static size
6445 * - the size requested by user or the best one we can fit
6446 * in to the sample max size
6447 * data
6448 * - user stack dump data
6449 * dynamic size
6450 * - the actual dumped size
6453 /* Static size. */
6454 perf_output_put(handle, dump_size);
6456 /* Data. */
6457 sp = perf_user_stack_pointer(regs);
6458 fs = force_uaccess_begin();
6459 rem = __output_copy_user(handle, (void *) sp, dump_size);
6460 force_uaccess_end(fs);
6461 dyn_size = dump_size - rem;
6463 perf_output_skip(handle, rem);
6465 /* Dynamic size. */
6466 perf_output_put(handle, dyn_size);
6470 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6471 struct perf_sample_data *data,
6472 size_t size)
6474 struct perf_event *sampler = event->aux_event;
6475 struct perf_buffer *rb;
6477 data->aux_size = 0;
6479 if (!sampler)
6480 goto out;
6482 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6483 goto out;
6485 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6486 goto out;
6488 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6489 if (!rb)
6490 goto out;
6493 * If this is an NMI hit inside sampling code, don't take
6494 * the sample. See also perf_aux_sample_output().
6496 if (READ_ONCE(rb->aux_in_sampling)) {
6497 data->aux_size = 0;
6498 } else {
6499 size = min_t(size_t, size, perf_aux_size(rb));
6500 data->aux_size = ALIGN(size, sizeof(u64));
6502 ring_buffer_put(rb);
6504 out:
6505 return data->aux_size;
6508 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6509 struct perf_event *event,
6510 struct perf_output_handle *handle,
6511 unsigned long size)
6513 unsigned long flags;
6514 long ret;
6517 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6518 * paths. If we start calling them in NMI context, they may race with
6519 * the IRQ ones, that is, for example, re-starting an event that's just
6520 * been stopped, which is why we're using a separate callback that
6521 * doesn't change the event state.
6523 * IRQs need to be disabled to prevent IPIs from racing with us.
6525 local_irq_save(flags);
6527 * Guard against NMI hits inside the critical section;
6528 * see also perf_prepare_sample_aux().
6530 WRITE_ONCE(rb->aux_in_sampling, 1);
6531 barrier();
6533 ret = event->pmu->snapshot_aux(event, handle, size);
6535 barrier();
6536 WRITE_ONCE(rb->aux_in_sampling, 0);
6537 local_irq_restore(flags);
6539 return ret;
6542 static void perf_aux_sample_output(struct perf_event *event,
6543 struct perf_output_handle *handle,
6544 struct perf_sample_data *data)
6546 struct perf_event *sampler = event->aux_event;
6547 struct perf_buffer *rb;
6548 unsigned long pad;
6549 long size;
6551 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6552 return;
6554 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6555 if (!rb)
6556 return;
6558 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6561 * An error here means that perf_output_copy() failed (returned a
6562 * non-zero surplus that it didn't copy), which in its current
6563 * enlightened implementation is not possible. If that changes, we'd
6564 * like to know.
6566 if (WARN_ON_ONCE(size < 0))
6567 goto out_put;
6570 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6571 * perf_prepare_sample_aux(), so should not be more than that.
6573 pad = data->aux_size - size;
6574 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6575 pad = 8;
6577 if (pad) {
6578 u64 zero = 0;
6579 perf_output_copy(handle, &zero, pad);
6582 out_put:
6583 ring_buffer_put(rb);
6586 static void __perf_event_header__init_id(struct perf_event_header *header,
6587 struct perf_sample_data *data,
6588 struct perf_event *event)
6590 u64 sample_type = event->attr.sample_type;
6592 data->type = sample_type;
6593 header->size += event->id_header_size;
6595 if (sample_type & PERF_SAMPLE_TID) {
6596 /* namespace issues */
6597 data->tid_entry.pid = perf_event_pid(event, current);
6598 data->tid_entry.tid = perf_event_tid(event, current);
6601 if (sample_type & PERF_SAMPLE_TIME)
6602 data->time = perf_event_clock(event);
6604 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6605 data->id = primary_event_id(event);
6607 if (sample_type & PERF_SAMPLE_STREAM_ID)
6608 data->stream_id = event->id;
6610 if (sample_type & PERF_SAMPLE_CPU) {
6611 data->cpu_entry.cpu = raw_smp_processor_id();
6612 data->cpu_entry.reserved = 0;
6616 void perf_event_header__init_id(struct perf_event_header *header,
6617 struct perf_sample_data *data,
6618 struct perf_event *event)
6620 if (event->attr.sample_id_all)
6621 __perf_event_header__init_id(header, data, event);
6624 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6625 struct perf_sample_data *data)
6627 u64 sample_type = data->type;
6629 if (sample_type & PERF_SAMPLE_TID)
6630 perf_output_put(handle, data->tid_entry);
6632 if (sample_type & PERF_SAMPLE_TIME)
6633 perf_output_put(handle, data->time);
6635 if (sample_type & PERF_SAMPLE_ID)
6636 perf_output_put(handle, data->id);
6638 if (sample_type & PERF_SAMPLE_STREAM_ID)
6639 perf_output_put(handle, data->stream_id);
6641 if (sample_type & PERF_SAMPLE_CPU)
6642 perf_output_put(handle, data->cpu_entry);
6644 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6645 perf_output_put(handle, data->id);
6648 void perf_event__output_id_sample(struct perf_event *event,
6649 struct perf_output_handle *handle,
6650 struct perf_sample_data *sample)
6652 if (event->attr.sample_id_all)
6653 __perf_event__output_id_sample(handle, sample);
6656 static void perf_output_read_one(struct perf_output_handle *handle,
6657 struct perf_event *event,
6658 u64 enabled, u64 running)
6660 u64 read_format = event->attr.read_format;
6661 u64 values[4];
6662 int n = 0;
6664 values[n++] = perf_event_count(event);
6665 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6666 values[n++] = enabled +
6667 atomic64_read(&event->child_total_time_enabled);
6669 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6670 values[n++] = running +
6671 atomic64_read(&event->child_total_time_running);
6673 if (read_format & PERF_FORMAT_ID)
6674 values[n++] = primary_event_id(event);
6676 __output_copy(handle, values, n * sizeof(u64));
6679 static void perf_output_read_group(struct perf_output_handle *handle,
6680 struct perf_event *event,
6681 u64 enabled, u64 running)
6683 struct perf_event *leader = event->group_leader, *sub;
6684 u64 read_format = event->attr.read_format;
6685 u64 values[5];
6686 int n = 0;
6688 values[n++] = 1 + leader->nr_siblings;
6690 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6691 values[n++] = enabled;
6693 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6694 values[n++] = running;
6696 if ((leader != event) &&
6697 (leader->state == PERF_EVENT_STATE_ACTIVE))
6698 leader->pmu->read(leader);
6700 values[n++] = perf_event_count(leader);
6701 if (read_format & PERF_FORMAT_ID)
6702 values[n++] = primary_event_id(leader);
6704 __output_copy(handle, values, n * sizeof(u64));
6706 for_each_sibling_event(sub, leader) {
6707 n = 0;
6709 if ((sub != event) &&
6710 (sub->state == PERF_EVENT_STATE_ACTIVE))
6711 sub->pmu->read(sub);
6713 values[n++] = perf_event_count(sub);
6714 if (read_format & PERF_FORMAT_ID)
6715 values[n++] = primary_event_id(sub);
6717 __output_copy(handle, values, n * sizeof(u64));
6721 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6722 PERF_FORMAT_TOTAL_TIME_RUNNING)
6725 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6727 * The problem is that its both hard and excessively expensive to iterate the
6728 * child list, not to mention that its impossible to IPI the children running
6729 * on another CPU, from interrupt/NMI context.
6731 static void perf_output_read(struct perf_output_handle *handle,
6732 struct perf_event *event)
6734 u64 enabled = 0, running = 0, now;
6735 u64 read_format = event->attr.read_format;
6738 * compute total_time_enabled, total_time_running
6739 * based on snapshot values taken when the event
6740 * was last scheduled in.
6742 * we cannot simply called update_context_time()
6743 * because of locking issue as we are called in
6744 * NMI context
6746 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6747 calc_timer_values(event, &now, &enabled, &running);
6749 if (event->attr.read_format & PERF_FORMAT_GROUP)
6750 perf_output_read_group(handle, event, enabled, running);
6751 else
6752 perf_output_read_one(handle, event, enabled, running);
6755 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6757 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6760 void perf_output_sample(struct perf_output_handle *handle,
6761 struct perf_event_header *header,
6762 struct perf_sample_data *data,
6763 struct perf_event *event)
6765 u64 sample_type = data->type;
6767 perf_output_put(handle, *header);
6769 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6770 perf_output_put(handle, data->id);
6772 if (sample_type & PERF_SAMPLE_IP)
6773 perf_output_put(handle, data->ip);
6775 if (sample_type & PERF_SAMPLE_TID)
6776 perf_output_put(handle, data->tid_entry);
6778 if (sample_type & PERF_SAMPLE_TIME)
6779 perf_output_put(handle, data->time);
6781 if (sample_type & PERF_SAMPLE_ADDR)
6782 perf_output_put(handle, data->addr);
6784 if (sample_type & PERF_SAMPLE_ID)
6785 perf_output_put(handle, data->id);
6787 if (sample_type & PERF_SAMPLE_STREAM_ID)
6788 perf_output_put(handle, data->stream_id);
6790 if (sample_type & PERF_SAMPLE_CPU)
6791 perf_output_put(handle, data->cpu_entry);
6793 if (sample_type & PERF_SAMPLE_PERIOD)
6794 perf_output_put(handle, data->period);
6796 if (sample_type & PERF_SAMPLE_READ)
6797 perf_output_read(handle, event);
6799 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6800 int size = 1;
6802 size += data->callchain->nr;
6803 size *= sizeof(u64);
6804 __output_copy(handle, data->callchain, size);
6807 if (sample_type & PERF_SAMPLE_RAW) {
6808 struct perf_raw_record *raw = data->raw;
6810 if (raw) {
6811 struct perf_raw_frag *frag = &raw->frag;
6813 perf_output_put(handle, raw->size);
6814 do {
6815 if (frag->copy) {
6816 __output_custom(handle, frag->copy,
6817 frag->data, frag->size);
6818 } else {
6819 __output_copy(handle, frag->data,
6820 frag->size);
6822 if (perf_raw_frag_last(frag))
6823 break;
6824 frag = frag->next;
6825 } while (1);
6826 if (frag->pad)
6827 __output_skip(handle, NULL, frag->pad);
6828 } else {
6829 struct {
6830 u32 size;
6831 u32 data;
6832 } raw = {
6833 .size = sizeof(u32),
6834 .data = 0,
6836 perf_output_put(handle, raw);
6840 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6841 if (data->br_stack) {
6842 size_t size;
6844 size = data->br_stack->nr
6845 * sizeof(struct perf_branch_entry);
6847 perf_output_put(handle, data->br_stack->nr);
6848 if (perf_sample_save_hw_index(event))
6849 perf_output_put(handle, data->br_stack->hw_idx);
6850 perf_output_copy(handle, data->br_stack->entries, size);
6851 } else {
6853 * we always store at least the value of nr
6855 u64 nr = 0;
6856 perf_output_put(handle, nr);
6860 if (sample_type & PERF_SAMPLE_REGS_USER) {
6861 u64 abi = data->regs_user.abi;
6864 * If there are no regs to dump, notice it through
6865 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6867 perf_output_put(handle, abi);
6869 if (abi) {
6870 u64 mask = event->attr.sample_regs_user;
6871 perf_output_sample_regs(handle,
6872 data->regs_user.regs,
6873 mask);
6877 if (sample_type & PERF_SAMPLE_STACK_USER) {
6878 perf_output_sample_ustack(handle,
6879 data->stack_user_size,
6880 data->regs_user.regs);
6883 if (sample_type & PERF_SAMPLE_WEIGHT)
6884 perf_output_put(handle, data->weight);
6886 if (sample_type & PERF_SAMPLE_DATA_SRC)
6887 perf_output_put(handle, data->data_src.val);
6889 if (sample_type & PERF_SAMPLE_TRANSACTION)
6890 perf_output_put(handle, data->txn);
6892 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6893 u64 abi = data->regs_intr.abi;
6895 * If there are no regs to dump, notice it through
6896 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6898 perf_output_put(handle, abi);
6900 if (abi) {
6901 u64 mask = event->attr.sample_regs_intr;
6903 perf_output_sample_regs(handle,
6904 data->regs_intr.regs,
6905 mask);
6909 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6910 perf_output_put(handle, data->phys_addr);
6912 if (sample_type & PERF_SAMPLE_CGROUP)
6913 perf_output_put(handle, data->cgroup);
6915 if (sample_type & PERF_SAMPLE_AUX) {
6916 perf_output_put(handle, data->aux_size);
6918 if (data->aux_size)
6919 perf_aux_sample_output(event, handle, data);
6922 if (!event->attr.watermark) {
6923 int wakeup_events = event->attr.wakeup_events;
6925 if (wakeup_events) {
6926 struct perf_buffer *rb = handle->rb;
6927 int events = local_inc_return(&rb->events);
6929 if (events >= wakeup_events) {
6930 local_sub(wakeup_events, &rb->events);
6931 local_inc(&rb->wakeup);
6937 static u64 perf_virt_to_phys(u64 virt)
6939 u64 phys_addr = 0;
6940 struct page *p = NULL;
6942 if (!virt)
6943 return 0;
6945 if (virt >= TASK_SIZE) {
6946 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6947 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6948 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6949 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6950 } else {
6952 * Walking the pages tables for user address.
6953 * Interrupts are disabled, so it prevents any tear down
6954 * of the page tables.
6955 * Try IRQ-safe get_user_page_fast_only first.
6956 * If failed, leave phys_addr as 0.
6958 if (current->mm != NULL) {
6959 pagefault_disable();
6960 if (get_user_page_fast_only(virt, 0, &p))
6961 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6962 pagefault_enable();
6965 if (p)
6966 put_page(p);
6969 return phys_addr;
6972 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6974 struct perf_callchain_entry *
6975 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6977 bool kernel = !event->attr.exclude_callchain_kernel;
6978 bool user = !event->attr.exclude_callchain_user;
6979 /* Disallow cross-task user callchains. */
6980 bool crosstask = event->ctx->task && event->ctx->task != current;
6981 const u32 max_stack = event->attr.sample_max_stack;
6982 struct perf_callchain_entry *callchain;
6984 if (!kernel && !user)
6985 return &__empty_callchain;
6987 callchain = get_perf_callchain(regs, 0, kernel, user,
6988 max_stack, crosstask, true);
6989 return callchain ?: &__empty_callchain;
6992 void perf_prepare_sample(struct perf_event_header *header,
6993 struct perf_sample_data *data,
6994 struct perf_event *event,
6995 struct pt_regs *regs)
6997 u64 sample_type = event->attr.sample_type;
6999 header->type = PERF_RECORD_SAMPLE;
7000 header->size = sizeof(*header) + event->header_size;
7002 header->misc = 0;
7003 header->misc |= perf_misc_flags(regs);
7005 __perf_event_header__init_id(header, data, event);
7007 if (sample_type & PERF_SAMPLE_IP)
7008 data->ip = perf_instruction_pointer(regs);
7010 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7011 int size = 1;
7013 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7014 data->callchain = perf_callchain(event, regs);
7016 size += data->callchain->nr;
7018 header->size += size * sizeof(u64);
7021 if (sample_type & PERF_SAMPLE_RAW) {
7022 struct perf_raw_record *raw = data->raw;
7023 int size;
7025 if (raw) {
7026 struct perf_raw_frag *frag = &raw->frag;
7027 u32 sum = 0;
7029 do {
7030 sum += frag->size;
7031 if (perf_raw_frag_last(frag))
7032 break;
7033 frag = frag->next;
7034 } while (1);
7036 size = round_up(sum + sizeof(u32), sizeof(u64));
7037 raw->size = size - sizeof(u32);
7038 frag->pad = raw->size - sum;
7039 } else {
7040 size = sizeof(u64);
7043 header->size += size;
7046 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7047 int size = sizeof(u64); /* nr */
7048 if (data->br_stack) {
7049 if (perf_sample_save_hw_index(event))
7050 size += sizeof(u64);
7052 size += data->br_stack->nr
7053 * sizeof(struct perf_branch_entry);
7055 header->size += size;
7058 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7059 perf_sample_regs_user(&data->regs_user, regs,
7060 &data->regs_user_copy);
7062 if (sample_type & PERF_SAMPLE_REGS_USER) {
7063 /* regs dump ABI info */
7064 int size = sizeof(u64);
7066 if (data->regs_user.regs) {
7067 u64 mask = event->attr.sample_regs_user;
7068 size += hweight64(mask) * sizeof(u64);
7071 header->size += size;
7074 if (sample_type & PERF_SAMPLE_STACK_USER) {
7076 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7077 * processed as the last one or have additional check added
7078 * in case new sample type is added, because we could eat
7079 * up the rest of the sample size.
7081 u16 stack_size = event->attr.sample_stack_user;
7082 u16 size = sizeof(u64);
7084 stack_size = perf_sample_ustack_size(stack_size, header->size,
7085 data->regs_user.regs);
7088 * If there is something to dump, add space for the dump
7089 * itself and for the field that tells the dynamic size,
7090 * which is how many have been actually dumped.
7092 if (stack_size)
7093 size += sizeof(u64) + stack_size;
7095 data->stack_user_size = stack_size;
7096 header->size += size;
7099 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7100 /* regs dump ABI info */
7101 int size = sizeof(u64);
7103 perf_sample_regs_intr(&data->regs_intr, regs);
7105 if (data->regs_intr.regs) {
7106 u64 mask = event->attr.sample_regs_intr;
7108 size += hweight64(mask) * sizeof(u64);
7111 header->size += size;
7114 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7115 data->phys_addr = perf_virt_to_phys(data->addr);
7117 #ifdef CONFIG_CGROUP_PERF
7118 if (sample_type & PERF_SAMPLE_CGROUP) {
7119 struct cgroup *cgrp;
7121 /* protected by RCU */
7122 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7123 data->cgroup = cgroup_id(cgrp);
7125 #endif
7127 if (sample_type & PERF_SAMPLE_AUX) {
7128 u64 size;
7130 header->size += sizeof(u64); /* size */
7133 * Given the 16bit nature of header::size, an AUX sample can
7134 * easily overflow it, what with all the preceding sample bits.
7135 * Make sure this doesn't happen by using up to U16_MAX bytes
7136 * per sample in total (rounded down to 8 byte boundary).
7138 size = min_t(size_t, U16_MAX - header->size,
7139 event->attr.aux_sample_size);
7140 size = rounddown(size, 8);
7141 size = perf_prepare_sample_aux(event, data, size);
7143 WARN_ON_ONCE(size + header->size > U16_MAX);
7144 header->size += size;
7147 * If you're adding more sample types here, you likely need to do
7148 * something about the overflowing header::size, like repurpose the
7149 * lowest 3 bits of size, which should be always zero at the moment.
7150 * This raises a more important question, do we really need 512k sized
7151 * samples and why, so good argumentation is in order for whatever you
7152 * do here next.
7154 WARN_ON_ONCE(header->size & 7);
7157 static __always_inline int
7158 __perf_event_output(struct perf_event *event,
7159 struct perf_sample_data *data,
7160 struct pt_regs *regs,
7161 int (*output_begin)(struct perf_output_handle *,
7162 struct perf_event *,
7163 unsigned int))
7165 struct perf_output_handle handle;
7166 struct perf_event_header header;
7167 int err;
7169 /* protect the callchain buffers */
7170 rcu_read_lock();
7172 perf_prepare_sample(&header, data, event, regs);
7174 err = output_begin(&handle, event, header.size);
7175 if (err)
7176 goto exit;
7178 perf_output_sample(&handle, &header, data, event);
7180 perf_output_end(&handle);
7182 exit:
7183 rcu_read_unlock();
7184 return err;
7187 void
7188 perf_event_output_forward(struct perf_event *event,
7189 struct perf_sample_data *data,
7190 struct pt_regs *regs)
7192 __perf_event_output(event, data, regs, perf_output_begin_forward);
7195 void
7196 perf_event_output_backward(struct perf_event *event,
7197 struct perf_sample_data *data,
7198 struct pt_regs *regs)
7200 __perf_event_output(event, data, regs, perf_output_begin_backward);
7204 perf_event_output(struct perf_event *event,
7205 struct perf_sample_data *data,
7206 struct pt_regs *regs)
7208 return __perf_event_output(event, data, regs, perf_output_begin);
7212 * read event_id
7215 struct perf_read_event {
7216 struct perf_event_header header;
7218 u32 pid;
7219 u32 tid;
7222 static void
7223 perf_event_read_event(struct perf_event *event,
7224 struct task_struct *task)
7226 struct perf_output_handle handle;
7227 struct perf_sample_data sample;
7228 struct perf_read_event read_event = {
7229 .header = {
7230 .type = PERF_RECORD_READ,
7231 .misc = 0,
7232 .size = sizeof(read_event) + event->read_size,
7234 .pid = perf_event_pid(event, task),
7235 .tid = perf_event_tid(event, task),
7237 int ret;
7239 perf_event_header__init_id(&read_event.header, &sample, event);
7240 ret = perf_output_begin(&handle, event, read_event.header.size);
7241 if (ret)
7242 return;
7244 perf_output_put(&handle, read_event);
7245 perf_output_read(&handle, event);
7246 perf_event__output_id_sample(event, &handle, &sample);
7248 perf_output_end(&handle);
7251 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7253 static void
7254 perf_iterate_ctx(struct perf_event_context *ctx,
7255 perf_iterate_f output,
7256 void *data, bool all)
7258 struct perf_event *event;
7260 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7261 if (!all) {
7262 if (event->state < PERF_EVENT_STATE_INACTIVE)
7263 continue;
7264 if (!event_filter_match(event))
7265 continue;
7268 output(event, data);
7272 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7274 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7275 struct perf_event *event;
7277 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7279 * Skip events that are not fully formed yet; ensure that
7280 * if we observe event->ctx, both event and ctx will be
7281 * complete enough. See perf_install_in_context().
7283 if (!smp_load_acquire(&event->ctx))
7284 continue;
7286 if (event->state < PERF_EVENT_STATE_INACTIVE)
7287 continue;
7288 if (!event_filter_match(event))
7289 continue;
7290 output(event, data);
7295 * Iterate all events that need to receive side-band events.
7297 * For new callers; ensure that account_pmu_sb_event() includes
7298 * your event, otherwise it might not get delivered.
7300 static void
7301 perf_iterate_sb(perf_iterate_f output, void *data,
7302 struct perf_event_context *task_ctx)
7304 struct perf_event_context *ctx;
7305 int ctxn;
7307 rcu_read_lock();
7308 preempt_disable();
7311 * If we have task_ctx != NULL we only notify the task context itself.
7312 * The task_ctx is set only for EXIT events before releasing task
7313 * context.
7315 if (task_ctx) {
7316 perf_iterate_ctx(task_ctx, output, data, false);
7317 goto done;
7320 perf_iterate_sb_cpu(output, data);
7322 for_each_task_context_nr(ctxn) {
7323 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7324 if (ctx)
7325 perf_iterate_ctx(ctx, output, data, false);
7327 done:
7328 preempt_enable();
7329 rcu_read_unlock();
7333 * Clear all file-based filters at exec, they'll have to be
7334 * re-instated when/if these objects are mmapped again.
7336 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7338 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7339 struct perf_addr_filter *filter;
7340 unsigned int restart = 0, count = 0;
7341 unsigned long flags;
7343 if (!has_addr_filter(event))
7344 return;
7346 raw_spin_lock_irqsave(&ifh->lock, flags);
7347 list_for_each_entry(filter, &ifh->list, entry) {
7348 if (filter->path.dentry) {
7349 event->addr_filter_ranges[count].start = 0;
7350 event->addr_filter_ranges[count].size = 0;
7351 restart++;
7354 count++;
7357 if (restart)
7358 event->addr_filters_gen++;
7359 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7361 if (restart)
7362 perf_event_stop(event, 1);
7365 void perf_event_exec(void)
7367 struct perf_event_context *ctx;
7368 int ctxn;
7370 rcu_read_lock();
7371 for_each_task_context_nr(ctxn) {
7372 ctx = current->perf_event_ctxp[ctxn];
7373 if (!ctx)
7374 continue;
7376 perf_event_enable_on_exec(ctxn);
7378 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7379 true);
7381 rcu_read_unlock();
7384 struct remote_output {
7385 struct perf_buffer *rb;
7386 int err;
7389 static void __perf_event_output_stop(struct perf_event *event, void *data)
7391 struct perf_event *parent = event->parent;
7392 struct remote_output *ro = data;
7393 struct perf_buffer *rb = ro->rb;
7394 struct stop_event_data sd = {
7395 .event = event,
7398 if (!has_aux(event))
7399 return;
7401 if (!parent)
7402 parent = event;
7405 * In case of inheritance, it will be the parent that links to the
7406 * ring-buffer, but it will be the child that's actually using it.
7408 * We are using event::rb to determine if the event should be stopped,
7409 * however this may race with ring_buffer_attach() (through set_output),
7410 * which will make us skip the event that actually needs to be stopped.
7411 * So ring_buffer_attach() has to stop an aux event before re-assigning
7412 * its rb pointer.
7414 if (rcu_dereference(parent->rb) == rb)
7415 ro->err = __perf_event_stop(&sd);
7418 static int __perf_pmu_output_stop(void *info)
7420 struct perf_event *event = info;
7421 struct pmu *pmu = event->ctx->pmu;
7422 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7423 struct remote_output ro = {
7424 .rb = event->rb,
7427 rcu_read_lock();
7428 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7429 if (cpuctx->task_ctx)
7430 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7431 &ro, false);
7432 rcu_read_unlock();
7434 return ro.err;
7437 static void perf_pmu_output_stop(struct perf_event *event)
7439 struct perf_event *iter;
7440 int err, cpu;
7442 restart:
7443 rcu_read_lock();
7444 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7446 * For per-CPU events, we need to make sure that neither they
7447 * nor their children are running; for cpu==-1 events it's
7448 * sufficient to stop the event itself if it's active, since
7449 * it can't have children.
7451 cpu = iter->cpu;
7452 if (cpu == -1)
7453 cpu = READ_ONCE(iter->oncpu);
7455 if (cpu == -1)
7456 continue;
7458 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7459 if (err == -EAGAIN) {
7460 rcu_read_unlock();
7461 goto restart;
7464 rcu_read_unlock();
7468 * task tracking -- fork/exit
7470 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7473 struct perf_task_event {
7474 struct task_struct *task;
7475 struct perf_event_context *task_ctx;
7477 struct {
7478 struct perf_event_header header;
7480 u32 pid;
7481 u32 ppid;
7482 u32 tid;
7483 u32 ptid;
7484 u64 time;
7485 } event_id;
7488 static int perf_event_task_match(struct perf_event *event)
7490 return event->attr.comm || event->attr.mmap ||
7491 event->attr.mmap2 || event->attr.mmap_data ||
7492 event->attr.task;
7495 static void perf_event_task_output(struct perf_event *event,
7496 void *data)
7498 struct perf_task_event *task_event = data;
7499 struct perf_output_handle handle;
7500 struct perf_sample_data sample;
7501 struct task_struct *task = task_event->task;
7502 int ret, size = task_event->event_id.header.size;
7504 if (!perf_event_task_match(event))
7505 return;
7507 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7509 ret = perf_output_begin(&handle, event,
7510 task_event->event_id.header.size);
7511 if (ret)
7512 goto out;
7514 task_event->event_id.pid = perf_event_pid(event, task);
7515 task_event->event_id.tid = perf_event_tid(event, task);
7517 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7518 task_event->event_id.ppid = perf_event_pid(event,
7519 task->real_parent);
7520 task_event->event_id.ptid = perf_event_pid(event,
7521 task->real_parent);
7522 } else { /* PERF_RECORD_FORK */
7523 task_event->event_id.ppid = perf_event_pid(event, current);
7524 task_event->event_id.ptid = perf_event_tid(event, current);
7527 task_event->event_id.time = perf_event_clock(event);
7529 perf_output_put(&handle, task_event->event_id);
7531 perf_event__output_id_sample(event, &handle, &sample);
7533 perf_output_end(&handle);
7534 out:
7535 task_event->event_id.header.size = size;
7538 static void perf_event_task(struct task_struct *task,
7539 struct perf_event_context *task_ctx,
7540 int new)
7542 struct perf_task_event task_event;
7544 if (!atomic_read(&nr_comm_events) &&
7545 !atomic_read(&nr_mmap_events) &&
7546 !atomic_read(&nr_task_events))
7547 return;
7549 task_event = (struct perf_task_event){
7550 .task = task,
7551 .task_ctx = task_ctx,
7552 .event_id = {
7553 .header = {
7554 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7555 .misc = 0,
7556 .size = sizeof(task_event.event_id),
7558 /* .pid */
7559 /* .ppid */
7560 /* .tid */
7561 /* .ptid */
7562 /* .time */
7566 perf_iterate_sb(perf_event_task_output,
7567 &task_event,
7568 task_ctx);
7571 void perf_event_fork(struct task_struct *task)
7573 perf_event_task(task, NULL, 1);
7574 perf_event_namespaces(task);
7578 * comm tracking
7581 struct perf_comm_event {
7582 struct task_struct *task;
7583 char *comm;
7584 int comm_size;
7586 struct {
7587 struct perf_event_header header;
7589 u32 pid;
7590 u32 tid;
7591 } event_id;
7594 static int perf_event_comm_match(struct perf_event *event)
7596 return event->attr.comm;
7599 static void perf_event_comm_output(struct perf_event *event,
7600 void *data)
7602 struct perf_comm_event *comm_event = data;
7603 struct perf_output_handle handle;
7604 struct perf_sample_data sample;
7605 int size = comm_event->event_id.header.size;
7606 int ret;
7608 if (!perf_event_comm_match(event))
7609 return;
7611 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7612 ret = perf_output_begin(&handle, event,
7613 comm_event->event_id.header.size);
7615 if (ret)
7616 goto out;
7618 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7619 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7621 perf_output_put(&handle, comm_event->event_id);
7622 __output_copy(&handle, comm_event->comm,
7623 comm_event->comm_size);
7625 perf_event__output_id_sample(event, &handle, &sample);
7627 perf_output_end(&handle);
7628 out:
7629 comm_event->event_id.header.size = size;
7632 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7634 char comm[TASK_COMM_LEN];
7635 unsigned int size;
7637 memset(comm, 0, sizeof(comm));
7638 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7639 size = ALIGN(strlen(comm)+1, sizeof(u64));
7641 comm_event->comm = comm;
7642 comm_event->comm_size = size;
7644 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7646 perf_iterate_sb(perf_event_comm_output,
7647 comm_event,
7648 NULL);
7651 void perf_event_comm(struct task_struct *task, bool exec)
7653 struct perf_comm_event comm_event;
7655 if (!atomic_read(&nr_comm_events))
7656 return;
7658 comm_event = (struct perf_comm_event){
7659 .task = task,
7660 /* .comm */
7661 /* .comm_size */
7662 .event_id = {
7663 .header = {
7664 .type = PERF_RECORD_COMM,
7665 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7666 /* .size */
7668 /* .pid */
7669 /* .tid */
7673 perf_event_comm_event(&comm_event);
7677 * namespaces tracking
7680 struct perf_namespaces_event {
7681 struct task_struct *task;
7683 struct {
7684 struct perf_event_header header;
7686 u32 pid;
7687 u32 tid;
7688 u64 nr_namespaces;
7689 struct perf_ns_link_info link_info[NR_NAMESPACES];
7690 } event_id;
7693 static int perf_event_namespaces_match(struct perf_event *event)
7695 return event->attr.namespaces;
7698 static void perf_event_namespaces_output(struct perf_event *event,
7699 void *data)
7701 struct perf_namespaces_event *namespaces_event = data;
7702 struct perf_output_handle handle;
7703 struct perf_sample_data sample;
7704 u16 header_size = namespaces_event->event_id.header.size;
7705 int ret;
7707 if (!perf_event_namespaces_match(event))
7708 return;
7710 perf_event_header__init_id(&namespaces_event->event_id.header,
7711 &sample, event);
7712 ret = perf_output_begin(&handle, event,
7713 namespaces_event->event_id.header.size);
7714 if (ret)
7715 goto out;
7717 namespaces_event->event_id.pid = perf_event_pid(event,
7718 namespaces_event->task);
7719 namespaces_event->event_id.tid = perf_event_tid(event,
7720 namespaces_event->task);
7722 perf_output_put(&handle, namespaces_event->event_id);
7724 perf_event__output_id_sample(event, &handle, &sample);
7726 perf_output_end(&handle);
7727 out:
7728 namespaces_event->event_id.header.size = header_size;
7731 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7732 struct task_struct *task,
7733 const struct proc_ns_operations *ns_ops)
7735 struct path ns_path;
7736 struct inode *ns_inode;
7737 int error;
7739 error = ns_get_path(&ns_path, task, ns_ops);
7740 if (!error) {
7741 ns_inode = ns_path.dentry->d_inode;
7742 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7743 ns_link_info->ino = ns_inode->i_ino;
7744 path_put(&ns_path);
7748 void perf_event_namespaces(struct task_struct *task)
7750 struct perf_namespaces_event namespaces_event;
7751 struct perf_ns_link_info *ns_link_info;
7753 if (!atomic_read(&nr_namespaces_events))
7754 return;
7756 namespaces_event = (struct perf_namespaces_event){
7757 .task = task,
7758 .event_id = {
7759 .header = {
7760 .type = PERF_RECORD_NAMESPACES,
7761 .misc = 0,
7762 .size = sizeof(namespaces_event.event_id),
7764 /* .pid */
7765 /* .tid */
7766 .nr_namespaces = NR_NAMESPACES,
7767 /* .link_info[NR_NAMESPACES] */
7771 ns_link_info = namespaces_event.event_id.link_info;
7773 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7774 task, &mntns_operations);
7776 #ifdef CONFIG_USER_NS
7777 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7778 task, &userns_operations);
7779 #endif
7780 #ifdef CONFIG_NET_NS
7781 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7782 task, &netns_operations);
7783 #endif
7784 #ifdef CONFIG_UTS_NS
7785 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7786 task, &utsns_operations);
7787 #endif
7788 #ifdef CONFIG_IPC_NS
7789 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7790 task, &ipcns_operations);
7791 #endif
7792 #ifdef CONFIG_PID_NS
7793 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7794 task, &pidns_operations);
7795 #endif
7796 #ifdef CONFIG_CGROUPS
7797 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7798 task, &cgroupns_operations);
7799 #endif
7801 perf_iterate_sb(perf_event_namespaces_output,
7802 &namespaces_event,
7803 NULL);
7807 * cgroup tracking
7809 #ifdef CONFIG_CGROUP_PERF
7811 struct perf_cgroup_event {
7812 char *path;
7813 int path_size;
7814 struct {
7815 struct perf_event_header header;
7816 u64 id;
7817 char path[];
7818 } event_id;
7821 static int perf_event_cgroup_match(struct perf_event *event)
7823 return event->attr.cgroup;
7826 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7828 struct perf_cgroup_event *cgroup_event = data;
7829 struct perf_output_handle handle;
7830 struct perf_sample_data sample;
7831 u16 header_size = cgroup_event->event_id.header.size;
7832 int ret;
7834 if (!perf_event_cgroup_match(event))
7835 return;
7837 perf_event_header__init_id(&cgroup_event->event_id.header,
7838 &sample, event);
7839 ret = perf_output_begin(&handle, event,
7840 cgroup_event->event_id.header.size);
7841 if (ret)
7842 goto out;
7844 perf_output_put(&handle, cgroup_event->event_id);
7845 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7847 perf_event__output_id_sample(event, &handle, &sample);
7849 perf_output_end(&handle);
7850 out:
7851 cgroup_event->event_id.header.size = header_size;
7854 static void perf_event_cgroup(struct cgroup *cgrp)
7856 struct perf_cgroup_event cgroup_event;
7857 char path_enomem[16] = "//enomem";
7858 char *pathname;
7859 size_t size;
7861 if (!atomic_read(&nr_cgroup_events))
7862 return;
7864 cgroup_event = (struct perf_cgroup_event){
7865 .event_id = {
7866 .header = {
7867 .type = PERF_RECORD_CGROUP,
7868 .misc = 0,
7869 .size = sizeof(cgroup_event.event_id),
7871 .id = cgroup_id(cgrp),
7875 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7876 if (pathname == NULL) {
7877 cgroup_event.path = path_enomem;
7878 } else {
7879 /* just to be sure to have enough space for alignment */
7880 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7881 cgroup_event.path = pathname;
7885 * Since our buffer works in 8 byte units we need to align our string
7886 * size to a multiple of 8. However, we must guarantee the tail end is
7887 * zero'd out to avoid leaking random bits to userspace.
7889 size = strlen(cgroup_event.path) + 1;
7890 while (!IS_ALIGNED(size, sizeof(u64)))
7891 cgroup_event.path[size++] = '\0';
7893 cgroup_event.event_id.header.size += size;
7894 cgroup_event.path_size = size;
7896 perf_iterate_sb(perf_event_cgroup_output,
7897 &cgroup_event,
7898 NULL);
7900 kfree(pathname);
7903 #endif
7906 * mmap tracking
7909 struct perf_mmap_event {
7910 struct vm_area_struct *vma;
7912 const char *file_name;
7913 int file_size;
7914 int maj, min;
7915 u64 ino;
7916 u64 ino_generation;
7917 u32 prot, flags;
7919 struct {
7920 struct perf_event_header header;
7922 u32 pid;
7923 u32 tid;
7924 u64 start;
7925 u64 len;
7926 u64 pgoff;
7927 } event_id;
7930 static int perf_event_mmap_match(struct perf_event *event,
7931 void *data)
7933 struct perf_mmap_event *mmap_event = data;
7934 struct vm_area_struct *vma = mmap_event->vma;
7935 int executable = vma->vm_flags & VM_EXEC;
7937 return (!executable && event->attr.mmap_data) ||
7938 (executable && (event->attr.mmap || event->attr.mmap2));
7941 static void perf_event_mmap_output(struct perf_event *event,
7942 void *data)
7944 struct perf_mmap_event *mmap_event = data;
7945 struct perf_output_handle handle;
7946 struct perf_sample_data sample;
7947 int size = mmap_event->event_id.header.size;
7948 u32 type = mmap_event->event_id.header.type;
7949 int ret;
7951 if (!perf_event_mmap_match(event, data))
7952 return;
7954 if (event->attr.mmap2) {
7955 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7956 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7957 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7958 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7959 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7960 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7961 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7964 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7965 ret = perf_output_begin(&handle, event,
7966 mmap_event->event_id.header.size);
7967 if (ret)
7968 goto out;
7970 mmap_event->event_id.pid = perf_event_pid(event, current);
7971 mmap_event->event_id.tid = perf_event_tid(event, current);
7973 perf_output_put(&handle, mmap_event->event_id);
7975 if (event->attr.mmap2) {
7976 perf_output_put(&handle, mmap_event->maj);
7977 perf_output_put(&handle, mmap_event->min);
7978 perf_output_put(&handle, mmap_event->ino);
7979 perf_output_put(&handle, mmap_event->ino_generation);
7980 perf_output_put(&handle, mmap_event->prot);
7981 perf_output_put(&handle, mmap_event->flags);
7984 __output_copy(&handle, mmap_event->file_name,
7985 mmap_event->file_size);
7987 perf_event__output_id_sample(event, &handle, &sample);
7989 perf_output_end(&handle);
7990 out:
7991 mmap_event->event_id.header.size = size;
7992 mmap_event->event_id.header.type = type;
7995 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7997 struct vm_area_struct *vma = mmap_event->vma;
7998 struct file *file = vma->vm_file;
7999 int maj = 0, min = 0;
8000 u64 ino = 0, gen = 0;
8001 u32 prot = 0, flags = 0;
8002 unsigned int size;
8003 char tmp[16];
8004 char *buf = NULL;
8005 char *name;
8007 if (vma->vm_flags & VM_READ)
8008 prot |= PROT_READ;
8009 if (vma->vm_flags & VM_WRITE)
8010 prot |= PROT_WRITE;
8011 if (vma->vm_flags & VM_EXEC)
8012 prot |= PROT_EXEC;
8014 if (vma->vm_flags & VM_MAYSHARE)
8015 flags = MAP_SHARED;
8016 else
8017 flags = MAP_PRIVATE;
8019 if (vma->vm_flags & VM_DENYWRITE)
8020 flags |= MAP_DENYWRITE;
8021 if (vma->vm_flags & VM_MAYEXEC)
8022 flags |= MAP_EXECUTABLE;
8023 if (vma->vm_flags & VM_LOCKED)
8024 flags |= MAP_LOCKED;
8025 if (is_vm_hugetlb_page(vma))
8026 flags |= MAP_HUGETLB;
8028 if (file) {
8029 struct inode *inode;
8030 dev_t dev;
8032 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8033 if (!buf) {
8034 name = "//enomem";
8035 goto cpy_name;
8038 * d_path() works from the end of the rb backwards, so we
8039 * need to add enough zero bytes after the string to handle
8040 * the 64bit alignment we do later.
8042 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8043 if (IS_ERR(name)) {
8044 name = "//toolong";
8045 goto cpy_name;
8047 inode = file_inode(vma->vm_file);
8048 dev = inode->i_sb->s_dev;
8049 ino = inode->i_ino;
8050 gen = inode->i_generation;
8051 maj = MAJOR(dev);
8052 min = MINOR(dev);
8054 goto got_name;
8055 } else {
8056 if (vma->vm_ops && vma->vm_ops->name) {
8057 name = (char *) vma->vm_ops->name(vma);
8058 if (name)
8059 goto cpy_name;
8062 name = (char *)arch_vma_name(vma);
8063 if (name)
8064 goto cpy_name;
8066 if (vma->vm_start <= vma->vm_mm->start_brk &&
8067 vma->vm_end >= vma->vm_mm->brk) {
8068 name = "[heap]";
8069 goto cpy_name;
8071 if (vma->vm_start <= vma->vm_mm->start_stack &&
8072 vma->vm_end >= vma->vm_mm->start_stack) {
8073 name = "[stack]";
8074 goto cpy_name;
8077 name = "//anon";
8078 goto cpy_name;
8081 cpy_name:
8082 strlcpy(tmp, name, sizeof(tmp));
8083 name = tmp;
8084 got_name:
8086 * Since our buffer works in 8 byte units we need to align our string
8087 * size to a multiple of 8. However, we must guarantee the tail end is
8088 * zero'd out to avoid leaking random bits to userspace.
8090 size = strlen(name)+1;
8091 while (!IS_ALIGNED(size, sizeof(u64)))
8092 name[size++] = '\0';
8094 mmap_event->file_name = name;
8095 mmap_event->file_size = size;
8096 mmap_event->maj = maj;
8097 mmap_event->min = min;
8098 mmap_event->ino = ino;
8099 mmap_event->ino_generation = gen;
8100 mmap_event->prot = prot;
8101 mmap_event->flags = flags;
8103 if (!(vma->vm_flags & VM_EXEC))
8104 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8106 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8108 perf_iterate_sb(perf_event_mmap_output,
8109 mmap_event,
8110 NULL);
8112 kfree(buf);
8116 * Check whether inode and address range match filter criteria.
8118 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8119 struct file *file, unsigned long offset,
8120 unsigned long size)
8122 /* d_inode(NULL) won't be equal to any mapped user-space file */
8123 if (!filter->path.dentry)
8124 return false;
8126 if (d_inode(filter->path.dentry) != file_inode(file))
8127 return false;
8129 if (filter->offset > offset + size)
8130 return false;
8132 if (filter->offset + filter->size < offset)
8133 return false;
8135 return true;
8138 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8139 struct vm_area_struct *vma,
8140 struct perf_addr_filter_range *fr)
8142 unsigned long vma_size = vma->vm_end - vma->vm_start;
8143 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8144 struct file *file = vma->vm_file;
8146 if (!perf_addr_filter_match(filter, file, off, vma_size))
8147 return false;
8149 if (filter->offset < off) {
8150 fr->start = vma->vm_start;
8151 fr->size = min(vma_size, filter->size - (off - filter->offset));
8152 } else {
8153 fr->start = vma->vm_start + filter->offset - off;
8154 fr->size = min(vma->vm_end - fr->start, filter->size);
8157 return true;
8160 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8162 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8163 struct vm_area_struct *vma = data;
8164 struct perf_addr_filter *filter;
8165 unsigned int restart = 0, count = 0;
8166 unsigned long flags;
8168 if (!has_addr_filter(event))
8169 return;
8171 if (!vma->vm_file)
8172 return;
8174 raw_spin_lock_irqsave(&ifh->lock, flags);
8175 list_for_each_entry(filter, &ifh->list, entry) {
8176 if (perf_addr_filter_vma_adjust(filter, vma,
8177 &event->addr_filter_ranges[count]))
8178 restart++;
8180 count++;
8183 if (restart)
8184 event->addr_filters_gen++;
8185 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8187 if (restart)
8188 perf_event_stop(event, 1);
8192 * Adjust all task's events' filters to the new vma
8194 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8196 struct perf_event_context *ctx;
8197 int ctxn;
8200 * Data tracing isn't supported yet and as such there is no need
8201 * to keep track of anything that isn't related to executable code:
8203 if (!(vma->vm_flags & VM_EXEC))
8204 return;
8206 rcu_read_lock();
8207 for_each_task_context_nr(ctxn) {
8208 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8209 if (!ctx)
8210 continue;
8212 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8214 rcu_read_unlock();
8217 void perf_event_mmap(struct vm_area_struct *vma)
8219 struct perf_mmap_event mmap_event;
8221 if (!atomic_read(&nr_mmap_events))
8222 return;
8224 mmap_event = (struct perf_mmap_event){
8225 .vma = vma,
8226 /* .file_name */
8227 /* .file_size */
8228 .event_id = {
8229 .header = {
8230 .type = PERF_RECORD_MMAP,
8231 .misc = PERF_RECORD_MISC_USER,
8232 /* .size */
8234 /* .pid */
8235 /* .tid */
8236 .start = vma->vm_start,
8237 .len = vma->vm_end - vma->vm_start,
8238 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8240 /* .maj (attr_mmap2 only) */
8241 /* .min (attr_mmap2 only) */
8242 /* .ino (attr_mmap2 only) */
8243 /* .ino_generation (attr_mmap2 only) */
8244 /* .prot (attr_mmap2 only) */
8245 /* .flags (attr_mmap2 only) */
8248 perf_addr_filters_adjust(vma);
8249 perf_event_mmap_event(&mmap_event);
8252 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8253 unsigned long size, u64 flags)
8255 struct perf_output_handle handle;
8256 struct perf_sample_data sample;
8257 struct perf_aux_event {
8258 struct perf_event_header header;
8259 u64 offset;
8260 u64 size;
8261 u64 flags;
8262 } rec = {
8263 .header = {
8264 .type = PERF_RECORD_AUX,
8265 .misc = 0,
8266 .size = sizeof(rec),
8268 .offset = head,
8269 .size = size,
8270 .flags = flags,
8272 int ret;
8274 perf_event_header__init_id(&rec.header, &sample, event);
8275 ret = perf_output_begin(&handle, event, rec.header.size);
8277 if (ret)
8278 return;
8280 perf_output_put(&handle, rec);
8281 perf_event__output_id_sample(event, &handle, &sample);
8283 perf_output_end(&handle);
8287 * Lost/dropped samples logging
8289 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8291 struct perf_output_handle handle;
8292 struct perf_sample_data sample;
8293 int ret;
8295 struct {
8296 struct perf_event_header header;
8297 u64 lost;
8298 } lost_samples_event = {
8299 .header = {
8300 .type = PERF_RECORD_LOST_SAMPLES,
8301 .misc = 0,
8302 .size = sizeof(lost_samples_event),
8304 .lost = lost,
8307 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8309 ret = perf_output_begin(&handle, event,
8310 lost_samples_event.header.size);
8311 if (ret)
8312 return;
8314 perf_output_put(&handle, lost_samples_event);
8315 perf_event__output_id_sample(event, &handle, &sample);
8316 perf_output_end(&handle);
8320 * context_switch tracking
8323 struct perf_switch_event {
8324 struct task_struct *task;
8325 struct task_struct *next_prev;
8327 struct {
8328 struct perf_event_header header;
8329 u32 next_prev_pid;
8330 u32 next_prev_tid;
8331 } event_id;
8334 static int perf_event_switch_match(struct perf_event *event)
8336 return event->attr.context_switch;
8339 static void perf_event_switch_output(struct perf_event *event, void *data)
8341 struct perf_switch_event *se = data;
8342 struct perf_output_handle handle;
8343 struct perf_sample_data sample;
8344 int ret;
8346 if (!perf_event_switch_match(event))
8347 return;
8349 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8350 if (event->ctx->task) {
8351 se->event_id.header.type = PERF_RECORD_SWITCH;
8352 se->event_id.header.size = sizeof(se->event_id.header);
8353 } else {
8354 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8355 se->event_id.header.size = sizeof(se->event_id);
8356 se->event_id.next_prev_pid =
8357 perf_event_pid(event, se->next_prev);
8358 se->event_id.next_prev_tid =
8359 perf_event_tid(event, se->next_prev);
8362 perf_event_header__init_id(&se->event_id.header, &sample, event);
8364 ret = perf_output_begin(&handle, event, se->event_id.header.size);
8365 if (ret)
8366 return;
8368 if (event->ctx->task)
8369 perf_output_put(&handle, se->event_id.header);
8370 else
8371 perf_output_put(&handle, se->event_id);
8373 perf_event__output_id_sample(event, &handle, &sample);
8375 perf_output_end(&handle);
8378 static void perf_event_switch(struct task_struct *task,
8379 struct task_struct *next_prev, bool sched_in)
8381 struct perf_switch_event switch_event;
8383 /* N.B. caller checks nr_switch_events != 0 */
8385 switch_event = (struct perf_switch_event){
8386 .task = task,
8387 .next_prev = next_prev,
8388 .event_id = {
8389 .header = {
8390 /* .type */
8391 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8392 /* .size */
8394 /* .next_prev_pid */
8395 /* .next_prev_tid */
8399 if (!sched_in && task->state == TASK_RUNNING)
8400 switch_event.event_id.header.misc |=
8401 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8403 perf_iterate_sb(perf_event_switch_output,
8404 &switch_event,
8405 NULL);
8409 * IRQ throttle logging
8412 static void perf_log_throttle(struct perf_event *event, int enable)
8414 struct perf_output_handle handle;
8415 struct perf_sample_data sample;
8416 int ret;
8418 struct {
8419 struct perf_event_header header;
8420 u64 time;
8421 u64 id;
8422 u64 stream_id;
8423 } throttle_event = {
8424 .header = {
8425 .type = PERF_RECORD_THROTTLE,
8426 .misc = 0,
8427 .size = sizeof(throttle_event),
8429 .time = perf_event_clock(event),
8430 .id = primary_event_id(event),
8431 .stream_id = event->id,
8434 if (enable)
8435 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8437 perf_event_header__init_id(&throttle_event.header, &sample, event);
8439 ret = perf_output_begin(&handle, event,
8440 throttle_event.header.size);
8441 if (ret)
8442 return;
8444 perf_output_put(&handle, throttle_event);
8445 perf_event__output_id_sample(event, &handle, &sample);
8446 perf_output_end(&handle);
8450 * ksymbol register/unregister tracking
8453 struct perf_ksymbol_event {
8454 const char *name;
8455 int name_len;
8456 struct {
8457 struct perf_event_header header;
8458 u64 addr;
8459 u32 len;
8460 u16 ksym_type;
8461 u16 flags;
8462 } event_id;
8465 static int perf_event_ksymbol_match(struct perf_event *event)
8467 return event->attr.ksymbol;
8470 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8472 struct perf_ksymbol_event *ksymbol_event = data;
8473 struct perf_output_handle handle;
8474 struct perf_sample_data sample;
8475 int ret;
8477 if (!perf_event_ksymbol_match(event))
8478 return;
8480 perf_event_header__init_id(&ksymbol_event->event_id.header,
8481 &sample, event);
8482 ret = perf_output_begin(&handle, event,
8483 ksymbol_event->event_id.header.size);
8484 if (ret)
8485 return;
8487 perf_output_put(&handle, ksymbol_event->event_id);
8488 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8489 perf_event__output_id_sample(event, &handle, &sample);
8491 perf_output_end(&handle);
8494 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8495 const char *sym)
8497 struct perf_ksymbol_event ksymbol_event;
8498 char name[KSYM_NAME_LEN];
8499 u16 flags = 0;
8500 int name_len;
8502 if (!atomic_read(&nr_ksymbol_events))
8503 return;
8505 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8506 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8507 goto err;
8509 strlcpy(name, sym, KSYM_NAME_LEN);
8510 name_len = strlen(name) + 1;
8511 while (!IS_ALIGNED(name_len, sizeof(u64)))
8512 name[name_len++] = '\0';
8513 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8515 if (unregister)
8516 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8518 ksymbol_event = (struct perf_ksymbol_event){
8519 .name = name,
8520 .name_len = name_len,
8521 .event_id = {
8522 .header = {
8523 .type = PERF_RECORD_KSYMBOL,
8524 .size = sizeof(ksymbol_event.event_id) +
8525 name_len,
8527 .addr = addr,
8528 .len = len,
8529 .ksym_type = ksym_type,
8530 .flags = flags,
8534 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8535 return;
8536 err:
8537 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8541 * bpf program load/unload tracking
8544 struct perf_bpf_event {
8545 struct bpf_prog *prog;
8546 struct {
8547 struct perf_event_header header;
8548 u16 type;
8549 u16 flags;
8550 u32 id;
8551 u8 tag[BPF_TAG_SIZE];
8552 } event_id;
8555 static int perf_event_bpf_match(struct perf_event *event)
8557 return event->attr.bpf_event;
8560 static void perf_event_bpf_output(struct perf_event *event, void *data)
8562 struct perf_bpf_event *bpf_event = data;
8563 struct perf_output_handle handle;
8564 struct perf_sample_data sample;
8565 int ret;
8567 if (!perf_event_bpf_match(event))
8568 return;
8570 perf_event_header__init_id(&bpf_event->event_id.header,
8571 &sample, event);
8572 ret = perf_output_begin(&handle, event,
8573 bpf_event->event_id.header.size);
8574 if (ret)
8575 return;
8577 perf_output_put(&handle, bpf_event->event_id);
8578 perf_event__output_id_sample(event, &handle, &sample);
8580 perf_output_end(&handle);
8583 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8584 enum perf_bpf_event_type type)
8586 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8587 int i;
8589 if (prog->aux->func_cnt == 0) {
8590 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8591 (u64)(unsigned long)prog->bpf_func,
8592 prog->jited_len, unregister,
8593 prog->aux->ksym.name);
8594 } else {
8595 for (i = 0; i < prog->aux->func_cnt; i++) {
8596 struct bpf_prog *subprog = prog->aux->func[i];
8598 perf_event_ksymbol(
8599 PERF_RECORD_KSYMBOL_TYPE_BPF,
8600 (u64)(unsigned long)subprog->bpf_func,
8601 subprog->jited_len, unregister,
8602 prog->aux->ksym.name);
8607 void perf_event_bpf_event(struct bpf_prog *prog,
8608 enum perf_bpf_event_type type,
8609 u16 flags)
8611 struct perf_bpf_event bpf_event;
8613 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8614 type >= PERF_BPF_EVENT_MAX)
8615 return;
8617 switch (type) {
8618 case PERF_BPF_EVENT_PROG_LOAD:
8619 case PERF_BPF_EVENT_PROG_UNLOAD:
8620 if (atomic_read(&nr_ksymbol_events))
8621 perf_event_bpf_emit_ksymbols(prog, type);
8622 break;
8623 default:
8624 break;
8627 if (!atomic_read(&nr_bpf_events))
8628 return;
8630 bpf_event = (struct perf_bpf_event){
8631 .prog = prog,
8632 .event_id = {
8633 .header = {
8634 .type = PERF_RECORD_BPF_EVENT,
8635 .size = sizeof(bpf_event.event_id),
8637 .type = type,
8638 .flags = flags,
8639 .id = prog->aux->id,
8643 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8645 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8646 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8649 struct perf_text_poke_event {
8650 const void *old_bytes;
8651 const void *new_bytes;
8652 size_t pad;
8653 u16 old_len;
8654 u16 new_len;
8656 struct {
8657 struct perf_event_header header;
8659 u64 addr;
8660 } event_id;
8663 static int perf_event_text_poke_match(struct perf_event *event)
8665 return event->attr.text_poke;
8668 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8670 struct perf_text_poke_event *text_poke_event = data;
8671 struct perf_output_handle handle;
8672 struct perf_sample_data sample;
8673 u64 padding = 0;
8674 int ret;
8676 if (!perf_event_text_poke_match(event))
8677 return;
8679 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8681 ret = perf_output_begin(&handle, event, text_poke_event->event_id.header.size);
8682 if (ret)
8683 return;
8685 perf_output_put(&handle, text_poke_event->event_id);
8686 perf_output_put(&handle, text_poke_event->old_len);
8687 perf_output_put(&handle, text_poke_event->new_len);
8689 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8690 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8692 if (text_poke_event->pad)
8693 __output_copy(&handle, &padding, text_poke_event->pad);
8695 perf_event__output_id_sample(event, &handle, &sample);
8697 perf_output_end(&handle);
8700 void perf_event_text_poke(const void *addr, const void *old_bytes,
8701 size_t old_len, const void *new_bytes, size_t new_len)
8703 struct perf_text_poke_event text_poke_event;
8704 size_t tot, pad;
8706 if (!atomic_read(&nr_text_poke_events))
8707 return;
8709 tot = sizeof(text_poke_event.old_len) + old_len;
8710 tot += sizeof(text_poke_event.new_len) + new_len;
8711 pad = ALIGN(tot, sizeof(u64)) - tot;
8713 text_poke_event = (struct perf_text_poke_event){
8714 .old_bytes = old_bytes,
8715 .new_bytes = new_bytes,
8716 .pad = pad,
8717 .old_len = old_len,
8718 .new_len = new_len,
8719 .event_id = {
8720 .header = {
8721 .type = PERF_RECORD_TEXT_POKE,
8722 .misc = PERF_RECORD_MISC_KERNEL,
8723 .size = sizeof(text_poke_event.event_id) + tot + pad,
8725 .addr = (unsigned long)addr,
8729 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8732 void perf_event_itrace_started(struct perf_event *event)
8734 event->attach_state |= PERF_ATTACH_ITRACE;
8737 static void perf_log_itrace_start(struct perf_event *event)
8739 struct perf_output_handle handle;
8740 struct perf_sample_data sample;
8741 struct perf_aux_event {
8742 struct perf_event_header header;
8743 u32 pid;
8744 u32 tid;
8745 } rec;
8746 int ret;
8748 if (event->parent)
8749 event = event->parent;
8751 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8752 event->attach_state & PERF_ATTACH_ITRACE)
8753 return;
8755 rec.header.type = PERF_RECORD_ITRACE_START;
8756 rec.header.misc = 0;
8757 rec.header.size = sizeof(rec);
8758 rec.pid = perf_event_pid(event, current);
8759 rec.tid = perf_event_tid(event, current);
8761 perf_event_header__init_id(&rec.header, &sample, event);
8762 ret = perf_output_begin(&handle, event, rec.header.size);
8764 if (ret)
8765 return;
8767 perf_output_put(&handle, rec);
8768 perf_event__output_id_sample(event, &handle, &sample);
8770 perf_output_end(&handle);
8773 static int
8774 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8776 struct hw_perf_event *hwc = &event->hw;
8777 int ret = 0;
8778 u64 seq;
8780 seq = __this_cpu_read(perf_throttled_seq);
8781 if (seq != hwc->interrupts_seq) {
8782 hwc->interrupts_seq = seq;
8783 hwc->interrupts = 1;
8784 } else {
8785 hwc->interrupts++;
8786 if (unlikely(throttle
8787 && hwc->interrupts >= max_samples_per_tick)) {
8788 __this_cpu_inc(perf_throttled_count);
8789 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8790 hwc->interrupts = MAX_INTERRUPTS;
8791 perf_log_throttle(event, 0);
8792 ret = 1;
8796 if (event->attr.freq) {
8797 u64 now = perf_clock();
8798 s64 delta = now - hwc->freq_time_stamp;
8800 hwc->freq_time_stamp = now;
8802 if (delta > 0 && delta < 2*TICK_NSEC)
8803 perf_adjust_period(event, delta, hwc->last_period, true);
8806 return ret;
8809 int perf_event_account_interrupt(struct perf_event *event)
8811 return __perf_event_account_interrupt(event, 1);
8815 * Generic event overflow handling, sampling.
8818 static int __perf_event_overflow(struct perf_event *event,
8819 int throttle, struct perf_sample_data *data,
8820 struct pt_regs *regs)
8822 int events = atomic_read(&event->event_limit);
8823 int ret = 0;
8826 * Non-sampling counters might still use the PMI to fold short
8827 * hardware counters, ignore those.
8829 if (unlikely(!is_sampling_event(event)))
8830 return 0;
8832 ret = __perf_event_account_interrupt(event, throttle);
8835 * XXX event_limit might not quite work as expected on inherited
8836 * events
8839 event->pending_kill = POLL_IN;
8840 if (events && atomic_dec_and_test(&event->event_limit)) {
8841 ret = 1;
8842 event->pending_kill = POLL_HUP;
8844 perf_event_disable_inatomic(event);
8847 READ_ONCE(event->overflow_handler)(event, data, regs);
8849 if (*perf_event_fasync(event) && event->pending_kill) {
8850 event->pending_wakeup = 1;
8851 irq_work_queue(&event->pending);
8854 return ret;
8857 int perf_event_overflow(struct perf_event *event,
8858 struct perf_sample_data *data,
8859 struct pt_regs *regs)
8861 return __perf_event_overflow(event, 1, data, regs);
8865 * Generic software event infrastructure
8868 struct swevent_htable {
8869 struct swevent_hlist *swevent_hlist;
8870 struct mutex hlist_mutex;
8871 int hlist_refcount;
8873 /* Recursion avoidance in each contexts */
8874 int recursion[PERF_NR_CONTEXTS];
8877 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8880 * We directly increment event->count and keep a second value in
8881 * event->hw.period_left to count intervals. This period event
8882 * is kept in the range [-sample_period, 0] so that we can use the
8883 * sign as trigger.
8886 u64 perf_swevent_set_period(struct perf_event *event)
8888 struct hw_perf_event *hwc = &event->hw;
8889 u64 period = hwc->last_period;
8890 u64 nr, offset;
8891 s64 old, val;
8893 hwc->last_period = hwc->sample_period;
8895 again:
8896 old = val = local64_read(&hwc->period_left);
8897 if (val < 0)
8898 return 0;
8900 nr = div64_u64(period + val, period);
8901 offset = nr * period;
8902 val -= offset;
8903 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8904 goto again;
8906 return nr;
8909 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8910 struct perf_sample_data *data,
8911 struct pt_regs *regs)
8913 struct hw_perf_event *hwc = &event->hw;
8914 int throttle = 0;
8916 if (!overflow)
8917 overflow = perf_swevent_set_period(event);
8919 if (hwc->interrupts == MAX_INTERRUPTS)
8920 return;
8922 for (; overflow; overflow--) {
8923 if (__perf_event_overflow(event, throttle,
8924 data, regs)) {
8926 * We inhibit the overflow from happening when
8927 * hwc->interrupts == MAX_INTERRUPTS.
8929 break;
8931 throttle = 1;
8935 static void perf_swevent_event(struct perf_event *event, u64 nr,
8936 struct perf_sample_data *data,
8937 struct pt_regs *regs)
8939 struct hw_perf_event *hwc = &event->hw;
8941 local64_add(nr, &event->count);
8943 if (!regs)
8944 return;
8946 if (!is_sampling_event(event))
8947 return;
8949 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8950 data->period = nr;
8951 return perf_swevent_overflow(event, 1, data, regs);
8952 } else
8953 data->period = event->hw.last_period;
8955 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8956 return perf_swevent_overflow(event, 1, data, regs);
8958 if (local64_add_negative(nr, &hwc->period_left))
8959 return;
8961 perf_swevent_overflow(event, 0, data, regs);
8964 static int perf_exclude_event(struct perf_event *event,
8965 struct pt_regs *regs)
8967 if (event->hw.state & PERF_HES_STOPPED)
8968 return 1;
8970 if (regs) {
8971 if (event->attr.exclude_user && user_mode(regs))
8972 return 1;
8974 if (event->attr.exclude_kernel && !user_mode(regs))
8975 return 1;
8978 return 0;
8981 static int perf_swevent_match(struct perf_event *event,
8982 enum perf_type_id type,
8983 u32 event_id,
8984 struct perf_sample_data *data,
8985 struct pt_regs *regs)
8987 if (event->attr.type != type)
8988 return 0;
8990 if (event->attr.config != event_id)
8991 return 0;
8993 if (perf_exclude_event(event, regs))
8994 return 0;
8996 return 1;
8999 static inline u64 swevent_hash(u64 type, u32 event_id)
9001 u64 val = event_id | (type << 32);
9003 return hash_64(val, SWEVENT_HLIST_BITS);
9006 static inline struct hlist_head *
9007 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9009 u64 hash = swevent_hash(type, event_id);
9011 return &hlist->heads[hash];
9014 /* For the read side: events when they trigger */
9015 static inline struct hlist_head *
9016 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9018 struct swevent_hlist *hlist;
9020 hlist = rcu_dereference(swhash->swevent_hlist);
9021 if (!hlist)
9022 return NULL;
9024 return __find_swevent_head(hlist, type, event_id);
9027 /* For the event head insertion and removal in the hlist */
9028 static inline struct hlist_head *
9029 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9031 struct swevent_hlist *hlist;
9032 u32 event_id = event->attr.config;
9033 u64 type = event->attr.type;
9036 * Event scheduling is always serialized against hlist allocation
9037 * and release. Which makes the protected version suitable here.
9038 * The context lock guarantees that.
9040 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9041 lockdep_is_held(&event->ctx->lock));
9042 if (!hlist)
9043 return NULL;
9045 return __find_swevent_head(hlist, type, event_id);
9048 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9049 u64 nr,
9050 struct perf_sample_data *data,
9051 struct pt_regs *regs)
9053 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9054 struct perf_event *event;
9055 struct hlist_head *head;
9057 rcu_read_lock();
9058 head = find_swevent_head_rcu(swhash, type, event_id);
9059 if (!head)
9060 goto end;
9062 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9063 if (perf_swevent_match(event, type, event_id, data, regs))
9064 perf_swevent_event(event, nr, data, regs);
9066 end:
9067 rcu_read_unlock();
9070 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9072 int perf_swevent_get_recursion_context(void)
9074 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9076 return get_recursion_context(swhash->recursion);
9078 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9080 void perf_swevent_put_recursion_context(int rctx)
9082 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9084 put_recursion_context(swhash->recursion, rctx);
9087 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9089 struct perf_sample_data data;
9091 if (WARN_ON_ONCE(!regs))
9092 return;
9094 perf_sample_data_init(&data, addr, 0);
9095 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9098 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9100 int rctx;
9102 preempt_disable_notrace();
9103 rctx = perf_swevent_get_recursion_context();
9104 if (unlikely(rctx < 0))
9105 goto fail;
9107 ___perf_sw_event(event_id, nr, regs, addr);
9109 perf_swevent_put_recursion_context(rctx);
9110 fail:
9111 preempt_enable_notrace();
9114 static void perf_swevent_read(struct perf_event *event)
9118 static int perf_swevent_add(struct perf_event *event, int flags)
9120 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9121 struct hw_perf_event *hwc = &event->hw;
9122 struct hlist_head *head;
9124 if (is_sampling_event(event)) {
9125 hwc->last_period = hwc->sample_period;
9126 perf_swevent_set_period(event);
9129 hwc->state = !(flags & PERF_EF_START);
9131 head = find_swevent_head(swhash, event);
9132 if (WARN_ON_ONCE(!head))
9133 return -EINVAL;
9135 hlist_add_head_rcu(&event->hlist_entry, head);
9136 perf_event_update_userpage(event);
9138 return 0;
9141 static void perf_swevent_del(struct perf_event *event, int flags)
9143 hlist_del_rcu(&event->hlist_entry);
9146 static void perf_swevent_start(struct perf_event *event, int flags)
9148 event->hw.state = 0;
9151 static void perf_swevent_stop(struct perf_event *event, int flags)
9153 event->hw.state = PERF_HES_STOPPED;
9156 /* Deref the hlist from the update side */
9157 static inline struct swevent_hlist *
9158 swevent_hlist_deref(struct swevent_htable *swhash)
9160 return rcu_dereference_protected(swhash->swevent_hlist,
9161 lockdep_is_held(&swhash->hlist_mutex));
9164 static void swevent_hlist_release(struct swevent_htable *swhash)
9166 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9168 if (!hlist)
9169 return;
9171 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9172 kfree_rcu(hlist, rcu_head);
9175 static void swevent_hlist_put_cpu(int cpu)
9177 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9179 mutex_lock(&swhash->hlist_mutex);
9181 if (!--swhash->hlist_refcount)
9182 swevent_hlist_release(swhash);
9184 mutex_unlock(&swhash->hlist_mutex);
9187 static void swevent_hlist_put(void)
9189 int cpu;
9191 for_each_possible_cpu(cpu)
9192 swevent_hlist_put_cpu(cpu);
9195 static int swevent_hlist_get_cpu(int cpu)
9197 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9198 int err = 0;
9200 mutex_lock(&swhash->hlist_mutex);
9201 if (!swevent_hlist_deref(swhash) &&
9202 cpumask_test_cpu(cpu, perf_online_mask)) {
9203 struct swevent_hlist *hlist;
9205 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9206 if (!hlist) {
9207 err = -ENOMEM;
9208 goto exit;
9210 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9212 swhash->hlist_refcount++;
9213 exit:
9214 mutex_unlock(&swhash->hlist_mutex);
9216 return err;
9219 static int swevent_hlist_get(void)
9221 int err, cpu, failed_cpu;
9223 mutex_lock(&pmus_lock);
9224 for_each_possible_cpu(cpu) {
9225 err = swevent_hlist_get_cpu(cpu);
9226 if (err) {
9227 failed_cpu = cpu;
9228 goto fail;
9231 mutex_unlock(&pmus_lock);
9232 return 0;
9233 fail:
9234 for_each_possible_cpu(cpu) {
9235 if (cpu == failed_cpu)
9236 break;
9237 swevent_hlist_put_cpu(cpu);
9239 mutex_unlock(&pmus_lock);
9240 return err;
9243 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9245 static void sw_perf_event_destroy(struct perf_event *event)
9247 u64 event_id = event->attr.config;
9249 WARN_ON(event->parent);
9251 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9252 swevent_hlist_put();
9255 static int perf_swevent_init(struct perf_event *event)
9257 u64 event_id = event->attr.config;
9259 if (event->attr.type != PERF_TYPE_SOFTWARE)
9260 return -ENOENT;
9263 * no branch sampling for software events
9265 if (has_branch_stack(event))
9266 return -EOPNOTSUPP;
9268 switch (event_id) {
9269 case PERF_COUNT_SW_CPU_CLOCK:
9270 case PERF_COUNT_SW_TASK_CLOCK:
9271 return -ENOENT;
9273 default:
9274 break;
9277 if (event_id >= PERF_COUNT_SW_MAX)
9278 return -ENOENT;
9280 if (!event->parent) {
9281 int err;
9283 err = swevent_hlist_get();
9284 if (err)
9285 return err;
9287 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9288 event->destroy = sw_perf_event_destroy;
9291 return 0;
9294 static struct pmu perf_swevent = {
9295 .task_ctx_nr = perf_sw_context,
9297 .capabilities = PERF_PMU_CAP_NO_NMI,
9299 .event_init = perf_swevent_init,
9300 .add = perf_swevent_add,
9301 .del = perf_swevent_del,
9302 .start = perf_swevent_start,
9303 .stop = perf_swevent_stop,
9304 .read = perf_swevent_read,
9307 #ifdef CONFIG_EVENT_TRACING
9309 static int perf_tp_filter_match(struct perf_event *event,
9310 struct perf_sample_data *data)
9312 void *record = data->raw->frag.data;
9314 /* only top level events have filters set */
9315 if (event->parent)
9316 event = event->parent;
9318 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9319 return 1;
9320 return 0;
9323 static int perf_tp_event_match(struct perf_event *event,
9324 struct perf_sample_data *data,
9325 struct pt_regs *regs)
9327 if (event->hw.state & PERF_HES_STOPPED)
9328 return 0;
9330 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9332 if (event->attr.exclude_kernel && !user_mode(regs))
9333 return 0;
9335 if (!perf_tp_filter_match(event, data))
9336 return 0;
9338 return 1;
9341 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9342 struct trace_event_call *call, u64 count,
9343 struct pt_regs *regs, struct hlist_head *head,
9344 struct task_struct *task)
9346 if (bpf_prog_array_valid(call)) {
9347 *(struct pt_regs **)raw_data = regs;
9348 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9349 perf_swevent_put_recursion_context(rctx);
9350 return;
9353 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9354 rctx, task);
9356 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9358 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9359 struct pt_regs *regs, struct hlist_head *head, int rctx,
9360 struct task_struct *task)
9362 struct perf_sample_data data;
9363 struct perf_event *event;
9365 struct perf_raw_record raw = {
9366 .frag = {
9367 .size = entry_size,
9368 .data = record,
9372 perf_sample_data_init(&data, 0, 0);
9373 data.raw = &raw;
9375 perf_trace_buf_update(record, event_type);
9377 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9378 if (perf_tp_event_match(event, &data, regs))
9379 perf_swevent_event(event, count, &data, regs);
9383 * If we got specified a target task, also iterate its context and
9384 * deliver this event there too.
9386 if (task && task != current) {
9387 struct perf_event_context *ctx;
9388 struct trace_entry *entry = record;
9390 rcu_read_lock();
9391 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9392 if (!ctx)
9393 goto unlock;
9395 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9396 if (event->cpu != smp_processor_id())
9397 continue;
9398 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9399 continue;
9400 if (event->attr.config != entry->type)
9401 continue;
9402 if (perf_tp_event_match(event, &data, regs))
9403 perf_swevent_event(event, count, &data, regs);
9405 unlock:
9406 rcu_read_unlock();
9409 perf_swevent_put_recursion_context(rctx);
9411 EXPORT_SYMBOL_GPL(perf_tp_event);
9413 static void tp_perf_event_destroy(struct perf_event *event)
9415 perf_trace_destroy(event);
9418 static int perf_tp_event_init(struct perf_event *event)
9420 int err;
9422 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9423 return -ENOENT;
9426 * no branch sampling for tracepoint events
9428 if (has_branch_stack(event))
9429 return -EOPNOTSUPP;
9431 err = perf_trace_init(event);
9432 if (err)
9433 return err;
9435 event->destroy = tp_perf_event_destroy;
9437 return 0;
9440 static struct pmu perf_tracepoint = {
9441 .task_ctx_nr = perf_sw_context,
9443 .event_init = perf_tp_event_init,
9444 .add = perf_trace_add,
9445 .del = perf_trace_del,
9446 .start = perf_swevent_start,
9447 .stop = perf_swevent_stop,
9448 .read = perf_swevent_read,
9451 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9453 * Flags in config, used by dynamic PMU kprobe and uprobe
9454 * The flags should match following PMU_FORMAT_ATTR().
9456 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9457 * if not set, create kprobe/uprobe
9459 * The following values specify a reference counter (or semaphore in the
9460 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9461 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9463 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9464 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9466 enum perf_probe_config {
9467 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9468 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9469 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9472 PMU_FORMAT_ATTR(retprobe, "config:0");
9473 #endif
9475 #ifdef CONFIG_KPROBE_EVENTS
9476 static struct attribute *kprobe_attrs[] = {
9477 &format_attr_retprobe.attr,
9478 NULL,
9481 static struct attribute_group kprobe_format_group = {
9482 .name = "format",
9483 .attrs = kprobe_attrs,
9486 static const struct attribute_group *kprobe_attr_groups[] = {
9487 &kprobe_format_group,
9488 NULL,
9491 static int perf_kprobe_event_init(struct perf_event *event);
9492 static struct pmu perf_kprobe = {
9493 .task_ctx_nr = perf_sw_context,
9494 .event_init = perf_kprobe_event_init,
9495 .add = perf_trace_add,
9496 .del = perf_trace_del,
9497 .start = perf_swevent_start,
9498 .stop = perf_swevent_stop,
9499 .read = perf_swevent_read,
9500 .attr_groups = kprobe_attr_groups,
9503 static int perf_kprobe_event_init(struct perf_event *event)
9505 int err;
9506 bool is_retprobe;
9508 if (event->attr.type != perf_kprobe.type)
9509 return -ENOENT;
9511 if (!perfmon_capable())
9512 return -EACCES;
9515 * no branch sampling for probe events
9517 if (has_branch_stack(event))
9518 return -EOPNOTSUPP;
9520 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9521 err = perf_kprobe_init(event, is_retprobe);
9522 if (err)
9523 return err;
9525 event->destroy = perf_kprobe_destroy;
9527 return 0;
9529 #endif /* CONFIG_KPROBE_EVENTS */
9531 #ifdef CONFIG_UPROBE_EVENTS
9532 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9534 static struct attribute *uprobe_attrs[] = {
9535 &format_attr_retprobe.attr,
9536 &format_attr_ref_ctr_offset.attr,
9537 NULL,
9540 static struct attribute_group uprobe_format_group = {
9541 .name = "format",
9542 .attrs = uprobe_attrs,
9545 static const struct attribute_group *uprobe_attr_groups[] = {
9546 &uprobe_format_group,
9547 NULL,
9550 static int perf_uprobe_event_init(struct perf_event *event);
9551 static struct pmu perf_uprobe = {
9552 .task_ctx_nr = perf_sw_context,
9553 .event_init = perf_uprobe_event_init,
9554 .add = perf_trace_add,
9555 .del = perf_trace_del,
9556 .start = perf_swevent_start,
9557 .stop = perf_swevent_stop,
9558 .read = perf_swevent_read,
9559 .attr_groups = uprobe_attr_groups,
9562 static int perf_uprobe_event_init(struct perf_event *event)
9564 int err;
9565 unsigned long ref_ctr_offset;
9566 bool is_retprobe;
9568 if (event->attr.type != perf_uprobe.type)
9569 return -ENOENT;
9571 if (!perfmon_capable())
9572 return -EACCES;
9575 * no branch sampling for probe events
9577 if (has_branch_stack(event))
9578 return -EOPNOTSUPP;
9580 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9581 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9582 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9583 if (err)
9584 return err;
9586 event->destroy = perf_uprobe_destroy;
9588 return 0;
9590 #endif /* CONFIG_UPROBE_EVENTS */
9592 static inline void perf_tp_register(void)
9594 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9595 #ifdef CONFIG_KPROBE_EVENTS
9596 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9597 #endif
9598 #ifdef CONFIG_UPROBE_EVENTS
9599 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9600 #endif
9603 static void perf_event_free_filter(struct perf_event *event)
9605 ftrace_profile_free_filter(event);
9608 #ifdef CONFIG_BPF_SYSCALL
9609 static void bpf_overflow_handler(struct perf_event *event,
9610 struct perf_sample_data *data,
9611 struct pt_regs *regs)
9613 struct bpf_perf_event_data_kern ctx = {
9614 .data = data,
9615 .event = event,
9617 int ret = 0;
9619 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9620 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9621 goto out;
9622 rcu_read_lock();
9623 ret = BPF_PROG_RUN(event->prog, &ctx);
9624 rcu_read_unlock();
9625 out:
9626 __this_cpu_dec(bpf_prog_active);
9627 if (!ret)
9628 return;
9630 event->orig_overflow_handler(event, data, regs);
9633 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9635 struct bpf_prog *prog;
9637 if (event->overflow_handler_context)
9638 /* hw breakpoint or kernel counter */
9639 return -EINVAL;
9641 if (event->prog)
9642 return -EEXIST;
9644 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9645 if (IS_ERR(prog))
9646 return PTR_ERR(prog);
9648 if (event->attr.precise_ip &&
9649 prog->call_get_stack &&
9650 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9651 event->attr.exclude_callchain_kernel ||
9652 event->attr.exclude_callchain_user)) {
9654 * On perf_event with precise_ip, calling bpf_get_stack()
9655 * may trigger unwinder warnings and occasional crashes.
9656 * bpf_get_[stack|stackid] works around this issue by using
9657 * callchain attached to perf_sample_data. If the
9658 * perf_event does not full (kernel and user) callchain
9659 * attached to perf_sample_data, do not allow attaching BPF
9660 * program that calls bpf_get_[stack|stackid].
9662 bpf_prog_put(prog);
9663 return -EPROTO;
9666 event->prog = prog;
9667 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9668 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9669 return 0;
9672 static void perf_event_free_bpf_handler(struct perf_event *event)
9674 struct bpf_prog *prog = event->prog;
9676 if (!prog)
9677 return;
9679 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9680 event->prog = NULL;
9681 bpf_prog_put(prog);
9683 #else
9684 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9686 return -EOPNOTSUPP;
9688 static void perf_event_free_bpf_handler(struct perf_event *event)
9691 #endif
9694 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9695 * with perf_event_open()
9697 static inline bool perf_event_is_tracing(struct perf_event *event)
9699 if (event->pmu == &perf_tracepoint)
9700 return true;
9701 #ifdef CONFIG_KPROBE_EVENTS
9702 if (event->pmu == &perf_kprobe)
9703 return true;
9704 #endif
9705 #ifdef CONFIG_UPROBE_EVENTS
9706 if (event->pmu == &perf_uprobe)
9707 return true;
9708 #endif
9709 return false;
9712 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9714 bool is_kprobe, is_tracepoint, is_syscall_tp;
9715 struct bpf_prog *prog;
9716 int ret;
9718 if (!perf_event_is_tracing(event))
9719 return perf_event_set_bpf_handler(event, prog_fd);
9721 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9722 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9723 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9724 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9725 /* bpf programs can only be attached to u/kprobe or tracepoint */
9726 return -EINVAL;
9728 prog = bpf_prog_get(prog_fd);
9729 if (IS_ERR(prog))
9730 return PTR_ERR(prog);
9732 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9733 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9734 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9735 /* valid fd, but invalid bpf program type */
9736 bpf_prog_put(prog);
9737 return -EINVAL;
9740 /* Kprobe override only works for kprobes, not uprobes. */
9741 if (prog->kprobe_override &&
9742 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9743 bpf_prog_put(prog);
9744 return -EINVAL;
9747 if (is_tracepoint || is_syscall_tp) {
9748 int off = trace_event_get_offsets(event->tp_event);
9750 if (prog->aux->max_ctx_offset > off) {
9751 bpf_prog_put(prog);
9752 return -EACCES;
9756 ret = perf_event_attach_bpf_prog(event, prog);
9757 if (ret)
9758 bpf_prog_put(prog);
9759 return ret;
9762 static void perf_event_free_bpf_prog(struct perf_event *event)
9764 if (!perf_event_is_tracing(event)) {
9765 perf_event_free_bpf_handler(event);
9766 return;
9768 perf_event_detach_bpf_prog(event);
9771 #else
9773 static inline void perf_tp_register(void)
9777 static void perf_event_free_filter(struct perf_event *event)
9781 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9783 return -ENOENT;
9786 static void perf_event_free_bpf_prog(struct perf_event *event)
9789 #endif /* CONFIG_EVENT_TRACING */
9791 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9792 void perf_bp_event(struct perf_event *bp, void *data)
9794 struct perf_sample_data sample;
9795 struct pt_regs *regs = data;
9797 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9799 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9800 perf_swevent_event(bp, 1, &sample, regs);
9802 #endif
9805 * Allocate a new address filter
9807 static struct perf_addr_filter *
9808 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9810 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9811 struct perf_addr_filter *filter;
9813 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9814 if (!filter)
9815 return NULL;
9817 INIT_LIST_HEAD(&filter->entry);
9818 list_add_tail(&filter->entry, filters);
9820 return filter;
9823 static void free_filters_list(struct list_head *filters)
9825 struct perf_addr_filter *filter, *iter;
9827 list_for_each_entry_safe(filter, iter, filters, entry) {
9828 path_put(&filter->path);
9829 list_del(&filter->entry);
9830 kfree(filter);
9835 * Free existing address filters and optionally install new ones
9837 static void perf_addr_filters_splice(struct perf_event *event,
9838 struct list_head *head)
9840 unsigned long flags;
9841 LIST_HEAD(list);
9843 if (!has_addr_filter(event))
9844 return;
9846 /* don't bother with children, they don't have their own filters */
9847 if (event->parent)
9848 return;
9850 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9852 list_splice_init(&event->addr_filters.list, &list);
9853 if (head)
9854 list_splice(head, &event->addr_filters.list);
9856 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9858 free_filters_list(&list);
9862 * Scan through mm's vmas and see if one of them matches the
9863 * @filter; if so, adjust filter's address range.
9864 * Called with mm::mmap_lock down for reading.
9866 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9867 struct mm_struct *mm,
9868 struct perf_addr_filter_range *fr)
9870 struct vm_area_struct *vma;
9872 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9873 if (!vma->vm_file)
9874 continue;
9876 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9877 return;
9882 * Update event's address range filters based on the
9883 * task's existing mappings, if any.
9885 static void perf_event_addr_filters_apply(struct perf_event *event)
9887 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9888 struct task_struct *task = READ_ONCE(event->ctx->task);
9889 struct perf_addr_filter *filter;
9890 struct mm_struct *mm = NULL;
9891 unsigned int count = 0;
9892 unsigned long flags;
9895 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9896 * will stop on the parent's child_mutex that our caller is also holding
9898 if (task == TASK_TOMBSTONE)
9899 return;
9901 if (ifh->nr_file_filters) {
9902 mm = get_task_mm(event->ctx->task);
9903 if (!mm)
9904 goto restart;
9906 mmap_read_lock(mm);
9909 raw_spin_lock_irqsave(&ifh->lock, flags);
9910 list_for_each_entry(filter, &ifh->list, entry) {
9911 if (filter->path.dentry) {
9913 * Adjust base offset if the filter is associated to a
9914 * binary that needs to be mapped:
9916 event->addr_filter_ranges[count].start = 0;
9917 event->addr_filter_ranges[count].size = 0;
9919 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9920 } else {
9921 event->addr_filter_ranges[count].start = filter->offset;
9922 event->addr_filter_ranges[count].size = filter->size;
9925 count++;
9928 event->addr_filters_gen++;
9929 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9931 if (ifh->nr_file_filters) {
9932 mmap_read_unlock(mm);
9934 mmput(mm);
9937 restart:
9938 perf_event_stop(event, 1);
9942 * Address range filtering: limiting the data to certain
9943 * instruction address ranges. Filters are ioctl()ed to us from
9944 * userspace as ascii strings.
9946 * Filter string format:
9948 * ACTION RANGE_SPEC
9949 * where ACTION is one of the
9950 * * "filter": limit the trace to this region
9951 * * "start": start tracing from this address
9952 * * "stop": stop tracing at this address/region;
9953 * RANGE_SPEC is
9954 * * for kernel addresses: <start address>[/<size>]
9955 * * for object files: <start address>[/<size>]@</path/to/object/file>
9957 * if <size> is not specified or is zero, the range is treated as a single
9958 * address; not valid for ACTION=="filter".
9960 enum {
9961 IF_ACT_NONE = -1,
9962 IF_ACT_FILTER,
9963 IF_ACT_START,
9964 IF_ACT_STOP,
9965 IF_SRC_FILE,
9966 IF_SRC_KERNEL,
9967 IF_SRC_FILEADDR,
9968 IF_SRC_KERNELADDR,
9971 enum {
9972 IF_STATE_ACTION = 0,
9973 IF_STATE_SOURCE,
9974 IF_STATE_END,
9977 static const match_table_t if_tokens = {
9978 { IF_ACT_FILTER, "filter" },
9979 { IF_ACT_START, "start" },
9980 { IF_ACT_STOP, "stop" },
9981 { IF_SRC_FILE, "%u/%u@%s" },
9982 { IF_SRC_KERNEL, "%u/%u" },
9983 { IF_SRC_FILEADDR, "%u@%s" },
9984 { IF_SRC_KERNELADDR, "%u" },
9985 { IF_ACT_NONE, NULL },
9989 * Address filter string parser
9991 static int
9992 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9993 struct list_head *filters)
9995 struct perf_addr_filter *filter = NULL;
9996 char *start, *orig, *filename = NULL;
9997 substring_t args[MAX_OPT_ARGS];
9998 int state = IF_STATE_ACTION, token;
9999 unsigned int kernel = 0;
10000 int ret = -EINVAL;
10002 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10003 if (!fstr)
10004 return -ENOMEM;
10006 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10007 static const enum perf_addr_filter_action_t actions[] = {
10008 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10009 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10010 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10012 ret = -EINVAL;
10014 if (!*start)
10015 continue;
10017 /* filter definition begins */
10018 if (state == IF_STATE_ACTION) {
10019 filter = perf_addr_filter_new(event, filters);
10020 if (!filter)
10021 goto fail;
10024 token = match_token(start, if_tokens, args);
10025 switch (token) {
10026 case IF_ACT_FILTER:
10027 case IF_ACT_START:
10028 case IF_ACT_STOP:
10029 if (state != IF_STATE_ACTION)
10030 goto fail;
10032 filter->action = actions[token];
10033 state = IF_STATE_SOURCE;
10034 break;
10036 case IF_SRC_KERNELADDR:
10037 case IF_SRC_KERNEL:
10038 kernel = 1;
10039 fallthrough;
10041 case IF_SRC_FILEADDR:
10042 case IF_SRC_FILE:
10043 if (state != IF_STATE_SOURCE)
10044 goto fail;
10046 *args[0].to = 0;
10047 ret = kstrtoul(args[0].from, 0, &filter->offset);
10048 if (ret)
10049 goto fail;
10051 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10052 *args[1].to = 0;
10053 ret = kstrtoul(args[1].from, 0, &filter->size);
10054 if (ret)
10055 goto fail;
10058 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10059 int fpos = token == IF_SRC_FILE ? 2 : 1;
10061 kfree(filename);
10062 filename = match_strdup(&args[fpos]);
10063 if (!filename) {
10064 ret = -ENOMEM;
10065 goto fail;
10069 state = IF_STATE_END;
10070 break;
10072 default:
10073 goto fail;
10077 * Filter definition is fully parsed, validate and install it.
10078 * Make sure that it doesn't contradict itself or the event's
10079 * attribute.
10081 if (state == IF_STATE_END) {
10082 ret = -EINVAL;
10083 if (kernel && event->attr.exclude_kernel)
10084 goto fail;
10087 * ACTION "filter" must have a non-zero length region
10088 * specified.
10090 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10091 !filter->size)
10092 goto fail;
10094 if (!kernel) {
10095 if (!filename)
10096 goto fail;
10099 * For now, we only support file-based filters
10100 * in per-task events; doing so for CPU-wide
10101 * events requires additional context switching
10102 * trickery, since same object code will be
10103 * mapped at different virtual addresses in
10104 * different processes.
10106 ret = -EOPNOTSUPP;
10107 if (!event->ctx->task)
10108 goto fail;
10110 /* look up the path and grab its inode */
10111 ret = kern_path(filename, LOOKUP_FOLLOW,
10112 &filter->path);
10113 if (ret)
10114 goto fail;
10116 ret = -EINVAL;
10117 if (!filter->path.dentry ||
10118 !S_ISREG(d_inode(filter->path.dentry)
10119 ->i_mode))
10120 goto fail;
10122 event->addr_filters.nr_file_filters++;
10125 /* ready to consume more filters */
10126 state = IF_STATE_ACTION;
10127 filter = NULL;
10131 if (state != IF_STATE_ACTION)
10132 goto fail;
10134 kfree(filename);
10135 kfree(orig);
10137 return 0;
10139 fail:
10140 kfree(filename);
10141 free_filters_list(filters);
10142 kfree(orig);
10144 return ret;
10147 static int
10148 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10150 LIST_HEAD(filters);
10151 int ret;
10154 * Since this is called in perf_ioctl() path, we're already holding
10155 * ctx::mutex.
10157 lockdep_assert_held(&event->ctx->mutex);
10159 if (WARN_ON_ONCE(event->parent))
10160 return -EINVAL;
10162 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10163 if (ret)
10164 goto fail_clear_files;
10166 ret = event->pmu->addr_filters_validate(&filters);
10167 if (ret)
10168 goto fail_free_filters;
10170 /* remove existing filters, if any */
10171 perf_addr_filters_splice(event, &filters);
10173 /* install new filters */
10174 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10176 return ret;
10178 fail_free_filters:
10179 free_filters_list(&filters);
10181 fail_clear_files:
10182 event->addr_filters.nr_file_filters = 0;
10184 return ret;
10187 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10189 int ret = -EINVAL;
10190 char *filter_str;
10192 filter_str = strndup_user(arg, PAGE_SIZE);
10193 if (IS_ERR(filter_str))
10194 return PTR_ERR(filter_str);
10196 #ifdef CONFIG_EVENT_TRACING
10197 if (perf_event_is_tracing(event)) {
10198 struct perf_event_context *ctx = event->ctx;
10201 * Beware, here be dragons!!
10203 * the tracepoint muck will deadlock against ctx->mutex, but
10204 * the tracepoint stuff does not actually need it. So
10205 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10206 * already have a reference on ctx.
10208 * This can result in event getting moved to a different ctx,
10209 * but that does not affect the tracepoint state.
10211 mutex_unlock(&ctx->mutex);
10212 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10213 mutex_lock(&ctx->mutex);
10214 } else
10215 #endif
10216 if (has_addr_filter(event))
10217 ret = perf_event_set_addr_filter(event, filter_str);
10219 kfree(filter_str);
10220 return ret;
10224 * hrtimer based swevent callback
10227 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10229 enum hrtimer_restart ret = HRTIMER_RESTART;
10230 struct perf_sample_data data;
10231 struct pt_regs *regs;
10232 struct perf_event *event;
10233 u64 period;
10235 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10237 if (event->state != PERF_EVENT_STATE_ACTIVE)
10238 return HRTIMER_NORESTART;
10240 event->pmu->read(event);
10242 perf_sample_data_init(&data, 0, event->hw.last_period);
10243 regs = get_irq_regs();
10245 if (regs && !perf_exclude_event(event, regs)) {
10246 if (!(event->attr.exclude_idle && is_idle_task(current)))
10247 if (__perf_event_overflow(event, 1, &data, regs))
10248 ret = HRTIMER_NORESTART;
10251 period = max_t(u64, 10000, event->hw.sample_period);
10252 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10254 return ret;
10257 static void perf_swevent_start_hrtimer(struct perf_event *event)
10259 struct hw_perf_event *hwc = &event->hw;
10260 s64 period;
10262 if (!is_sampling_event(event))
10263 return;
10265 period = local64_read(&hwc->period_left);
10266 if (period) {
10267 if (period < 0)
10268 period = 10000;
10270 local64_set(&hwc->period_left, 0);
10271 } else {
10272 period = max_t(u64, 10000, hwc->sample_period);
10274 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10275 HRTIMER_MODE_REL_PINNED_HARD);
10278 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10280 struct hw_perf_event *hwc = &event->hw;
10282 if (is_sampling_event(event)) {
10283 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10284 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10286 hrtimer_cancel(&hwc->hrtimer);
10290 static void perf_swevent_init_hrtimer(struct perf_event *event)
10292 struct hw_perf_event *hwc = &event->hw;
10294 if (!is_sampling_event(event))
10295 return;
10297 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10298 hwc->hrtimer.function = perf_swevent_hrtimer;
10301 * Since hrtimers have a fixed rate, we can do a static freq->period
10302 * mapping and avoid the whole period adjust feedback stuff.
10304 if (event->attr.freq) {
10305 long freq = event->attr.sample_freq;
10307 event->attr.sample_period = NSEC_PER_SEC / freq;
10308 hwc->sample_period = event->attr.sample_period;
10309 local64_set(&hwc->period_left, hwc->sample_period);
10310 hwc->last_period = hwc->sample_period;
10311 event->attr.freq = 0;
10316 * Software event: cpu wall time clock
10319 static void cpu_clock_event_update(struct perf_event *event)
10321 s64 prev;
10322 u64 now;
10324 now = local_clock();
10325 prev = local64_xchg(&event->hw.prev_count, now);
10326 local64_add(now - prev, &event->count);
10329 static void cpu_clock_event_start(struct perf_event *event, int flags)
10331 local64_set(&event->hw.prev_count, local_clock());
10332 perf_swevent_start_hrtimer(event);
10335 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10337 perf_swevent_cancel_hrtimer(event);
10338 cpu_clock_event_update(event);
10341 static int cpu_clock_event_add(struct perf_event *event, int flags)
10343 if (flags & PERF_EF_START)
10344 cpu_clock_event_start(event, flags);
10345 perf_event_update_userpage(event);
10347 return 0;
10350 static void cpu_clock_event_del(struct perf_event *event, int flags)
10352 cpu_clock_event_stop(event, flags);
10355 static void cpu_clock_event_read(struct perf_event *event)
10357 cpu_clock_event_update(event);
10360 static int cpu_clock_event_init(struct perf_event *event)
10362 if (event->attr.type != PERF_TYPE_SOFTWARE)
10363 return -ENOENT;
10365 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10366 return -ENOENT;
10369 * no branch sampling for software events
10371 if (has_branch_stack(event))
10372 return -EOPNOTSUPP;
10374 perf_swevent_init_hrtimer(event);
10376 return 0;
10379 static struct pmu perf_cpu_clock = {
10380 .task_ctx_nr = perf_sw_context,
10382 .capabilities = PERF_PMU_CAP_NO_NMI,
10384 .event_init = cpu_clock_event_init,
10385 .add = cpu_clock_event_add,
10386 .del = cpu_clock_event_del,
10387 .start = cpu_clock_event_start,
10388 .stop = cpu_clock_event_stop,
10389 .read = cpu_clock_event_read,
10393 * Software event: task time clock
10396 static void task_clock_event_update(struct perf_event *event, u64 now)
10398 u64 prev;
10399 s64 delta;
10401 prev = local64_xchg(&event->hw.prev_count, now);
10402 delta = now - prev;
10403 local64_add(delta, &event->count);
10406 static void task_clock_event_start(struct perf_event *event, int flags)
10408 local64_set(&event->hw.prev_count, event->ctx->time);
10409 perf_swevent_start_hrtimer(event);
10412 static void task_clock_event_stop(struct perf_event *event, int flags)
10414 perf_swevent_cancel_hrtimer(event);
10415 task_clock_event_update(event, event->ctx->time);
10418 static int task_clock_event_add(struct perf_event *event, int flags)
10420 if (flags & PERF_EF_START)
10421 task_clock_event_start(event, flags);
10422 perf_event_update_userpage(event);
10424 return 0;
10427 static void task_clock_event_del(struct perf_event *event, int flags)
10429 task_clock_event_stop(event, PERF_EF_UPDATE);
10432 static void task_clock_event_read(struct perf_event *event)
10434 u64 now = perf_clock();
10435 u64 delta = now - event->ctx->timestamp;
10436 u64 time = event->ctx->time + delta;
10438 task_clock_event_update(event, time);
10441 static int task_clock_event_init(struct perf_event *event)
10443 if (event->attr.type != PERF_TYPE_SOFTWARE)
10444 return -ENOENT;
10446 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10447 return -ENOENT;
10450 * no branch sampling for software events
10452 if (has_branch_stack(event))
10453 return -EOPNOTSUPP;
10455 perf_swevent_init_hrtimer(event);
10457 return 0;
10460 static struct pmu perf_task_clock = {
10461 .task_ctx_nr = perf_sw_context,
10463 .capabilities = PERF_PMU_CAP_NO_NMI,
10465 .event_init = task_clock_event_init,
10466 .add = task_clock_event_add,
10467 .del = task_clock_event_del,
10468 .start = task_clock_event_start,
10469 .stop = task_clock_event_stop,
10470 .read = task_clock_event_read,
10473 static void perf_pmu_nop_void(struct pmu *pmu)
10477 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10481 static int perf_pmu_nop_int(struct pmu *pmu)
10483 return 0;
10486 static int perf_event_nop_int(struct perf_event *event, u64 value)
10488 return 0;
10491 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10493 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10495 __this_cpu_write(nop_txn_flags, flags);
10497 if (flags & ~PERF_PMU_TXN_ADD)
10498 return;
10500 perf_pmu_disable(pmu);
10503 static int perf_pmu_commit_txn(struct pmu *pmu)
10505 unsigned int flags = __this_cpu_read(nop_txn_flags);
10507 __this_cpu_write(nop_txn_flags, 0);
10509 if (flags & ~PERF_PMU_TXN_ADD)
10510 return 0;
10512 perf_pmu_enable(pmu);
10513 return 0;
10516 static void perf_pmu_cancel_txn(struct pmu *pmu)
10518 unsigned int flags = __this_cpu_read(nop_txn_flags);
10520 __this_cpu_write(nop_txn_flags, 0);
10522 if (flags & ~PERF_PMU_TXN_ADD)
10523 return;
10525 perf_pmu_enable(pmu);
10528 static int perf_event_idx_default(struct perf_event *event)
10530 return 0;
10534 * Ensures all contexts with the same task_ctx_nr have the same
10535 * pmu_cpu_context too.
10537 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10539 struct pmu *pmu;
10541 if (ctxn < 0)
10542 return NULL;
10544 list_for_each_entry(pmu, &pmus, entry) {
10545 if (pmu->task_ctx_nr == ctxn)
10546 return pmu->pmu_cpu_context;
10549 return NULL;
10552 static void free_pmu_context(struct pmu *pmu)
10555 * Static contexts such as perf_sw_context have a global lifetime
10556 * and may be shared between different PMUs. Avoid freeing them
10557 * when a single PMU is going away.
10559 if (pmu->task_ctx_nr > perf_invalid_context)
10560 return;
10562 free_percpu(pmu->pmu_cpu_context);
10566 * Let userspace know that this PMU supports address range filtering:
10568 static ssize_t nr_addr_filters_show(struct device *dev,
10569 struct device_attribute *attr,
10570 char *page)
10572 struct pmu *pmu = dev_get_drvdata(dev);
10574 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10576 DEVICE_ATTR_RO(nr_addr_filters);
10578 static struct idr pmu_idr;
10580 static ssize_t
10581 type_show(struct device *dev, struct device_attribute *attr, char *page)
10583 struct pmu *pmu = dev_get_drvdata(dev);
10585 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10587 static DEVICE_ATTR_RO(type);
10589 static ssize_t
10590 perf_event_mux_interval_ms_show(struct device *dev,
10591 struct device_attribute *attr,
10592 char *page)
10594 struct pmu *pmu = dev_get_drvdata(dev);
10596 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10599 static DEFINE_MUTEX(mux_interval_mutex);
10601 static ssize_t
10602 perf_event_mux_interval_ms_store(struct device *dev,
10603 struct device_attribute *attr,
10604 const char *buf, size_t count)
10606 struct pmu *pmu = dev_get_drvdata(dev);
10607 int timer, cpu, ret;
10609 ret = kstrtoint(buf, 0, &timer);
10610 if (ret)
10611 return ret;
10613 if (timer < 1)
10614 return -EINVAL;
10616 /* same value, noting to do */
10617 if (timer == pmu->hrtimer_interval_ms)
10618 return count;
10620 mutex_lock(&mux_interval_mutex);
10621 pmu->hrtimer_interval_ms = timer;
10623 /* update all cpuctx for this PMU */
10624 cpus_read_lock();
10625 for_each_online_cpu(cpu) {
10626 struct perf_cpu_context *cpuctx;
10627 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10628 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10630 cpu_function_call(cpu,
10631 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10633 cpus_read_unlock();
10634 mutex_unlock(&mux_interval_mutex);
10636 return count;
10638 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10640 static struct attribute *pmu_dev_attrs[] = {
10641 &dev_attr_type.attr,
10642 &dev_attr_perf_event_mux_interval_ms.attr,
10643 NULL,
10645 ATTRIBUTE_GROUPS(pmu_dev);
10647 static int pmu_bus_running;
10648 static struct bus_type pmu_bus = {
10649 .name = "event_source",
10650 .dev_groups = pmu_dev_groups,
10653 static void pmu_dev_release(struct device *dev)
10655 kfree(dev);
10658 static int pmu_dev_alloc(struct pmu *pmu)
10660 int ret = -ENOMEM;
10662 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10663 if (!pmu->dev)
10664 goto out;
10666 pmu->dev->groups = pmu->attr_groups;
10667 device_initialize(pmu->dev);
10668 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10669 if (ret)
10670 goto free_dev;
10672 dev_set_drvdata(pmu->dev, pmu);
10673 pmu->dev->bus = &pmu_bus;
10674 pmu->dev->release = pmu_dev_release;
10675 ret = device_add(pmu->dev);
10676 if (ret)
10677 goto free_dev;
10679 /* For PMUs with address filters, throw in an extra attribute: */
10680 if (pmu->nr_addr_filters)
10681 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10683 if (ret)
10684 goto del_dev;
10686 if (pmu->attr_update)
10687 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10689 if (ret)
10690 goto del_dev;
10692 out:
10693 return ret;
10695 del_dev:
10696 device_del(pmu->dev);
10698 free_dev:
10699 put_device(pmu->dev);
10700 goto out;
10703 static struct lock_class_key cpuctx_mutex;
10704 static struct lock_class_key cpuctx_lock;
10706 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10708 int cpu, ret, max = PERF_TYPE_MAX;
10710 mutex_lock(&pmus_lock);
10711 ret = -ENOMEM;
10712 pmu->pmu_disable_count = alloc_percpu(int);
10713 if (!pmu->pmu_disable_count)
10714 goto unlock;
10716 pmu->type = -1;
10717 if (!name)
10718 goto skip_type;
10719 pmu->name = name;
10721 if (type != PERF_TYPE_SOFTWARE) {
10722 if (type >= 0)
10723 max = type;
10725 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10726 if (ret < 0)
10727 goto free_pdc;
10729 WARN_ON(type >= 0 && ret != type);
10731 type = ret;
10733 pmu->type = type;
10735 if (pmu_bus_running) {
10736 ret = pmu_dev_alloc(pmu);
10737 if (ret)
10738 goto free_idr;
10741 skip_type:
10742 if (pmu->task_ctx_nr == perf_hw_context) {
10743 static int hw_context_taken = 0;
10746 * Other than systems with heterogeneous CPUs, it never makes
10747 * sense for two PMUs to share perf_hw_context. PMUs which are
10748 * uncore must use perf_invalid_context.
10750 if (WARN_ON_ONCE(hw_context_taken &&
10751 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10752 pmu->task_ctx_nr = perf_invalid_context;
10754 hw_context_taken = 1;
10757 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10758 if (pmu->pmu_cpu_context)
10759 goto got_cpu_context;
10761 ret = -ENOMEM;
10762 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10763 if (!pmu->pmu_cpu_context)
10764 goto free_dev;
10766 for_each_possible_cpu(cpu) {
10767 struct perf_cpu_context *cpuctx;
10769 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10770 __perf_event_init_context(&cpuctx->ctx);
10771 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10772 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10773 cpuctx->ctx.pmu = pmu;
10774 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10776 __perf_mux_hrtimer_init(cpuctx, cpu);
10778 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10779 cpuctx->heap = cpuctx->heap_default;
10782 got_cpu_context:
10783 if (!pmu->start_txn) {
10784 if (pmu->pmu_enable) {
10786 * If we have pmu_enable/pmu_disable calls, install
10787 * transaction stubs that use that to try and batch
10788 * hardware accesses.
10790 pmu->start_txn = perf_pmu_start_txn;
10791 pmu->commit_txn = perf_pmu_commit_txn;
10792 pmu->cancel_txn = perf_pmu_cancel_txn;
10793 } else {
10794 pmu->start_txn = perf_pmu_nop_txn;
10795 pmu->commit_txn = perf_pmu_nop_int;
10796 pmu->cancel_txn = perf_pmu_nop_void;
10800 if (!pmu->pmu_enable) {
10801 pmu->pmu_enable = perf_pmu_nop_void;
10802 pmu->pmu_disable = perf_pmu_nop_void;
10805 if (!pmu->check_period)
10806 pmu->check_period = perf_event_nop_int;
10808 if (!pmu->event_idx)
10809 pmu->event_idx = perf_event_idx_default;
10812 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10813 * since these cannot be in the IDR. This way the linear search
10814 * is fast, provided a valid software event is provided.
10816 if (type == PERF_TYPE_SOFTWARE || !name)
10817 list_add_rcu(&pmu->entry, &pmus);
10818 else
10819 list_add_tail_rcu(&pmu->entry, &pmus);
10821 atomic_set(&pmu->exclusive_cnt, 0);
10822 ret = 0;
10823 unlock:
10824 mutex_unlock(&pmus_lock);
10826 return ret;
10828 free_dev:
10829 device_del(pmu->dev);
10830 put_device(pmu->dev);
10832 free_idr:
10833 if (pmu->type != PERF_TYPE_SOFTWARE)
10834 idr_remove(&pmu_idr, pmu->type);
10836 free_pdc:
10837 free_percpu(pmu->pmu_disable_count);
10838 goto unlock;
10840 EXPORT_SYMBOL_GPL(perf_pmu_register);
10842 void perf_pmu_unregister(struct pmu *pmu)
10844 mutex_lock(&pmus_lock);
10845 list_del_rcu(&pmu->entry);
10848 * We dereference the pmu list under both SRCU and regular RCU, so
10849 * synchronize against both of those.
10851 synchronize_srcu(&pmus_srcu);
10852 synchronize_rcu();
10854 free_percpu(pmu->pmu_disable_count);
10855 if (pmu->type != PERF_TYPE_SOFTWARE)
10856 idr_remove(&pmu_idr, pmu->type);
10857 if (pmu_bus_running) {
10858 if (pmu->nr_addr_filters)
10859 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10860 device_del(pmu->dev);
10861 put_device(pmu->dev);
10863 free_pmu_context(pmu);
10864 mutex_unlock(&pmus_lock);
10866 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10868 static inline bool has_extended_regs(struct perf_event *event)
10870 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10871 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10874 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10876 struct perf_event_context *ctx = NULL;
10877 int ret;
10879 if (!try_module_get(pmu->module))
10880 return -ENODEV;
10883 * A number of pmu->event_init() methods iterate the sibling_list to,
10884 * for example, validate if the group fits on the PMU. Therefore,
10885 * if this is a sibling event, acquire the ctx->mutex to protect
10886 * the sibling_list.
10888 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10890 * This ctx->mutex can nest when we're called through
10891 * inheritance. See the perf_event_ctx_lock_nested() comment.
10893 ctx = perf_event_ctx_lock_nested(event->group_leader,
10894 SINGLE_DEPTH_NESTING);
10895 BUG_ON(!ctx);
10898 event->pmu = pmu;
10899 ret = pmu->event_init(event);
10901 if (ctx)
10902 perf_event_ctx_unlock(event->group_leader, ctx);
10904 if (!ret) {
10905 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10906 has_extended_regs(event))
10907 ret = -EOPNOTSUPP;
10909 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10910 event_has_any_exclude_flag(event))
10911 ret = -EINVAL;
10913 if (ret && event->destroy)
10914 event->destroy(event);
10917 if (ret)
10918 module_put(pmu->module);
10920 return ret;
10923 static struct pmu *perf_init_event(struct perf_event *event)
10925 int idx, type, ret;
10926 struct pmu *pmu;
10928 idx = srcu_read_lock(&pmus_srcu);
10930 /* Try parent's PMU first: */
10931 if (event->parent && event->parent->pmu) {
10932 pmu = event->parent->pmu;
10933 ret = perf_try_init_event(pmu, event);
10934 if (!ret)
10935 goto unlock;
10939 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
10940 * are often aliases for PERF_TYPE_RAW.
10942 type = event->attr.type;
10943 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
10944 type = PERF_TYPE_RAW;
10946 again:
10947 rcu_read_lock();
10948 pmu = idr_find(&pmu_idr, type);
10949 rcu_read_unlock();
10950 if (pmu) {
10951 ret = perf_try_init_event(pmu, event);
10952 if (ret == -ENOENT && event->attr.type != type) {
10953 type = event->attr.type;
10954 goto again;
10957 if (ret)
10958 pmu = ERR_PTR(ret);
10960 goto unlock;
10963 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
10964 ret = perf_try_init_event(pmu, event);
10965 if (!ret)
10966 goto unlock;
10968 if (ret != -ENOENT) {
10969 pmu = ERR_PTR(ret);
10970 goto unlock;
10973 pmu = ERR_PTR(-ENOENT);
10974 unlock:
10975 srcu_read_unlock(&pmus_srcu, idx);
10977 return pmu;
10980 static void attach_sb_event(struct perf_event *event)
10982 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10984 raw_spin_lock(&pel->lock);
10985 list_add_rcu(&event->sb_list, &pel->list);
10986 raw_spin_unlock(&pel->lock);
10990 * We keep a list of all !task (and therefore per-cpu) events
10991 * that need to receive side-band records.
10993 * This avoids having to scan all the various PMU per-cpu contexts
10994 * looking for them.
10996 static void account_pmu_sb_event(struct perf_event *event)
10998 if (is_sb_event(event))
10999 attach_sb_event(event);
11002 static void account_event_cpu(struct perf_event *event, int cpu)
11004 if (event->parent)
11005 return;
11007 if (is_cgroup_event(event))
11008 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11011 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11012 static void account_freq_event_nohz(void)
11014 #ifdef CONFIG_NO_HZ_FULL
11015 /* Lock so we don't race with concurrent unaccount */
11016 spin_lock(&nr_freq_lock);
11017 if (atomic_inc_return(&nr_freq_events) == 1)
11018 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11019 spin_unlock(&nr_freq_lock);
11020 #endif
11023 static void account_freq_event(void)
11025 if (tick_nohz_full_enabled())
11026 account_freq_event_nohz();
11027 else
11028 atomic_inc(&nr_freq_events);
11032 static void account_event(struct perf_event *event)
11034 bool inc = false;
11036 if (event->parent)
11037 return;
11039 if (event->attach_state & PERF_ATTACH_TASK)
11040 inc = true;
11041 if (event->attr.mmap || event->attr.mmap_data)
11042 atomic_inc(&nr_mmap_events);
11043 if (event->attr.comm)
11044 atomic_inc(&nr_comm_events);
11045 if (event->attr.namespaces)
11046 atomic_inc(&nr_namespaces_events);
11047 if (event->attr.cgroup)
11048 atomic_inc(&nr_cgroup_events);
11049 if (event->attr.task)
11050 atomic_inc(&nr_task_events);
11051 if (event->attr.freq)
11052 account_freq_event();
11053 if (event->attr.context_switch) {
11054 atomic_inc(&nr_switch_events);
11055 inc = true;
11057 if (has_branch_stack(event))
11058 inc = true;
11059 if (is_cgroup_event(event))
11060 inc = true;
11061 if (event->attr.ksymbol)
11062 atomic_inc(&nr_ksymbol_events);
11063 if (event->attr.bpf_event)
11064 atomic_inc(&nr_bpf_events);
11065 if (event->attr.text_poke)
11066 atomic_inc(&nr_text_poke_events);
11068 if (inc) {
11070 * We need the mutex here because static_branch_enable()
11071 * must complete *before* the perf_sched_count increment
11072 * becomes visible.
11074 if (atomic_inc_not_zero(&perf_sched_count))
11075 goto enabled;
11077 mutex_lock(&perf_sched_mutex);
11078 if (!atomic_read(&perf_sched_count)) {
11079 static_branch_enable(&perf_sched_events);
11081 * Guarantee that all CPUs observe they key change and
11082 * call the perf scheduling hooks before proceeding to
11083 * install events that need them.
11085 synchronize_rcu();
11088 * Now that we have waited for the sync_sched(), allow further
11089 * increments to by-pass the mutex.
11091 atomic_inc(&perf_sched_count);
11092 mutex_unlock(&perf_sched_mutex);
11094 enabled:
11096 account_event_cpu(event, event->cpu);
11098 account_pmu_sb_event(event);
11102 * Allocate and initialize an event structure
11104 static struct perf_event *
11105 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11106 struct task_struct *task,
11107 struct perf_event *group_leader,
11108 struct perf_event *parent_event,
11109 perf_overflow_handler_t overflow_handler,
11110 void *context, int cgroup_fd)
11112 struct pmu *pmu;
11113 struct perf_event *event;
11114 struct hw_perf_event *hwc;
11115 long err = -EINVAL;
11117 if ((unsigned)cpu >= nr_cpu_ids) {
11118 if (!task || cpu != -1)
11119 return ERR_PTR(-EINVAL);
11122 event = kzalloc(sizeof(*event), GFP_KERNEL);
11123 if (!event)
11124 return ERR_PTR(-ENOMEM);
11127 * Single events are their own group leaders, with an
11128 * empty sibling list:
11130 if (!group_leader)
11131 group_leader = event;
11133 mutex_init(&event->child_mutex);
11134 INIT_LIST_HEAD(&event->child_list);
11136 INIT_LIST_HEAD(&event->event_entry);
11137 INIT_LIST_HEAD(&event->sibling_list);
11138 INIT_LIST_HEAD(&event->active_list);
11139 init_event_group(event);
11140 INIT_LIST_HEAD(&event->rb_entry);
11141 INIT_LIST_HEAD(&event->active_entry);
11142 INIT_LIST_HEAD(&event->addr_filters.list);
11143 INIT_HLIST_NODE(&event->hlist_entry);
11146 init_waitqueue_head(&event->waitq);
11147 event->pending_disable = -1;
11148 init_irq_work(&event->pending, perf_pending_event);
11150 mutex_init(&event->mmap_mutex);
11151 raw_spin_lock_init(&event->addr_filters.lock);
11153 atomic_long_set(&event->refcount, 1);
11154 event->cpu = cpu;
11155 event->attr = *attr;
11156 event->group_leader = group_leader;
11157 event->pmu = NULL;
11158 event->oncpu = -1;
11160 event->parent = parent_event;
11162 event->ns = get_pid_ns(task_active_pid_ns(current));
11163 event->id = atomic64_inc_return(&perf_event_id);
11165 event->state = PERF_EVENT_STATE_INACTIVE;
11167 if (task) {
11168 event->attach_state = PERF_ATTACH_TASK;
11170 * XXX pmu::event_init needs to know what task to account to
11171 * and we cannot use the ctx information because we need the
11172 * pmu before we get a ctx.
11174 event->hw.target = get_task_struct(task);
11177 event->clock = &local_clock;
11178 if (parent_event)
11179 event->clock = parent_event->clock;
11181 if (!overflow_handler && parent_event) {
11182 overflow_handler = parent_event->overflow_handler;
11183 context = parent_event->overflow_handler_context;
11184 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11185 if (overflow_handler == bpf_overflow_handler) {
11186 struct bpf_prog *prog = parent_event->prog;
11188 bpf_prog_inc(prog);
11189 event->prog = prog;
11190 event->orig_overflow_handler =
11191 parent_event->orig_overflow_handler;
11193 #endif
11196 if (overflow_handler) {
11197 event->overflow_handler = overflow_handler;
11198 event->overflow_handler_context = context;
11199 } else if (is_write_backward(event)){
11200 event->overflow_handler = perf_event_output_backward;
11201 event->overflow_handler_context = NULL;
11202 } else {
11203 event->overflow_handler = perf_event_output_forward;
11204 event->overflow_handler_context = NULL;
11207 perf_event__state_init(event);
11209 pmu = NULL;
11211 hwc = &event->hw;
11212 hwc->sample_period = attr->sample_period;
11213 if (attr->freq && attr->sample_freq)
11214 hwc->sample_period = 1;
11215 hwc->last_period = hwc->sample_period;
11217 local64_set(&hwc->period_left, hwc->sample_period);
11220 * We currently do not support PERF_SAMPLE_READ on inherited events.
11221 * See perf_output_read().
11223 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11224 goto err_ns;
11226 if (!has_branch_stack(event))
11227 event->attr.branch_sample_type = 0;
11229 pmu = perf_init_event(event);
11230 if (IS_ERR(pmu)) {
11231 err = PTR_ERR(pmu);
11232 goto err_ns;
11236 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11237 * be different on other CPUs in the uncore mask.
11239 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11240 err = -EINVAL;
11241 goto err_pmu;
11244 if (event->attr.aux_output &&
11245 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11246 err = -EOPNOTSUPP;
11247 goto err_pmu;
11250 if (cgroup_fd != -1) {
11251 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11252 if (err)
11253 goto err_pmu;
11256 err = exclusive_event_init(event);
11257 if (err)
11258 goto err_pmu;
11260 if (has_addr_filter(event)) {
11261 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11262 sizeof(struct perf_addr_filter_range),
11263 GFP_KERNEL);
11264 if (!event->addr_filter_ranges) {
11265 err = -ENOMEM;
11266 goto err_per_task;
11270 * Clone the parent's vma offsets: they are valid until exec()
11271 * even if the mm is not shared with the parent.
11273 if (event->parent) {
11274 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11276 raw_spin_lock_irq(&ifh->lock);
11277 memcpy(event->addr_filter_ranges,
11278 event->parent->addr_filter_ranges,
11279 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11280 raw_spin_unlock_irq(&ifh->lock);
11283 /* force hw sync on the address filters */
11284 event->addr_filters_gen = 1;
11287 if (!event->parent) {
11288 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11289 err = get_callchain_buffers(attr->sample_max_stack);
11290 if (err)
11291 goto err_addr_filters;
11295 err = security_perf_event_alloc(event);
11296 if (err)
11297 goto err_callchain_buffer;
11299 /* symmetric to unaccount_event() in _free_event() */
11300 account_event(event);
11302 return event;
11304 err_callchain_buffer:
11305 if (!event->parent) {
11306 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11307 put_callchain_buffers();
11309 err_addr_filters:
11310 kfree(event->addr_filter_ranges);
11312 err_per_task:
11313 exclusive_event_destroy(event);
11315 err_pmu:
11316 if (is_cgroup_event(event))
11317 perf_detach_cgroup(event);
11318 if (event->destroy)
11319 event->destroy(event);
11320 module_put(pmu->module);
11321 err_ns:
11322 if (event->ns)
11323 put_pid_ns(event->ns);
11324 if (event->hw.target)
11325 put_task_struct(event->hw.target);
11326 kfree(event);
11328 return ERR_PTR(err);
11331 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11332 struct perf_event_attr *attr)
11334 u32 size;
11335 int ret;
11337 /* Zero the full structure, so that a short copy will be nice. */
11338 memset(attr, 0, sizeof(*attr));
11340 ret = get_user(size, &uattr->size);
11341 if (ret)
11342 return ret;
11344 /* ABI compatibility quirk: */
11345 if (!size)
11346 size = PERF_ATTR_SIZE_VER0;
11347 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11348 goto err_size;
11350 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11351 if (ret) {
11352 if (ret == -E2BIG)
11353 goto err_size;
11354 return ret;
11357 attr->size = size;
11359 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11360 return -EINVAL;
11362 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11363 return -EINVAL;
11365 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11366 return -EINVAL;
11368 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11369 u64 mask = attr->branch_sample_type;
11371 /* only using defined bits */
11372 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11373 return -EINVAL;
11375 /* at least one branch bit must be set */
11376 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11377 return -EINVAL;
11379 /* propagate priv level, when not set for branch */
11380 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11382 /* exclude_kernel checked on syscall entry */
11383 if (!attr->exclude_kernel)
11384 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11386 if (!attr->exclude_user)
11387 mask |= PERF_SAMPLE_BRANCH_USER;
11389 if (!attr->exclude_hv)
11390 mask |= PERF_SAMPLE_BRANCH_HV;
11392 * adjust user setting (for HW filter setup)
11394 attr->branch_sample_type = mask;
11396 /* privileged levels capture (kernel, hv): check permissions */
11397 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11398 ret = perf_allow_kernel(attr);
11399 if (ret)
11400 return ret;
11404 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11405 ret = perf_reg_validate(attr->sample_regs_user);
11406 if (ret)
11407 return ret;
11410 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11411 if (!arch_perf_have_user_stack_dump())
11412 return -ENOSYS;
11415 * We have __u32 type for the size, but so far
11416 * we can only use __u16 as maximum due to the
11417 * __u16 sample size limit.
11419 if (attr->sample_stack_user >= USHRT_MAX)
11420 return -EINVAL;
11421 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11422 return -EINVAL;
11425 if (!attr->sample_max_stack)
11426 attr->sample_max_stack = sysctl_perf_event_max_stack;
11428 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11429 ret = perf_reg_validate(attr->sample_regs_intr);
11431 #ifndef CONFIG_CGROUP_PERF
11432 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11433 return -EINVAL;
11434 #endif
11436 out:
11437 return ret;
11439 err_size:
11440 put_user(sizeof(*attr), &uattr->size);
11441 ret = -E2BIG;
11442 goto out;
11445 static int
11446 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11448 struct perf_buffer *rb = NULL;
11449 int ret = -EINVAL;
11451 if (!output_event)
11452 goto set;
11454 /* don't allow circular references */
11455 if (event == output_event)
11456 goto out;
11459 * Don't allow cross-cpu buffers
11461 if (output_event->cpu != event->cpu)
11462 goto out;
11465 * If its not a per-cpu rb, it must be the same task.
11467 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11468 goto out;
11471 * Mixing clocks in the same buffer is trouble you don't need.
11473 if (output_event->clock != event->clock)
11474 goto out;
11477 * Either writing ring buffer from beginning or from end.
11478 * Mixing is not allowed.
11480 if (is_write_backward(output_event) != is_write_backward(event))
11481 goto out;
11484 * If both events generate aux data, they must be on the same PMU
11486 if (has_aux(event) && has_aux(output_event) &&
11487 event->pmu != output_event->pmu)
11488 goto out;
11490 set:
11491 mutex_lock(&event->mmap_mutex);
11492 /* Can't redirect output if we've got an active mmap() */
11493 if (atomic_read(&event->mmap_count))
11494 goto unlock;
11496 if (output_event) {
11497 /* get the rb we want to redirect to */
11498 rb = ring_buffer_get(output_event);
11499 if (!rb)
11500 goto unlock;
11503 ring_buffer_attach(event, rb);
11505 ret = 0;
11506 unlock:
11507 mutex_unlock(&event->mmap_mutex);
11509 out:
11510 return ret;
11513 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11515 if (b < a)
11516 swap(a, b);
11518 mutex_lock(a);
11519 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11522 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11524 bool nmi_safe = false;
11526 switch (clk_id) {
11527 case CLOCK_MONOTONIC:
11528 event->clock = &ktime_get_mono_fast_ns;
11529 nmi_safe = true;
11530 break;
11532 case CLOCK_MONOTONIC_RAW:
11533 event->clock = &ktime_get_raw_fast_ns;
11534 nmi_safe = true;
11535 break;
11537 case CLOCK_REALTIME:
11538 event->clock = &ktime_get_real_ns;
11539 break;
11541 case CLOCK_BOOTTIME:
11542 event->clock = &ktime_get_boottime_ns;
11543 break;
11545 case CLOCK_TAI:
11546 event->clock = &ktime_get_clocktai_ns;
11547 break;
11549 default:
11550 return -EINVAL;
11553 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11554 return -EINVAL;
11556 return 0;
11560 * Variation on perf_event_ctx_lock_nested(), except we take two context
11561 * mutexes.
11563 static struct perf_event_context *
11564 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11565 struct perf_event_context *ctx)
11567 struct perf_event_context *gctx;
11569 again:
11570 rcu_read_lock();
11571 gctx = READ_ONCE(group_leader->ctx);
11572 if (!refcount_inc_not_zero(&gctx->refcount)) {
11573 rcu_read_unlock();
11574 goto again;
11576 rcu_read_unlock();
11578 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11580 if (group_leader->ctx != gctx) {
11581 mutex_unlock(&ctx->mutex);
11582 mutex_unlock(&gctx->mutex);
11583 put_ctx(gctx);
11584 goto again;
11587 return gctx;
11591 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11593 * @attr_uptr: event_id type attributes for monitoring/sampling
11594 * @pid: target pid
11595 * @cpu: target cpu
11596 * @group_fd: group leader event fd
11598 SYSCALL_DEFINE5(perf_event_open,
11599 struct perf_event_attr __user *, attr_uptr,
11600 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11602 struct perf_event *group_leader = NULL, *output_event = NULL;
11603 struct perf_event *event, *sibling;
11604 struct perf_event_attr attr;
11605 struct perf_event_context *ctx, *gctx;
11606 struct file *event_file = NULL;
11607 struct fd group = {NULL, 0};
11608 struct task_struct *task = NULL;
11609 struct pmu *pmu;
11610 int event_fd;
11611 int move_group = 0;
11612 int err;
11613 int f_flags = O_RDWR;
11614 int cgroup_fd = -1;
11616 /* for future expandability... */
11617 if (flags & ~PERF_FLAG_ALL)
11618 return -EINVAL;
11620 /* Do we allow access to perf_event_open(2) ? */
11621 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11622 if (err)
11623 return err;
11625 err = perf_copy_attr(attr_uptr, &attr);
11626 if (err)
11627 return err;
11629 if (!attr.exclude_kernel) {
11630 err = perf_allow_kernel(&attr);
11631 if (err)
11632 return err;
11635 if (attr.namespaces) {
11636 if (!perfmon_capable())
11637 return -EACCES;
11640 if (attr.freq) {
11641 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11642 return -EINVAL;
11643 } else {
11644 if (attr.sample_period & (1ULL << 63))
11645 return -EINVAL;
11648 /* Only privileged users can get physical addresses */
11649 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11650 err = perf_allow_kernel(&attr);
11651 if (err)
11652 return err;
11655 err = security_locked_down(LOCKDOWN_PERF);
11656 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11657 /* REGS_INTR can leak data, lockdown must prevent this */
11658 return err;
11660 err = 0;
11663 * In cgroup mode, the pid argument is used to pass the fd
11664 * opened to the cgroup directory in cgroupfs. The cpu argument
11665 * designates the cpu on which to monitor threads from that
11666 * cgroup.
11668 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11669 return -EINVAL;
11671 if (flags & PERF_FLAG_FD_CLOEXEC)
11672 f_flags |= O_CLOEXEC;
11674 event_fd = get_unused_fd_flags(f_flags);
11675 if (event_fd < 0)
11676 return event_fd;
11678 if (group_fd != -1) {
11679 err = perf_fget_light(group_fd, &group);
11680 if (err)
11681 goto err_fd;
11682 group_leader = group.file->private_data;
11683 if (flags & PERF_FLAG_FD_OUTPUT)
11684 output_event = group_leader;
11685 if (flags & PERF_FLAG_FD_NO_GROUP)
11686 group_leader = NULL;
11689 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11690 task = find_lively_task_by_vpid(pid);
11691 if (IS_ERR(task)) {
11692 err = PTR_ERR(task);
11693 goto err_group_fd;
11697 if (task && group_leader &&
11698 group_leader->attr.inherit != attr.inherit) {
11699 err = -EINVAL;
11700 goto err_task;
11703 if (task) {
11704 err = mutex_lock_interruptible(&task->signal->exec_update_mutex);
11705 if (err)
11706 goto err_task;
11709 * Preserve ptrace permission check for backwards compatibility.
11711 * We must hold exec_update_mutex across this and any potential
11712 * perf_install_in_context() call for this new event to
11713 * serialize against exec() altering our credentials (and the
11714 * perf_event_exit_task() that could imply).
11716 err = -EACCES;
11717 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11718 goto err_cred;
11721 if (flags & PERF_FLAG_PID_CGROUP)
11722 cgroup_fd = pid;
11724 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11725 NULL, NULL, cgroup_fd);
11726 if (IS_ERR(event)) {
11727 err = PTR_ERR(event);
11728 goto err_cred;
11731 if (is_sampling_event(event)) {
11732 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11733 err = -EOPNOTSUPP;
11734 goto err_alloc;
11739 * Special case software events and allow them to be part of
11740 * any hardware group.
11742 pmu = event->pmu;
11744 if (attr.use_clockid) {
11745 err = perf_event_set_clock(event, attr.clockid);
11746 if (err)
11747 goto err_alloc;
11750 if (pmu->task_ctx_nr == perf_sw_context)
11751 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11753 if (group_leader) {
11754 if (is_software_event(event) &&
11755 !in_software_context(group_leader)) {
11757 * If the event is a sw event, but the group_leader
11758 * is on hw context.
11760 * Allow the addition of software events to hw
11761 * groups, this is safe because software events
11762 * never fail to schedule.
11764 pmu = group_leader->ctx->pmu;
11765 } else if (!is_software_event(event) &&
11766 is_software_event(group_leader) &&
11767 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11769 * In case the group is a pure software group, and we
11770 * try to add a hardware event, move the whole group to
11771 * the hardware context.
11773 move_group = 1;
11778 * Get the target context (task or percpu):
11780 ctx = find_get_context(pmu, task, event);
11781 if (IS_ERR(ctx)) {
11782 err = PTR_ERR(ctx);
11783 goto err_alloc;
11787 * Look up the group leader (we will attach this event to it):
11789 if (group_leader) {
11790 err = -EINVAL;
11793 * Do not allow a recursive hierarchy (this new sibling
11794 * becoming part of another group-sibling):
11796 if (group_leader->group_leader != group_leader)
11797 goto err_context;
11799 /* All events in a group should have the same clock */
11800 if (group_leader->clock != event->clock)
11801 goto err_context;
11804 * Make sure we're both events for the same CPU;
11805 * grouping events for different CPUs is broken; since
11806 * you can never concurrently schedule them anyhow.
11808 if (group_leader->cpu != event->cpu)
11809 goto err_context;
11812 * Make sure we're both on the same task, or both
11813 * per-CPU events.
11815 if (group_leader->ctx->task != ctx->task)
11816 goto err_context;
11819 * Do not allow to attach to a group in a different task
11820 * or CPU context. If we're moving SW events, we'll fix
11821 * this up later, so allow that.
11823 if (!move_group && group_leader->ctx != ctx)
11824 goto err_context;
11827 * Only a group leader can be exclusive or pinned
11829 if (attr.exclusive || attr.pinned)
11830 goto err_context;
11833 if (output_event) {
11834 err = perf_event_set_output(event, output_event);
11835 if (err)
11836 goto err_context;
11839 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11840 f_flags);
11841 if (IS_ERR(event_file)) {
11842 err = PTR_ERR(event_file);
11843 event_file = NULL;
11844 goto err_context;
11847 if (move_group) {
11848 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11850 if (gctx->task == TASK_TOMBSTONE) {
11851 err = -ESRCH;
11852 goto err_locked;
11856 * Check if we raced against another sys_perf_event_open() call
11857 * moving the software group underneath us.
11859 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11861 * If someone moved the group out from under us, check
11862 * if this new event wound up on the same ctx, if so
11863 * its the regular !move_group case, otherwise fail.
11865 if (gctx != ctx) {
11866 err = -EINVAL;
11867 goto err_locked;
11868 } else {
11869 perf_event_ctx_unlock(group_leader, gctx);
11870 move_group = 0;
11875 * Failure to create exclusive events returns -EBUSY.
11877 err = -EBUSY;
11878 if (!exclusive_event_installable(group_leader, ctx))
11879 goto err_locked;
11881 for_each_sibling_event(sibling, group_leader) {
11882 if (!exclusive_event_installable(sibling, ctx))
11883 goto err_locked;
11885 } else {
11886 mutex_lock(&ctx->mutex);
11889 if (ctx->task == TASK_TOMBSTONE) {
11890 err = -ESRCH;
11891 goto err_locked;
11894 if (!perf_event_validate_size(event)) {
11895 err = -E2BIG;
11896 goto err_locked;
11899 if (!task) {
11901 * Check if the @cpu we're creating an event for is online.
11903 * We use the perf_cpu_context::ctx::mutex to serialize against
11904 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11906 struct perf_cpu_context *cpuctx =
11907 container_of(ctx, struct perf_cpu_context, ctx);
11909 if (!cpuctx->online) {
11910 err = -ENODEV;
11911 goto err_locked;
11915 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
11916 err = -EINVAL;
11917 goto err_locked;
11921 * Must be under the same ctx::mutex as perf_install_in_context(),
11922 * because we need to serialize with concurrent event creation.
11924 if (!exclusive_event_installable(event, ctx)) {
11925 err = -EBUSY;
11926 goto err_locked;
11929 WARN_ON_ONCE(ctx->parent_ctx);
11932 * This is the point on no return; we cannot fail hereafter. This is
11933 * where we start modifying current state.
11936 if (move_group) {
11938 * See perf_event_ctx_lock() for comments on the details
11939 * of swizzling perf_event::ctx.
11941 perf_remove_from_context(group_leader, 0);
11942 put_ctx(gctx);
11944 for_each_sibling_event(sibling, group_leader) {
11945 perf_remove_from_context(sibling, 0);
11946 put_ctx(gctx);
11950 * Wait for everybody to stop referencing the events through
11951 * the old lists, before installing it on new lists.
11953 synchronize_rcu();
11956 * Install the group siblings before the group leader.
11958 * Because a group leader will try and install the entire group
11959 * (through the sibling list, which is still in-tact), we can
11960 * end up with siblings installed in the wrong context.
11962 * By installing siblings first we NO-OP because they're not
11963 * reachable through the group lists.
11965 for_each_sibling_event(sibling, group_leader) {
11966 perf_event__state_init(sibling);
11967 perf_install_in_context(ctx, sibling, sibling->cpu);
11968 get_ctx(ctx);
11972 * Removing from the context ends up with disabled
11973 * event. What we want here is event in the initial
11974 * startup state, ready to be add into new context.
11976 perf_event__state_init(group_leader);
11977 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11978 get_ctx(ctx);
11982 * Precalculate sample_data sizes; do while holding ctx::mutex such
11983 * that we're serialized against further additions and before
11984 * perf_install_in_context() which is the point the event is active and
11985 * can use these values.
11987 perf_event__header_size(event);
11988 perf_event__id_header_size(event);
11990 event->owner = current;
11992 perf_install_in_context(ctx, event, event->cpu);
11993 perf_unpin_context(ctx);
11995 if (move_group)
11996 perf_event_ctx_unlock(group_leader, gctx);
11997 mutex_unlock(&ctx->mutex);
11999 if (task) {
12000 mutex_unlock(&task->signal->exec_update_mutex);
12001 put_task_struct(task);
12004 mutex_lock(&current->perf_event_mutex);
12005 list_add_tail(&event->owner_entry, &current->perf_event_list);
12006 mutex_unlock(&current->perf_event_mutex);
12009 * Drop the reference on the group_event after placing the
12010 * new event on the sibling_list. This ensures destruction
12011 * of the group leader will find the pointer to itself in
12012 * perf_group_detach().
12014 fdput(group);
12015 fd_install(event_fd, event_file);
12016 return event_fd;
12018 err_locked:
12019 if (move_group)
12020 perf_event_ctx_unlock(group_leader, gctx);
12021 mutex_unlock(&ctx->mutex);
12022 /* err_file: */
12023 fput(event_file);
12024 err_context:
12025 perf_unpin_context(ctx);
12026 put_ctx(ctx);
12027 err_alloc:
12029 * If event_file is set, the fput() above will have called ->release()
12030 * and that will take care of freeing the event.
12032 if (!event_file)
12033 free_event(event);
12034 err_cred:
12035 if (task)
12036 mutex_unlock(&task->signal->exec_update_mutex);
12037 err_task:
12038 if (task)
12039 put_task_struct(task);
12040 err_group_fd:
12041 fdput(group);
12042 err_fd:
12043 put_unused_fd(event_fd);
12044 return err;
12048 * perf_event_create_kernel_counter
12050 * @attr: attributes of the counter to create
12051 * @cpu: cpu in which the counter is bound
12052 * @task: task to profile (NULL for percpu)
12054 struct perf_event *
12055 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12056 struct task_struct *task,
12057 perf_overflow_handler_t overflow_handler,
12058 void *context)
12060 struct perf_event_context *ctx;
12061 struct perf_event *event;
12062 int err;
12065 * Grouping is not supported for kernel events, neither is 'AUX',
12066 * make sure the caller's intentions are adjusted.
12068 if (attr->aux_output)
12069 return ERR_PTR(-EINVAL);
12071 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12072 overflow_handler, context, -1);
12073 if (IS_ERR(event)) {
12074 err = PTR_ERR(event);
12075 goto err;
12078 /* Mark owner so we could distinguish it from user events. */
12079 event->owner = TASK_TOMBSTONE;
12082 * Get the target context (task or percpu):
12084 ctx = find_get_context(event->pmu, task, event);
12085 if (IS_ERR(ctx)) {
12086 err = PTR_ERR(ctx);
12087 goto err_free;
12090 WARN_ON_ONCE(ctx->parent_ctx);
12091 mutex_lock(&ctx->mutex);
12092 if (ctx->task == TASK_TOMBSTONE) {
12093 err = -ESRCH;
12094 goto err_unlock;
12097 if (!task) {
12099 * Check if the @cpu we're creating an event for is online.
12101 * We use the perf_cpu_context::ctx::mutex to serialize against
12102 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12104 struct perf_cpu_context *cpuctx =
12105 container_of(ctx, struct perf_cpu_context, ctx);
12106 if (!cpuctx->online) {
12107 err = -ENODEV;
12108 goto err_unlock;
12112 if (!exclusive_event_installable(event, ctx)) {
12113 err = -EBUSY;
12114 goto err_unlock;
12117 perf_install_in_context(ctx, event, event->cpu);
12118 perf_unpin_context(ctx);
12119 mutex_unlock(&ctx->mutex);
12121 return event;
12123 err_unlock:
12124 mutex_unlock(&ctx->mutex);
12125 perf_unpin_context(ctx);
12126 put_ctx(ctx);
12127 err_free:
12128 free_event(event);
12129 err:
12130 return ERR_PTR(err);
12132 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12134 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12136 struct perf_event_context *src_ctx;
12137 struct perf_event_context *dst_ctx;
12138 struct perf_event *event, *tmp;
12139 LIST_HEAD(events);
12141 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12142 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12145 * See perf_event_ctx_lock() for comments on the details
12146 * of swizzling perf_event::ctx.
12148 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12149 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12150 event_entry) {
12151 perf_remove_from_context(event, 0);
12152 unaccount_event_cpu(event, src_cpu);
12153 put_ctx(src_ctx);
12154 list_add(&event->migrate_entry, &events);
12158 * Wait for the events to quiesce before re-instating them.
12160 synchronize_rcu();
12163 * Re-instate events in 2 passes.
12165 * Skip over group leaders and only install siblings on this first
12166 * pass, siblings will not get enabled without a leader, however a
12167 * leader will enable its siblings, even if those are still on the old
12168 * context.
12170 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12171 if (event->group_leader == event)
12172 continue;
12174 list_del(&event->migrate_entry);
12175 if (event->state >= PERF_EVENT_STATE_OFF)
12176 event->state = PERF_EVENT_STATE_INACTIVE;
12177 account_event_cpu(event, dst_cpu);
12178 perf_install_in_context(dst_ctx, event, dst_cpu);
12179 get_ctx(dst_ctx);
12183 * Once all the siblings are setup properly, install the group leaders
12184 * to make it go.
12186 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12187 list_del(&event->migrate_entry);
12188 if (event->state >= PERF_EVENT_STATE_OFF)
12189 event->state = PERF_EVENT_STATE_INACTIVE;
12190 account_event_cpu(event, dst_cpu);
12191 perf_install_in_context(dst_ctx, event, dst_cpu);
12192 get_ctx(dst_ctx);
12194 mutex_unlock(&dst_ctx->mutex);
12195 mutex_unlock(&src_ctx->mutex);
12197 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12199 static void sync_child_event(struct perf_event *child_event,
12200 struct task_struct *child)
12202 struct perf_event *parent_event = child_event->parent;
12203 u64 child_val;
12205 if (child_event->attr.inherit_stat)
12206 perf_event_read_event(child_event, child);
12208 child_val = perf_event_count(child_event);
12211 * Add back the child's count to the parent's count:
12213 atomic64_add(child_val, &parent_event->child_count);
12214 atomic64_add(child_event->total_time_enabled,
12215 &parent_event->child_total_time_enabled);
12216 atomic64_add(child_event->total_time_running,
12217 &parent_event->child_total_time_running);
12220 static void
12221 perf_event_exit_event(struct perf_event *child_event,
12222 struct perf_event_context *child_ctx,
12223 struct task_struct *child)
12225 struct perf_event *parent_event = child_event->parent;
12228 * Do not destroy the 'original' grouping; because of the context
12229 * switch optimization the original events could've ended up in a
12230 * random child task.
12232 * If we were to destroy the original group, all group related
12233 * operations would cease to function properly after this random
12234 * child dies.
12236 * Do destroy all inherited groups, we don't care about those
12237 * and being thorough is better.
12239 raw_spin_lock_irq(&child_ctx->lock);
12240 WARN_ON_ONCE(child_ctx->is_active);
12242 if (parent_event)
12243 perf_group_detach(child_event);
12244 list_del_event(child_event, child_ctx);
12245 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12246 raw_spin_unlock_irq(&child_ctx->lock);
12249 * Parent events are governed by their filedesc, retain them.
12251 if (!parent_event) {
12252 perf_event_wakeup(child_event);
12253 return;
12256 * Child events can be cleaned up.
12259 sync_child_event(child_event, child);
12262 * Remove this event from the parent's list
12264 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12265 mutex_lock(&parent_event->child_mutex);
12266 list_del_init(&child_event->child_list);
12267 mutex_unlock(&parent_event->child_mutex);
12270 * Kick perf_poll() for is_event_hup().
12272 perf_event_wakeup(parent_event);
12273 free_event(child_event);
12274 put_event(parent_event);
12277 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12279 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12280 struct perf_event *child_event, *next;
12282 WARN_ON_ONCE(child != current);
12284 child_ctx = perf_pin_task_context(child, ctxn);
12285 if (!child_ctx)
12286 return;
12289 * In order to reduce the amount of tricky in ctx tear-down, we hold
12290 * ctx::mutex over the entire thing. This serializes against almost
12291 * everything that wants to access the ctx.
12293 * The exception is sys_perf_event_open() /
12294 * perf_event_create_kernel_count() which does find_get_context()
12295 * without ctx::mutex (it cannot because of the move_group double mutex
12296 * lock thing). See the comments in perf_install_in_context().
12298 mutex_lock(&child_ctx->mutex);
12301 * In a single ctx::lock section, de-schedule the events and detach the
12302 * context from the task such that we cannot ever get it scheduled back
12303 * in.
12305 raw_spin_lock_irq(&child_ctx->lock);
12306 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12309 * Now that the context is inactive, destroy the task <-> ctx relation
12310 * and mark the context dead.
12312 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12313 put_ctx(child_ctx); /* cannot be last */
12314 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12315 put_task_struct(current); /* cannot be last */
12317 clone_ctx = unclone_ctx(child_ctx);
12318 raw_spin_unlock_irq(&child_ctx->lock);
12320 if (clone_ctx)
12321 put_ctx(clone_ctx);
12324 * Report the task dead after unscheduling the events so that we
12325 * won't get any samples after PERF_RECORD_EXIT. We can however still
12326 * get a few PERF_RECORD_READ events.
12328 perf_event_task(child, child_ctx, 0);
12330 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12331 perf_event_exit_event(child_event, child_ctx, child);
12333 mutex_unlock(&child_ctx->mutex);
12335 put_ctx(child_ctx);
12339 * When a child task exits, feed back event values to parent events.
12341 * Can be called with exec_update_mutex held when called from
12342 * setup_new_exec().
12344 void perf_event_exit_task(struct task_struct *child)
12346 struct perf_event *event, *tmp;
12347 int ctxn;
12349 mutex_lock(&child->perf_event_mutex);
12350 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12351 owner_entry) {
12352 list_del_init(&event->owner_entry);
12355 * Ensure the list deletion is visible before we clear
12356 * the owner, closes a race against perf_release() where
12357 * we need to serialize on the owner->perf_event_mutex.
12359 smp_store_release(&event->owner, NULL);
12361 mutex_unlock(&child->perf_event_mutex);
12363 for_each_task_context_nr(ctxn)
12364 perf_event_exit_task_context(child, ctxn);
12367 * The perf_event_exit_task_context calls perf_event_task
12368 * with child's task_ctx, which generates EXIT events for
12369 * child contexts and sets child->perf_event_ctxp[] to NULL.
12370 * At this point we need to send EXIT events to cpu contexts.
12372 perf_event_task(child, NULL, 0);
12375 static void perf_free_event(struct perf_event *event,
12376 struct perf_event_context *ctx)
12378 struct perf_event *parent = event->parent;
12380 if (WARN_ON_ONCE(!parent))
12381 return;
12383 mutex_lock(&parent->child_mutex);
12384 list_del_init(&event->child_list);
12385 mutex_unlock(&parent->child_mutex);
12387 put_event(parent);
12389 raw_spin_lock_irq(&ctx->lock);
12390 perf_group_detach(event);
12391 list_del_event(event, ctx);
12392 raw_spin_unlock_irq(&ctx->lock);
12393 free_event(event);
12397 * Free a context as created by inheritance by perf_event_init_task() below,
12398 * used by fork() in case of fail.
12400 * Even though the task has never lived, the context and events have been
12401 * exposed through the child_list, so we must take care tearing it all down.
12403 void perf_event_free_task(struct task_struct *task)
12405 struct perf_event_context *ctx;
12406 struct perf_event *event, *tmp;
12407 int ctxn;
12409 for_each_task_context_nr(ctxn) {
12410 ctx = task->perf_event_ctxp[ctxn];
12411 if (!ctx)
12412 continue;
12414 mutex_lock(&ctx->mutex);
12415 raw_spin_lock_irq(&ctx->lock);
12417 * Destroy the task <-> ctx relation and mark the context dead.
12419 * This is important because even though the task hasn't been
12420 * exposed yet the context has been (through child_list).
12422 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12423 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12424 put_task_struct(task); /* cannot be last */
12425 raw_spin_unlock_irq(&ctx->lock);
12427 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12428 perf_free_event(event, ctx);
12430 mutex_unlock(&ctx->mutex);
12433 * perf_event_release_kernel() could've stolen some of our
12434 * child events and still have them on its free_list. In that
12435 * case we must wait for these events to have been freed (in
12436 * particular all their references to this task must've been
12437 * dropped).
12439 * Without this copy_process() will unconditionally free this
12440 * task (irrespective of its reference count) and
12441 * _free_event()'s put_task_struct(event->hw.target) will be a
12442 * use-after-free.
12444 * Wait for all events to drop their context reference.
12446 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12447 put_ctx(ctx); /* must be last */
12451 void perf_event_delayed_put(struct task_struct *task)
12453 int ctxn;
12455 for_each_task_context_nr(ctxn)
12456 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12459 struct file *perf_event_get(unsigned int fd)
12461 struct file *file = fget(fd);
12462 if (!file)
12463 return ERR_PTR(-EBADF);
12465 if (file->f_op != &perf_fops) {
12466 fput(file);
12467 return ERR_PTR(-EBADF);
12470 return file;
12473 const struct perf_event *perf_get_event(struct file *file)
12475 if (file->f_op != &perf_fops)
12476 return ERR_PTR(-EINVAL);
12478 return file->private_data;
12481 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12483 if (!event)
12484 return ERR_PTR(-EINVAL);
12486 return &event->attr;
12490 * Inherit an event from parent task to child task.
12492 * Returns:
12493 * - valid pointer on success
12494 * - NULL for orphaned events
12495 * - IS_ERR() on error
12497 static struct perf_event *
12498 inherit_event(struct perf_event *parent_event,
12499 struct task_struct *parent,
12500 struct perf_event_context *parent_ctx,
12501 struct task_struct *child,
12502 struct perf_event *group_leader,
12503 struct perf_event_context *child_ctx)
12505 enum perf_event_state parent_state = parent_event->state;
12506 struct perf_event *child_event;
12507 unsigned long flags;
12510 * Instead of creating recursive hierarchies of events,
12511 * we link inherited events back to the original parent,
12512 * which has a filp for sure, which we use as the reference
12513 * count:
12515 if (parent_event->parent)
12516 parent_event = parent_event->parent;
12518 child_event = perf_event_alloc(&parent_event->attr,
12519 parent_event->cpu,
12520 child,
12521 group_leader, parent_event,
12522 NULL, NULL, -1);
12523 if (IS_ERR(child_event))
12524 return child_event;
12527 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12528 !child_ctx->task_ctx_data) {
12529 struct pmu *pmu = child_event->pmu;
12531 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12532 if (!child_ctx->task_ctx_data) {
12533 free_event(child_event);
12534 return ERR_PTR(-ENOMEM);
12539 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12540 * must be under the same lock in order to serialize against
12541 * perf_event_release_kernel(), such that either we must observe
12542 * is_orphaned_event() or they will observe us on the child_list.
12544 mutex_lock(&parent_event->child_mutex);
12545 if (is_orphaned_event(parent_event) ||
12546 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12547 mutex_unlock(&parent_event->child_mutex);
12548 /* task_ctx_data is freed with child_ctx */
12549 free_event(child_event);
12550 return NULL;
12553 get_ctx(child_ctx);
12556 * Make the child state follow the state of the parent event,
12557 * not its attr.disabled bit. We hold the parent's mutex,
12558 * so we won't race with perf_event_{en, dis}able_family.
12560 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12561 child_event->state = PERF_EVENT_STATE_INACTIVE;
12562 else
12563 child_event->state = PERF_EVENT_STATE_OFF;
12565 if (parent_event->attr.freq) {
12566 u64 sample_period = parent_event->hw.sample_period;
12567 struct hw_perf_event *hwc = &child_event->hw;
12569 hwc->sample_period = sample_period;
12570 hwc->last_period = sample_period;
12572 local64_set(&hwc->period_left, sample_period);
12575 child_event->ctx = child_ctx;
12576 child_event->overflow_handler = parent_event->overflow_handler;
12577 child_event->overflow_handler_context
12578 = parent_event->overflow_handler_context;
12581 * Precalculate sample_data sizes
12583 perf_event__header_size(child_event);
12584 perf_event__id_header_size(child_event);
12587 * Link it up in the child's context:
12589 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12590 add_event_to_ctx(child_event, child_ctx);
12591 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12594 * Link this into the parent event's child list
12596 list_add_tail(&child_event->child_list, &parent_event->child_list);
12597 mutex_unlock(&parent_event->child_mutex);
12599 return child_event;
12603 * Inherits an event group.
12605 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12606 * This matches with perf_event_release_kernel() removing all child events.
12608 * Returns:
12609 * - 0 on success
12610 * - <0 on error
12612 static int inherit_group(struct perf_event *parent_event,
12613 struct task_struct *parent,
12614 struct perf_event_context *parent_ctx,
12615 struct task_struct *child,
12616 struct perf_event_context *child_ctx)
12618 struct perf_event *leader;
12619 struct perf_event *sub;
12620 struct perf_event *child_ctr;
12622 leader = inherit_event(parent_event, parent, parent_ctx,
12623 child, NULL, child_ctx);
12624 if (IS_ERR(leader))
12625 return PTR_ERR(leader);
12627 * @leader can be NULL here because of is_orphaned_event(). In this
12628 * case inherit_event() will create individual events, similar to what
12629 * perf_group_detach() would do anyway.
12631 for_each_sibling_event(sub, parent_event) {
12632 child_ctr = inherit_event(sub, parent, parent_ctx,
12633 child, leader, child_ctx);
12634 if (IS_ERR(child_ctr))
12635 return PTR_ERR(child_ctr);
12637 if (sub->aux_event == parent_event && child_ctr &&
12638 !perf_get_aux_event(child_ctr, leader))
12639 return -EINVAL;
12641 return 0;
12645 * Creates the child task context and tries to inherit the event-group.
12647 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12648 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12649 * consistent with perf_event_release_kernel() removing all child events.
12651 * Returns:
12652 * - 0 on success
12653 * - <0 on error
12655 static int
12656 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12657 struct perf_event_context *parent_ctx,
12658 struct task_struct *child, int ctxn,
12659 int *inherited_all)
12661 int ret;
12662 struct perf_event_context *child_ctx;
12664 if (!event->attr.inherit) {
12665 *inherited_all = 0;
12666 return 0;
12669 child_ctx = child->perf_event_ctxp[ctxn];
12670 if (!child_ctx) {
12672 * This is executed from the parent task context, so
12673 * inherit events that have been marked for cloning.
12674 * First allocate and initialize a context for the
12675 * child.
12677 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12678 if (!child_ctx)
12679 return -ENOMEM;
12681 child->perf_event_ctxp[ctxn] = child_ctx;
12684 ret = inherit_group(event, parent, parent_ctx,
12685 child, child_ctx);
12687 if (ret)
12688 *inherited_all = 0;
12690 return ret;
12694 * Initialize the perf_event context in task_struct
12696 static int perf_event_init_context(struct task_struct *child, int ctxn)
12698 struct perf_event_context *child_ctx, *parent_ctx;
12699 struct perf_event_context *cloned_ctx;
12700 struct perf_event *event;
12701 struct task_struct *parent = current;
12702 int inherited_all = 1;
12703 unsigned long flags;
12704 int ret = 0;
12706 if (likely(!parent->perf_event_ctxp[ctxn]))
12707 return 0;
12710 * If the parent's context is a clone, pin it so it won't get
12711 * swapped under us.
12713 parent_ctx = perf_pin_task_context(parent, ctxn);
12714 if (!parent_ctx)
12715 return 0;
12718 * No need to check if parent_ctx != NULL here; since we saw
12719 * it non-NULL earlier, the only reason for it to become NULL
12720 * is if we exit, and since we're currently in the middle of
12721 * a fork we can't be exiting at the same time.
12725 * Lock the parent list. No need to lock the child - not PID
12726 * hashed yet and not running, so nobody can access it.
12728 mutex_lock(&parent_ctx->mutex);
12731 * We dont have to disable NMIs - we are only looking at
12732 * the list, not manipulating it:
12734 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12735 ret = inherit_task_group(event, parent, parent_ctx,
12736 child, ctxn, &inherited_all);
12737 if (ret)
12738 goto out_unlock;
12742 * We can't hold ctx->lock when iterating the ->flexible_group list due
12743 * to allocations, but we need to prevent rotation because
12744 * rotate_ctx() will change the list from interrupt context.
12746 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12747 parent_ctx->rotate_disable = 1;
12748 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12750 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12751 ret = inherit_task_group(event, parent, parent_ctx,
12752 child, ctxn, &inherited_all);
12753 if (ret)
12754 goto out_unlock;
12757 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12758 parent_ctx->rotate_disable = 0;
12760 child_ctx = child->perf_event_ctxp[ctxn];
12762 if (child_ctx && inherited_all) {
12764 * Mark the child context as a clone of the parent
12765 * context, or of whatever the parent is a clone of.
12767 * Note that if the parent is a clone, the holding of
12768 * parent_ctx->lock avoids it from being uncloned.
12770 cloned_ctx = parent_ctx->parent_ctx;
12771 if (cloned_ctx) {
12772 child_ctx->parent_ctx = cloned_ctx;
12773 child_ctx->parent_gen = parent_ctx->parent_gen;
12774 } else {
12775 child_ctx->parent_ctx = parent_ctx;
12776 child_ctx->parent_gen = parent_ctx->generation;
12778 get_ctx(child_ctx->parent_ctx);
12781 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12782 out_unlock:
12783 mutex_unlock(&parent_ctx->mutex);
12785 perf_unpin_context(parent_ctx);
12786 put_ctx(parent_ctx);
12788 return ret;
12792 * Initialize the perf_event context in task_struct
12794 int perf_event_init_task(struct task_struct *child)
12796 int ctxn, ret;
12798 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12799 mutex_init(&child->perf_event_mutex);
12800 INIT_LIST_HEAD(&child->perf_event_list);
12802 for_each_task_context_nr(ctxn) {
12803 ret = perf_event_init_context(child, ctxn);
12804 if (ret) {
12805 perf_event_free_task(child);
12806 return ret;
12810 return 0;
12813 static void __init perf_event_init_all_cpus(void)
12815 struct swevent_htable *swhash;
12816 int cpu;
12818 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12820 for_each_possible_cpu(cpu) {
12821 swhash = &per_cpu(swevent_htable, cpu);
12822 mutex_init(&swhash->hlist_mutex);
12823 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12825 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12826 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12828 #ifdef CONFIG_CGROUP_PERF
12829 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12830 #endif
12831 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
12835 static void perf_swevent_init_cpu(unsigned int cpu)
12837 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12839 mutex_lock(&swhash->hlist_mutex);
12840 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12841 struct swevent_hlist *hlist;
12843 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12844 WARN_ON(!hlist);
12845 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12847 mutex_unlock(&swhash->hlist_mutex);
12850 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12851 static void __perf_event_exit_context(void *__info)
12853 struct perf_event_context *ctx = __info;
12854 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12855 struct perf_event *event;
12857 raw_spin_lock(&ctx->lock);
12858 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12859 list_for_each_entry(event, &ctx->event_list, event_entry)
12860 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12861 raw_spin_unlock(&ctx->lock);
12864 static void perf_event_exit_cpu_context(int cpu)
12866 struct perf_cpu_context *cpuctx;
12867 struct perf_event_context *ctx;
12868 struct pmu *pmu;
12870 mutex_lock(&pmus_lock);
12871 list_for_each_entry(pmu, &pmus, entry) {
12872 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12873 ctx = &cpuctx->ctx;
12875 mutex_lock(&ctx->mutex);
12876 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12877 cpuctx->online = 0;
12878 mutex_unlock(&ctx->mutex);
12880 cpumask_clear_cpu(cpu, perf_online_mask);
12881 mutex_unlock(&pmus_lock);
12883 #else
12885 static void perf_event_exit_cpu_context(int cpu) { }
12887 #endif
12889 int perf_event_init_cpu(unsigned int cpu)
12891 struct perf_cpu_context *cpuctx;
12892 struct perf_event_context *ctx;
12893 struct pmu *pmu;
12895 perf_swevent_init_cpu(cpu);
12897 mutex_lock(&pmus_lock);
12898 cpumask_set_cpu(cpu, perf_online_mask);
12899 list_for_each_entry(pmu, &pmus, entry) {
12900 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12901 ctx = &cpuctx->ctx;
12903 mutex_lock(&ctx->mutex);
12904 cpuctx->online = 1;
12905 mutex_unlock(&ctx->mutex);
12907 mutex_unlock(&pmus_lock);
12909 return 0;
12912 int perf_event_exit_cpu(unsigned int cpu)
12914 perf_event_exit_cpu_context(cpu);
12915 return 0;
12918 static int
12919 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12921 int cpu;
12923 for_each_online_cpu(cpu)
12924 perf_event_exit_cpu(cpu);
12926 return NOTIFY_OK;
12930 * Run the perf reboot notifier at the very last possible moment so that
12931 * the generic watchdog code runs as long as possible.
12933 static struct notifier_block perf_reboot_notifier = {
12934 .notifier_call = perf_reboot,
12935 .priority = INT_MIN,
12938 void __init perf_event_init(void)
12940 int ret;
12942 idr_init(&pmu_idr);
12944 perf_event_init_all_cpus();
12945 init_srcu_struct(&pmus_srcu);
12946 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12947 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12948 perf_pmu_register(&perf_task_clock, NULL, -1);
12949 perf_tp_register();
12950 perf_event_init_cpu(smp_processor_id());
12951 register_reboot_notifier(&perf_reboot_notifier);
12953 ret = init_hw_breakpoint();
12954 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12957 * Build time assertion that we keep the data_head at the intended
12958 * location. IOW, validation we got the __reserved[] size right.
12960 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12961 != 1024);
12964 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12965 char *page)
12967 struct perf_pmu_events_attr *pmu_attr =
12968 container_of(attr, struct perf_pmu_events_attr, attr);
12970 if (pmu_attr->event_str)
12971 return sprintf(page, "%s\n", pmu_attr->event_str);
12973 return 0;
12975 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
12977 static int __init perf_event_sysfs_init(void)
12979 struct pmu *pmu;
12980 int ret;
12982 mutex_lock(&pmus_lock);
12984 ret = bus_register(&pmu_bus);
12985 if (ret)
12986 goto unlock;
12988 list_for_each_entry(pmu, &pmus, entry) {
12989 if (!pmu->name || pmu->type < 0)
12990 continue;
12992 ret = pmu_dev_alloc(pmu);
12993 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12995 pmu_bus_running = 1;
12996 ret = 0;
12998 unlock:
12999 mutex_unlock(&pmus_lock);
13001 return ret;
13003 device_initcall(perf_event_sysfs_init);
13005 #ifdef CONFIG_CGROUP_PERF
13006 static struct cgroup_subsys_state *
13007 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13009 struct perf_cgroup *jc;
13011 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13012 if (!jc)
13013 return ERR_PTR(-ENOMEM);
13015 jc->info = alloc_percpu(struct perf_cgroup_info);
13016 if (!jc->info) {
13017 kfree(jc);
13018 return ERR_PTR(-ENOMEM);
13021 return &jc->css;
13024 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13026 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13028 free_percpu(jc->info);
13029 kfree(jc);
13032 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13034 perf_event_cgroup(css->cgroup);
13035 return 0;
13038 static int __perf_cgroup_move(void *info)
13040 struct task_struct *task = info;
13041 rcu_read_lock();
13042 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13043 rcu_read_unlock();
13044 return 0;
13047 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13049 struct task_struct *task;
13050 struct cgroup_subsys_state *css;
13052 cgroup_taskset_for_each(task, css, tset)
13053 task_function_call(task, __perf_cgroup_move, task);
13056 struct cgroup_subsys perf_event_cgrp_subsys = {
13057 .css_alloc = perf_cgroup_css_alloc,
13058 .css_free = perf_cgroup_css_free,
13059 .css_online = perf_cgroup_css_online,
13060 .attach = perf_cgroup_attach,
13062 * Implicitly enable on dfl hierarchy so that perf events can
13063 * always be filtered by cgroup2 path as long as perf_event
13064 * controller is not mounted on a legacy hierarchy.
13066 .implicit_on_dfl = true,
13067 .threaded = true,
13069 #endif /* CONFIG_CGROUP_PERF */