Merge tag 'regmap-fix-v5.11-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux/fpc-iii.git] / kernel / events / core.c
blob55d18791a72de38b77ae29440cf5b0a57b8db37d
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>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
57 #include "internal.h"
59 #include <asm/irq_regs.h>
61 typedef int (*remote_function_f)(void *);
63 struct remote_function_call {
64 struct task_struct *p;
65 remote_function_f func;
66 void *info;
67 int ret;
70 static void remote_function(void *data)
72 struct remote_function_call *tfc = data;
73 struct task_struct *p = tfc->p;
75 if (p) {
76 /* -EAGAIN */
77 if (task_cpu(p) != smp_processor_id())
78 return;
81 * Now that we're on right CPU with IRQs disabled, we can test
82 * if we hit the right task without races.
85 tfc->ret = -ESRCH; /* No such (running) process */
86 if (p != current)
87 return;
90 tfc->ret = tfc->func(tfc->info);
93 /**
94 * task_function_call - call a function on the cpu on which a task runs
95 * @p: the task to evaluate
96 * @func: the function to be called
97 * @info: the function call argument
99 * Calls the function @func when the task is currently running. This might
100 * be on the current CPU, which just calls the function directly. This will
101 * retry due to any failures in smp_call_function_single(), such as if the
102 * task_cpu() goes offline concurrently.
104 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
106 static int
107 task_function_call(struct task_struct *p, remote_function_f func, void *info)
109 struct remote_function_call data = {
110 .p = p,
111 .func = func,
112 .info = info,
113 .ret = -EAGAIN,
115 int ret;
117 for (;;) {
118 ret = smp_call_function_single(task_cpu(p), remote_function,
119 &data, 1);
120 if (!ret)
121 ret = data.ret;
123 if (ret != -EAGAIN)
124 break;
126 cond_resched();
129 return ret;
133 * cpu_function_call - call a function on the cpu
134 * @func: the function to be called
135 * @info: the function call argument
137 * Calls the function @func on the remote cpu.
139 * returns: @func return value or -ENXIO when the cpu is offline
141 static int cpu_function_call(int cpu, remote_function_f func, void *info)
143 struct remote_function_call data = {
144 .p = NULL,
145 .func = func,
146 .info = info,
147 .ret = -ENXIO, /* No such CPU */
150 smp_call_function_single(cpu, remote_function, &data, 1);
152 return data.ret;
155 static inline struct perf_cpu_context *
156 __get_cpu_context(struct perf_event_context *ctx)
158 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
161 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
162 struct perf_event_context *ctx)
164 raw_spin_lock(&cpuctx->ctx.lock);
165 if (ctx)
166 raw_spin_lock(&ctx->lock);
169 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
170 struct perf_event_context *ctx)
172 if (ctx)
173 raw_spin_unlock(&ctx->lock);
174 raw_spin_unlock(&cpuctx->ctx.lock);
177 #define TASK_TOMBSTONE ((void *)-1L)
179 static bool is_kernel_event(struct perf_event *event)
181 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
185 * On task ctx scheduling...
187 * When !ctx->nr_events a task context will not be scheduled. This means
188 * we can disable the scheduler hooks (for performance) without leaving
189 * pending task ctx state.
191 * This however results in two special cases:
193 * - removing the last event from a task ctx; this is relatively straight
194 * forward and is done in __perf_remove_from_context.
196 * - adding the first event to a task ctx; this is tricky because we cannot
197 * rely on ctx->is_active and therefore cannot use event_function_call().
198 * See perf_install_in_context().
200 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
203 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
204 struct perf_event_context *, void *);
206 struct event_function_struct {
207 struct perf_event *event;
208 event_f func;
209 void *data;
212 static int event_function(void *info)
214 struct event_function_struct *efs = info;
215 struct perf_event *event = efs->event;
216 struct perf_event_context *ctx = event->ctx;
217 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
218 struct perf_event_context *task_ctx = cpuctx->task_ctx;
219 int ret = 0;
221 lockdep_assert_irqs_disabled();
223 perf_ctx_lock(cpuctx, task_ctx);
225 * Since we do the IPI call without holding ctx->lock things can have
226 * changed, double check we hit the task we set out to hit.
228 if (ctx->task) {
229 if (ctx->task != current) {
230 ret = -ESRCH;
231 goto unlock;
235 * We only use event_function_call() on established contexts,
236 * and event_function() is only ever called when active (or
237 * rather, we'll have bailed in task_function_call() or the
238 * above ctx->task != current test), therefore we must have
239 * ctx->is_active here.
241 WARN_ON_ONCE(!ctx->is_active);
243 * And since we have ctx->is_active, cpuctx->task_ctx must
244 * match.
246 WARN_ON_ONCE(task_ctx != ctx);
247 } else {
248 WARN_ON_ONCE(&cpuctx->ctx != ctx);
251 efs->func(event, cpuctx, ctx, efs->data);
252 unlock:
253 perf_ctx_unlock(cpuctx, task_ctx);
255 return ret;
258 static void event_function_call(struct perf_event *event, event_f func, void *data)
260 struct perf_event_context *ctx = event->ctx;
261 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
262 struct event_function_struct efs = {
263 .event = event,
264 .func = func,
265 .data = data,
268 if (!event->parent) {
270 * If this is a !child event, we must hold ctx::mutex to
271 * stabilize the the event->ctx relation. See
272 * perf_event_ctx_lock().
274 lockdep_assert_held(&ctx->mutex);
277 if (!task) {
278 cpu_function_call(event->cpu, event_function, &efs);
279 return;
282 if (task == TASK_TOMBSTONE)
283 return;
285 again:
286 if (!task_function_call(task, event_function, &efs))
287 return;
289 raw_spin_lock_irq(&ctx->lock);
291 * Reload the task pointer, it might have been changed by
292 * a concurrent perf_event_context_sched_out().
294 task = ctx->task;
295 if (task == TASK_TOMBSTONE) {
296 raw_spin_unlock_irq(&ctx->lock);
297 return;
299 if (ctx->is_active) {
300 raw_spin_unlock_irq(&ctx->lock);
301 goto again;
303 func(event, NULL, ctx, data);
304 raw_spin_unlock_irq(&ctx->lock);
308 * Similar to event_function_call() + event_function(), but hard assumes IRQs
309 * are already disabled and we're on the right CPU.
311 static void event_function_local(struct perf_event *event, event_f func, void *data)
313 struct perf_event_context *ctx = event->ctx;
314 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
315 struct task_struct *task = READ_ONCE(ctx->task);
316 struct perf_event_context *task_ctx = NULL;
318 lockdep_assert_irqs_disabled();
320 if (task) {
321 if (task == TASK_TOMBSTONE)
322 return;
324 task_ctx = ctx;
327 perf_ctx_lock(cpuctx, task_ctx);
329 task = ctx->task;
330 if (task == TASK_TOMBSTONE)
331 goto unlock;
333 if (task) {
335 * We must be either inactive or active and the right task,
336 * otherwise we're screwed, since we cannot IPI to somewhere
337 * else.
339 if (ctx->is_active) {
340 if (WARN_ON_ONCE(task != current))
341 goto unlock;
343 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
344 goto unlock;
346 } else {
347 WARN_ON_ONCE(&cpuctx->ctx != ctx);
350 func(event, cpuctx, ctx, data);
351 unlock:
352 perf_ctx_unlock(cpuctx, task_ctx);
355 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
356 PERF_FLAG_FD_OUTPUT |\
357 PERF_FLAG_PID_CGROUP |\
358 PERF_FLAG_FD_CLOEXEC)
361 * branch priv levels that need permission checks
363 #define PERF_SAMPLE_BRANCH_PERM_PLM \
364 (PERF_SAMPLE_BRANCH_KERNEL |\
365 PERF_SAMPLE_BRANCH_HV)
367 enum event_type_t {
368 EVENT_FLEXIBLE = 0x1,
369 EVENT_PINNED = 0x2,
370 EVENT_TIME = 0x4,
371 /* see ctx_resched() for details */
372 EVENT_CPU = 0x8,
373 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
377 * perf_sched_events : >0 events exist
378 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
381 static void perf_sched_delayed(struct work_struct *work);
382 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
383 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
384 static DEFINE_MUTEX(perf_sched_mutex);
385 static atomic_t perf_sched_count;
387 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
388 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
390 static atomic_t nr_mmap_events __read_mostly;
391 static atomic_t nr_comm_events __read_mostly;
392 static atomic_t nr_namespaces_events __read_mostly;
393 static atomic_t nr_task_events __read_mostly;
394 static atomic_t nr_freq_events __read_mostly;
395 static atomic_t nr_switch_events __read_mostly;
396 static atomic_t nr_ksymbol_events __read_mostly;
397 static atomic_t nr_bpf_events __read_mostly;
398 static atomic_t nr_cgroup_events __read_mostly;
399 static atomic_t nr_text_poke_events __read_mostly;
401 static LIST_HEAD(pmus);
402 static DEFINE_MUTEX(pmus_lock);
403 static struct srcu_struct pmus_srcu;
404 static cpumask_var_t perf_online_mask;
407 * perf event paranoia level:
408 * -1 - not paranoid at all
409 * 0 - disallow raw tracepoint access for unpriv
410 * 1 - disallow cpu events for unpriv
411 * 2 - disallow kernel profiling for unpriv
413 int sysctl_perf_event_paranoid __read_mostly = 2;
415 /* Minimum for 512 kiB + 1 user control page */
416 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
419 * max perf event sample rate
421 #define DEFAULT_MAX_SAMPLE_RATE 100000
422 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
423 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
425 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
427 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
428 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
430 static int perf_sample_allowed_ns __read_mostly =
431 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
433 static void update_perf_cpu_limits(void)
435 u64 tmp = perf_sample_period_ns;
437 tmp *= sysctl_perf_cpu_time_max_percent;
438 tmp = div_u64(tmp, 100);
439 if (!tmp)
440 tmp = 1;
442 WRITE_ONCE(perf_sample_allowed_ns, tmp);
445 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
447 int perf_proc_update_handler(struct ctl_table *table, int write,
448 void *buffer, size_t *lenp, loff_t *ppos)
450 int ret;
451 int perf_cpu = sysctl_perf_cpu_time_max_percent;
453 * If throttling is disabled don't allow the write:
455 if (write && (perf_cpu == 100 || perf_cpu == 0))
456 return -EINVAL;
458 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
459 if (ret || !write)
460 return ret;
462 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
463 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
464 update_perf_cpu_limits();
466 return 0;
469 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
471 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
472 void *buffer, size_t *lenp, loff_t *ppos)
474 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
476 if (ret || !write)
477 return ret;
479 if (sysctl_perf_cpu_time_max_percent == 100 ||
480 sysctl_perf_cpu_time_max_percent == 0) {
481 printk(KERN_WARNING
482 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
483 WRITE_ONCE(perf_sample_allowed_ns, 0);
484 } else {
485 update_perf_cpu_limits();
488 return 0;
492 * perf samples are done in some very critical code paths (NMIs).
493 * If they take too much CPU time, the system can lock up and not
494 * get any real work done. This will drop the sample rate when
495 * we detect that events are taking too long.
497 #define NR_ACCUMULATED_SAMPLES 128
498 static DEFINE_PER_CPU(u64, running_sample_length);
500 static u64 __report_avg;
501 static u64 __report_allowed;
503 static void perf_duration_warn(struct irq_work *w)
505 printk_ratelimited(KERN_INFO
506 "perf: interrupt took too long (%lld > %lld), lowering "
507 "kernel.perf_event_max_sample_rate to %d\n",
508 __report_avg, __report_allowed,
509 sysctl_perf_event_sample_rate);
512 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
514 void perf_sample_event_took(u64 sample_len_ns)
516 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
517 u64 running_len;
518 u64 avg_len;
519 u32 max;
521 if (max_len == 0)
522 return;
524 /* Decay the counter by 1 average sample. */
525 running_len = __this_cpu_read(running_sample_length);
526 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
527 running_len += sample_len_ns;
528 __this_cpu_write(running_sample_length, running_len);
531 * Note: this will be biased artifically low until we have
532 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
533 * from having to maintain a count.
535 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
536 if (avg_len <= max_len)
537 return;
539 __report_avg = avg_len;
540 __report_allowed = max_len;
543 * Compute a throttle threshold 25% below the current duration.
545 avg_len += avg_len / 4;
546 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
547 if (avg_len < max)
548 max /= (u32)avg_len;
549 else
550 max = 1;
552 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
553 WRITE_ONCE(max_samples_per_tick, max);
555 sysctl_perf_event_sample_rate = max * HZ;
556 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
558 if (!irq_work_queue(&perf_duration_work)) {
559 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
560 "kernel.perf_event_max_sample_rate to %d\n",
561 __report_avg, __report_allowed,
562 sysctl_perf_event_sample_rate);
566 static atomic64_t perf_event_id;
568 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
569 enum event_type_t event_type);
571 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
572 enum event_type_t event_type,
573 struct task_struct *task);
575 static void update_context_time(struct perf_event_context *ctx);
576 static u64 perf_event_time(struct perf_event *event);
578 void __weak perf_event_print_debug(void) { }
580 extern __weak const char *perf_pmu_name(void)
582 return "pmu";
585 static inline u64 perf_clock(void)
587 return local_clock();
590 static inline u64 perf_event_clock(struct perf_event *event)
592 return event->clock();
596 * State based event timekeeping...
598 * The basic idea is to use event->state to determine which (if any) time
599 * fields to increment with the current delta. This means we only need to
600 * update timestamps when we change state or when they are explicitly requested
601 * (read).
603 * Event groups make things a little more complicated, but not terribly so. The
604 * rules for a group are that if the group leader is OFF the entire group is
605 * OFF, irrespecive of what the group member states are. This results in
606 * __perf_effective_state().
608 * A futher ramification is that when a group leader flips between OFF and
609 * !OFF, we need to update all group member times.
612 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
613 * need to make sure the relevant context time is updated before we try and
614 * update our timestamps.
617 static __always_inline enum perf_event_state
618 __perf_effective_state(struct perf_event *event)
620 struct perf_event *leader = event->group_leader;
622 if (leader->state <= PERF_EVENT_STATE_OFF)
623 return leader->state;
625 return event->state;
628 static __always_inline void
629 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
631 enum perf_event_state state = __perf_effective_state(event);
632 u64 delta = now - event->tstamp;
634 *enabled = event->total_time_enabled;
635 if (state >= PERF_EVENT_STATE_INACTIVE)
636 *enabled += delta;
638 *running = event->total_time_running;
639 if (state >= PERF_EVENT_STATE_ACTIVE)
640 *running += delta;
643 static void perf_event_update_time(struct perf_event *event)
645 u64 now = perf_event_time(event);
647 __perf_update_times(event, now, &event->total_time_enabled,
648 &event->total_time_running);
649 event->tstamp = now;
652 static void perf_event_update_sibling_time(struct perf_event *leader)
654 struct perf_event *sibling;
656 for_each_sibling_event(sibling, leader)
657 perf_event_update_time(sibling);
660 static void
661 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
663 if (event->state == state)
664 return;
666 perf_event_update_time(event);
668 * If a group leader gets enabled/disabled all its siblings
669 * are affected too.
671 if ((event->state < 0) ^ (state < 0))
672 perf_event_update_sibling_time(event);
674 WRITE_ONCE(event->state, state);
677 #ifdef CONFIG_CGROUP_PERF
679 static inline bool
680 perf_cgroup_match(struct perf_event *event)
682 struct perf_event_context *ctx = event->ctx;
683 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
685 /* @event doesn't care about cgroup */
686 if (!event->cgrp)
687 return true;
689 /* wants specific cgroup scope but @cpuctx isn't associated with any */
690 if (!cpuctx->cgrp)
691 return false;
694 * Cgroup scoping is recursive. An event enabled for a cgroup is
695 * also enabled for all its descendant cgroups. If @cpuctx's
696 * cgroup is a descendant of @event's (the test covers identity
697 * case), it's a match.
699 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
700 event->cgrp->css.cgroup);
703 static inline void perf_detach_cgroup(struct perf_event *event)
705 css_put(&event->cgrp->css);
706 event->cgrp = NULL;
709 static inline int is_cgroup_event(struct perf_event *event)
711 return event->cgrp != NULL;
714 static inline u64 perf_cgroup_event_time(struct perf_event *event)
716 struct perf_cgroup_info *t;
718 t = per_cpu_ptr(event->cgrp->info, event->cpu);
719 return t->time;
722 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
724 struct perf_cgroup_info *info;
725 u64 now;
727 now = perf_clock();
729 info = this_cpu_ptr(cgrp->info);
731 info->time += now - info->timestamp;
732 info->timestamp = now;
735 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
737 struct perf_cgroup *cgrp = cpuctx->cgrp;
738 struct cgroup_subsys_state *css;
740 if (cgrp) {
741 for (css = &cgrp->css; css; css = css->parent) {
742 cgrp = container_of(css, struct perf_cgroup, css);
743 __update_cgrp_time(cgrp);
748 static inline void update_cgrp_time_from_event(struct perf_event *event)
750 struct perf_cgroup *cgrp;
753 * ensure we access cgroup data only when needed and
754 * when we know the cgroup is pinned (css_get)
756 if (!is_cgroup_event(event))
757 return;
759 cgrp = perf_cgroup_from_task(current, event->ctx);
761 * Do not update time when cgroup is not active
763 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
764 __update_cgrp_time(event->cgrp);
767 static inline void
768 perf_cgroup_set_timestamp(struct task_struct *task,
769 struct perf_event_context *ctx)
771 struct perf_cgroup *cgrp;
772 struct perf_cgroup_info *info;
773 struct cgroup_subsys_state *css;
776 * ctx->lock held by caller
777 * ensure we do not access cgroup data
778 * unless we have the cgroup pinned (css_get)
780 if (!task || !ctx->nr_cgroups)
781 return;
783 cgrp = perf_cgroup_from_task(task, ctx);
785 for (css = &cgrp->css; css; css = css->parent) {
786 cgrp = container_of(css, struct perf_cgroup, css);
787 info = this_cpu_ptr(cgrp->info);
788 info->timestamp = ctx->timestamp;
792 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
794 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
795 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
798 * reschedule events based on the cgroup constraint of task.
800 * mode SWOUT : schedule out everything
801 * mode SWIN : schedule in based on cgroup for next
803 static void perf_cgroup_switch(struct task_struct *task, int mode)
805 struct perf_cpu_context *cpuctx;
806 struct list_head *list;
807 unsigned long flags;
810 * Disable interrupts and preemption to avoid this CPU's
811 * cgrp_cpuctx_entry to change under us.
813 local_irq_save(flags);
815 list = this_cpu_ptr(&cgrp_cpuctx_list);
816 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
817 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
819 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
820 perf_pmu_disable(cpuctx->ctx.pmu);
822 if (mode & PERF_CGROUP_SWOUT) {
823 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
825 * must not be done before ctxswout due
826 * to event_filter_match() in event_sched_out()
828 cpuctx->cgrp = NULL;
831 if (mode & PERF_CGROUP_SWIN) {
832 WARN_ON_ONCE(cpuctx->cgrp);
834 * set cgrp before ctxsw in to allow
835 * event_filter_match() to not have to pass
836 * task around
837 * we pass the cpuctx->ctx to perf_cgroup_from_task()
838 * because cgorup events are only per-cpu
840 cpuctx->cgrp = perf_cgroup_from_task(task,
841 &cpuctx->ctx);
842 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
844 perf_pmu_enable(cpuctx->ctx.pmu);
845 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
848 local_irq_restore(flags);
851 static inline void perf_cgroup_sched_out(struct task_struct *task,
852 struct task_struct *next)
854 struct perf_cgroup *cgrp1;
855 struct perf_cgroup *cgrp2 = NULL;
857 rcu_read_lock();
859 * we come here when we know perf_cgroup_events > 0
860 * we do not need to pass the ctx here because we know
861 * we are holding the rcu lock
863 cgrp1 = perf_cgroup_from_task(task, NULL);
864 cgrp2 = perf_cgroup_from_task(next, NULL);
867 * only schedule out current cgroup events if we know
868 * that we are switching to a different cgroup. Otherwise,
869 * do no touch the cgroup events.
871 if (cgrp1 != cgrp2)
872 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
874 rcu_read_unlock();
877 static inline void perf_cgroup_sched_in(struct task_struct *prev,
878 struct task_struct *task)
880 struct perf_cgroup *cgrp1;
881 struct perf_cgroup *cgrp2 = NULL;
883 rcu_read_lock();
885 * we come here when we know perf_cgroup_events > 0
886 * we do not need to pass the ctx here because we know
887 * we are holding the rcu lock
889 cgrp1 = perf_cgroup_from_task(task, NULL);
890 cgrp2 = perf_cgroup_from_task(prev, NULL);
893 * only need to schedule in cgroup events if we are changing
894 * cgroup during ctxsw. Cgroup events were not scheduled
895 * out of ctxsw out if that was not the case.
897 if (cgrp1 != cgrp2)
898 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
900 rcu_read_unlock();
903 static int perf_cgroup_ensure_storage(struct perf_event *event,
904 struct cgroup_subsys_state *css)
906 struct perf_cpu_context *cpuctx;
907 struct perf_event **storage;
908 int cpu, heap_size, ret = 0;
911 * Allow storage to have sufficent space for an iterator for each
912 * possibly nested cgroup plus an iterator for events with no cgroup.
914 for (heap_size = 1; css; css = css->parent)
915 heap_size++;
917 for_each_possible_cpu(cpu) {
918 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
919 if (heap_size <= cpuctx->heap_size)
920 continue;
922 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
923 GFP_KERNEL, cpu_to_node(cpu));
924 if (!storage) {
925 ret = -ENOMEM;
926 break;
929 raw_spin_lock_irq(&cpuctx->ctx.lock);
930 if (cpuctx->heap_size < heap_size) {
931 swap(cpuctx->heap, storage);
932 if (storage == cpuctx->heap_default)
933 storage = NULL;
934 cpuctx->heap_size = heap_size;
936 raw_spin_unlock_irq(&cpuctx->ctx.lock);
938 kfree(storage);
941 return ret;
944 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
945 struct perf_event_attr *attr,
946 struct perf_event *group_leader)
948 struct perf_cgroup *cgrp;
949 struct cgroup_subsys_state *css;
950 struct fd f = fdget(fd);
951 int ret = 0;
953 if (!f.file)
954 return -EBADF;
956 css = css_tryget_online_from_dir(f.file->f_path.dentry,
957 &perf_event_cgrp_subsys);
958 if (IS_ERR(css)) {
959 ret = PTR_ERR(css);
960 goto out;
963 ret = perf_cgroup_ensure_storage(event, css);
964 if (ret)
965 goto out;
967 cgrp = container_of(css, struct perf_cgroup, css);
968 event->cgrp = cgrp;
971 * all events in a group must monitor
972 * the same cgroup because a task belongs
973 * to only one perf cgroup at a time
975 if (group_leader && group_leader->cgrp != cgrp) {
976 perf_detach_cgroup(event);
977 ret = -EINVAL;
979 out:
980 fdput(f);
981 return ret;
984 static inline void
985 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
987 struct perf_cgroup_info *t;
988 t = per_cpu_ptr(event->cgrp->info, event->cpu);
989 event->shadow_ctx_time = now - t->timestamp;
992 static inline void
993 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
995 struct perf_cpu_context *cpuctx;
997 if (!is_cgroup_event(event))
998 return;
1001 * Because cgroup events are always per-cpu events,
1002 * @ctx == &cpuctx->ctx.
1004 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1007 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1008 * matching the event's cgroup, we must do this for every new event,
1009 * because if the first would mismatch, the second would not try again
1010 * and we would leave cpuctx->cgrp unset.
1012 if (ctx->is_active && !cpuctx->cgrp) {
1013 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1015 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1016 cpuctx->cgrp = cgrp;
1019 if (ctx->nr_cgroups++)
1020 return;
1022 list_add(&cpuctx->cgrp_cpuctx_entry,
1023 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1026 static inline void
1027 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1029 struct perf_cpu_context *cpuctx;
1031 if (!is_cgroup_event(event))
1032 return;
1035 * Because cgroup events are always per-cpu events,
1036 * @ctx == &cpuctx->ctx.
1038 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1040 if (--ctx->nr_cgroups)
1041 return;
1043 if (ctx->is_active && cpuctx->cgrp)
1044 cpuctx->cgrp = NULL;
1046 list_del(&cpuctx->cgrp_cpuctx_entry);
1049 #else /* !CONFIG_CGROUP_PERF */
1051 static inline bool
1052 perf_cgroup_match(struct perf_event *event)
1054 return true;
1057 static inline void perf_detach_cgroup(struct perf_event *event)
1060 static inline int is_cgroup_event(struct perf_event *event)
1062 return 0;
1065 static inline void update_cgrp_time_from_event(struct perf_event *event)
1069 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1073 static inline void perf_cgroup_sched_out(struct task_struct *task,
1074 struct task_struct *next)
1078 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1079 struct task_struct *task)
1083 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1084 struct perf_event_attr *attr,
1085 struct perf_event *group_leader)
1087 return -EINVAL;
1090 static inline void
1091 perf_cgroup_set_timestamp(struct task_struct *task,
1092 struct perf_event_context *ctx)
1096 static inline void
1097 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1101 static inline void
1102 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1106 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1108 return 0;
1111 static inline void
1112 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1116 static inline void
1117 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1120 #endif
1123 * set default to be dependent on timer tick just
1124 * like original code
1126 #define PERF_CPU_HRTIMER (1000 / HZ)
1128 * function must be called with interrupts disabled
1130 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1132 struct perf_cpu_context *cpuctx;
1133 bool rotations;
1135 lockdep_assert_irqs_disabled();
1137 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1138 rotations = perf_rotate_context(cpuctx);
1140 raw_spin_lock(&cpuctx->hrtimer_lock);
1141 if (rotations)
1142 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1143 else
1144 cpuctx->hrtimer_active = 0;
1145 raw_spin_unlock(&cpuctx->hrtimer_lock);
1147 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1150 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1152 struct hrtimer *timer = &cpuctx->hrtimer;
1153 struct pmu *pmu = cpuctx->ctx.pmu;
1154 u64 interval;
1156 /* no multiplexing needed for SW PMU */
1157 if (pmu->task_ctx_nr == perf_sw_context)
1158 return;
1161 * check default is sane, if not set then force to
1162 * default interval (1/tick)
1164 interval = pmu->hrtimer_interval_ms;
1165 if (interval < 1)
1166 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1168 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1170 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1171 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1172 timer->function = perf_mux_hrtimer_handler;
1175 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1177 struct hrtimer *timer = &cpuctx->hrtimer;
1178 struct pmu *pmu = cpuctx->ctx.pmu;
1179 unsigned long flags;
1181 /* not for SW PMU */
1182 if (pmu->task_ctx_nr == perf_sw_context)
1183 return 0;
1185 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1186 if (!cpuctx->hrtimer_active) {
1187 cpuctx->hrtimer_active = 1;
1188 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1189 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1191 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1193 return 0;
1196 void perf_pmu_disable(struct pmu *pmu)
1198 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1199 if (!(*count)++)
1200 pmu->pmu_disable(pmu);
1203 void perf_pmu_enable(struct pmu *pmu)
1205 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1206 if (!--(*count))
1207 pmu->pmu_enable(pmu);
1210 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1213 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1214 * perf_event_task_tick() are fully serialized because they're strictly cpu
1215 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1216 * disabled, while perf_event_task_tick is called from IRQ context.
1218 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1220 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1222 lockdep_assert_irqs_disabled();
1224 WARN_ON(!list_empty(&ctx->active_ctx_list));
1226 list_add(&ctx->active_ctx_list, head);
1229 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1231 lockdep_assert_irqs_disabled();
1233 WARN_ON(list_empty(&ctx->active_ctx_list));
1235 list_del_init(&ctx->active_ctx_list);
1238 static void get_ctx(struct perf_event_context *ctx)
1240 refcount_inc(&ctx->refcount);
1243 static void *alloc_task_ctx_data(struct pmu *pmu)
1245 if (pmu->task_ctx_cache)
1246 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1248 return NULL;
1251 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1253 if (pmu->task_ctx_cache && task_ctx_data)
1254 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1257 static void free_ctx(struct rcu_head *head)
1259 struct perf_event_context *ctx;
1261 ctx = container_of(head, struct perf_event_context, rcu_head);
1262 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1263 kfree(ctx);
1266 static void put_ctx(struct perf_event_context *ctx)
1268 if (refcount_dec_and_test(&ctx->refcount)) {
1269 if (ctx->parent_ctx)
1270 put_ctx(ctx->parent_ctx);
1271 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1272 put_task_struct(ctx->task);
1273 call_rcu(&ctx->rcu_head, free_ctx);
1278 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1279 * perf_pmu_migrate_context() we need some magic.
1281 * Those places that change perf_event::ctx will hold both
1282 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1284 * Lock ordering is by mutex address. There are two other sites where
1285 * perf_event_context::mutex nests and those are:
1287 * - perf_event_exit_task_context() [ child , 0 ]
1288 * perf_event_exit_event()
1289 * put_event() [ parent, 1 ]
1291 * - perf_event_init_context() [ parent, 0 ]
1292 * inherit_task_group()
1293 * inherit_group()
1294 * inherit_event()
1295 * perf_event_alloc()
1296 * perf_init_event()
1297 * perf_try_init_event() [ child , 1 ]
1299 * While it appears there is an obvious deadlock here -- the parent and child
1300 * nesting levels are inverted between the two. This is in fact safe because
1301 * life-time rules separate them. That is an exiting task cannot fork, and a
1302 * spawning task cannot (yet) exit.
1304 * But remember that that these are parent<->child context relations, and
1305 * migration does not affect children, therefore these two orderings should not
1306 * interact.
1308 * The change in perf_event::ctx does not affect children (as claimed above)
1309 * because the sys_perf_event_open() case will install a new event and break
1310 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1311 * concerned with cpuctx and that doesn't have children.
1313 * The places that change perf_event::ctx will issue:
1315 * perf_remove_from_context();
1316 * synchronize_rcu();
1317 * perf_install_in_context();
1319 * to affect the change. The remove_from_context() + synchronize_rcu() should
1320 * quiesce the event, after which we can install it in the new location. This
1321 * means that only external vectors (perf_fops, prctl) can perturb the event
1322 * while in transit. Therefore all such accessors should also acquire
1323 * perf_event_context::mutex to serialize against this.
1325 * However; because event->ctx can change while we're waiting to acquire
1326 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1327 * function.
1329 * Lock order:
1330 * exec_update_lock
1331 * task_struct::perf_event_mutex
1332 * perf_event_context::mutex
1333 * perf_event::child_mutex;
1334 * perf_event_context::lock
1335 * perf_event::mmap_mutex
1336 * mmap_lock
1337 * perf_addr_filters_head::lock
1339 * cpu_hotplug_lock
1340 * pmus_lock
1341 * cpuctx->mutex / perf_event_context::mutex
1343 static struct perf_event_context *
1344 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1346 struct perf_event_context *ctx;
1348 again:
1349 rcu_read_lock();
1350 ctx = READ_ONCE(event->ctx);
1351 if (!refcount_inc_not_zero(&ctx->refcount)) {
1352 rcu_read_unlock();
1353 goto again;
1355 rcu_read_unlock();
1357 mutex_lock_nested(&ctx->mutex, nesting);
1358 if (event->ctx != ctx) {
1359 mutex_unlock(&ctx->mutex);
1360 put_ctx(ctx);
1361 goto again;
1364 return ctx;
1367 static inline struct perf_event_context *
1368 perf_event_ctx_lock(struct perf_event *event)
1370 return perf_event_ctx_lock_nested(event, 0);
1373 static void perf_event_ctx_unlock(struct perf_event *event,
1374 struct perf_event_context *ctx)
1376 mutex_unlock(&ctx->mutex);
1377 put_ctx(ctx);
1381 * This must be done under the ctx->lock, such as to serialize against
1382 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1383 * calling scheduler related locks and ctx->lock nests inside those.
1385 static __must_check struct perf_event_context *
1386 unclone_ctx(struct perf_event_context *ctx)
1388 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1390 lockdep_assert_held(&ctx->lock);
1392 if (parent_ctx)
1393 ctx->parent_ctx = NULL;
1394 ctx->generation++;
1396 return parent_ctx;
1399 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1400 enum pid_type type)
1402 u32 nr;
1404 * only top level events have the pid namespace they were created in
1406 if (event->parent)
1407 event = event->parent;
1409 nr = __task_pid_nr_ns(p, type, event->ns);
1410 /* avoid -1 if it is idle thread or runs in another ns */
1411 if (!nr && !pid_alive(p))
1412 nr = -1;
1413 return nr;
1416 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1418 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1421 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1423 return perf_event_pid_type(event, p, PIDTYPE_PID);
1427 * If we inherit events we want to return the parent event id
1428 * to userspace.
1430 static u64 primary_event_id(struct perf_event *event)
1432 u64 id = event->id;
1434 if (event->parent)
1435 id = event->parent->id;
1437 return id;
1441 * Get the perf_event_context for a task and lock it.
1443 * This has to cope with with the fact that until it is locked,
1444 * the context could get moved to another task.
1446 static struct perf_event_context *
1447 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1449 struct perf_event_context *ctx;
1451 retry:
1453 * One of the few rules of preemptible RCU is that one cannot do
1454 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1455 * part of the read side critical section was irqs-enabled -- see
1456 * rcu_read_unlock_special().
1458 * Since ctx->lock nests under rq->lock we must ensure the entire read
1459 * side critical section has interrupts disabled.
1461 local_irq_save(*flags);
1462 rcu_read_lock();
1463 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1464 if (ctx) {
1466 * If this context is a clone of another, it might
1467 * get swapped for another underneath us by
1468 * perf_event_task_sched_out, though the
1469 * rcu_read_lock() protects us from any context
1470 * getting freed. Lock the context and check if it
1471 * got swapped before we could get the lock, and retry
1472 * if so. If we locked the right context, then it
1473 * can't get swapped on us any more.
1475 raw_spin_lock(&ctx->lock);
1476 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1477 raw_spin_unlock(&ctx->lock);
1478 rcu_read_unlock();
1479 local_irq_restore(*flags);
1480 goto retry;
1483 if (ctx->task == TASK_TOMBSTONE ||
1484 !refcount_inc_not_zero(&ctx->refcount)) {
1485 raw_spin_unlock(&ctx->lock);
1486 ctx = NULL;
1487 } else {
1488 WARN_ON_ONCE(ctx->task != task);
1491 rcu_read_unlock();
1492 if (!ctx)
1493 local_irq_restore(*flags);
1494 return ctx;
1498 * Get the context for a task and increment its pin_count so it
1499 * can't get swapped to another task. This also increments its
1500 * reference count so that the context can't get freed.
1502 static struct perf_event_context *
1503 perf_pin_task_context(struct task_struct *task, int ctxn)
1505 struct perf_event_context *ctx;
1506 unsigned long flags;
1508 ctx = perf_lock_task_context(task, ctxn, &flags);
1509 if (ctx) {
1510 ++ctx->pin_count;
1511 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1513 return ctx;
1516 static void perf_unpin_context(struct perf_event_context *ctx)
1518 unsigned long flags;
1520 raw_spin_lock_irqsave(&ctx->lock, flags);
1521 --ctx->pin_count;
1522 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1526 * Update the record of the current time in a context.
1528 static void update_context_time(struct perf_event_context *ctx)
1530 u64 now = perf_clock();
1532 ctx->time += now - ctx->timestamp;
1533 ctx->timestamp = now;
1536 static u64 perf_event_time(struct perf_event *event)
1538 struct perf_event_context *ctx = event->ctx;
1540 if (is_cgroup_event(event))
1541 return perf_cgroup_event_time(event);
1543 return ctx ? ctx->time : 0;
1546 static enum event_type_t get_event_type(struct perf_event *event)
1548 struct perf_event_context *ctx = event->ctx;
1549 enum event_type_t event_type;
1551 lockdep_assert_held(&ctx->lock);
1554 * It's 'group type', really, because if our group leader is
1555 * pinned, so are we.
1557 if (event->group_leader != event)
1558 event = event->group_leader;
1560 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1561 if (!ctx->task)
1562 event_type |= EVENT_CPU;
1564 return event_type;
1568 * Helper function to initialize event group nodes.
1570 static void init_event_group(struct perf_event *event)
1572 RB_CLEAR_NODE(&event->group_node);
1573 event->group_index = 0;
1577 * Extract pinned or flexible groups from the context
1578 * based on event attrs bits.
1580 static struct perf_event_groups *
1581 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1583 if (event->attr.pinned)
1584 return &ctx->pinned_groups;
1585 else
1586 return &ctx->flexible_groups;
1590 * Helper function to initializes perf_event_group trees.
1592 static void perf_event_groups_init(struct perf_event_groups *groups)
1594 groups->tree = RB_ROOT;
1595 groups->index = 0;
1599 * Compare function for event groups;
1601 * Implements complex key that first sorts by CPU and then by virtual index
1602 * which provides ordering when rotating groups for the same CPU.
1604 static bool
1605 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1607 if (left->cpu < right->cpu)
1608 return true;
1609 if (left->cpu > right->cpu)
1610 return false;
1612 #ifdef CONFIG_CGROUP_PERF
1613 if (left->cgrp != right->cgrp) {
1614 if (!left->cgrp || !left->cgrp->css.cgroup) {
1616 * Left has no cgroup but right does, no cgroups come
1617 * first.
1619 return true;
1621 if (!right->cgrp || !right->cgrp->css.cgroup) {
1623 * Right has no cgroup but left does, no cgroups come
1624 * first.
1626 return false;
1628 /* Two dissimilar cgroups, order by id. */
1629 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1630 return true;
1632 return false;
1634 #endif
1636 if (left->group_index < right->group_index)
1637 return true;
1638 if (left->group_index > right->group_index)
1639 return false;
1641 return false;
1645 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1646 * key (see perf_event_groups_less). This places it last inside the CPU
1647 * subtree.
1649 static void
1650 perf_event_groups_insert(struct perf_event_groups *groups,
1651 struct perf_event *event)
1653 struct perf_event *node_event;
1654 struct rb_node *parent;
1655 struct rb_node **node;
1657 event->group_index = ++groups->index;
1659 node = &groups->tree.rb_node;
1660 parent = *node;
1662 while (*node) {
1663 parent = *node;
1664 node_event = container_of(*node, struct perf_event, group_node);
1666 if (perf_event_groups_less(event, node_event))
1667 node = &parent->rb_left;
1668 else
1669 node = &parent->rb_right;
1672 rb_link_node(&event->group_node, parent, node);
1673 rb_insert_color(&event->group_node, &groups->tree);
1677 * Helper function to insert event into the pinned or flexible groups.
1679 static void
1680 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1682 struct perf_event_groups *groups;
1684 groups = get_event_groups(event, ctx);
1685 perf_event_groups_insert(groups, event);
1689 * Delete a group from a tree.
1691 static void
1692 perf_event_groups_delete(struct perf_event_groups *groups,
1693 struct perf_event *event)
1695 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1696 RB_EMPTY_ROOT(&groups->tree));
1698 rb_erase(&event->group_node, &groups->tree);
1699 init_event_group(event);
1703 * Helper function to delete event from its groups.
1705 static void
1706 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1708 struct perf_event_groups *groups;
1710 groups = get_event_groups(event, ctx);
1711 perf_event_groups_delete(groups, event);
1715 * Get the leftmost event in the cpu/cgroup subtree.
1717 static struct perf_event *
1718 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1719 struct cgroup *cgrp)
1721 struct perf_event *node_event = NULL, *match = NULL;
1722 struct rb_node *node = groups->tree.rb_node;
1723 #ifdef CONFIG_CGROUP_PERF
1724 u64 node_cgrp_id, cgrp_id = 0;
1726 if (cgrp)
1727 cgrp_id = cgrp->kn->id;
1728 #endif
1730 while (node) {
1731 node_event = container_of(node, struct perf_event, group_node);
1733 if (cpu < node_event->cpu) {
1734 node = node->rb_left;
1735 continue;
1737 if (cpu > node_event->cpu) {
1738 node = node->rb_right;
1739 continue;
1741 #ifdef CONFIG_CGROUP_PERF
1742 node_cgrp_id = 0;
1743 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1744 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1746 if (cgrp_id < node_cgrp_id) {
1747 node = node->rb_left;
1748 continue;
1750 if (cgrp_id > node_cgrp_id) {
1751 node = node->rb_right;
1752 continue;
1754 #endif
1755 match = node_event;
1756 node = node->rb_left;
1759 return match;
1763 * Like rb_entry_next_safe() for the @cpu subtree.
1765 static struct perf_event *
1766 perf_event_groups_next(struct perf_event *event)
1768 struct perf_event *next;
1769 #ifdef CONFIG_CGROUP_PERF
1770 u64 curr_cgrp_id = 0;
1771 u64 next_cgrp_id = 0;
1772 #endif
1774 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1775 if (next == NULL || next->cpu != event->cpu)
1776 return NULL;
1778 #ifdef CONFIG_CGROUP_PERF
1779 if (event->cgrp && event->cgrp->css.cgroup)
1780 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1782 if (next->cgrp && next->cgrp->css.cgroup)
1783 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1785 if (curr_cgrp_id != next_cgrp_id)
1786 return NULL;
1787 #endif
1788 return next;
1792 * Iterate through the whole groups tree.
1794 #define perf_event_groups_for_each(event, groups) \
1795 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1796 typeof(*event), group_node); event; \
1797 event = rb_entry_safe(rb_next(&event->group_node), \
1798 typeof(*event), group_node))
1801 * Add an event from the lists for its context.
1802 * Must be called with ctx->mutex and ctx->lock held.
1804 static void
1805 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1807 lockdep_assert_held(&ctx->lock);
1809 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1810 event->attach_state |= PERF_ATTACH_CONTEXT;
1812 event->tstamp = perf_event_time(event);
1815 * If we're a stand alone event or group leader, we go to the context
1816 * list, group events are kept attached to the group so that
1817 * perf_group_detach can, at all times, locate all siblings.
1819 if (event->group_leader == event) {
1820 event->group_caps = event->event_caps;
1821 add_event_to_groups(event, ctx);
1824 list_add_rcu(&event->event_entry, &ctx->event_list);
1825 ctx->nr_events++;
1826 if (event->attr.inherit_stat)
1827 ctx->nr_stat++;
1829 if (event->state > PERF_EVENT_STATE_OFF)
1830 perf_cgroup_event_enable(event, ctx);
1832 ctx->generation++;
1836 * Initialize event state based on the perf_event_attr::disabled.
1838 static inline void perf_event__state_init(struct perf_event *event)
1840 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1841 PERF_EVENT_STATE_INACTIVE;
1844 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1846 int entry = sizeof(u64); /* value */
1847 int size = 0;
1848 int nr = 1;
1850 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1851 size += sizeof(u64);
1853 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1854 size += sizeof(u64);
1856 if (event->attr.read_format & PERF_FORMAT_ID)
1857 entry += sizeof(u64);
1859 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1860 nr += nr_siblings;
1861 size += sizeof(u64);
1864 size += entry * nr;
1865 event->read_size = size;
1868 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1870 struct perf_sample_data *data;
1871 u16 size = 0;
1873 if (sample_type & PERF_SAMPLE_IP)
1874 size += sizeof(data->ip);
1876 if (sample_type & PERF_SAMPLE_ADDR)
1877 size += sizeof(data->addr);
1879 if (sample_type & PERF_SAMPLE_PERIOD)
1880 size += sizeof(data->period);
1882 if (sample_type & PERF_SAMPLE_WEIGHT)
1883 size += sizeof(data->weight);
1885 if (sample_type & PERF_SAMPLE_READ)
1886 size += event->read_size;
1888 if (sample_type & PERF_SAMPLE_DATA_SRC)
1889 size += sizeof(data->data_src.val);
1891 if (sample_type & PERF_SAMPLE_TRANSACTION)
1892 size += sizeof(data->txn);
1894 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1895 size += sizeof(data->phys_addr);
1897 if (sample_type & PERF_SAMPLE_CGROUP)
1898 size += sizeof(data->cgroup);
1900 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1901 size += sizeof(data->data_page_size);
1903 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1904 size += sizeof(data->code_page_size);
1906 event->header_size = size;
1910 * Called at perf_event creation and when events are attached/detached from a
1911 * group.
1913 static void perf_event__header_size(struct perf_event *event)
1915 __perf_event_read_size(event,
1916 event->group_leader->nr_siblings);
1917 __perf_event_header_size(event, event->attr.sample_type);
1920 static void perf_event__id_header_size(struct perf_event *event)
1922 struct perf_sample_data *data;
1923 u64 sample_type = event->attr.sample_type;
1924 u16 size = 0;
1926 if (sample_type & PERF_SAMPLE_TID)
1927 size += sizeof(data->tid_entry);
1929 if (sample_type & PERF_SAMPLE_TIME)
1930 size += sizeof(data->time);
1932 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1933 size += sizeof(data->id);
1935 if (sample_type & PERF_SAMPLE_ID)
1936 size += sizeof(data->id);
1938 if (sample_type & PERF_SAMPLE_STREAM_ID)
1939 size += sizeof(data->stream_id);
1941 if (sample_type & PERF_SAMPLE_CPU)
1942 size += sizeof(data->cpu_entry);
1944 event->id_header_size = size;
1947 static bool perf_event_validate_size(struct perf_event *event)
1950 * The values computed here will be over-written when we actually
1951 * attach the event.
1953 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1954 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1955 perf_event__id_header_size(event);
1958 * Sum the lot; should not exceed the 64k limit we have on records.
1959 * Conservative limit to allow for callchains and other variable fields.
1961 if (event->read_size + event->header_size +
1962 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1963 return false;
1965 return true;
1968 static void perf_group_attach(struct perf_event *event)
1970 struct perf_event *group_leader = event->group_leader, *pos;
1972 lockdep_assert_held(&event->ctx->lock);
1975 * We can have double attach due to group movement in perf_event_open.
1977 if (event->attach_state & PERF_ATTACH_GROUP)
1978 return;
1980 event->attach_state |= PERF_ATTACH_GROUP;
1982 if (group_leader == event)
1983 return;
1985 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1987 group_leader->group_caps &= event->event_caps;
1989 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1990 group_leader->nr_siblings++;
1992 perf_event__header_size(group_leader);
1994 for_each_sibling_event(pos, group_leader)
1995 perf_event__header_size(pos);
1999 * Remove an event from the lists for its context.
2000 * Must be called with ctx->mutex and ctx->lock held.
2002 static void
2003 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2005 WARN_ON_ONCE(event->ctx != ctx);
2006 lockdep_assert_held(&ctx->lock);
2009 * We can have double detach due to exit/hot-unplug + close.
2011 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2012 return;
2014 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2016 ctx->nr_events--;
2017 if (event->attr.inherit_stat)
2018 ctx->nr_stat--;
2020 list_del_rcu(&event->event_entry);
2022 if (event->group_leader == event)
2023 del_event_from_groups(event, ctx);
2026 * If event was in error state, then keep it
2027 * that way, otherwise bogus counts will be
2028 * returned on read(). The only way to get out
2029 * of error state is by explicit re-enabling
2030 * of the event
2032 if (event->state > PERF_EVENT_STATE_OFF) {
2033 perf_cgroup_event_disable(event, ctx);
2034 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2037 ctx->generation++;
2040 static int
2041 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2043 if (!has_aux(aux_event))
2044 return 0;
2046 if (!event->pmu->aux_output_match)
2047 return 0;
2049 return event->pmu->aux_output_match(aux_event);
2052 static void put_event(struct perf_event *event);
2053 static void event_sched_out(struct perf_event *event,
2054 struct perf_cpu_context *cpuctx,
2055 struct perf_event_context *ctx);
2057 static void perf_put_aux_event(struct perf_event *event)
2059 struct perf_event_context *ctx = event->ctx;
2060 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2061 struct perf_event *iter;
2064 * If event uses aux_event tear down the link
2066 if (event->aux_event) {
2067 iter = event->aux_event;
2068 event->aux_event = NULL;
2069 put_event(iter);
2070 return;
2074 * If the event is an aux_event, tear down all links to
2075 * it from other events.
2077 for_each_sibling_event(iter, event->group_leader) {
2078 if (iter->aux_event != event)
2079 continue;
2081 iter->aux_event = NULL;
2082 put_event(event);
2085 * If it's ACTIVE, schedule it out and put it into ERROR
2086 * state so that we don't try to schedule it again. Note
2087 * that perf_event_enable() will clear the ERROR status.
2089 event_sched_out(iter, cpuctx, ctx);
2090 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2094 static bool perf_need_aux_event(struct perf_event *event)
2096 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2099 static int perf_get_aux_event(struct perf_event *event,
2100 struct perf_event *group_leader)
2103 * Our group leader must be an aux event if we want to be
2104 * an aux_output. This way, the aux event will precede its
2105 * aux_output events in the group, and therefore will always
2106 * schedule first.
2108 if (!group_leader)
2109 return 0;
2112 * aux_output and aux_sample_size are mutually exclusive.
2114 if (event->attr.aux_output && event->attr.aux_sample_size)
2115 return 0;
2117 if (event->attr.aux_output &&
2118 !perf_aux_output_match(event, group_leader))
2119 return 0;
2121 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2122 return 0;
2124 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2125 return 0;
2128 * Link aux_outputs to their aux event; this is undone in
2129 * perf_group_detach() by perf_put_aux_event(). When the
2130 * group in torn down, the aux_output events loose their
2131 * link to the aux_event and can't schedule any more.
2133 event->aux_event = group_leader;
2135 return 1;
2138 static inline struct list_head *get_event_list(struct perf_event *event)
2140 struct perf_event_context *ctx = event->ctx;
2141 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2145 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2146 * cannot exist on their own, schedule them out and move them into the ERROR
2147 * state. Also see _perf_event_enable(), it will not be able to recover
2148 * this ERROR state.
2150 static inline void perf_remove_sibling_event(struct perf_event *event)
2152 struct perf_event_context *ctx = event->ctx;
2153 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2155 event_sched_out(event, cpuctx, ctx);
2156 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2159 static void perf_group_detach(struct perf_event *event)
2161 struct perf_event *leader = event->group_leader;
2162 struct perf_event *sibling, *tmp;
2163 struct perf_event_context *ctx = event->ctx;
2165 lockdep_assert_held(&ctx->lock);
2168 * We can have double detach due to exit/hot-unplug + close.
2170 if (!(event->attach_state & PERF_ATTACH_GROUP))
2171 return;
2173 event->attach_state &= ~PERF_ATTACH_GROUP;
2175 perf_put_aux_event(event);
2178 * If this is a sibling, remove it from its group.
2180 if (leader != event) {
2181 list_del_init(&event->sibling_list);
2182 event->group_leader->nr_siblings--;
2183 goto out;
2187 * If this was a group event with sibling events then
2188 * upgrade the siblings to singleton events by adding them
2189 * to whatever list we are on.
2191 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2193 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2194 perf_remove_sibling_event(sibling);
2196 sibling->group_leader = sibling;
2197 list_del_init(&sibling->sibling_list);
2199 /* Inherit group flags from the previous leader */
2200 sibling->group_caps = event->group_caps;
2202 if (!RB_EMPTY_NODE(&event->group_node)) {
2203 add_event_to_groups(sibling, event->ctx);
2205 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2206 list_add_tail(&sibling->active_list, get_event_list(sibling));
2209 WARN_ON_ONCE(sibling->ctx != event->ctx);
2212 out:
2213 for_each_sibling_event(tmp, leader)
2214 perf_event__header_size(tmp);
2216 perf_event__header_size(leader);
2219 static bool is_orphaned_event(struct perf_event *event)
2221 return event->state == PERF_EVENT_STATE_DEAD;
2224 static inline int __pmu_filter_match(struct perf_event *event)
2226 struct pmu *pmu = event->pmu;
2227 return pmu->filter_match ? pmu->filter_match(event) : 1;
2231 * Check whether we should attempt to schedule an event group based on
2232 * PMU-specific filtering. An event group can consist of HW and SW events,
2233 * potentially with a SW leader, so we must check all the filters, to
2234 * determine whether a group is schedulable:
2236 static inline int pmu_filter_match(struct perf_event *event)
2238 struct perf_event *sibling;
2240 if (!__pmu_filter_match(event))
2241 return 0;
2243 for_each_sibling_event(sibling, event) {
2244 if (!__pmu_filter_match(sibling))
2245 return 0;
2248 return 1;
2251 static inline int
2252 event_filter_match(struct perf_event *event)
2254 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2255 perf_cgroup_match(event) && pmu_filter_match(event);
2258 static void
2259 event_sched_out(struct perf_event *event,
2260 struct perf_cpu_context *cpuctx,
2261 struct perf_event_context *ctx)
2263 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2265 WARN_ON_ONCE(event->ctx != ctx);
2266 lockdep_assert_held(&ctx->lock);
2268 if (event->state != PERF_EVENT_STATE_ACTIVE)
2269 return;
2272 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2273 * we can schedule events _OUT_ individually through things like
2274 * __perf_remove_from_context().
2276 list_del_init(&event->active_list);
2278 perf_pmu_disable(event->pmu);
2280 event->pmu->del(event, 0);
2281 event->oncpu = -1;
2283 if (READ_ONCE(event->pending_disable) >= 0) {
2284 WRITE_ONCE(event->pending_disable, -1);
2285 perf_cgroup_event_disable(event, ctx);
2286 state = PERF_EVENT_STATE_OFF;
2288 perf_event_set_state(event, state);
2290 if (!is_software_event(event))
2291 cpuctx->active_oncpu--;
2292 if (!--ctx->nr_active)
2293 perf_event_ctx_deactivate(ctx);
2294 if (event->attr.freq && event->attr.sample_freq)
2295 ctx->nr_freq--;
2296 if (event->attr.exclusive || !cpuctx->active_oncpu)
2297 cpuctx->exclusive = 0;
2299 perf_pmu_enable(event->pmu);
2302 static void
2303 group_sched_out(struct perf_event *group_event,
2304 struct perf_cpu_context *cpuctx,
2305 struct perf_event_context *ctx)
2307 struct perf_event *event;
2309 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2310 return;
2312 perf_pmu_disable(ctx->pmu);
2314 event_sched_out(group_event, cpuctx, ctx);
2317 * Schedule out siblings (if any):
2319 for_each_sibling_event(event, group_event)
2320 event_sched_out(event, cpuctx, ctx);
2322 perf_pmu_enable(ctx->pmu);
2325 #define DETACH_GROUP 0x01UL
2328 * Cross CPU call to remove a performance event
2330 * We disable the event on the hardware level first. After that we
2331 * remove it from the context list.
2333 static void
2334 __perf_remove_from_context(struct perf_event *event,
2335 struct perf_cpu_context *cpuctx,
2336 struct perf_event_context *ctx,
2337 void *info)
2339 unsigned long flags = (unsigned long)info;
2341 if (ctx->is_active & EVENT_TIME) {
2342 update_context_time(ctx);
2343 update_cgrp_time_from_cpuctx(cpuctx);
2346 event_sched_out(event, cpuctx, ctx);
2347 if (flags & DETACH_GROUP)
2348 perf_group_detach(event);
2349 list_del_event(event, ctx);
2351 if (!ctx->nr_events && ctx->is_active) {
2352 ctx->is_active = 0;
2353 ctx->rotate_necessary = 0;
2354 if (ctx->task) {
2355 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2356 cpuctx->task_ctx = NULL;
2362 * Remove the event from a task's (or a CPU's) list of events.
2364 * If event->ctx is a cloned context, callers must make sure that
2365 * every task struct that event->ctx->task could possibly point to
2366 * remains valid. This is OK when called from perf_release since
2367 * that only calls us on the top-level context, which can't be a clone.
2368 * When called from perf_event_exit_task, it's OK because the
2369 * context has been detached from its task.
2371 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2373 struct perf_event_context *ctx = event->ctx;
2375 lockdep_assert_held(&ctx->mutex);
2377 event_function_call(event, __perf_remove_from_context, (void *)flags);
2380 * The above event_function_call() can NO-OP when it hits
2381 * TASK_TOMBSTONE. In that case we must already have been detached
2382 * from the context (by perf_event_exit_event()) but the grouping
2383 * might still be in-tact.
2385 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2386 if ((flags & DETACH_GROUP) &&
2387 (event->attach_state & PERF_ATTACH_GROUP)) {
2389 * Since in that case we cannot possibly be scheduled, simply
2390 * detach now.
2392 raw_spin_lock_irq(&ctx->lock);
2393 perf_group_detach(event);
2394 raw_spin_unlock_irq(&ctx->lock);
2399 * Cross CPU call to disable a performance event
2401 static void __perf_event_disable(struct perf_event *event,
2402 struct perf_cpu_context *cpuctx,
2403 struct perf_event_context *ctx,
2404 void *info)
2406 if (event->state < PERF_EVENT_STATE_INACTIVE)
2407 return;
2409 if (ctx->is_active & EVENT_TIME) {
2410 update_context_time(ctx);
2411 update_cgrp_time_from_event(event);
2414 if (event == event->group_leader)
2415 group_sched_out(event, cpuctx, ctx);
2416 else
2417 event_sched_out(event, cpuctx, ctx);
2419 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2420 perf_cgroup_event_disable(event, ctx);
2424 * Disable an event.
2426 * If event->ctx is a cloned context, callers must make sure that
2427 * every task struct that event->ctx->task could possibly point to
2428 * remains valid. This condition is satisfied when called through
2429 * perf_event_for_each_child or perf_event_for_each because they
2430 * hold the top-level event's child_mutex, so any descendant that
2431 * goes to exit will block in perf_event_exit_event().
2433 * When called from perf_pending_event it's OK because event->ctx
2434 * is the current context on this CPU and preemption is disabled,
2435 * hence we can't get into perf_event_task_sched_out for this context.
2437 static void _perf_event_disable(struct perf_event *event)
2439 struct perf_event_context *ctx = event->ctx;
2441 raw_spin_lock_irq(&ctx->lock);
2442 if (event->state <= PERF_EVENT_STATE_OFF) {
2443 raw_spin_unlock_irq(&ctx->lock);
2444 return;
2446 raw_spin_unlock_irq(&ctx->lock);
2448 event_function_call(event, __perf_event_disable, NULL);
2451 void perf_event_disable_local(struct perf_event *event)
2453 event_function_local(event, __perf_event_disable, NULL);
2457 * Strictly speaking kernel users cannot create groups and therefore this
2458 * interface does not need the perf_event_ctx_lock() magic.
2460 void perf_event_disable(struct perf_event *event)
2462 struct perf_event_context *ctx;
2464 ctx = perf_event_ctx_lock(event);
2465 _perf_event_disable(event);
2466 perf_event_ctx_unlock(event, ctx);
2468 EXPORT_SYMBOL_GPL(perf_event_disable);
2470 void perf_event_disable_inatomic(struct perf_event *event)
2472 WRITE_ONCE(event->pending_disable, smp_processor_id());
2473 /* can fail, see perf_pending_event_disable() */
2474 irq_work_queue(&event->pending);
2477 static void perf_set_shadow_time(struct perf_event *event,
2478 struct perf_event_context *ctx)
2481 * use the correct time source for the time snapshot
2483 * We could get by without this by leveraging the
2484 * fact that to get to this function, the caller
2485 * has most likely already called update_context_time()
2486 * and update_cgrp_time_xx() and thus both timestamp
2487 * are identical (or very close). Given that tstamp is,
2488 * already adjusted for cgroup, we could say that:
2489 * tstamp - ctx->timestamp
2490 * is equivalent to
2491 * tstamp - cgrp->timestamp.
2493 * Then, in perf_output_read(), the calculation would
2494 * work with no changes because:
2495 * - event is guaranteed scheduled in
2496 * - no scheduled out in between
2497 * - thus the timestamp would be the same
2499 * But this is a bit hairy.
2501 * So instead, we have an explicit cgroup call to remain
2502 * within the time time source all along. We believe it
2503 * is cleaner and simpler to understand.
2505 if (is_cgroup_event(event))
2506 perf_cgroup_set_shadow_time(event, event->tstamp);
2507 else
2508 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2511 #define MAX_INTERRUPTS (~0ULL)
2513 static void perf_log_throttle(struct perf_event *event, int enable);
2514 static void perf_log_itrace_start(struct perf_event *event);
2516 static int
2517 event_sched_in(struct perf_event *event,
2518 struct perf_cpu_context *cpuctx,
2519 struct perf_event_context *ctx)
2521 int ret = 0;
2523 WARN_ON_ONCE(event->ctx != ctx);
2525 lockdep_assert_held(&ctx->lock);
2527 if (event->state <= PERF_EVENT_STATE_OFF)
2528 return 0;
2530 WRITE_ONCE(event->oncpu, smp_processor_id());
2532 * Order event::oncpu write to happen before the ACTIVE state is
2533 * visible. This allows perf_event_{stop,read}() to observe the correct
2534 * ->oncpu if it sees ACTIVE.
2536 smp_wmb();
2537 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2540 * Unthrottle events, since we scheduled we might have missed several
2541 * ticks already, also for a heavily scheduling task there is little
2542 * guarantee it'll get a tick in a timely manner.
2544 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2545 perf_log_throttle(event, 1);
2546 event->hw.interrupts = 0;
2549 perf_pmu_disable(event->pmu);
2551 perf_set_shadow_time(event, ctx);
2553 perf_log_itrace_start(event);
2555 if (event->pmu->add(event, PERF_EF_START)) {
2556 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2557 event->oncpu = -1;
2558 ret = -EAGAIN;
2559 goto out;
2562 if (!is_software_event(event))
2563 cpuctx->active_oncpu++;
2564 if (!ctx->nr_active++)
2565 perf_event_ctx_activate(ctx);
2566 if (event->attr.freq && event->attr.sample_freq)
2567 ctx->nr_freq++;
2569 if (event->attr.exclusive)
2570 cpuctx->exclusive = 1;
2572 out:
2573 perf_pmu_enable(event->pmu);
2575 return ret;
2578 static int
2579 group_sched_in(struct perf_event *group_event,
2580 struct perf_cpu_context *cpuctx,
2581 struct perf_event_context *ctx)
2583 struct perf_event *event, *partial_group = NULL;
2584 struct pmu *pmu = ctx->pmu;
2586 if (group_event->state == PERF_EVENT_STATE_OFF)
2587 return 0;
2589 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2591 if (event_sched_in(group_event, cpuctx, ctx))
2592 goto error;
2595 * Schedule in siblings as one group (if any):
2597 for_each_sibling_event(event, group_event) {
2598 if (event_sched_in(event, cpuctx, ctx)) {
2599 partial_group = event;
2600 goto group_error;
2604 if (!pmu->commit_txn(pmu))
2605 return 0;
2607 group_error:
2609 * Groups can be scheduled in as one unit only, so undo any
2610 * partial group before returning:
2611 * The events up to the failed event are scheduled out normally.
2613 for_each_sibling_event(event, group_event) {
2614 if (event == partial_group)
2615 break;
2617 event_sched_out(event, cpuctx, ctx);
2619 event_sched_out(group_event, cpuctx, ctx);
2621 error:
2622 pmu->cancel_txn(pmu);
2623 return -EAGAIN;
2627 * Work out whether we can put this event group on the CPU now.
2629 static int group_can_go_on(struct perf_event *event,
2630 struct perf_cpu_context *cpuctx,
2631 int can_add_hw)
2634 * Groups consisting entirely of software events can always go on.
2636 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2637 return 1;
2639 * If an exclusive group is already on, no other hardware
2640 * events can go on.
2642 if (cpuctx->exclusive)
2643 return 0;
2645 * If this group is exclusive and there are already
2646 * events on the CPU, it can't go on.
2648 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2649 return 0;
2651 * Otherwise, try to add it if all previous groups were able
2652 * to go on.
2654 return can_add_hw;
2657 static void add_event_to_ctx(struct perf_event *event,
2658 struct perf_event_context *ctx)
2660 list_add_event(event, ctx);
2661 perf_group_attach(event);
2664 static void ctx_sched_out(struct perf_event_context *ctx,
2665 struct perf_cpu_context *cpuctx,
2666 enum event_type_t event_type);
2667 static void
2668 ctx_sched_in(struct perf_event_context *ctx,
2669 struct perf_cpu_context *cpuctx,
2670 enum event_type_t event_type,
2671 struct task_struct *task);
2673 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2674 struct perf_event_context *ctx,
2675 enum event_type_t event_type)
2677 if (!cpuctx->task_ctx)
2678 return;
2680 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2681 return;
2683 ctx_sched_out(ctx, cpuctx, event_type);
2686 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2687 struct perf_event_context *ctx,
2688 struct task_struct *task)
2690 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2691 if (ctx)
2692 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2693 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2694 if (ctx)
2695 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2699 * We want to maintain the following priority of scheduling:
2700 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2701 * - task pinned (EVENT_PINNED)
2702 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2703 * - task flexible (EVENT_FLEXIBLE).
2705 * In order to avoid unscheduling and scheduling back in everything every
2706 * time an event is added, only do it for the groups of equal priority and
2707 * below.
2709 * This can be called after a batch operation on task events, in which case
2710 * event_type is a bit mask of the types of events involved. For CPU events,
2711 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2713 static void ctx_resched(struct perf_cpu_context *cpuctx,
2714 struct perf_event_context *task_ctx,
2715 enum event_type_t event_type)
2717 enum event_type_t ctx_event_type;
2718 bool cpu_event = !!(event_type & EVENT_CPU);
2721 * If pinned groups are involved, flexible groups also need to be
2722 * scheduled out.
2724 if (event_type & EVENT_PINNED)
2725 event_type |= EVENT_FLEXIBLE;
2727 ctx_event_type = event_type & EVENT_ALL;
2729 perf_pmu_disable(cpuctx->ctx.pmu);
2730 if (task_ctx)
2731 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2734 * Decide which cpu ctx groups to schedule out based on the types
2735 * of events that caused rescheduling:
2736 * - EVENT_CPU: schedule out corresponding groups;
2737 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2738 * - otherwise, do nothing more.
2740 if (cpu_event)
2741 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2742 else if (ctx_event_type & EVENT_PINNED)
2743 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2745 perf_event_sched_in(cpuctx, task_ctx, current);
2746 perf_pmu_enable(cpuctx->ctx.pmu);
2749 void perf_pmu_resched(struct pmu *pmu)
2751 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2752 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2754 perf_ctx_lock(cpuctx, task_ctx);
2755 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2756 perf_ctx_unlock(cpuctx, task_ctx);
2760 * Cross CPU call to install and enable a performance event
2762 * Very similar to remote_function() + event_function() but cannot assume that
2763 * things like ctx->is_active and cpuctx->task_ctx are set.
2765 static int __perf_install_in_context(void *info)
2767 struct perf_event *event = info;
2768 struct perf_event_context *ctx = event->ctx;
2769 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2770 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2771 bool reprogram = true;
2772 int ret = 0;
2774 raw_spin_lock(&cpuctx->ctx.lock);
2775 if (ctx->task) {
2776 raw_spin_lock(&ctx->lock);
2777 task_ctx = ctx;
2779 reprogram = (ctx->task == current);
2782 * If the task is running, it must be running on this CPU,
2783 * otherwise we cannot reprogram things.
2785 * If its not running, we don't care, ctx->lock will
2786 * serialize against it becoming runnable.
2788 if (task_curr(ctx->task) && !reprogram) {
2789 ret = -ESRCH;
2790 goto unlock;
2793 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2794 } else if (task_ctx) {
2795 raw_spin_lock(&task_ctx->lock);
2798 #ifdef CONFIG_CGROUP_PERF
2799 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2801 * If the current cgroup doesn't match the event's
2802 * cgroup, we should not try to schedule it.
2804 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2805 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2806 event->cgrp->css.cgroup);
2808 #endif
2810 if (reprogram) {
2811 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2812 add_event_to_ctx(event, ctx);
2813 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2814 } else {
2815 add_event_to_ctx(event, ctx);
2818 unlock:
2819 perf_ctx_unlock(cpuctx, task_ctx);
2821 return ret;
2824 static bool exclusive_event_installable(struct perf_event *event,
2825 struct perf_event_context *ctx);
2828 * Attach a performance event to a context.
2830 * Very similar to event_function_call, see comment there.
2832 static void
2833 perf_install_in_context(struct perf_event_context *ctx,
2834 struct perf_event *event,
2835 int cpu)
2837 struct task_struct *task = READ_ONCE(ctx->task);
2839 lockdep_assert_held(&ctx->mutex);
2841 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2843 if (event->cpu != -1)
2844 event->cpu = cpu;
2847 * Ensures that if we can observe event->ctx, both the event and ctx
2848 * will be 'complete'. See perf_iterate_sb_cpu().
2850 smp_store_release(&event->ctx, ctx);
2853 * perf_event_attr::disabled events will not run and can be initialized
2854 * without IPI. Except when this is the first event for the context, in
2855 * that case we need the magic of the IPI to set ctx->is_active.
2857 * The IOC_ENABLE that is sure to follow the creation of a disabled
2858 * event will issue the IPI and reprogram the hardware.
2860 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2861 raw_spin_lock_irq(&ctx->lock);
2862 if (ctx->task == TASK_TOMBSTONE) {
2863 raw_spin_unlock_irq(&ctx->lock);
2864 return;
2866 add_event_to_ctx(event, ctx);
2867 raw_spin_unlock_irq(&ctx->lock);
2868 return;
2871 if (!task) {
2872 cpu_function_call(cpu, __perf_install_in_context, event);
2873 return;
2877 * Should not happen, we validate the ctx is still alive before calling.
2879 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2880 return;
2883 * Installing events is tricky because we cannot rely on ctx->is_active
2884 * to be set in case this is the nr_events 0 -> 1 transition.
2886 * Instead we use task_curr(), which tells us if the task is running.
2887 * However, since we use task_curr() outside of rq::lock, we can race
2888 * against the actual state. This means the result can be wrong.
2890 * If we get a false positive, we retry, this is harmless.
2892 * If we get a false negative, things are complicated. If we are after
2893 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2894 * value must be correct. If we're before, it doesn't matter since
2895 * perf_event_context_sched_in() will program the counter.
2897 * However, this hinges on the remote context switch having observed
2898 * our task->perf_event_ctxp[] store, such that it will in fact take
2899 * ctx::lock in perf_event_context_sched_in().
2901 * We do this by task_function_call(), if the IPI fails to hit the task
2902 * we know any future context switch of task must see the
2903 * perf_event_ctpx[] store.
2907 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2908 * task_cpu() load, such that if the IPI then does not find the task
2909 * running, a future context switch of that task must observe the
2910 * store.
2912 smp_mb();
2913 again:
2914 if (!task_function_call(task, __perf_install_in_context, event))
2915 return;
2917 raw_spin_lock_irq(&ctx->lock);
2918 task = ctx->task;
2919 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2921 * Cannot happen because we already checked above (which also
2922 * cannot happen), and we hold ctx->mutex, which serializes us
2923 * against perf_event_exit_task_context().
2925 raw_spin_unlock_irq(&ctx->lock);
2926 return;
2929 * If the task is not running, ctx->lock will avoid it becoming so,
2930 * thus we can safely install the event.
2932 if (task_curr(task)) {
2933 raw_spin_unlock_irq(&ctx->lock);
2934 goto again;
2936 add_event_to_ctx(event, ctx);
2937 raw_spin_unlock_irq(&ctx->lock);
2941 * Cross CPU call to enable a performance event
2943 static void __perf_event_enable(struct perf_event *event,
2944 struct perf_cpu_context *cpuctx,
2945 struct perf_event_context *ctx,
2946 void *info)
2948 struct perf_event *leader = event->group_leader;
2949 struct perf_event_context *task_ctx;
2951 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2952 event->state <= PERF_EVENT_STATE_ERROR)
2953 return;
2955 if (ctx->is_active)
2956 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2958 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2959 perf_cgroup_event_enable(event, ctx);
2961 if (!ctx->is_active)
2962 return;
2964 if (!event_filter_match(event)) {
2965 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2966 return;
2970 * If the event is in a group and isn't the group leader,
2971 * then don't put it on unless the group is on.
2973 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2974 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2975 return;
2978 task_ctx = cpuctx->task_ctx;
2979 if (ctx->task)
2980 WARN_ON_ONCE(task_ctx != ctx);
2982 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2986 * Enable an event.
2988 * If event->ctx is a cloned context, callers must make sure that
2989 * every task struct that event->ctx->task could possibly point to
2990 * remains valid. This condition is satisfied when called through
2991 * perf_event_for_each_child or perf_event_for_each as described
2992 * for perf_event_disable.
2994 static void _perf_event_enable(struct perf_event *event)
2996 struct perf_event_context *ctx = event->ctx;
2998 raw_spin_lock_irq(&ctx->lock);
2999 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3000 event->state < PERF_EVENT_STATE_ERROR) {
3001 out:
3002 raw_spin_unlock_irq(&ctx->lock);
3003 return;
3007 * If the event is in error state, clear that first.
3009 * That way, if we see the event in error state below, we know that it
3010 * has gone back into error state, as distinct from the task having
3011 * been scheduled away before the cross-call arrived.
3013 if (event->state == PERF_EVENT_STATE_ERROR) {
3015 * Detached SIBLING events cannot leave ERROR state.
3017 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3018 event->group_leader == event)
3019 goto out;
3021 event->state = PERF_EVENT_STATE_OFF;
3023 raw_spin_unlock_irq(&ctx->lock);
3025 event_function_call(event, __perf_event_enable, NULL);
3029 * See perf_event_disable();
3031 void perf_event_enable(struct perf_event *event)
3033 struct perf_event_context *ctx;
3035 ctx = perf_event_ctx_lock(event);
3036 _perf_event_enable(event);
3037 perf_event_ctx_unlock(event, ctx);
3039 EXPORT_SYMBOL_GPL(perf_event_enable);
3041 struct stop_event_data {
3042 struct perf_event *event;
3043 unsigned int restart;
3046 static int __perf_event_stop(void *info)
3048 struct stop_event_data *sd = info;
3049 struct perf_event *event = sd->event;
3051 /* if it's already INACTIVE, do nothing */
3052 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3053 return 0;
3055 /* matches smp_wmb() in event_sched_in() */
3056 smp_rmb();
3059 * There is a window with interrupts enabled before we get here,
3060 * so we need to check again lest we try to stop another CPU's event.
3062 if (READ_ONCE(event->oncpu) != smp_processor_id())
3063 return -EAGAIN;
3065 event->pmu->stop(event, PERF_EF_UPDATE);
3068 * May race with the actual stop (through perf_pmu_output_stop()),
3069 * but it is only used for events with AUX ring buffer, and such
3070 * events will refuse to restart because of rb::aux_mmap_count==0,
3071 * see comments in perf_aux_output_begin().
3073 * Since this is happening on an event-local CPU, no trace is lost
3074 * while restarting.
3076 if (sd->restart)
3077 event->pmu->start(event, 0);
3079 return 0;
3082 static int perf_event_stop(struct perf_event *event, int restart)
3084 struct stop_event_data sd = {
3085 .event = event,
3086 .restart = restart,
3088 int ret = 0;
3090 do {
3091 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3092 return 0;
3094 /* matches smp_wmb() in event_sched_in() */
3095 smp_rmb();
3098 * We only want to restart ACTIVE events, so if the event goes
3099 * inactive here (event->oncpu==-1), there's nothing more to do;
3100 * fall through with ret==-ENXIO.
3102 ret = cpu_function_call(READ_ONCE(event->oncpu),
3103 __perf_event_stop, &sd);
3104 } while (ret == -EAGAIN);
3106 return ret;
3110 * In order to contain the amount of racy and tricky in the address filter
3111 * configuration management, it is a two part process:
3113 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3114 * we update the addresses of corresponding vmas in
3115 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3116 * (p2) when an event is scheduled in (pmu::add), it calls
3117 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3118 * if the generation has changed since the previous call.
3120 * If (p1) happens while the event is active, we restart it to force (p2).
3122 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3123 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3124 * ioctl;
3125 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3126 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3127 * for reading;
3128 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3129 * of exec.
3131 void perf_event_addr_filters_sync(struct perf_event *event)
3133 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3135 if (!has_addr_filter(event))
3136 return;
3138 raw_spin_lock(&ifh->lock);
3139 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3140 event->pmu->addr_filters_sync(event);
3141 event->hw.addr_filters_gen = event->addr_filters_gen;
3143 raw_spin_unlock(&ifh->lock);
3145 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3147 static int _perf_event_refresh(struct perf_event *event, int refresh)
3150 * not supported on inherited events
3152 if (event->attr.inherit || !is_sampling_event(event))
3153 return -EINVAL;
3155 atomic_add(refresh, &event->event_limit);
3156 _perf_event_enable(event);
3158 return 0;
3162 * See perf_event_disable()
3164 int perf_event_refresh(struct perf_event *event, int refresh)
3166 struct perf_event_context *ctx;
3167 int ret;
3169 ctx = perf_event_ctx_lock(event);
3170 ret = _perf_event_refresh(event, refresh);
3171 perf_event_ctx_unlock(event, ctx);
3173 return ret;
3175 EXPORT_SYMBOL_GPL(perf_event_refresh);
3177 static int perf_event_modify_breakpoint(struct perf_event *bp,
3178 struct perf_event_attr *attr)
3180 int err;
3182 _perf_event_disable(bp);
3184 err = modify_user_hw_breakpoint_check(bp, attr, true);
3186 if (!bp->attr.disabled)
3187 _perf_event_enable(bp);
3189 return err;
3192 static int perf_event_modify_attr(struct perf_event *event,
3193 struct perf_event_attr *attr)
3195 if (event->attr.type != attr->type)
3196 return -EINVAL;
3198 switch (event->attr.type) {
3199 case PERF_TYPE_BREAKPOINT:
3200 return perf_event_modify_breakpoint(event, attr);
3201 default:
3202 /* Place holder for future additions. */
3203 return -EOPNOTSUPP;
3207 static void ctx_sched_out(struct perf_event_context *ctx,
3208 struct perf_cpu_context *cpuctx,
3209 enum event_type_t event_type)
3211 struct perf_event *event, *tmp;
3212 int is_active = ctx->is_active;
3214 lockdep_assert_held(&ctx->lock);
3216 if (likely(!ctx->nr_events)) {
3218 * See __perf_remove_from_context().
3220 WARN_ON_ONCE(ctx->is_active);
3221 if (ctx->task)
3222 WARN_ON_ONCE(cpuctx->task_ctx);
3223 return;
3226 ctx->is_active &= ~event_type;
3227 if (!(ctx->is_active & EVENT_ALL))
3228 ctx->is_active = 0;
3230 if (ctx->task) {
3231 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3232 if (!ctx->is_active)
3233 cpuctx->task_ctx = NULL;
3237 * Always update time if it was set; not only when it changes.
3238 * Otherwise we can 'forget' to update time for any but the last
3239 * context we sched out. For example:
3241 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3242 * ctx_sched_out(.event_type = EVENT_PINNED)
3244 * would only update time for the pinned events.
3246 if (is_active & EVENT_TIME) {
3247 /* update (and stop) ctx time */
3248 update_context_time(ctx);
3249 update_cgrp_time_from_cpuctx(cpuctx);
3252 is_active ^= ctx->is_active; /* changed bits */
3254 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3255 return;
3257 perf_pmu_disable(ctx->pmu);
3258 if (is_active & EVENT_PINNED) {
3259 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3260 group_sched_out(event, cpuctx, ctx);
3263 if (is_active & EVENT_FLEXIBLE) {
3264 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3265 group_sched_out(event, cpuctx, ctx);
3268 * Since we cleared EVENT_FLEXIBLE, also clear
3269 * rotate_necessary, is will be reset by
3270 * ctx_flexible_sched_in() when needed.
3272 ctx->rotate_necessary = 0;
3274 perf_pmu_enable(ctx->pmu);
3278 * Test whether two contexts are equivalent, i.e. whether they have both been
3279 * cloned from the same version of the same context.
3281 * Equivalence is measured using a generation number in the context that is
3282 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3283 * and list_del_event().
3285 static int context_equiv(struct perf_event_context *ctx1,
3286 struct perf_event_context *ctx2)
3288 lockdep_assert_held(&ctx1->lock);
3289 lockdep_assert_held(&ctx2->lock);
3291 /* Pinning disables the swap optimization */
3292 if (ctx1->pin_count || ctx2->pin_count)
3293 return 0;
3295 /* If ctx1 is the parent of ctx2 */
3296 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3297 return 1;
3299 /* If ctx2 is the parent of ctx1 */
3300 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3301 return 1;
3304 * If ctx1 and ctx2 have the same parent; we flatten the parent
3305 * hierarchy, see perf_event_init_context().
3307 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3308 ctx1->parent_gen == ctx2->parent_gen)
3309 return 1;
3311 /* Unmatched */
3312 return 0;
3315 static void __perf_event_sync_stat(struct perf_event *event,
3316 struct perf_event *next_event)
3318 u64 value;
3320 if (!event->attr.inherit_stat)
3321 return;
3324 * Update the event value, we cannot use perf_event_read()
3325 * because we're in the middle of a context switch and have IRQs
3326 * disabled, which upsets smp_call_function_single(), however
3327 * we know the event must be on the current CPU, therefore we
3328 * don't need to use it.
3330 if (event->state == PERF_EVENT_STATE_ACTIVE)
3331 event->pmu->read(event);
3333 perf_event_update_time(event);
3336 * In order to keep per-task stats reliable we need to flip the event
3337 * values when we flip the contexts.
3339 value = local64_read(&next_event->count);
3340 value = local64_xchg(&event->count, value);
3341 local64_set(&next_event->count, value);
3343 swap(event->total_time_enabled, next_event->total_time_enabled);
3344 swap(event->total_time_running, next_event->total_time_running);
3347 * Since we swizzled the values, update the user visible data too.
3349 perf_event_update_userpage(event);
3350 perf_event_update_userpage(next_event);
3353 static void perf_event_sync_stat(struct perf_event_context *ctx,
3354 struct perf_event_context *next_ctx)
3356 struct perf_event *event, *next_event;
3358 if (!ctx->nr_stat)
3359 return;
3361 update_context_time(ctx);
3363 event = list_first_entry(&ctx->event_list,
3364 struct perf_event, event_entry);
3366 next_event = list_first_entry(&next_ctx->event_list,
3367 struct perf_event, event_entry);
3369 while (&event->event_entry != &ctx->event_list &&
3370 &next_event->event_entry != &next_ctx->event_list) {
3372 __perf_event_sync_stat(event, next_event);
3374 event = list_next_entry(event, event_entry);
3375 next_event = list_next_entry(next_event, event_entry);
3379 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3380 struct task_struct *next)
3382 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3383 struct perf_event_context *next_ctx;
3384 struct perf_event_context *parent, *next_parent;
3385 struct perf_cpu_context *cpuctx;
3386 int do_switch = 1;
3387 struct pmu *pmu;
3389 if (likely(!ctx))
3390 return;
3392 pmu = ctx->pmu;
3393 cpuctx = __get_cpu_context(ctx);
3394 if (!cpuctx->task_ctx)
3395 return;
3397 rcu_read_lock();
3398 next_ctx = next->perf_event_ctxp[ctxn];
3399 if (!next_ctx)
3400 goto unlock;
3402 parent = rcu_dereference(ctx->parent_ctx);
3403 next_parent = rcu_dereference(next_ctx->parent_ctx);
3405 /* If neither context have a parent context; they cannot be clones. */
3406 if (!parent && !next_parent)
3407 goto unlock;
3409 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3411 * Looks like the two contexts are clones, so we might be
3412 * able to optimize the context switch. We lock both
3413 * contexts and check that they are clones under the
3414 * lock (including re-checking that neither has been
3415 * uncloned in the meantime). It doesn't matter which
3416 * order we take the locks because no other cpu could
3417 * be trying to lock both of these tasks.
3419 raw_spin_lock(&ctx->lock);
3420 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3421 if (context_equiv(ctx, next_ctx)) {
3423 WRITE_ONCE(ctx->task, next);
3424 WRITE_ONCE(next_ctx->task, task);
3426 perf_pmu_disable(pmu);
3428 if (cpuctx->sched_cb_usage && pmu->sched_task)
3429 pmu->sched_task(ctx, false);
3432 * PMU specific parts of task perf context can require
3433 * additional synchronization. As an example of such
3434 * synchronization see implementation details of Intel
3435 * LBR call stack data profiling;
3437 if (pmu->swap_task_ctx)
3438 pmu->swap_task_ctx(ctx, next_ctx);
3439 else
3440 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3442 perf_pmu_enable(pmu);
3445 * RCU_INIT_POINTER here is safe because we've not
3446 * modified the ctx and the above modification of
3447 * ctx->task and ctx->task_ctx_data are immaterial
3448 * since those values are always verified under
3449 * ctx->lock which we're now holding.
3451 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3452 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3454 do_switch = 0;
3456 perf_event_sync_stat(ctx, next_ctx);
3458 raw_spin_unlock(&next_ctx->lock);
3459 raw_spin_unlock(&ctx->lock);
3461 unlock:
3462 rcu_read_unlock();
3464 if (do_switch) {
3465 raw_spin_lock(&ctx->lock);
3466 perf_pmu_disable(pmu);
3468 if (cpuctx->sched_cb_usage && pmu->sched_task)
3469 pmu->sched_task(ctx, false);
3470 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3472 perf_pmu_enable(pmu);
3473 raw_spin_unlock(&ctx->lock);
3477 void perf_sched_cb_dec(struct pmu *pmu)
3479 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3481 --cpuctx->sched_cb_usage;
3485 void perf_sched_cb_inc(struct pmu *pmu)
3487 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3489 cpuctx->sched_cb_usage++;
3493 * This function provides the context switch callback to the lower code
3494 * layer. It is invoked ONLY when the context switch callback is enabled.
3496 * This callback is relevant even to per-cpu events; for example multi event
3497 * PEBS requires this to provide PID/TID information. This requires we flush
3498 * all queued PEBS records before we context switch to a new task.
3500 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3502 struct pmu *pmu;
3504 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3506 if (WARN_ON_ONCE(!pmu->sched_task))
3507 return;
3509 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3510 perf_pmu_disable(pmu);
3512 pmu->sched_task(cpuctx->task_ctx, sched_in);
3514 perf_pmu_enable(pmu);
3515 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3518 static void perf_event_switch(struct task_struct *task,
3519 struct task_struct *next_prev, bool sched_in);
3521 #define for_each_task_context_nr(ctxn) \
3522 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3525 * Called from scheduler to remove the events of the current task,
3526 * with interrupts disabled.
3528 * We stop each event and update the event value in event->count.
3530 * This does not protect us against NMI, but disable()
3531 * sets the disabled bit in the control field of event _before_
3532 * accessing the event control register. If a NMI hits, then it will
3533 * not restart the event.
3535 void __perf_event_task_sched_out(struct task_struct *task,
3536 struct task_struct *next)
3538 int ctxn;
3540 if (atomic_read(&nr_switch_events))
3541 perf_event_switch(task, next, false);
3543 for_each_task_context_nr(ctxn)
3544 perf_event_context_sched_out(task, ctxn, next);
3547 * if cgroup events exist on this CPU, then we need
3548 * to check if we have to switch out PMU state.
3549 * cgroup event are system-wide mode only
3551 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3552 perf_cgroup_sched_out(task, next);
3556 * Called with IRQs disabled
3558 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3559 enum event_type_t event_type)
3561 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3564 static bool perf_less_group_idx(const void *l, const void *r)
3566 const struct perf_event *le = *(const struct perf_event **)l;
3567 const struct perf_event *re = *(const struct perf_event **)r;
3569 return le->group_index < re->group_index;
3572 static void swap_ptr(void *l, void *r)
3574 void **lp = l, **rp = r;
3576 swap(*lp, *rp);
3579 static const struct min_heap_callbacks perf_min_heap = {
3580 .elem_size = sizeof(struct perf_event *),
3581 .less = perf_less_group_idx,
3582 .swp = swap_ptr,
3585 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3587 struct perf_event **itrs = heap->data;
3589 if (event) {
3590 itrs[heap->nr] = event;
3591 heap->nr++;
3595 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3596 struct perf_event_groups *groups, int cpu,
3597 int (*func)(struct perf_event *, void *),
3598 void *data)
3600 #ifdef CONFIG_CGROUP_PERF
3601 struct cgroup_subsys_state *css = NULL;
3602 #endif
3603 /* Space for per CPU and/or any CPU event iterators. */
3604 struct perf_event *itrs[2];
3605 struct min_heap event_heap;
3606 struct perf_event **evt;
3607 int ret;
3609 if (cpuctx) {
3610 event_heap = (struct min_heap){
3611 .data = cpuctx->heap,
3612 .nr = 0,
3613 .size = cpuctx->heap_size,
3616 lockdep_assert_held(&cpuctx->ctx.lock);
3618 #ifdef CONFIG_CGROUP_PERF
3619 if (cpuctx->cgrp)
3620 css = &cpuctx->cgrp->css;
3621 #endif
3622 } else {
3623 event_heap = (struct min_heap){
3624 .data = itrs,
3625 .nr = 0,
3626 .size = ARRAY_SIZE(itrs),
3628 /* Events not within a CPU context may be on any CPU. */
3629 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3631 evt = event_heap.data;
3633 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3635 #ifdef CONFIG_CGROUP_PERF
3636 for (; css; css = css->parent)
3637 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3638 #endif
3640 min_heapify_all(&event_heap, &perf_min_heap);
3642 while (event_heap.nr) {
3643 ret = func(*evt, data);
3644 if (ret)
3645 return ret;
3647 *evt = perf_event_groups_next(*evt);
3648 if (*evt)
3649 min_heapify(&event_heap, 0, &perf_min_heap);
3650 else
3651 min_heap_pop(&event_heap, &perf_min_heap);
3654 return 0;
3657 static int merge_sched_in(struct perf_event *event, void *data)
3659 struct perf_event_context *ctx = event->ctx;
3660 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3661 int *can_add_hw = data;
3663 if (event->state <= PERF_EVENT_STATE_OFF)
3664 return 0;
3666 if (!event_filter_match(event))
3667 return 0;
3669 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3670 if (!group_sched_in(event, cpuctx, ctx))
3671 list_add_tail(&event->active_list, get_event_list(event));
3674 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3675 if (event->attr.pinned) {
3676 perf_cgroup_event_disable(event, ctx);
3677 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3680 *can_add_hw = 0;
3681 ctx->rotate_necessary = 1;
3682 perf_mux_hrtimer_restart(cpuctx);
3685 return 0;
3688 static void
3689 ctx_pinned_sched_in(struct perf_event_context *ctx,
3690 struct perf_cpu_context *cpuctx)
3692 int can_add_hw = 1;
3694 if (ctx != &cpuctx->ctx)
3695 cpuctx = NULL;
3697 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3698 smp_processor_id(),
3699 merge_sched_in, &can_add_hw);
3702 static void
3703 ctx_flexible_sched_in(struct perf_event_context *ctx,
3704 struct perf_cpu_context *cpuctx)
3706 int can_add_hw = 1;
3708 if (ctx != &cpuctx->ctx)
3709 cpuctx = NULL;
3711 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3712 smp_processor_id(),
3713 merge_sched_in, &can_add_hw);
3716 static void
3717 ctx_sched_in(struct perf_event_context *ctx,
3718 struct perf_cpu_context *cpuctx,
3719 enum event_type_t event_type,
3720 struct task_struct *task)
3722 int is_active = ctx->is_active;
3723 u64 now;
3725 lockdep_assert_held(&ctx->lock);
3727 if (likely(!ctx->nr_events))
3728 return;
3730 ctx->is_active |= (event_type | EVENT_TIME);
3731 if (ctx->task) {
3732 if (!is_active)
3733 cpuctx->task_ctx = ctx;
3734 else
3735 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3738 is_active ^= ctx->is_active; /* changed bits */
3740 if (is_active & EVENT_TIME) {
3741 /* start ctx time */
3742 now = perf_clock();
3743 ctx->timestamp = now;
3744 perf_cgroup_set_timestamp(task, ctx);
3748 * First go through the list and put on any pinned groups
3749 * in order to give them the best chance of going on.
3751 if (is_active & EVENT_PINNED)
3752 ctx_pinned_sched_in(ctx, cpuctx);
3754 /* Then walk through the lower prio flexible groups */
3755 if (is_active & EVENT_FLEXIBLE)
3756 ctx_flexible_sched_in(ctx, cpuctx);
3759 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3760 enum event_type_t event_type,
3761 struct task_struct *task)
3763 struct perf_event_context *ctx = &cpuctx->ctx;
3765 ctx_sched_in(ctx, cpuctx, event_type, task);
3768 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3769 struct task_struct *task)
3771 struct perf_cpu_context *cpuctx;
3772 struct pmu *pmu = ctx->pmu;
3774 cpuctx = __get_cpu_context(ctx);
3775 if (cpuctx->task_ctx == ctx) {
3776 if (cpuctx->sched_cb_usage)
3777 __perf_pmu_sched_task(cpuctx, true);
3778 return;
3781 perf_ctx_lock(cpuctx, ctx);
3783 * We must check ctx->nr_events while holding ctx->lock, such
3784 * that we serialize against perf_install_in_context().
3786 if (!ctx->nr_events)
3787 goto unlock;
3789 perf_pmu_disable(pmu);
3791 * We want to keep the following priority order:
3792 * cpu pinned (that don't need to move), task pinned,
3793 * cpu flexible, task flexible.
3795 * However, if task's ctx is not carrying any pinned
3796 * events, no need to flip the cpuctx's events around.
3798 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3799 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3800 perf_event_sched_in(cpuctx, ctx, task);
3802 if (cpuctx->sched_cb_usage && pmu->sched_task)
3803 pmu->sched_task(cpuctx->task_ctx, true);
3805 perf_pmu_enable(pmu);
3807 unlock:
3808 perf_ctx_unlock(cpuctx, ctx);
3812 * Called from scheduler to add the events of the current task
3813 * with interrupts disabled.
3815 * We restore the event value and then enable it.
3817 * This does not protect us against NMI, but enable()
3818 * sets the enabled bit in the control field of event _before_
3819 * accessing the event control register. If a NMI hits, then it will
3820 * keep the event running.
3822 void __perf_event_task_sched_in(struct task_struct *prev,
3823 struct task_struct *task)
3825 struct perf_event_context *ctx;
3826 int ctxn;
3829 * If cgroup events exist on this CPU, then we need to check if we have
3830 * to switch in PMU state; cgroup event are system-wide mode only.
3832 * Since cgroup events are CPU events, we must schedule these in before
3833 * we schedule in the task events.
3835 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3836 perf_cgroup_sched_in(prev, task);
3838 for_each_task_context_nr(ctxn) {
3839 ctx = task->perf_event_ctxp[ctxn];
3840 if (likely(!ctx))
3841 continue;
3843 perf_event_context_sched_in(ctx, task);
3846 if (atomic_read(&nr_switch_events))
3847 perf_event_switch(task, prev, true);
3850 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3852 u64 frequency = event->attr.sample_freq;
3853 u64 sec = NSEC_PER_SEC;
3854 u64 divisor, dividend;
3856 int count_fls, nsec_fls, frequency_fls, sec_fls;
3858 count_fls = fls64(count);
3859 nsec_fls = fls64(nsec);
3860 frequency_fls = fls64(frequency);
3861 sec_fls = 30;
3864 * We got @count in @nsec, with a target of sample_freq HZ
3865 * the target period becomes:
3867 * @count * 10^9
3868 * period = -------------------
3869 * @nsec * sample_freq
3874 * Reduce accuracy by one bit such that @a and @b converge
3875 * to a similar magnitude.
3877 #define REDUCE_FLS(a, b) \
3878 do { \
3879 if (a##_fls > b##_fls) { \
3880 a >>= 1; \
3881 a##_fls--; \
3882 } else { \
3883 b >>= 1; \
3884 b##_fls--; \
3886 } while (0)
3889 * Reduce accuracy until either term fits in a u64, then proceed with
3890 * the other, so that finally we can do a u64/u64 division.
3892 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3893 REDUCE_FLS(nsec, frequency);
3894 REDUCE_FLS(sec, count);
3897 if (count_fls + sec_fls > 64) {
3898 divisor = nsec * frequency;
3900 while (count_fls + sec_fls > 64) {
3901 REDUCE_FLS(count, sec);
3902 divisor >>= 1;
3905 dividend = count * sec;
3906 } else {
3907 dividend = count * sec;
3909 while (nsec_fls + frequency_fls > 64) {
3910 REDUCE_FLS(nsec, frequency);
3911 dividend >>= 1;
3914 divisor = nsec * frequency;
3917 if (!divisor)
3918 return dividend;
3920 return div64_u64(dividend, divisor);
3923 static DEFINE_PER_CPU(int, perf_throttled_count);
3924 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3926 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3928 struct hw_perf_event *hwc = &event->hw;
3929 s64 period, sample_period;
3930 s64 delta;
3932 period = perf_calculate_period(event, nsec, count);
3934 delta = (s64)(period - hwc->sample_period);
3935 delta = (delta + 7) / 8; /* low pass filter */
3937 sample_period = hwc->sample_period + delta;
3939 if (!sample_period)
3940 sample_period = 1;
3942 hwc->sample_period = sample_period;
3944 if (local64_read(&hwc->period_left) > 8*sample_period) {
3945 if (disable)
3946 event->pmu->stop(event, PERF_EF_UPDATE);
3948 local64_set(&hwc->period_left, 0);
3950 if (disable)
3951 event->pmu->start(event, PERF_EF_RELOAD);
3956 * combine freq adjustment with unthrottling to avoid two passes over the
3957 * events. At the same time, make sure, having freq events does not change
3958 * the rate of unthrottling as that would introduce bias.
3960 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3961 int needs_unthr)
3963 struct perf_event *event;
3964 struct hw_perf_event *hwc;
3965 u64 now, period = TICK_NSEC;
3966 s64 delta;
3969 * only need to iterate over all events iff:
3970 * - context have events in frequency mode (needs freq adjust)
3971 * - there are events to unthrottle on this cpu
3973 if (!(ctx->nr_freq || needs_unthr))
3974 return;
3976 raw_spin_lock(&ctx->lock);
3977 perf_pmu_disable(ctx->pmu);
3979 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3980 if (event->state != PERF_EVENT_STATE_ACTIVE)
3981 continue;
3983 if (!event_filter_match(event))
3984 continue;
3986 perf_pmu_disable(event->pmu);
3988 hwc = &event->hw;
3990 if (hwc->interrupts == MAX_INTERRUPTS) {
3991 hwc->interrupts = 0;
3992 perf_log_throttle(event, 1);
3993 event->pmu->start(event, 0);
3996 if (!event->attr.freq || !event->attr.sample_freq)
3997 goto next;
4000 * stop the event and update event->count
4002 event->pmu->stop(event, PERF_EF_UPDATE);
4004 now = local64_read(&event->count);
4005 delta = now - hwc->freq_count_stamp;
4006 hwc->freq_count_stamp = now;
4009 * restart the event
4010 * reload only if value has changed
4011 * we have stopped the event so tell that
4012 * to perf_adjust_period() to avoid stopping it
4013 * twice.
4015 if (delta > 0)
4016 perf_adjust_period(event, period, delta, false);
4018 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4019 next:
4020 perf_pmu_enable(event->pmu);
4023 perf_pmu_enable(ctx->pmu);
4024 raw_spin_unlock(&ctx->lock);
4028 * Move @event to the tail of the @ctx's elegible events.
4030 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4033 * Rotate the first entry last of non-pinned groups. Rotation might be
4034 * disabled by the inheritance code.
4036 if (ctx->rotate_disable)
4037 return;
4039 perf_event_groups_delete(&ctx->flexible_groups, event);
4040 perf_event_groups_insert(&ctx->flexible_groups, event);
4043 /* pick an event from the flexible_groups to rotate */
4044 static inline struct perf_event *
4045 ctx_event_to_rotate(struct perf_event_context *ctx)
4047 struct perf_event *event;
4049 /* pick the first active flexible event */
4050 event = list_first_entry_or_null(&ctx->flexible_active,
4051 struct perf_event, active_list);
4053 /* if no active flexible event, pick the first event */
4054 if (!event) {
4055 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4056 typeof(*event), group_node);
4060 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4061 * finds there are unschedulable events, it will set it again.
4063 ctx->rotate_necessary = 0;
4065 return event;
4068 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4070 struct perf_event *cpu_event = NULL, *task_event = NULL;
4071 struct perf_event_context *task_ctx = NULL;
4072 int cpu_rotate, task_rotate;
4075 * Since we run this from IRQ context, nobody can install new
4076 * events, thus the event count values are stable.
4079 cpu_rotate = cpuctx->ctx.rotate_necessary;
4080 task_ctx = cpuctx->task_ctx;
4081 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4083 if (!(cpu_rotate || task_rotate))
4084 return false;
4086 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4087 perf_pmu_disable(cpuctx->ctx.pmu);
4089 if (task_rotate)
4090 task_event = ctx_event_to_rotate(task_ctx);
4091 if (cpu_rotate)
4092 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4095 * As per the order given at ctx_resched() first 'pop' task flexible
4096 * and then, if needed CPU flexible.
4098 if (task_event || (task_ctx && cpu_event))
4099 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4100 if (cpu_event)
4101 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4103 if (task_event)
4104 rotate_ctx(task_ctx, task_event);
4105 if (cpu_event)
4106 rotate_ctx(&cpuctx->ctx, cpu_event);
4108 perf_event_sched_in(cpuctx, task_ctx, current);
4110 perf_pmu_enable(cpuctx->ctx.pmu);
4111 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4113 return true;
4116 void perf_event_task_tick(void)
4118 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4119 struct perf_event_context *ctx, *tmp;
4120 int throttled;
4122 lockdep_assert_irqs_disabled();
4124 __this_cpu_inc(perf_throttled_seq);
4125 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4126 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4128 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4129 perf_adjust_freq_unthr_context(ctx, throttled);
4132 static int event_enable_on_exec(struct perf_event *event,
4133 struct perf_event_context *ctx)
4135 if (!event->attr.enable_on_exec)
4136 return 0;
4138 event->attr.enable_on_exec = 0;
4139 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4140 return 0;
4142 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4144 return 1;
4148 * Enable all of a task's events that have been marked enable-on-exec.
4149 * This expects task == current.
4151 static void perf_event_enable_on_exec(int ctxn)
4153 struct perf_event_context *ctx, *clone_ctx = NULL;
4154 enum event_type_t event_type = 0;
4155 struct perf_cpu_context *cpuctx;
4156 struct perf_event *event;
4157 unsigned long flags;
4158 int enabled = 0;
4160 local_irq_save(flags);
4161 ctx = current->perf_event_ctxp[ctxn];
4162 if (!ctx || !ctx->nr_events)
4163 goto out;
4165 cpuctx = __get_cpu_context(ctx);
4166 perf_ctx_lock(cpuctx, ctx);
4167 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4168 list_for_each_entry(event, &ctx->event_list, event_entry) {
4169 enabled |= event_enable_on_exec(event, ctx);
4170 event_type |= get_event_type(event);
4174 * Unclone and reschedule this context if we enabled any event.
4176 if (enabled) {
4177 clone_ctx = unclone_ctx(ctx);
4178 ctx_resched(cpuctx, ctx, event_type);
4179 } else {
4180 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4182 perf_ctx_unlock(cpuctx, ctx);
4184 out:
4185 local_irq_restore(flags);
4187 if (clone_ctx)
4188 put_ctx(clone_ctx);
4191 struct perf_read_data {
4192 struct perf_event *event;
4193 bool group;
4194 int ret;
4197 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4199 u16 local_pkg, event_pkg;
4201 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4202 int local_cpu = smp_processor_id();
4204 event_pkg = topology_physical_package_id(event_cpu);
4205 local_pkg = topology_physical_package_id(local_cpu);
4207 if (event_pkg == local_pkg)
4208 return local_cpu;
4211 return event_cpu;
4215 * Cross CPU call to read the hardware event
4217 static void __perf_event_read(void *info)
4219 struct perf_read_data *data = info;
4220 struct perf_event *sub, *event = data->event;
4221 struct perf_event_context *ctx = event->ctx;
4222 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4223 struct pmu *pmu = event->pmu;
4226 * If this is a task context, we need to check whether it is
4227 * the current task context of this cpu. If not it has been
4228 * scheduled out before the smp call arrived. In that case
4229 * event->count would have been updated to a recent sample
4230 * when the event was scheduled out.
4232 if (ctx->task && cpuctx->task_ctx != ctx)
4233 return;
4235 raw_spin_lock(&ctx->lock);
4236 if (ctx->is_active & EVENT_TIME) {
4237 update_context_time(ctx);
4238 update_cgrp_time_from_event(event);
4241 perf_event_update_time(event);
4242 if (data->group)
4243 perf_event_update_sibling_time(event);
4245 if (event->state != PERF_EVENT_STATE_ACTIVE)
4246 goto unlock;
4248 if (!data->group) {
4249 pmu->read(event);
4250 data->ret = 0;
4251 goto unlock;
4254 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4256 pmu->read(event);
4258 for_each_sibling_event(sub, event) {
4259 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4261 * Use sibling's PMU rather than @event's since
4262 * sibling could be on different (eg: software) PMU.
4264 sub->pmu->read(sub);
4268 data->ret = pmu->commit_txn(pmu);
4270 unlock:
4271 raw_spin_unlock(&ctx->lock);
4274 static inline u64 perf_event_count(struct perf_event *event)
4276 return local64_read(&event->count) + atomic64_read(&event->child_count);
4280 * NMI-safe method to read a local event, that is an event that
4281 * is:
4282 * - either for the current task, or for this CPU
4283 * - does not have inherit set, for inherited task events
4284 * will not be local and we cannot read them atomically
4285 * - must not have a pmu::count method
4287 int perf_event_read_local(struct perf_event *event, u64 *value,
4288 u64 *enabled, u64 *running)
4290 unsigned long flags;
4291 int ret = 0;
4294 * Disabling interrupts avoids all counter scheduling (context
4295 * switches, timer based rotation and IPIs).
4297 local_irq_save(flags);
4300 * It must not be an event with inherit set, we cannot read
4301 * all child counters from atomic context.
4303 if (event->attr.inherit) {
4304 ret = -EOPNOTSUPP;
4305 goto out;
4308 /* If this is a per-task event, it must be for current */
4309 if ((event->attach_state & PERF_ATTACH_TASK) &&
4310 event->hw.target != current) {
4311 ret = -EINVAL;
4312 goto out;
4315 /* If this is a per-CPU event, it must be for this CPU */
4316 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4317 event->cpu != smp_processor_id()) {
4318 ret = -EINVAL;
4319 goto out;
4322 /* If this is a pinned event it must be running on this CPU */
4323 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4324 ret = -EBUSY;
4325 goto out;
4329 * If the event is currently on this CPU, its either a per-task event,
4330 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4331 * oncpu == -1).
4333 if (event->oncpu == smp_processor_id())
4334 event->pmu->read(event);
4336 *value = local64_read(&event->count);
4337 if (enabled || running) {
4338 u64 now = event->shadow_ctx_time + perf_clock();
4339 u64 __enabled, __running;
4341 __perf_update_times(event, now, &__enabled, &__running);
4342 if (enabled)
4343 *enabled = __enabled;
4344 if (running)
4345 *running = __running;
4347 out:
4348 local_irq_restore(flags);
4350 return ret;
4353 static int perf_event_read(struct perf_event *event, bool group)
4355 enum perf_event_state state = READ_ONCE(event->state);
4356 int event_cpu, ret = 0;
4359 * If event is enabled and currently active on a CPU, update the
4360 * value in the event structure:
4362 again:
4363 if (state == PERF_EVENT_STATE_ACTIVE) {
4364 struct perf_read_data data;
4367 * Orders the ->state and ->oncpu loads such that if we see
4368 * ACTIVE we must also see the right ->oncpu.
4370 * Matches the smp_wmb() from event_sched_in().
4372 smp_rmb();
4374 event_cpu = READ_ONCE(event->oncpu);
4375 if ((unsigned)event_cpu >= nr_cpu_ids)
4376 return 0;
4378 data = (struct perf_read_data){
4379 .event = event,
4380 .group = group,
4381 .ret = 0,
4384 preempt_disable();
4385 event_cpu = __perf_event_read_cpu(event, event_cpu);
4388 * Purposely ignore the smp_call_function_single() return
4389 * value.
4391 * If event_cpu isn't a valid CPU it means the event got
4392 * scheduled out and that will have updated the event count.
4394 * Therefore, either way, we'll have an up-to-date event count
4395 * after this.
4397 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4398 preempt_enable();
4399 ret = data.ret;
4401 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4402 struct perf_event_context *ctx = event->ctx;
4403 unsigned long flags;
4405 raw_spin_lock_irqsave(&ctx->lock, flags);
4406 state = event->state;
4407 if (state != PERF_EVENT_STATE_INACTIVE) {
4408 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4409 goto again;
4413 * May read while context is not active (e.g., thread is
4414 * blocked), in that case we cannot update context time
4416 if (ctx->is_active & EVENT_TIME) {
4417 update_context_time(ctx);
4418 update_cgrp_time_from_event(event);
4421 perf_event_update_time(event);
4422 if (group)
4423 perf_event_update_sibling_time(event);
4424 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4427 return ret;
4431 * Initialize the perf_event context in a task_struct:
4433 static void __perf_event_init_context(struct perf_event_context *ctx)
4435 raw_spin_lock_init(&ctx->lock);
4436 mutex_init(&ctx->mutex);
4437 INIT_LIST_HEAD(&ctx->active_ctx_list);
4438 perf_event_groups_init(&ctx->pinned_groups);
4439 perf_event_groups_init(&ctx->flexible_groups);
4440 INIT_LIST_HEAD(&ctx->event_list);
4441 INIT_LIST_HEAD(&ctx->pinned_active);
4442 INIT_LIST_HEAD(&ctx->flexible_active);
4443 refcount_set(&ctx->refcount, 1);
4446 static struct perf_event_context *
4447 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4449 struct perf_event_context *ctx;
4451 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4452 if (!ctx)
4453 return NULL;
4455 __perf_event_init_context(ctx);
4456 if (task)
4457 ctx->task = get_task_struct(task);
4458 ctx->pmu = pmu;
4460 return ctx;
4463 static struct task_struct *
4464 find_lively_task_by_vpid(pid_t vpid)
4466 struct task_struct *task;
4468 rcu_read_lock();
4469 if (!vpid)
4470 task = current;
4471 else
4472 task = find_task_by_vpid(vpid);
4473 if (task)
4474 get_task_struct(task);
4475 rcu_read_unlock();
4477 if (!task)
4478 return ERR_PTR(-ESRCH);
4480 return task;
4484 * Returns a matching context with refcount and pincount.
4486 static struct perf_event_context *
4487 find_get_context(struct pmu *pmu, struct task_struct *task,
4488 struct perf_event *event)
4490 struct perf_event_context *ctx, *clone_ctx = NULL;
4491 struct perf_cpu_context *cpuctx;
4492 void *task_ctx_data = NULL;
4493 unsigned long flags;
4494 int ctxn, err;
4495 int cpu = event->cpu;
4497 if (!task) {
4498 /* Must be root to operate on a CPU event: */
4499 err = perf_allow_cpu(&event->attr);
4500 if (err)
4501 return ERR_PTR(err);
4503 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4504 ctx = &cpuctx->ctx;
4505 get_ctx(ctx);
4506 ++ctx->pin_count;
4508 return ctx;
4511 err = -EINVAL;
4512 ctxn = pmu->task_ctx_nr;
4513 if (ctxn < 0)
4514 goto errout;
4516 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4517 task_ctx_data = alloc_task_ctx_data(pmu);
4518 if (!task_ctx_data) {
4519 err = -ENOMEM;
4520 goto errout;
4524 retry:
4525 ctx = perf_lock_task_context(task, ctxn, &flags);
4526 if (ctx) {
4527 clone_ctx = unclone_ctx(ctx);
4528 ++ctx->pin_count;
4530 if (task_ctx_data && !ctx->task_ctx_data) {
4531 ctx->task_ctx_data = task_ctx_data;
4532 task_ctx_data = NULL;
4534 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4536 if (clone_ctx)
4537 put_ctx(clone_ctx);
4538 } else {
4539 ctx = alloc_perf_context(pmu, task);
4540 err = -ENOMEM;
4541 if (!ctx)
4542 goto errout;
4544 if (task_ctx_data) {
4545 ctx->task_ctx_data = task_ctx_data;
4546 task_ctx_data = NULL;
4549 err = 0;
4550 mutex_lock(&task->perf_event_mutex);
4552 * If it has already passed perf_event_exit_task().
4553 * we must see PF_EXITING, it takes this mutex too.
4555 if (task->flags & PF_EXITING)
4556 err = -ESRCH;
4557 else if (task->perf_event_ctxp[ctxn])
4558 err = -EAGAIN;
4559 else {
4560 get_ctx(ctx);
4561 ++ctx->pin_count;
4562 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4564 mutex_unlock(&task->perf_event_mutex);
4566 if (unlikely(err)) {
4567 put_ctx(ctx);
4569 if (err == -EAGAIN)
4570 goto retry;
4571 goto errout;
4575 free_task_ctx_data(pmu, task_ctx_data);
4576 return ctx;
4578 errout:
4579 free_task_ctx_data(pmu, task_ctx_data);
4580 return ERR_PTR(err);
4583 static void perf_event_free_filter(struct perf_event *event);
4584 static void perf_event_free_bpf_prog(struct perf_event *event);
4586 static void free_event_rcu(struct rcu_head *head)
4588 struct perf_event *event;
4590 event = container_of(head, struct perf_event, rcu_head);
4591 if (event->ns)
4592 put_pid_ns(event->ns);
4593 perf_event_free_filter(event);
4594 kfree(event);
4597 static void ring_buffer_attach(struct perf_event *event,
4598 struct perf_buffer *rb);
4600 static void detach_sb_event(struct perf_event *event)
4602 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4604 raw_spin_lock(&pel->lock);
4605 list_del_rcu(&event->sb_list);
4606 raw_spin_unlock(&pel->lock);
4609 static bool is_sb_event(struct perf_event *event)
4611 struct perf_event_attr *attr = &event->attr;
4613 if (event->parent)
4614 return false;
4616 if (event->attach_state & PERF_ATTACH_TASK)
4617 return false;
4619 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4620 attr->comm || attr->comm_exec ||
4621 attr->task || attr->ksymbol ||
4622 attr->context_switch || attr->text_poke ||
4623 attr->bpf_event)
4624 return true;
4625 return false;
4628 static void unaccount_pmu_sb_event(struct perf_event *event)
4630 if (is_sb_event(event))
4631 detach_sb_event(event);
4634 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4636 if (event->parent)
4637 return;
4639 if (is_cgroup_event(event))
4640 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4643 #ifdef CONFIG_NO_HZ_FULL
4644 static DEFINE_SPINLOCK(nr_freq_lock);
4645 #endif
4647 static void unaccount_freq_event_nohz(void)
4649 #ifdef CONFIG_NO_HZ_FULL
4650 spin_lock(&nr_freq_lock);
4651 if (atomic_dec_and_test(&nr_freq_events))
4652 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4653 spin_unlock(&nr_freq_lock);
4654 #endif
4657 static void unaccount_freq_event(void)
4659 if (tick_nohz_full_enabled())
4660 unaccount_freq_event_nohz();
4661 else
4662 atomic_dec(&nr_freq_events);
4665 static void unaccount_event(struct perf_event *event)
4667 bool dec = false;
4669 if (event->parent)
4670 return;
4672 if (event->attach_state & PERF_ATTACH_TASK)
4673 dec = true;
4674 if (event->attr.mmap || event->attr.mmap_data)
4675 atomic_dec(&nr_mmap_events);
4676 if (event->attr.comm)
4677 atomic_dec(&nr_comm_events);
4678 if (event->attr.namespaces)
4679 atomic_dec(&nr_namespaces_events);
4680 if (event->attr.cgroup)
4681 atomic_dec(&nr_cgroup_events);
4682 if (event->attr.task)
4683 atomic_dec(&nr_task_events);
4684 if (event->attr.freq)
4685 unaccount_freq_event();
4686 if (event->attr.context_switch) {
4687 dec = true;
4688 atomic_dec(&nr_switch_events);
4690 if (is_cgroup_event(event))
4691 dec = true;
4692 if (has_branch_stack(event))
4693 dec = true;
4694 if (event->attr.ksymbol)
4695 atomic_dec(&nr_ksymbol_events);
4696 if (event->attr.bpf_event)
4697 atomic_dec(&nr_bpf_events);
4698 if (event->attr.text_poke)
4699 atomic_dec(&nr_text_poke_events);
4701 if (dec) {
4702 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4703 schedule_delayed_work(&perf_sched_work, HZ);
4706 unaccount_event_cpu(event, event->cpu);
4708 unaccount_pmu_sb_event(event);
4711 static void perf_sched_delayed(struct work_struct *work)
4713 mutex_lock(&perf_sched_mutex);
4714 if (atomic_dec_and_test(&perf_sched_count))
4715 static_branch_disable(&perf_sched_events);
4716 mutex_unlock(&perf_sched_mutex);
4720 * The following implement mutual exclusion of events on "exclusive" pmus
4721 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4722 * at a time, so we disallow creating events that might conflict, namely:
4724 * 1) cpu-wide events in the presence of per-task events,
4725 * 2) per-task events in the presence of cpu-wide events,
4726 * 3) two matching events on the same context.
4728 * The former two cases are handled in the allocation path (perf_event_alloc(),
4729 * _free_event()), the latter -- before the first perf_install_in_context().
4731 static int exclusive_event_init(struct perf_event *event)
4733 struct pmu *pmu = event->pmu;
4735 if (!is_exclusive_pmu(pmu))
4736 return 0;
4739 * Prevent co-existence of per-task and cpu-wide events on the
4740 * same exclusive pmu.
4742 * Negative pmu::exclusive_cnt means there are cpu-wide
4743 * events on this "exclusive" pmu, positive means there are
4744 * per-task events.
4746 * Since this is called in perf_event_alloc() path, event::ctx
4747 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4748 * to mean "per-task event", because unlike other attach states it
4749 * never gets cleared.
4751 if (event->attach_state & PERF_ATTACH_TASK) {
4752 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4753 return -EBUSY;
4754 } else {
4755 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4756 return -EBUSY;
4759 return 0;
4762 static void exclusive_event_destroy(struct perf_event *event)
4764 struct pmu *pmu = event->pmu;
4766 if (!is_exclusive_pmu(pmu))
4767 return;
4769 /* see comment in exclusive_event_init() */
4770 if (event->attach_state & PERF_ATTACH_TASK)
4771 atomic_dec(&pmu->exclusive_cnt);
4772 else
4773 atomic_inc(&pmu->exclusive_cnt);
4776 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4778 if ((e1->pmu == e2->pmu) &&
4779 (e1->cpu == e2->cpu ||
4780 e1->cpu == -1 ||
4781 e2->cpu == -1))
4782 return true;
4783 return false;
4786 static bool exclusive_event_installable(struct perf_event *event,
4787 struct perf_event_context *ctx)
4789 struct perf_event *iter_event;
4790 struct pmu *pmu = event->pmu;
4792 lockdep_assert_held(&ctx->mutex);
4794 if (!is_exclusive_pmu(pmu))
4795 return true;
4797 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4798 if (exclusive_event_match(iter_event, event))
4799 return false;
4802 return true;
4805 static void perf_addr_filters_splice(struct perf_event *event,
4806 struct list_head *head);
4808 static void _free_event(struct perf_event *event)
4810 irq_work_sync(&event->pending);
4812 unaccount_event(event);
4814 security_perf_event_free(event);
4816 if (event->rb) {
4818 * Can happen when we close an event with re-directed output.
4820 * Since we have a 0 refcount, perf_mmap_close() will skip
4821 * over us; possibly making our ring_buffer_put() the last.
4823 mutex_lock(&event->mmap_mutex);
4824 ring_buffer_attach(event, NULL);
4825 mutex_unlock(&event->mmap_mutex);
4828 if (is_cgroup_event(event))
4829 perf_detach_cgroup(event);
4831 if (!event->parent) {
4832 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4833 put_callchain_buffers();
4836 perf_event_free_bpf_prog(event);
4837 perf_addr_filters_splice(event, NULL);
4838 kfree(event->addr_filter_ranges);
4840 if (event->destroy)
4841 event->destroy(event);
4844 * Must be after ->destroy(), due to uprobe_perf_close() using
4845 * hw.target.
4847 if (event->hw.target)
4848 put_task_struct(event->hw.target);
4851 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4852 * all task references must be cleaned up.
4854 if (event->ctx)
4855 put_ctx(event->ctx);
4857 exclusive_event_destroy(event);
4858 module_put(event->pmu->module);
4860 call_rcu(&event->rcu_head, free_event_rcu);
4864 * Used to free events which have a known refcount of 1, such as in error paths
4865 * where the event isn't exposed yet and inherited events.
4867 static void free_event(struct perf_event *event)
4869 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4870 "unexpected event refcount: %ld; ptr=%p\n",
4871 atomic_long_read(&event->refcount), event)) {
4872 /* leak to avoid use-after-free */
4873 return;
4876 _free_event(event);
4880 * Remove user event from the owner task.
4882 static void perf_remove_from_owner(struct perf_event *event)
4884 struct task_struct *owner;
4886 rcu_read_lock();
4888 * Matches the smp_store_release() in perf_event_exit_task(). If we
4889 * observe !owner it means the list deletion is complete and we can
4890 * indeed free this event, otherwise we need to serialize on
4891 * owner->perf_event_mutex.
4893 owner = READ_ONCE(event->owner);
4894 if (owner) {
4896 * Since delayed_put_task_struct() also drops the last
4897 * task reference we can safely take a new reference
4898 * while holding the rcu_read_lock().
4900 get_task_struct(owner);
4902 rcu_read_unlock();
4904 if (owner) {
4906 * If we're here through perf_event_exit_task() we're already
4907 * holding ctx->mutex which would be an inversion wrt. the
4908 * normal lock order.
4910 * However we can safely take this lock because its the child
4911 * ctx->mutex.
4913 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4916 * We have to re-check the event->owner field, if it is cleared
4917 * we raced with perf_event_exit_task(), acquiring the mutex
4918 * ensured they're done, and we can proceed with freeing the
4919 * event.
4921 if (event->owner) {
4922 list_del_init(&event->owner_entry);
4923 smp_store_release(&event->owner, NULL);
4925 mutex_unlock(&owner->perf_event_mutex);
4926 put_task_struct(owner);
4930 static void put_event(struct perf_event *event)
4932 if (!atomic_long_dec_and_test(&event->refcount))
4933 return;
4935 _free_event(event);
4939 * Kill an event dead; while event:refcount will preserve the event
4940 * object, it will not preserve its functionality. Once the last 'user'
4941 * gives up the object, we'll destroy the thing.
4943 int perf_event_release_kernel(struct perf_event *event)
4945 struct perf_event_context *ctx = event->ctx;
4946 struct perf_event *child, *tmp;
4947 LIST_HEAD(free_list);
4950 * If we got here through err_file: fput(event_file); we will not have
4951 * attached to a context yet.
4953 if (!ctx) {
4954 WARN_ON_ONCE(event->attach_state &
4955 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4956 goto no_ctx;
4959 if (!is_kernel_event(event))
4960 perf_remove_from_owner(event);
4962 ctx = perf_event_ctx_lock(event);
4963 WARN_ON_ONCE(ctx->parent_ctx);
4964 perf_remove_from_context(event, DETACH_GROUP);
4966 raw_spin_lock_irq(&ctx->lock);
4968 * Mark this event as STATE_DEAD, there is no external reference to it
4969 * anymore.
4971 * Anybody acquiring event->child_mutex after the below loop _must_
4972 * also see this, most importantly inherit_event() which will avoid
4973 * placing more children on the list.
4975 * Thus this guarantees that we will in fact observe and kill _ALL_
4976 * child events.
4978 event->state = PERF_EVENT_STATE_DEAD;
4979 raw_spin_unlock_irq(&ctx->lock);
4981 perf_event_ctx_unlock(event, ctx);
4983 again:
4984 mutex_lock(&event->child_mutex);
4985 list_for_each_entry(child, &event->child_list, child_list) {
4988 * Cannot change, child events are not migrated, see the
4989 * comment with perf_event_ctx_lock_nested().
4991 ctx = READ_ONCE(child->ctx);
4993 * Since child_mutex nests inside ctx::mutex, we must jump
4994 * through hoops. We start by grabbing a reference on the ctx.
4996 * Since the event cannot get freed while we hold the
4997 * child_mutex, the context must also exist and have a !0
4998 * reference count.
5000 get_ctx(ctx);
5003 * Now that we have a ctx ref, we can drop child_mutex, and
5004 * acquire ctx::mutex without fear of it going away. Then we
5005 * can re-acquire child_mutex.
5007 mutex_unlock(&event->child_mutex);
5008 mutex_lock(&ctx->mutex);
5009 mutex_lock(&event->child_mutex);
5012 * Now that we hold ctx::mutex and child_mutex, revalidate our
5013 * state, if child is still the first entry, it didn't get freed
5014 * and we can continue doing so.
5016 tmp = list_first_entry_or_null(&event->child_list,
5017 struct perf_event, child_list);
5018 if (tmp == child) {
5019 perf_remove_from_context(child, DETACH_GROUP);
5020 list_move(&child->child_list, &free_list);
5022 * This matches the refcount bump in inherit_event();
5023 * this can't be the last reference.
5025 put_event(event);
5028 mutex_unlock(&event->child_mutex);
5029 mutex_unlock(&ctx->mutex);
5030 put_ctx(ctx);
5031 goto again;
5033 mutex_unlock(&event->child_mutex);
5035 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5036 void *var = &child->ctx->refcount;
5038 list_del(&child->child_list);
5039 free_event(child);
5042 * Wake any perf_event_free_task() waiting for this event to be
5043 * freed.
5045 smp_mb(); /* pairs with wait_var_event() */
5046 wake_up_var(var);
5049 no_ctx:
5050 put_event(event); /* Must be the 'last' reference */
5051 return 0;
5053 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5056 * Called when the last reference to the file is gone.
5058 static int perf_release(struct inode *inode, struct file *file)
5060 perf_event_release_kernel(file->private_data);
5061 return 0;
5064 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5066 struct perf_event *child;
5067 u64 total = 0;
5069 *enabled = 0;
5070 *running = 0;
5072 mutex_lock(&event->child_mutex);
5074 (void)perf_event_read(event, false);
5075 total += perf_event_count(event);
5077 *enabled += event->total_time_enabled +
5078 atomic64_read(&event->child_total_time_enabled);
5079 *running += event->total_time_running +
5080 atomic64_read(&event->child_total_time_running);
5082 list_for_each_entry(child, &event->child_list, child_list) {
5083 (void)perf_event_read(child, false);
5084 total += perf_event_count(child);
5085 *enabled += child->total_time_enabled;
5086 *running += child->total_time_running;
5088 mutex_unlock(&event->child_mutex);
5090 return total;
5093 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5095 struct perf_event_context *ctx;
5096 u64 count;
5098 ctx = perf_event_ctx_lock(event);
5099 count = __perf_event_read_value(event, enabled, running);
5100 perf_event_ctx_unlock(event, ctx);
5102 return count;
5104 EXPORT_SYMBOL_GPL(perf_event_read_value);
5106 static int __perf_read_group_add(struct perf_event *leader,
5107 u64 read_format, u64 *values)
5109 struct perf_event_context *ctx = leader->ctx;
5110 struct perf_event *sub;
5111 unsigned long flags;
5112 int n = 1; /* skip @nr */
5113 int ret;
5115 ret = perf_event_read(leader, true);
5116 if (ret)
5117 return ret;
5119 raw_spin_lock_irqsave(&ctx->lock, flags);
5122 * Since we co-schedule groups, {enabled,running} times of siblings
5123 * will be identical to those of the leader, so we only publish one
5124 * set.
5126 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5127 values[n++] += leader->total_time_enabled +
5128 atomic64_read(&leader->child_total_time_enabled);
5131 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5132 values[n++] += leader->total_time_running +
5133 atomic64_read(&leader->child_total_time_running);
5137 * Write {count,id} tuples for every sibling.
5139 values[n++] += perf_event_count(leader);
5140 if (read_format & PERF_FORMAT_ID)
5141 values[n++] = primary_event_id(leader);
5143 for_each_sibling_event(sub, leader) {
5144 values[n++] += perf_event_count(sub);
5145 if (read_format & PERF_FORMAT_ID)
5146 values[n++] = primary_event_id(sub);
5149 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5150 return 0;
5153 static int perf_read_group(struct perf_event *event,
5154 u64 read_format, char __user *buf)
5156 struct perf_event *leader = event->group_leader, *child;
5157 struct perf_event_context *ctx = leader->ctx;
5158 int ret;
5159 u64 *values;
5161 lockdep_assert_held(&ctx->mutex);
5163 values = kzalloc(event->read_size, GFP_KERNEL);
5164 if (!values)
5165 return -ENOMEM;
5167 values[0] = 1 + leader->nr_siblings;
5170 * By locking the child_mutex of the leader we effectively
5171 * lock the child list of all siblings.. XXX explain how.
5173 mutex_lock(&leader->child_mutex);
5175 ret = __perf_read_group_add(leader, read_format, values);
5176 if (ret)
5177 goto unlock;
5179 list_for_each_entry(child, &leader->child_list, child_list) {
5180 ret = __perf_read_group_add(child, read_format, values);
5181 if (ret)
5182 goto unlock;
5185 mutex_unlock(&leader->child_mutex);
5187 ret = event->read_size;
5188 if (copy_to_user(buf, values, event->read_size))
5189 ret = -EFAULT;
5190 goto out;
5192 unlock:
5193 mutex_unlock(&leader->child_mutex);
5194 out:
5195 kfree(values);
5196 return ret;
5199 static int perf_read_one(struct perf_event *event,
5200 u64 read_format, char __user *buf)
5202 u64 enabled, running;
5203 u64 values[4];
5204 int n = 0;
5206 values[n++] = __perf_event_read_value(event, &enabled, &running);
5207 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5208 values[n++] = enabled;
5209 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5210 values[n++] = running;
5211 if (read_format & PERF_FORMAT_ID)
5212 values[n++] = primary_event_id(event);
5214 if (copy_to_user(buf, values, n * sizeof(u64)))
5215 return -EFAULT;
5217 return n * sizeof(u64);
5220 static bool is_event_hup(struct perf_event *event)
5222 bool no_children;
5224 if (event->state > PERF_EVENT_STATE_EXIT)
5225 return false;
5227 mutex_lock(&event->child_mutex);
5228 no_children = list_empty(&event->child_list);
5229 mutex_unlock(&event->child_mutex);
5230 return no_children;
5234 * Read the performance event - simple non blocking version for now
5236 static ssize_t
5237 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5239 u64 read_format = event->attr.read_format;
5240 int ret;
5243 * Return end-of-file for a read on an event that is in
5244 * error state (i.e. because it was pinned but it couldn't be
5245 * scheduled on to the CPU at some point).
5247 if (event->state == PERF_EVENT_STATE_ERROR)
5248 return 0;
5250 if (count < event->read_size)
5251 return -ENOSPC;
5253 WARN_ON_ONCE(event->ctx->parent_ctx);
5254 if (read_format & PERF_FORMAT_GROUP)
5255 ret = perf_read_group(event, read_format, buf);
5256 else
5257 ret = perf_read_one(event, read_format, buf);
5259 return ret;
5262 static ssize_t
5263 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5265 struct perf_event *event = file->private_data;
5266 struct perf_event_context *ctx;
5267 int ret;
5269 ret = security_perf_event_read(event);
5270 if (ret)
5271 return ret;
5273 ctx = perf_event_ctx_lock(event);
5274 ret = __perf_read(event, buf, count);
5275 perf_event_ctx_unlock(event, ctx);
5277 return ret;
5280 static __poll_t perf_poll(struct file *file, poll_table *wait)
5282 struct perf_event *event = file->private_data;
5283 struct perf_buffer *rb;
5284 __poll_t events = EPOLLHUP;
5286 poll_wait(file, &event->waitq, wait);
5288 if (is_event_hup(event))
5289 return events;
5292 * Pin the event->rb by taking event->mmap_mutex; otherwise
5293 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5295 mutex_lock(&event->mmap_mutex);
5296 rb = event->rb;
5297 if (rb)
5298 events = atomic_xchg(&rb->poll, 0);
5299 mutex_unlock(&event->mmap_mutex);
5300 return events;
5303 static void _perf_event_reset(struct perf_event *event)
5305 (void)perf_event_read(event, false);
5306 local64_set(&event->count, 0);
5307 perf_event_update_userpage(event);
5310 /* Assume it's not an event with inherit set. */
5311 u64 perf_event_pause(struct perf_event *event, bool reset)
5313 struct perf_event_context *ctx;
5314 u64 count;
5316 ctx = perf_event_ctx_lock(event);
5317 WARN_ON_ONCE(event->attr.inherit);
5318 _perf_event_disable(event);
5319 count = local64_read(&event->count);
5320 if (reset)
5321 local64_set(&event->count, 0);
5322 perf_event_ctx_unlock(event, ctx);
5324 return count;
5326 EXPORT_SYMBOL_GPL(perf_event_pause);
5329 * Holding the top-level event's child_mutex means that any
5330 * descendant process that has inherited this event will block
5331 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5332 * task existence requirements of perf_event_enable/disable.
5334 static void perf_event_for_each_child(struct perf_event *event,
5335 void (*func)(struct perf_event *))
5337 struct perf_event *child;
5339 WARN_ON_ONCE(event->ctx->parent_ctx);
5341 mutex_lock(&event->child_mutex);
5342 func(event);
5343 list_for_each_entry(child, &event->child_list, child_list)
5344 func(child);
5345 mutex_unlock(&event->child_mutex);
5348 static void perf_event_for_each(struct perf_event *event,
5349 void (*func)(struct perf_event *))
5351 struct perf_event_context *ctx = event->ctx;
5352 struct perf_event *sibling;
5354 lockdep_assert_held(&ctx->mutex);
5356 event = event->group_leader;
5358 perf_event_for_each_child(event, func);
5359 for_each_sibling_event(sibling, event)
5360 perf_event_for_each_child(sibling, func);
5363 static void __perf_event_period(struct perf_event *event,
5364 struct perf_cpu_context *cpuctx,
5365 struct perf_event_context *ctx,
5366 void *info)
5368 u64 value = *((u64 *)info);
5369 bool active;
5371 if (event->attr.freq) {
5372 event->attr.sample_freq = value;
5373 } else {
5374 event->attr.sample_period = value;
5375 event->hw.sample_period = value;
5378 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5379 if (active) {
5380 perf_pmu_disable(ctx->pmu);
5382 * We could be throttled; unthrottle now to avoid the tick
5383 * trying to unthrottle while we already re-started the event.
5385 if (event->hw.interrupts == MAX_INTERRUPTS) {
5386 event->hw.interrupts = 0;
5387 perf_log_throttle(event, 1);
5389 event->pmu->stop(event, PERF_EF_UPDATE);
5392 local64_set(&event->hw.period_left, 0);
5394 if (active) {
5395 event->pmu->start(event, PERF_EF_RELOAD);
5396 perf_pmu_enable(ctx->pmu);
5400 static int perf_event_check_period(struct perf_event *event, u64 value)
5402 return event->pmu->check_period(event, value);
5405 static int _perf_event_period(struct perf_event *event, u64 value)
5407 if (!is_sampling_event(event))
5408 return -EINVAL;
5410 if (!value)
5411 return -EINVAL;
5413 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5414 return -EINVAL;
5416 if (perf_event_check_period(event, value))
5417 return -EINVAL;
5419 if (!event->attr.freq && (value & (1ULL << 63)))
5420 return -EINVAL;
5422 event_function_call(event, __perf_event_period, &value);
5424 return 0;
5427 int perf_event_period(struct perf_event *event, u64 value)
5429 struct perf_event_context *ctx;
5430 int ret;
5432 ctx = perf_event_ctx_lock(event);
5433 ret = _perf_event_period(event, value);
5434 perf_event_ctx_unlock(event, ctx);
5436 return ret;
5438 EXPORT_SYMBOL_GPL(perf_event_period);
5440 static const struct file_operations perf_fops;
5442 static inline int perf_fget_light(int fd, struct fd *p)
5444 struct fd f = fdget(fd);
5445 if (!f.file)
5446 return -EBADF;
5448 if (f.file->f_op != &perf_fops) {
5449 fdput(f);
5450 return -EBADF;
5452 *p = f;
5453 return 0;
5456 static int perf_event_set_output(struct perf_event *event,
5457 struct perf_event *output_event);
5458 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5459 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5460 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5461 struct perf_event_attr *attr);
5463 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5465 void (*func)(struct perf_event *);
5466 u32 flags = arg;
5468 switch (cmd) {
5469 case PERF_EVENT_IOC_ENABLE:
5470 func = _perf_event_enable;
5471 break;
5472 case PERF_EVENT_IOC_DISABLE:
5473 func = _perf_event_disable;
5474 break;
5475 case PERF_EVENT_IOC_RESET:
5476 func = _perf_event_reset;
5477 break;
5479 case PERF_EVENT_IOC_REFRESH:
5480 return _perf_event_refresh(event, arg);
5482 case PERF_EVENT_IOC_PERIOD:
5484 u64 value;
5486 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5487 return -EFAULT;
5489 return _perf_event_period(event, value);
5491 case PERF_EVENT_IOC_ID:
5493 u64 id = primary_event_id(event);
5495 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5496 return -EFAULT;
5497 return 0;
5500 case PERF_EVENT_IOC_SET_OUTPUT:
5502 int ret;
5503 if (arg != -1) {
5504 struct perf_event *output_event;
5505 struct fd output;
5506 ret = perf_fget_light(arg, &output);
5507 if (ret)
5508 return ret;
5509 output_event = output.file->private_data;
5510 ret = perf_event_set_output(event, output_event);
5511 fdput(output);
5512 } else {
5513 ret = perf_event_set_output(event, NULL);
5515 return ret;
5518 case PERF_EVENT_IOC_SET_FILTER:
5519 return perf_event_set_filter(event, (void __user *)arg);
5521 case PERF_EVENT_IOC_SET_BPF:
5522 return perf_event_set_bpf_prog(event, arg);
5524 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5525 struct perf_buffer *rb;
5527 rcu_read_lock();
5528 rb = rcu_dereference(event->rb);
5529 if (!rb || !rb->nr_pages) {
5530 rcu_read_unlock();
5531 return -EINVAL;
5533 rb_toggle_paused(rb, !!arg);
5534 rcu_read_unlock();
5535 return 0;
5538 case PERF_EVENT_IOC_QUERY_BPF:
5539 return perf_event_query_prog_array(event, (void __user *)arg);
5541 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5542 struct perf_event_attr new_attr;
5543 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5544 &new_attr);
5546 if (err)
5547 return err;
5549 return perf_event_modify_attr(event, &new_attr);
5551 default:
5552 return -ENOTTY;
5555 if (flags & PERF_IOC_FLAG_GROUP)
5556 perf_event_for_each(event, func);
5557 else
5558 perf_event_for_each_child(event, func);
5560 return 0;
5563 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5565 struct perf_event *event = file->private_data;
5566 struct perf_event_context *ctx;
5567 long ret;
5569 /* Treat ioctl like writes as it is likely a mutating operation. */
5570 ret = security_perf_event_write(event);
5571 if (ret)
5572 return ret;
5574 ctx = perf_event_ctx_lock(event);
5575 ret = _perf_ioctl(event, cmd, arg);
5576 perf_event_ctx_unlock(event, ctx);
5578 return ret;
5581 #ifdef CONFIG_COMPAT
5582 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5583 unsigned long arg)
5585 switch (_IOC_NR(cmd)) {
5586 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5587 case _IOC_NR(PERF_EVENT_IOC_ID):
5588 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5589 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5590 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5591 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5592 cmd &= ~IOCSIZE_MASK;
5593 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5595 break;
5597 return perf_ioctl(file, cmd, arg);
5599 #else
5600 # define perf_compat_ioctl NULL
5601 #endif
5603 int perf_event_task_enable(void)
5605 struct perf_event_context *ctx;
5606 struct perf_event *event;
5608 mutex_lock(&current->perf_event_mutex);
5609 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5610 ctx = perf_event_ctx_lock(event);
5611 perf_event_for_each_child(event, _perf_event_enable);
5612 perf_event_ctx_unlock(event, ctx);
5614 mutex_unlock(&current->perf_event_mutex);
5616 return 0;
5619 int perf_event_task_disable(void)
5621 struct perf_event_context *ctx;
5622 struct perf_event *event;
5624 mutex_lock(&current->perf_event_mutex);
5625 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5626 ctx = perf_event_ctx_lock(event);
5627 perf_event_for_each_child(event, _perf_event_disable);
5628 perf_event_ctx_unlock(event, ctx);
5630 mutex_unlock(&current->perf_event_mutex);
5632 return 0;
5635 static int perf_event_index(struct perf_event *event)
5637 if (event->hw.state & PERF_HES_STOPPED)
5638 return 0;
5640 if (event->state != PERF_EVENT_STATE_ACTIVE)
5641 return 0;
5643 return event->pmu->event_idx(event);
5646 static void calc_timer_values(struct perf_event *event,
5647 u64 *now,
5648 u64 *enabled,
5649 u64 *running)
5651 u64 ctx_time;
5653 *now = perf_clock();
5654 ctx_time = event->shadow_ctx_time + *now;
5655 __perf_update_times(event, ctx_time, enabled, running);
5658 static void perf_event_init_userpage(struct perf_event *event)
5660 struct perf_event_mmap_page *userpg;
5661 struct perf_buffer *rb;
5663 rcu_read_lock();
5664 rb = rcu_dereference(event->rb);
5665 if (!rb)
5666 goto unlock;
5668 userpg = rb->user_page;
5670 /* Allow new userspace to detect that bit 0 is deprecated */
5671 userpg->cap_bit0_is_deprecated = 1;
5672 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5673 userpg->data_offset = PAGE_SIZE;
5674 userpg->data_size = perf_data_size(rb);
5676 unlock:
5677 rcu_read_unlock();
5680 void __weak arch_perf_update_userpage(
5681 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5686 * Callers need to ensure there can be no nesting of this function, otherwise
5687 * the seqlock logic goes bad. We can not serialize this because the arch
5688 * code calls this from NMI context.
5690 void perf_event_update_userpage(struct perf_event *event)
5692 struct perf_event_mmap_page *userpg;
5693 struct perf_buffer *rb;
5694 u64 enabled, running, now;
5696 rcu_read_lock();
5697 rb = rcu_dereference(event->rb);
5698 if (!rb)
5699 goto unlock;
5702 * compute total_time_enabled, total_time_running
5703 * based on snapshot values taken when the event
5704 * was last scheduled in.
5706 * we cannot simply called update_context_time()
5707 * because of locking issue as we can be called in
5708 * NMI context
5710 calc_timer_values(event, &now, &enabled, &running);
5712 userpg = rb->user_page;
5714 * Disable preemption to guarantee consistent time stamps are stored to
5715 * the user page.
5717 preempt_disable();
5718 ++userpg->lock;
5719 barrier();
5720 userpg->index = perf_event_index(event);
5721 userpg->offset = perf_event_count(event);
5722 if (userpg->index)
5723 userpg->offset -= local64_read(&event->hw.prev_count);
5725 userpg->time_enabled = enabled +
5726 atomic64_read(&event->child_total_time_enabled);
5728 userpg->time_running = running +
5729 atomic64_read(&event->child_total_time_running);
5731 arch_perf_update_userpage(event, userpg, now);
5733 barrier();
5734 ++userpg->lock;
5735 preempt_enable();
5736 unlock:
5737 rcu_read_unlock();
5739 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5741 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5743 struct perf_event *event = vmf->vma->vm_file->private_data;
5744 struct perf_buffer *rb;
5745 vm_fault_t ret = VM_FAULT_SIGBUS;
5747 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5748 if (vmf->pgoff == 0)
5749 ret = 0;
5750 return ret;
5753 rcu_read_lock();
5754 rb = rcu_dereference(event->rb);
5755 if (!rb)
5756 goto unlock;
5758 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5759 goto unlock;
5761 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5762 if (!vmf->page)
5763 goto unlock;
5765 get_page(vmf->page);
5766 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5767 vmf->page->index = vmf->pgoff;
5769 ret = 0;
5770 unlock:
5771 rcu_read_unlock();
5773 return ret;
5776 static void ring_buffer_attach(struct perf_event *event,
5777 struct perf_buffer *rb)
5779 struct perf_buffer *old_rb = NULL;
5780 unsigned long flags;
5782 if (event->rb) {
5784 * Should be impossible, we set this when removing
5785 * event->rb_entry and wait/clear when adding event->rb_entry.
5787 WARN_ON_ONCE(event->rcu_pending);
5789 old_rb = event->rb;
5790 spin_lock_irqsave(&old_rb->event_lock, flags);
5791 list_del_rcu(&event->rb_entry);
5792 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5794 event->rcu_batches = get_state_synchronize_rcu();
5795 event->rcu_pending = 1;
5798 if (rb) {
5799 if (event->rcu_pending) {
5800 cond_synchronize_rcu(event->rcu_batches);
5801 event->rcu_pending = 0;
5804 spin_lock_irqsave(&rb->event_lock, flags);
5805 list_add_rcu(&event->rb_entry, &rb->event_list);
5806 spin_unlock_irqrestore(&rb->event_lock, flags);
5810 * Avoid racing with perf_mmap_close(AUX): stop the event
5811 * before swizzling the event::rb pointer; if it's getting
5812 * unmapped, its aux_mmap_count will be 0 and it won't
5813 * restart. See the comment in __perf_pmu_output_stop().
5815 * Data will inevitably be lost when set_output is done in
5816 * mid-air, but then again, whoever does it like this is
5817 * not in for the data anyway.
5819 if (has_aux(event))
5820 perf_event_stop(event, 0);
5822 rcu_assign_pointer(event->rb, rb);
5824 if (old_rb) {
5825 ring_buffer_put(old_rb);
5827 * Since we detached before setting the new rb, so that we
5828 * could attach the new rb, we could have missed a wakeup.
5829 * Provide it now.
5831 wake_up_all(&event->waitq);
5835 static void ring_buffer_wakeup(struct perf_event *event)
5837 struct perf_buffer *rb;
5839 rcu_read_lock();
5840 rb = rcu_dereference(event->rb);
5841 if (rb) {
5842 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5843 wake_up_all(&event->waitq);
5845 rcu_read_unlock();
5848 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5850 struct perf_buffer *rb;
5852 rcu_read_lock();
5853 rb = rcu_dereference(event->rb);
5854 if (rb) {
5855 if (!refcount_inc_not_zero(&rb->refcount))
5856 rb = NULL;
5858 rcu_read_unlock();
5860 return rb;
5863 void ring_buffer_put(struct perf_buffer *rb)
5865 if (!refcount_dec_and_test(&rb->refcount))
5866 return;
5868 WARN_ON_ONCE(!list_empty(&rb->event_list));
5870 call_rcu(&rb->rcu_head, rb_free_rcu);
5873 static void perf_mmap_open(struct vm_area_struct *vma)
5875 struct perf_event *event = vma->vm_file->private_data;
5877 atomic_inc(&event->mmap_count);
5878 atomic_inc(&event->rb->mmap_count);
5880 if (vma->vm_pgoff)
5881 atomic_inc(&event->rb->aux_mmap_count);
5883 if (event->pmu->event_mapped)
5884 event->pmu->event_mapped(event, vma->vm_mm);
5887 static void perf_pmu_output_stop(struct perf_event *event);
5890 * A buffer can be mmap()ed multiple times; either directly through the same
5891 * event, or through other events by use of perf_event_set_output().
5893 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5894 * the buffer here, where we still have a VM context. This means we need
5895 * to detach all events redirecting to us.
5897 static void perf_mmap_close(struct vm_area_struct *vma)
5899 struct perf_event *event = vma->vm_file->private_data;
5900 struct perf_buffer *rb = ring_buffer_get(event);
5901 struct user_struct *mmap_user = rb->mmap_user;
5902 int mmap_locked = rb->mmap_locked;
5903 unsigned long size = perf_data_size(rb);
5904 bool detach_rest = false;
5906 if (event->pmu->event_unmapped)
5907 event->pmu->event_unmapped(event, vma->vm_mm);
5910 * rb->aux_mmap_count will always drop before rb->mmap_count and
5911 * event->mmap_count, so it is ok to use event->mmap_mutex to
5912 * serialize with perf_mmap here.
5914 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5915 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5917 * Stop all AUX events that are writing to this buffer,
5918 * so that we can free its AUX pages and corresponding PMU
5919 * data. Note that after rb::aux_mmap_count dropped to zero,
5920 * they won't start any more (see perf_aux_output_begin()).
5922 perf_pmu_output_stop(event);
5924 /* now it's safe to free the pages */
5925 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5926 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5928 /* this has to be the last one */
5929 rb_free_aux(rb);
5930 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5932 mutex_unlock(&event->mmap_mutex);
5935 if (atomic_dec_and_test(&rb->mmap_count))
5936 detach_rest = true;
5938 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5939 goto out_put;
5941 ring_buffer_attach(event, NULL);
5942 mutex_unlock(&event->mmap_mutex);
5944 /* If there's still other mmap()s of this buffer, we're done. */
5945 if (!detach_rest)
5946 goto out_put;
5949 * No other mmap()s, detach from all other events that might redirect
5950 * into the now unreachable buffer. Somewhat complicated by the
5951 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5953 again:
5954 rcu_read_lock();
5955 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5956 if (!atomic_long_inc_not_zero(&event->refcount)) {
5958 * This event is en-route to free_event() which will
5959 * detach it and remove it from the list.
5961 continue;
5963 rcu_read_unlock();
5965 mutex_lock(&event->mmap_mutex);
5967 * Check we didn't race with perf_event_set_output() which can
5968 * swizzle the rb from under us while we were waiting to
5969 * acquire mmap_mutex.
5971 * If we find a different rb; ignore this event, a next
5972 * iteration will no longer find it on the list. We have to
5973 * still restart the iteration to make sure we're not now
5974 * iterating the wrong list.
5976 if (event->rb == rb)
5977 ring_buffer_attach(event, NULL);
5979 mutex_unlock(&event->mmap_mutex);
5980 put_event(event);
5983 * Restart the iteration; either we're on the wrong list or
5984 * destroyed its integrity by doing a deletion.
5986 goto again;
5988 rcu_read_unlock();
5991 * It could be there's still a few 0-ref events on the list; they'll
5992 * get cleaned up by free_event() -- they'll also still have their
5993 * ref on the rb and will free it whenever they are done with it.
5995 * Aside from that, this buffer is 'fully' detached and unmapped,
5996 * undo the VM accounting.
5999 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6000 &mmap_user->locked_vm);
6001 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6002 free_uid(mmap_user);
6004 out_put:
6005 ring_buffer_put(rb); /* could be last */
6008 static const struct vm_operations_struct perf_mmap_vmops = {
6009 .open = perf_mmap_open,
6010 .close = perf_mmap_close, /* non mergeable */
6011 .fault = perf_mmap_fault,
6012 .page_mkwrite = perf_mmap_fault,
6015 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6017 struct perf_event *event = file->private_data;
6018 unsigned long user_locked, user_lock_limit;
6019 struct user_struct *user = current_user();
6020 struct perf_buffer *rb = NULL;
6021 unsigned long locked, lock_limit;
6022 unsigned long vma_size;
6023 unsigned long nr_pages;
6024 long user_extra = 0, extra = 0;
6025 int ret = 0, flags = 0;
6028 * Don't allow mmap() of inherited per-task counters. This would
6029 * create a performance issue due to all children writing to the
6030 * same rb.
6032 if (event->cpu == -1 && event->attr.inherit)
6033 return -EINVAL;
6035 if (!(vma->vm_flags & VM_SHARED))
6036 return -EINVAL;
6038 ret = security_perf_event_read(event);
6039 if (ret)
6040 return ret;
6042 vma_size = vma->vm_end - vma->vm_start;
6044 if (vma->vm_pgoff == 0) {
6045 nr_pages = (vma_size / PAGE_SIZE) - 1;
6046 } else {
6048 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6049 * mapped, all subsequent mappings should have the same size
6050 * and offset. Must be above the normal perf buffer.
6052 u64 aux_offset, aux_size;
6054 if (!event->rb)
6055 return -EINVAL;
6057 nr_pages = vma_size / PAGE_SIZE;
6059 mutex_lock(&event->mmap_mutex);
6060 ret = -EINVAL;
6062 rb = event->rb;
6063 if (!rb)
6064 goto aux_unlock;
6066 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6067 aux_size = READ_ONCE(rb->user_page->aux_size);
6069 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6070 goto aux_unlock;
6072 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6073 goto aux_unlock;
6075 /* already mapped with a different offset */
6076 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6077 goto aux_unlock;
6079 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6080 goto aux_unlock;
6082 /* already mapped with a different size */
6083 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6084 goto aux_unlock;
6086 if (!is_power_of_2(nr_pages))
6087 goto aux_unlock;
6089 if (!atomic_inc_not_zero(&rb->mmap_count))
6090 goto aux_unlock;
6092 if (rb_has_aux(rb)) {
6093 atomic_inc(&rb->aux_mmap_count);
6094 ret = 0;
6095 goto unlock;
6098 atomic_set(&rb->aux_mmap_count, 1);
6099 user_extra = nr_pages;
6101 goto accounting;
6105 * If we have rb pages ensure they're a power-of-two number, so we
6106 * can do bitmasks instead of modulo.
6108 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6109 return -EINVAL;
6111 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6112 return -EINVAL;
6114 WARN_ON_ONCE(event->ctx->parent_ctx);
6115 again:
6116 mutex_lock(&event->mmap_mutex);
6117 if (event->rb) {
6118 if (event->rb->nr_pages != nr_pages) {
6119 ret = -EINVAL;
6120 goto unlock;
6123 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6125 * Raced against perf_mmap_close() through
6126 * perf_event_set_output(). Try again, hope for better
6127 * luck.
6129 mutex_unlock(&event->mmap_mutex);
6130 goto again;
6133 goto unlock;
6136 user_extra = nr_pages + 1;
6138 accounting:
6139 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6142 * Increase the limit linearly with more CPUs:
6144 user_lock_limit *= num_online_cpus();
6146 user_locked = atomic_long_read(&user->locked_vm);
6149 * sysctl_perf_event_mlock may have changed, so that
6150 * user->locked_vm > user_lock_limit
6152 if (user_locked > user_lock_limit)
6153 user_locked = user_lock_limit;
6154 user_locked += user_extra;
6156 if (user_locked > user_lock_limit) {
6158 * charge locked_vm until it hits user_lock_limit;
6159 * charge the rest from pinned_vm
6161 extra = user_locked - user_lock_limit;
6162 user_extra -= extra;
6165 lock_limit = rlimit(RLIMIT_MEMLOCK);
6166 lock_limit >>= PAGE_SHIFT;
6167 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6169 if ((locked > lock_limit) && perf_is_paranoid() &&
6170 !capable(CAP_IPC_LOCK)) {
6171 ret = -EPERM;
6172 goto unlock;
6175 WARN_ON(!rb && event->rb);
6177 if (vma->vm_flags & VM_WRITE)
6178 flags |= RING_BUFFER_WRITABLE;
6180 if (!rb) {
6181 rb = rb_alloc(nr_pages,
6182 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6183 event->cpu, flags);
6185 if (!rb) {
6186 ret = -ENOMEM;
6187 goto unlock;
6190 atomic_set(&rb->mmap_count, 1);
6191 rb->mmap_user = get_current_user();
6192 rb->mmap_locked = extra;
6194 ring_buffer_attach(event, rb);
6196 perf_event_init_userpage(event);
6197 perf_event_update_userpage(event);
6198 } else {
6199 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6200 event->attr.aux_watermark, flags);
6201 if (!ret)
6202 rb->aux_mmap_locked = extra;
6205 unlock:
6206 if (!ret) {
6207 atomic_long_add(user_extra, &user->locked_vm);
6208 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6210 atomic_inc(&event->mmap_count);
6211 } else if (rb) {
6212 atomic_dec(&rb->mmap_count);
6214 aux_unlock:
6215 mutex_unlock(&event->mmap_mutex);
6218 * Since pinned accounting is per vm we cannot allow fork() to copy our
6219 * vma.
6221 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6222 vma->vm_ops = &perf_mmap_vmops;
6224 if (event->pmu->event_mapped)
6225 event->pmu->event_mapped(event, vma->vm_mm);
6227 return ret;
6230 static int perf_fasync(int fd, struct file *filp, int on)
6232 struct inode *inode = file_inode(filp);
6233 struct perf_event *event = filp->private_data;
6234 int retval;
6236 inode_lock(inode);
6237 retval = fasync_helper(fd, filp, on, &event->fasync);
6238 inode_unlock(inode);
6240 if (retval < 0)
6241 return retval;
6243 return 0;
6246 static const struct file_operations perf_fops = {
6247 .llseek = no_llseek,
6248 .release = perf_release,
6249 .read = perf_read,
6250 .poll = perf_poll,
6251 .unlocked_ioctl = perf_ioctl,
6252 .compat_ioctl = perf_compat_ioctl,
6253 .mmap = perf_mmap,
6254 .fasync = perf_fasync,
6258 * Perf event wakeup
6260 * If there's data, ensure we set the poll() state and publish everything
6261 * to user-space before waking everybody up.
6264 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6266 /* only the parent has fasync state */
6267 if (event->parent)
6268 event = event->parent;
6269 return &event->fasync;
6272 void perf_event_wakeup(struct perf_event *event)
6274 ring_buffer_wakeup(event);
6276 if (event->pending_kill) {
6277 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6278 event->pending_kill = 0;
6282 static void perf_pending_event_disable(struct perf_event *event)
6284 int cpu = READ_ONCE(event->pending_disable);
6286 if (cpu < 0)
6287 return;
6289 if (cpu == smp_processor_id()) {
6290 WRITE_ONCE(event->pending_disable, -1);
6291 perf_event_disable_local(event);
6292 return;
6296 * CPU-A CPU-B
6298 * perf_event_disable_inatomic()
6299 * @pending_disable = CPU-A;
6300 * irq_work_queue();
6302 * sched-out
6303 * @pending_disable = -1;
6305 * sched-in
6306 * perf_event_disable_inatomic()
6307 * @pending_disable = CPU-B;
6308 * irq_work_queue(); // FAILS
6310 * irq_work_run()
6311 * perf_pending_event()
6313 * But the event runs on CPU-B and wants disabling there.
6315 irq_work_queue_on(&event->pending, cpu);
6318 static void perf_pending_event(struct irq_work *entry)
6320 struct perf_event *event = container_of(entry, struct perf_event, pending);
6321 int rctx;
6323 rctx = perf_swevent_get_recursion_context();
6325 * If we 'fail' here, that's OK, it means recursion is already disabled
6326 * and we won't recurse 'further'.
6329 perf_pending_event_disable(event);
6331 if (event->pending_wakeup) {
6332 event->pending_wakeup = 0;
6333 perf_event_wakeup(event);
6336 if (rctx >= 0)
6337 perf_swevent_put_recursion_context(rctx);
6341 * We assume there is only KVM supporting the callbacks.
6342 * Later on, we might change it to a list if there is
6343 * another virtualization implementation supporting the callbacks.
6345 struct perf_guest_info_callbacks *perf_guest_cbs;
6347 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6349 perf_guest_cbs = cbs;
6350 return 0;
6352 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6354 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6356 perf_guest_cbs = NULL;
6357 return 0;
6359 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6361 static void
6362 perf_output_sample_regs(struct perf_output_handle *handle,
6363 struct pt_regs *regs, u64 mask)
6365 int bit;
6366 DECLARE_BITMAP(_mask, 64);
6368 bitmap_from_u64(_mask, mask);
6369 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6370 u64 val;
6372 val = perf_reg_value(regs, bit);
6373 perf_output_put(handle, val);
6377 static void perf_sample_regs_user(struct perf_regs *regs_user,
6378 struct pt_regs *regs)
6380 if (user_mode(regs)) {
6381 regs_user->abi = perf_reg_abi(current);
6382 regs_user->regs = regs;
6383 } else if (!(current->flags & PF_KTHREAD)) {
6384 perf_get_regs_user(regs_user, regs);
6385 } else {
6386 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6387 regs_user->regs = NULL;
6391 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6392 struct pt_regs *regs)
6394 regs_intr->regs = regs;
6395 regs_intr->abi = perf_reg_abi(current);
6400 * Get remaining task size from user stack pointer.
6402 * It'd be better to take stack vma map and limit this more
6403 * precisely, but there's no way to get it safely under interrupt,
6404 * so using TASK_SIZE as limit.
6406 static u64 perf_ustack_task_size(struct pt_regs *regs)
6408 unsigned long addr = perf_user_stack_pointer(regs);
6410 if (!addr || addr >= TASK_SIZE)
6411 return 0;
6413 return TASK_SIZE - addr;
6416 static u16
6417 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6418 struct pt_regs *regs)
6420 u64 task_size;
6422 /* No regs, no stack pointer, no dump. */
6423 if (!regs)
6424 return 0;
6427 * Check if we fit in with the requested stack size into the:
6428 * - TASK_SIZE
6429 * If we don't, we limit the size to the TASK_SIZE.
6431 * - remaining sample size
6432 * If we don't, we customize the stack size to
6433 * fit in to the remaining sample size.
6436 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6437 stack_size = min(stack_size, (u16) task_size);
6439 /* Current header size plus static size and dynamic size. */
6440 header_size += 2 * sizeof(u64);
6442 /* Do we fit in with the current stack dump size? */
6443 if ((u16) (header_size + stack_size) < header_size) {
6445 * If we overflow the maximum size for the sample,
6446 * we customize the stack dump size to fit in.
6448 stack_size = USHRT_MAX - header_size - sizeof(u64);
6449 stack_size = round_up(stack_size, sizeof(u64));
6452 return stack_size;
6455 static void
6456 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6457 struct pt_regs *regs)
6459 /* Case of a kernel thread, nothing to dump */
6460 if (!regs) {
6461 u64 size = 0;
6462 perf_output_put(handle, size);
6463 } else {
6464 unsigned long sp;
6465 unsigned int rem;
6466 u64 dyn_size;
6467 mm_segment_t fs;
6470 * We dump:
6471 * static size
6472 * - the size requested by user or the best one we can fit
6473 * in to the sample max size
6474 * data
6475 * - user stack dump data
6476 * dynamic size
6477 * - the actual dumped size
6480 /* Static size. */
6481 perf_output_put(handle, dump_size);
6483 /* Data. */
6484 sp = perf_user_stack_pointer(regs);
6485 fs = force_uaccess_begin();
6486 rem = __output_copy_user(handle, (void *) sp, dump_size);
6487 force_uaccess_end(fs);
6488 dyn_size = dump_size - rem;
6490 perf_output_skip(handle, rem);
6492 /* Dynamic size. */
6493 perf_output_put(handle, dyn_size);
6497 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6498 struct perf_sample_data *data,
6499 size_t size)
6501 struct perf_event *sampler = event->aux_event;
6502 struct perf_buffer *rb;
6504 data->aux_size = 0;
6506 if (!sampler)
6507 goto out;
6509 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6510 goto out;
6512 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6513 goto out;
6515 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6516 if (!rb)
6517 goto out;
6520 * If this is an NMI hit inside sampling code, don't take
6521 * the sample. See also perf_aux_sample_output().
6523 if (READ_ONCE(rb->aux_in_sampling)) {
6524 data->aux_size = 0;
6525 } else {
6526 size = min_t(size_t, size, perf_aux_size(rb));
6527 data->aux_size = ALIGN(size, sizeof(u64));
6529 ring_buffer_put(rb);
6531 out:
6532 return data->aux_size;
6535 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6536 struct perf_event *event,
6537 struct perf_output_handle *handle,
6538 unsigned long size)
6540 unsigned long flags;
6541 long ret;
6544 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6545 * paths. If we start calling them in NMI context, they may race with
6546 * the IRQ ones, that is, for example, re-starting an event that's just
6547 * been stopped, which is why we're using a separate callback that
6548 * doesn't change the event state.
6550 * IRQs need to be disabled to prevent IPIs from racing with us.
6552 local_irq_save(flags);
6554 * Guard against NMI hits inside the critical section;
6555 * see also perf_prepare_sample_aux().
6557 WRITE_ONCE(rb->aux_in_sampling, 1);
6558 barrier();
6560 ret = event->pmu->snapshot_aux(event, handle, size);
6562 barrier();
6563 WRITE_ONCE(rb->aux_in_sampling, 0);
6564 local_irq_restore(flags);
6566 return ret;
6569 static void perf_aux_sample_output(struct perf_event *event,
6570 struct perf_output_handle *handle,
6571 struct perf_sample_data *data)
6573 struct perf_event *sampler = event->aux_event;
6574 struct perf_buffer *rb;
6575 unsigned long pad;
6576 long size;
6578 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6579 return;
6581 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6582 if (!rb)
6583 return;
6585 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6588 * An error here means that perf_output_copy() failed (returned a
6589 * non-zero surplus that it didn't copy), which in its current
6590 * enlightened implementation is not possible. If that changes, we'd
6591 * like to know.
6593 if (WARN_ON_ONCE(size < 0))
6594 goto out_put;
6597 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6598 * perf_prepare_sample_aux(), so should not be more than that.
6600 pad = data->aux_size - size;
6601 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6602 pad = 8;
6604 if (pad) {
6605 u64 zero = 0;
6606 perf_output_copy(handle, &zero, pad);
6609 out_put:
6610 ring_buffer_put(rb);
6613 static void __perf_event_header__init_id(struct perf_event_header *header,
6614 struct perf_sample_data *data,
6615 struct perf_event *event)
6617 u64 sample_type = event->attr.sample_type;
6619 data->type = sample_type;
6620 header->size += event->id_header_size;
6622 if (sample_type & PERF_SAMPLE_TID) {
6623 /* namespace issues */
6624 data->tid_entry.pid = perf_event_pid(event, current);
6625 data->tid_entry.tid = perf_event_tid(event, current);
6628 if (sample_type & PERF_SAMPLE_TIME)
6629 data->time = perf_event_clock(event);
6631 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6632 data->id = primary_event_id(event);
6634 if (sample_type & PERF_SAMPLE_STREAM_ID)
6635 data->stream_id = event->id;
6637 if (sample_type & PERF_SAMPLE_CPU) {
6638 data->cpu_entry.cpu = raw_smp_processor_id();
6639 data->cpu_entry.reserved = 0;
6643 void perf_event_header__init_id(struct perf_event_header *header,
6644 struct perf_sample_data *data,
6645 struct perf_event *event)
6647 if (event->attr.sample_id_all)
6648 __perf_event_header__init_id(header, data, event);
6651 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6652 struct perf_sample_data *data)
6654 u64 sample_type = data->type;
6656 if (sample_type & PERF_SAMPLE_TID)
6657 perf_output_put(handle, data->tid_entry);
6659 if (sample_type & PERF_SAMPLE_TIME)
6660 perf_output_put(handle, data->time);
6662 if (sample_type & PERF_SAMPLE_ID)
6663 perf_output_put(handle, data->id);
6665 if (sample_type & PERF_SAMPLE_STREAM_ID)
6666 perf_output_put(handle, data->stream_id);
6668 if (sample_type & PERF_SAMPLE_CPU)
6669 perf_output_put(handle, data->cpu_entry);
6671 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6672 perf_output_put(handle, data->id);
6675 void perf_event__output_id_sample(struct perf_event *event,
6676 struct perf_output_handle *handle,
6677 struct perf_sample_data *sample)
6679 if (event->attr.sample_id_all)
6680 __perf_event__output_id_sample(handle, sample);
6683 static void perf_output_read_one(struct perf_output_handle *handle,
6684 struct perf_event *event,
6685 u64 enabled, u64 running)
6687 u64 read_format = event->attr.read_format;
6688 u64 values[4];
6689 int n = 0;
6691 values[n++] = perf_event_count(event);
6692 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6693 values[n++] = enabled +
6694 atomic64_read(&event->child_total_time_enabled);
6696 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6697 values[n++] = running +
6698 atomic64_read(&event->child_total_time_running);
6700 if (read_format & PERF_FORMAT_ID)
6701 values[n++] = primary_event_id(event);
6703 __output_copy(handle, values, n * sizeof(u64));
6706 static void perf_output_read_group(struct perf_output_handle *handle,
6707 struct perf_event *event,
6708 u64 enabled, u64 running)
6710 struct perf_event *leader = event->group_leader, *sub;
6711 u64 read_format = event->attr.read_format;
6712 u64 values[5];
6713 int n = 0;
6715 values[n++] = 1 + leader->nr_siblings;
6717 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6718 values[n++] = enabled;
6720 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6721 values[n++] = running;
6723 if ((leader != event) &&
6724 (leader->state == PERF_EVENT_STATE_ACTIVE))
6725 leader->pmu->read(leader);
6727 values[n++] = perf_event_count(leader);
6728 if (read_format & PERF_FORMAT_ID)
6729 values[n++] = primary_event_id(leader);
6731 __output_copy(handle, values, n * sizeof(u64));
6733 for_each_sibling_event(sub, leader) {
6734 n = 0;
6736 if ((sub != event) &&
6737 (sub->state == PERF_EVENT_STATE_ACTIVE))
6738 sub->pmu->read(sub);
6740 values[n++] = perf_event_count(sub);
6741 if (read_format & PERF_FORMAT_ID)
6742 values[n++] = primary_event_id(sub);
6744 __output_copy(handle, values, n * sizeof(u64));
6748 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6749 PERF_FORMAT_TOTAL_TIME_RUNNING)
6752 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6754 * The problem is that its both hard and excessively expensive to iterate the
6755 * child list, not to mention that its impossible to IPI the children running
6756 * on another CPU, from interrupt/NMI context.
6758 static void perf_output_read(struct perf_output_handle *handle,
6759 struct perf_event *event)
6761 u64 enabled = 0, running = 0, now;
6762 u64 read_format = event->attr.read_format;
6765 * compute total_time_enabled, total_time_running
6766 * based on snapshot values taken when the event
6767 * was last scheduled in.
6769 * we cannot simply called update_context_time()
6770 * because of locking issue as we are called in
6771 * NMI context
6773 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6774 calc_timer_values(event, &now, &enabled, &running);
6776 if (event->attr.read_format & PERF_FORMAT_GROUP)
6777 perf_output_read_group(handle, event, enabled, running);
6778 else
6779 perf_output_read_one(handle, event, enabled, running);
6782 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6784 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6787 void perf_output_sample(struct perf_output_handle *handle,
6788 struct perf_event_header *header,
6789 struct perf_sample_data *data,
6790 struct perf_event *event)
6792 u64 sample_type = data->type;
6794 perf_output_put(handle, *header);
6796 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6797 perf_output_put(handle, data->id);
6799 if (sample_type & PERF_SAMPLE_IP)
6800 perf_output_put(handle, data->ip);
6802 if (sample_type & PERF_SAMPLE_TID)
6803 perf_output_put(handle, data->tid_entry);
6805 if (sample_type & PERF_SAMPLE_TIME)
6806 perf_output_put(handle, data->time);
6808 if (sample_type & PERF_SAMPLE_ADDR)
6809 perf_output_put(handle, data->addr);
6811 if (sample_type & PERF_SAMPLE_ID)
6812 perf_output_put(handle, data->id);
6814 if (sample_type & PERF_SAMPLE_STREAM_ID)
6815 perf_output_put(handle, data->stream_id);
6817 if (sample_type & PERF_SAMPLE_CPU)
6818 perf_output_put(handle, data->cpu_entry);
6820 if (sample_type & PERF_SAMPLE_PERIOD)
6821 perf_output_put(handle, data->period);
6823 if (sample_type & PERF_SAMPLE_READ)
6824 perf_output_read(handle, event);
6826 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6827 int size = 1;
6829 size += data->callchain->nr;
6830 size *= sizeof(u64);
6831 __output_copy(handle, data->callchain, size);
6834 if (sample_type & PERF_SAMPLE_RAW) {
6835 struct perf_raw_record *raw = data->raw;
6837 if (raw) {
6838 struct perf_raw_frag *frag = &raw->frag;
6840 perf_output_put(handle, raw->size);
6841 do {
6842 if (frag->copy) {
6843 __output_custom(handle, frag->copy,
6844 frag->data, frag->size);
6845 } else {
6846 __output_copy(handle, frag->data,
6847 frag->size);
6849 if (perf_raw_frag_last(frag))
6850 break;
6851 frag = frag->next;
6852 } while (1);
6853 if (frag->pad)
6854 __output_skip(handle, NULL, frag->pad);
6855 } else {
6856 struct {
6857 u32 size;
6858 u32 data;
6859 } raw = {
6860 .size = sizeof(u32),
6861 .data = 0,
6863 perf_output_put(handle, raw);
6867 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6868 if (data->br_stack) {
6869 size_t size;
6871 size = data->br_stack->nr
6872 * sizeof(struct perf_branch_entry);
6874 perf_output_put(handle, data->br_stack->nr);
6875 if (perf_sample_save_hw_index(event))
6876 perf_output_put(handle, data->br_stack->hw_idx);
6877 perf_output_copy(handle, data->br_stack->entries, size);
6878 } else {
6880 * we always store at least the value of nr
6882 u64 nr = 0;
6883 perf_output_put(handle, nr);
6887 if (sample_type & PERF_SAMPLE_REGS_USER) {
6888 u64 abi = data->regs_user.abi;
6891 * If there are no regs to dump, notice it through
6892 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6894 perf_output_put(handle, abi);
6896 if (abi) {
6897 u64 mask = event->attr.sample_regs_user;
6898 perf_output_sample_regs(handle,
6899 data->regs_user.regs,
6900 mask);
6904 if (sample_type & PERF_SAMPLE_STACK_USER) {
6905 perf_output_sample_ustack(handle,
6906 data->stack_user_size,
6907 data->regs_user.regs);
6910 if (sample_type & PERF_SAMPLE_WEIGHT)
6911 perf_output_put(handle, data->weight);
6913 if (sample_type & PERF_SAMPLE_DATA_SRC)
6914 perf_output_put(handle, data->data_src.val);
6916 if (sample_type & PERF_SAMPLE_TRANSACTION)
6917 perf_output_put(handle, data->txn);
6919 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6920 u64 abi = data->regs_intr.abi;
6922 * If there are no regs to dump, notice it through
6923 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6925 perf_output_put(handle, abi);
6927 if (abi) {
6928 u64 mask = event->attr.sample_regs_intr;
6930 perf_output_sample_regs(handle,
6931 data->regs_intr.regs,
6932 mask);
6936 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6937 perf_output_put(handle, data->phys_addr);
6939 if (sample_type & PERF_SAMPLE_CGROUP)
6940 perf_output_put(handle, data->cgroup);
6942 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
6943 perf_output_put(handle, data->data_page_size);
6945 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
6946 perf_output_put(handle, data->code_page_size);
6948 if (sample_type & PERF_SAMPLE_AUX) {
6949 perf_output_put(handle, data->aux_size);
6951 if (data->aux_size)
6952 perf_aux_sample_output(event, handle, data);
6955 if (!event->attr.watermark) {
6956 int wakeup_events = event->attr.wakeup_events;
6958 if (wakeup_events) {
6959 struct perf_buffer *rb = handle->rb;
6960 int events = local_inc_return(&rb->events);
6962 if (events >= wakeup_events) {
6963 local_sub(wakeup_events, &rb->events);
6964 local_inc(&rb->wakeup);
6970 static u64 perf_virt_to_phys(u64 virt)
6972 u64 phys_addr = 0;
6973 struct page *p = NULL;
6975 if (!virt)
6976 return 0;
6978 if (virt >= TASK_SIZE) {
6979 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6980 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6981 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6982 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6983 } else {
6985 * Walking the pages tables for user address.
6986 * Interrupts are disabled, so it prevents any tear down
6987 * of the page tables.
6988 * Try IRQ-safe get_user_page_fast_only first.
6989 * If failed, leave phys_addr as 0.
6991 if (current->mm != NULL) {
6992 pagefault_disable();
6993 if (get_user_page_fast_only(virt, 0, &p))
6994 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6995 pagefault_enable();
6998 if (p)
6999 put_page(p);
7002 return phys_addr;
7006 * Return the pagetable size of a given virtual address.
7008 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7010 u64 size = 0;
7012 #ifdef CONFIG_HAVE_FAST_GUP
7013 pgd_t *pgdp, pgd;
7014 p4d_t *p4dp, p4d;
7015 pud_t *pudp, pud;
7016 pmd_t *pmdp, pmd;
7017 pte_t *ptep, pte;
7019 pgdp = pgd_offset(mm, addr);
7020 pgd = READ_ONCE(*pgdp);
7021 if (pgd_none(pgd))
7022 return 0;
7024 if (pgd_leaf(pgd))
7025 return pgd_leaf_size(pgd);
7027 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7028 p4d = READ_ONCE(*p4dp);
7029 if (!p4d_present(p4d))
7030 return 0;
7032 if (p4d_leaf(p4d))
7033 return p4d_leaf_size(p4d);
7035 pudp = pud_offset_lockless(p4dp, p4d, addr);
7036 pud = READ_ONCE(*pudp);
7037 if (!pud_present(pud))
7038 return 0;
7040 if (pud_leaf(pud))
7041 return pud_leaf_size(pud);
7043 pmdp = pmd_offset_lockless(pudp, pud, addr);
7044 pmd = READ_ONCE(*pmdp);
7045 if (!pmd_present(pmd))
7046 return 0;
7048 if (pmd_leaf(pmd))
7049 return pmd_leaf_size(pmd);
7051 ptep = pte_offset_map(&pmd, addr);
7052 pte = ptep_get_lockless(ptep);
7053 if (pte_present(pte))
7054 size = pte_leaf_size(pte);
7055 pte_unmap(ptep);
7056 #endif /* CONFIG_HAVE_FAST_GUP */
7058 return size;
7061 static u64 perf_get_page_size(unsigned long addr)
7063 struct mm_struct *mm;
7064 unsigned long flags;
7065 u64 size;
7067 if (!addr)
7068 return 0;
7071 * Software page-table walkers must disable IRQs,
7072 * which prevents any tear down of the page tables.
7074 local_irq_save(flags);
7076 mm = current->mm;
7077 if (!mm) {
7079 * For kernel threads and the like, use init_mm so that
7080 * we can find kernel memory.
7082 mm = &init_mm;
7085 size = perf_get_pgtable_size(mm, addr);
7087 local_irq_restore(flags);
7089 return size;
7092 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7094 struct perf_callchain_entry *
7095 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7097 bool kernel = !event->attr.exclude_callchain_kernel;
7098 bool user = !event->attr.exclude_callchain_user;
7099 /* Disallow cross-task user callchains. */
7100 bool crosstask = event->ctx->task && event->ctx->task != current;
7101 const u32 max_stack = event->attr.sample_max_stack;
7102 struct perf_callchain_entry *callchain;
7104 if (!kernel && !user)
7105 return &__empty_callchain;
7107 callchain = get_perf_callchain(regs, 0, kernel, user,
7108 max_stack, crosstask, true);
7109 return callchain ?: &__empty_callchain;
7112 void perf_prepare_sample(struct perf_event_header *header,
7113 struct perf_sample_data *data,
7114 struct perf_event *event,
7115 struct pt_regs *regs)
7117 u64 sample_type = event->attr.sample_type;
7119 header->type = PERF_RECORD_SAMPLE;
7120 header->size = sizeof(*header) + event->header_size;
7122 header->misc = 0;
7123 header->misc |= perf_misc_flags(regs);
7125 __perf_event_header__init_id(header, data, event);
7127 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7128 data->ip = perf_instruction_pointer(regs);
7130 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7131 int size = 1;
7133 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7134 data->callchain = perf_callchain(event, regs);
7136 size += data->callchain->nr;
7138 header->size += size * sizeof(u64);
7141 if (sample_type & PERF_SAMPLE_RAW) {
7142 struct perf_raw_record *raw = data->raw;
7143 int size;
7145 if (raw) {
7146 struct perf_raw_frag *frag = &raw->frag;
7147 u32 sum = 0;
7149 do {
7150 sum += frag->size;
7151 if (perf_raw_frag_last(frag))
7152 break;
7153 frag = frag->next;
7154 } while (1);
7156 size = round_up(sum + sizeof(u32), sizeof(u64));
7157 raw->size = size - sizeof(u32);
7158 frag->pad = raw->size - sum;
7159 } else {
7160 size = sizeof(u64);
7163 header->size += size;
7166 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7167 int size = sizeof(u64); /* nr */
7168 if (data->br_stack) {
7169 if (perf_sample_save_hw_index(event))
7170 size += sizeof(u64);
7172 size += data->br_stack->nr
7173 * sizeof(struct perf_branch_entry);
7175 header->size += size;
7178 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7179 perf_sample_regs_user(&data->regs_user, regs);
7181 if (sample_type & PERF_SAMPLE_REGS_USER) {
7182 /* regs dump ABI info */
7183 int size = sizeof(u64);
7185 if (data->regs_user.regs) {
7186 u64 mask = event->attr.sample_regs_user;
7187 size += hweight64(mask) * sizeof(u64);
7190 header->size += size;
7193 if (sample_type & PERF_SAMPLE_STACK_USER) {
7195 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7196 * processed as the last one or have additional check added
7197 * in case new sample type is added, because we could eat
7198 * up the rest of the sample size.
7200 u16 stack_size = event->attr.sample_stack_user;
7201 u16 size = sizeof(u64);
7203 stack_size = perf_sample_ustack_size(stack_size, header->size,
7204 data->regs_user.regs);
7207 * If there is something to dump, add space for the dump
7208 * itself and for the field that tells the dynamic size,
7209 * which is how many have been actually dumped.
7211 if (stack_size)
7212 size += sizeof(u64) + stack_size;
7214 data->stack_user_size = stack_size;
7215 header->size += size;
7218 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7219 /* regs dump ABI info */
7220 int size = sizeof(u64);
7222 perf_sample_regs_intr(&data->regs_intr, regs);
7224 if (data->regs_intr.regs) {
7225 u64 mask = event->attr.sample_regs_intr;
7227 size += hweight64(mask) * sizeof(u64);
7230 header->size += size;
7233 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7234 data->phys_addr = perf_virt_to_phys(data->addr);
7236 #ifdef CONFIG_CGROUP_PERF
7237 if (sample_type & PERF_SAMPLE_CGROUP) {
7238 struct cgroup *cgrp;
7240 /* protected by RCU */
7241 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7242 data->cgroup = cgroup_id(cgrp);
7244 #endif
7247 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7248 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7249 * but the value will not dump to the userspace.
7251 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7252 data->data_page_size = perf_get_page_size(data->addr);
7254 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7255 data->code_page_size = perf_get_page_size(data->ip);
7257 if (sample_type & PERF_SAMPLE_AUX) {
7258 u64 size;
7260 header->size += sizeof(u64); /* size */
7263 * Given the 16bit nature of header::size, an AUX sample can
7264 * easily overflow it, what with all the preceding sample bits.
7265 * Make sure this doesn't happen by using up to U16_MAX bytes
7266 * per sample in total (rounded down to 8 byte boundary).
7268 size = min_t(size_t, U16_MAX - header->size,
7269 event->attr.aux_sample_size);
7270 size = rounddown(size, 8);
7271 size = perf_prepare_sample_aux(event, data, size);
7273 WARN_ON_ONCE(size + header->size > U16_MAX);
7274 header->size += size;
7277 * If you're adding more sample types here, you likely need to do
7278 * something about the overflowing header::size, like repurpose the
7279 * lowest 3 bits of size, which should be always zero at the moment.
7280 * This raises a more important question, do we really need 512k sized
7281 * samples and why, so good argumentation is in order for whatever you
7282 * do here next.
7284 WARN_ON_ONCE(header->size & 7);
7287 static __always_inline int
7288 __perf_event_output(struct perf_event *event,
7289 struct perf_sample_data *data,
7290 struct pt_regs *regs,
7291 int (*output_begin)(struct perf_output_handle *,
7292 struct perf_sample_data *,
7293 struct perf_event *,
7294 unsigned int))
7296 struct perf_output_handle handle;
7297 struct perf_event_header header;
7298 int err;
7300 /* protect the callchain buffers */
7301 rcu_read_lock();
7303 perf_prepare_sample(&header, data, event, regs);
7305 err = output_begin(&handle, data, event, header.size);
7306 if (err)
7307 goto exit;
7309 perf_output_sample(&handle, &header, data, event);
7311 perf_output_end(&handle);
7313 exit:
7314 rcu_read_unlock();
7315 return err;
7318 void
7319 perf_event_output_forward(struct perf_event *event,
7320 struct perf_sample_data *data,
7321 struct pt_regs *regs)
7323 __perf_event_output(event, data, regs, perf_output_begin_forward);
7326 void
7327 perf_event_output_backward(struct perf_event *event,
7328 struct perf_sample_data *data,
7329 struct pt_regs *regs)
7331 __perf_event_output(event, data, regs, perf_output_begin_backward);
7335 perf_event_output(struct perf_event *event,
7336 struct perf_sample_data *data,
7337 struct pt_regs *regs)
7339 return __perf_event_output(event, data, regs, perf_output_begin);
7343 * read event_id
7346 struct perf_read_event {
7347 struct perf_event_header header;
7349 u32 pid;
7350 u32 tid;
7353 static void
7354 perf_event_read_event(struct perf_event *event,
7355 struct task_struct *task)
7357 struct perf_output_handle handle;
7358 struct perf_sample_data sample;
7359 struct perf_read_event read_event = {
7360 .header = {
7361 .type = PERF_RECORD_READ,
7362 .misc = 0,
7363 .size = sizeof(read_event) + event->read_size,
7365 .pid = perf_event_pid(event, task),
7366 .tid = perf_event_tid(event, task),
7368 int ret;
7370 perf_event_header__init_id(&read_event.header, &sample, event);
7371 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7372 if (ret)
7373 return;
7375 perf_output_put(&handle, read_event);
7376 perf_output_read(&handle, event);
7377 perf_event__output_id_sample(event, &handle, &sample);
7379 perf_output_end(&handle);
7382 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7384 static void
7385 perf_iterate_ctx(struct perf_event_context *ctx,
7386 perf_iterate_f output,
7387 void *data, bool all)
7389 struct perf_event *event;
7391 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7392 if (!all) {
7393 if (event->state < PERF_EVENT_STATE_INACTIVE)
7394 continue;
7395 if (!event_filter_match(event))
7396 continue;
7399 output(event, data);
7403 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7405 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7406 struct perf_event *event;
7408 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7410 * Skip events that are not fully formed yet; ensure that
7411 * if we observe event->ctx, both event and ctx will be
7412 * complete enough. See perf_install_in_context().
7414 if (!smp_load_acquire(&event->ctx))
7415 continue;
7417 if (event->state < PERF_EVENT_STATE_INACTIVE)
7418 continue;
7419 if (!event_filter_match(event))
7420 continue;
7421 output(event, data);
7426 * Iterate all events that need to receive side-band events.
7428 * For new callers; ensure that account_pmu_sb_event() includes
7429 * your event, otherwise it might not get delivered.
7431 static void
7432 perf_iterate_sb(perf_iterate_f output, void *data,
7433 struct perf_event_context *task_ctx)
7435 struct perf_event_context *ctx;
7436 int ctxn;
7438 rcu_read_lock();
7439 preempt_disable();
7442 * If we have task_ctx != NULL we only notify the task context itself.
7443 * The task_ctx is set only for EXIT events before releasing task
7444 * context.
7446 if (task_ctx) {
7447 perf_iterate_ctx(task_ctx, output, data, false);
7448 goto done;
7451 perf_iterate_sb_cpu(output, data);
7453 for_each_task_context_nr(ctxn) {
7454 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7455 if (ctx)
7456 perf_iterate_ctx(ctx, output, data, false);
7458 done:
7459 preempt_enable();
7460 rcu_read_unlock();
7464 * Clear all file-based filters at exec, they'll have to be
7465 * re-instated when/if these objects are mmapped again.
7467 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7469 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7470 struct perf_addr_filter *filter;
7471 unsigned int restart = 0, count = 0;
7472 unsigned long flags;
7474 if (!has_addr_filter(event))
7475 return;
7477 raw_spin_lock_irqsave(&ifh->lock, flags);
7478 list_for_each_entry(filter, &ifh->list, entry) {
7479 if (filter->path.dentry) {
7480 event->addr_filter_ranges[count].start = 0;
7481 event->addr_filter_ranges[count].size = 0;
7482 restart++;
7485 count++;
7488 if (restart)
7489 event->addr_filters_gen++;
7490 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7492 if (restart)
7493 perf_event_stop(event, 1);
7496 void perf_event_exec(void)
7498 struct perf_event_context *ctx;
7499 int ctxn;
7501 rcu_read_lock();
7502 for_each_task_context_nr(ctxn) {
7503 ctx = current->perf_event_ctxp[ctxn];
7504 if (!ctx)
7505 continue;
7507 perf_event_enable_on_exec(ctxn);
7509 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7510 true);
7512 rcu_read_unlock();
7515 struct remote_output {
7516 struct perf_buffer *rb;
7517 int err;
7520 static void __perf_event_output_stop(struct perf_event *event, void *data)
7522 struct perf_event *parent = event->parent;
7523 struct remote_output *ro = data;
7524 struct perf_buffer *rb = ro->rb;
7525 struct stop_event_data sd = {
7526 .event = event,
7529 if (!has_aux(event))
7530 return;
7532 if (!parent)
7533 parent = event;
7536 * In case of inheritance, it will be the parent that links to the
7537 * ring-buffer, but it will be the child that's actually using it.
7539 * We are using event::rb to determine if the event should be stopped,
7540 * however this may race with ring_buffer_attach() (through set_output),
7541 * which will make us skip the event that actually needs to be stopped.
7542 * So ring_buffer_attach() has to stop an aux event before re-assigning
7543 * its rb pointer.
7545 if (rcu_dereference(parent->rb) == rb)
7546 ro->err = __perf_event_stop(&sd);
7549 static int __perf_pmu_output_stop(void *info)
7551 struct perf_event *event = info;
7552 struct pmu *pmu = event->ctx->pmu;
7553 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7554 struct remote_output ro = {
7555 .rb = event->rb,
7558 rcu_read_lock();
7559 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7560 if (cpuctx->task_ctx)
7561 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7562 &ro, false);
7563 rcu_read_unlock();
7565 return ro.err;
7568 static void perf_pmu_output_stop(struct perf_event *event)
7570 struct perf_event *iter;
7571 int err, cpu;
7573 restart:
7574 rcu_read_lock();
7575 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7577 * For per-CPU events, we need to make sure that neither they
7578 * nor their children are running; for cpu==-1 events it's
7579 * sufficient to stop the event itself if it's active, since
7580 * it can't have children.
7582 cpu = iter->cpu;
7583 if (cpu == -1)
7584 cpu = READ_ONCE(iter->oncpu);
7586 if (cpu == -1)
7587 continue;
7589 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7590 if (err == -EAGAIN) {
7591 rcu_read_unlock();
7592 goto restart;
7595 rcu_read_unlock();
7599 * task tracking -- fork/exit
7601 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7604 struct perf_task_event {
7605 struct task_struct *task;
7606 struct perf_event_context *task_ctx;
7608 struct {
7609 struct perf_event_header header;
7611 u32 pid;
7612 u32 ppid;
7613 u32 tid;
7614 u32 ptid;
7615 u64 time;
7616 } event_id;
7619 static int perf_event_task_match(struct perf_event *event)
7621 return event->attr.comm || event->attr.mmap ||
7622 event->attr.mmap2 || event->attr.mmap_data ||
7623 event->attr.task;
7626 static void perf_event_task_output(struct perf_event *event,
7627 void *data)
7629 struct perf_task_event *task_event = data;
7630 struct perf_output_handle handle;
7631 struct perf_sample_data sample;
7632 struct task_struct *task = task_event->task;
7633 int ret, size = task_event->event_id.header.size;
7635 if (!perf_event_task_match(event))
7636 return;
7638 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7640 ret = perf_output_begin(&handle, &sample, event,
7641 task_event->event_id.header.size);
7642 if (ret)
7643 goto out;
7645 task_event->event_id.pid = perf_event_pid(event, task);
7646 task_event->event_id.tid = perf_event_tid(event, task);
7648 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7649 task_event->event_id.ppid = perf_event_pid(event,
7650 task->real_parent);
7651 task_event->event_id.ptid = perf_event_pid(event,
7652 task->real_parent);
7653 } else { /* PERF_RECORD_FORK */
7654 task_event->event_id.ppid = perf_event_pid(event, current);
7655 task_event->event_id.ptid = perf_event_tid(event, current);
7658 task_event->event_id.time = perf_event_clock(event);
7660 perf_output_put(&handle, task_event->event_id);
7662 perf_event__output_id_sample(event, &handle, &sample);
7664 perf_output_end(&handle);
7665 out:
7666 task_event->event_id.header.size = size;
7669 static void perf_event_task(struct task_struct *task,
7670 struct perf_event_context *task_ctx,
7671 int new)
7673 struct perf_task_event task_event;
7675 if (!atomic_read(&nr_comm_events) &&
7676 !atomic_read(&nr_mmap_events) &&
7677 !atomic_read(&nr_task_events))
7678 return;
7680 task_event = (struct perf_task_event){
7681 .task = task,
7682 .task_ctx = task_ctx,
7683 .event_id = {
7684 .header = {
7685 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7686 .misc = 0,
7687 .size = sizeof(task_event.event_id),
7689 /* .pid */
7690 /* .ppid */
7691 /* .tid */
7692 /* .ptid */
7693 /* .time */
7697 perf_iterate_sb(perf_event_task_output,
7698 &task_event,
7699 task_ctx);
7702 void perf_event_fork(struct task_struct *task)
7704 perf_event_task(task, NULL, 1);
7705 perf_event_namespaces(task);
7709 * comm tracking
7712 struct perf_comm_event {
7713 struct task_struct *task;
7714 char *comm;
7715 int comm_size;
7717 struct {
7718 struct perf_event_header header;
7720 u32 pid;
7721 u32 tid;
7722 } event_id;
7725 static int perf_event_comm_match(struct perf_event *event)
7727 return event->attr.comm;
7730 static void perf_event_comm_output(struct perf_event *event,
7731 void *data)
7733 struct perf_comm_event *comm_event = data;
7734 struct perf_output_handle handle;
7735 struct perf_sample_data sample;
7736 int size = comm_event->event_id.header.size;
7737 int ret;
7739 if (!perf_event_comm_match(event))
7740 return;
7742 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7743 ret = perf_output_begin(&handle, &sample, event,
7744 comm_event->event_id.header.size);
7746 if (ret)
7747 goto out;
7749 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7750 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7752 perf_output_put(&handle, comm_event->event_id);
7753 __output_copy(&handle, comm_event->comm,
7754 comm_event->comm_size);
7756 perf_event__output_id_sample(event, &handle, &sample);
7758 perf_output_end(&handle);
7759 out:
7760 comm_event->event_id.header.size = size;
7763 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7765 char comm[TASK_COMM_LEN];
7766 unsigned int size;
7768 memset(comm, 0, sizeof(comm));
7769 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7770 size = ALIGN(strlen(comm)+1, sizeof(u64));
7772 comm_event->comm = comm;
7773 comm_event->comm_size = size;
7775 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7777 perf_iterate_sb(perf_event_comm_output,
7778 comm_event,
7779 NULL);
7782 void perf_event_comm(struct task_struct *task, bool exec)
7784 struct perf_comm_event comm_event;
7786 if (!atomic_read(&nr_comm_events))
7787 return;
7789 comm_event = (struct perf_comm_event){
7790 .task = task,
7791 /* .comm */
7792 /* .comm_size */
7793 .event_id = {
7794 .header = {
7795 .type = PERF_RECORD_COMM,
7796 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7797 /* .size */
7799 /* .pid */
7800 /* .tid */
7804 perf_event_comm_event(&comm_event);
7808 * namespaces tracking
7811 struct perf_namespaces_event {
7812 struct task_struct *task;
7814 struct {
7815 struct perf_event_header header;
7817 u32 pid;
7818 u32 tid;
7819 u64 nr_namespaces;
7820 struct perf_ns_link_info link_info[NR_NAMESPACES];
7821 } event_id;
7824 static int perf_event_namespaces_match(struct perf_event *event)
7826 return event->attr.namespaces;
7829 static void perf_event_namespaces_output(struct perf_event *event,
7830 void *data)
7832 struct perf_namespaces_event *namespaces_event = data;
7833 struct perf_output_handle handle;
7834 struct perf_sample_data sample;
7835 u16 header_size = namespaces_event->event_id.header.size;
7836 int ret;
7838 if (!perf_event_namespaces_match(event))
7839 return;
7841 perf_event_header__init_id(&namespaces_event->event_id.header,
7842 &sample, event);
7843 ret = perf_output_begin(&handle, &sample, event,
7844 namespaces_event->event_id.header.size);
7845 if (ret)
7846 goto out;
7848 namespaces_event->event_id.pid = perf_event_pid(event,
7849 namespaces_event->task);
7850 namespaces_event->event_id.tid = perf_event_tid(event,
7851 namespaces_event->task);
7853 perf_output_put(&handle, namespaces_event->event_id);
7855 perf_event__output_id_sample(event, &handle, &sample);
7857 perf_output_end(&handle);
7858 out:
7859 namespaces_event->event_id.header.size = header_size;
7862 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7863 struct task_struct *task,
7864 const struct proc_ns_operations *ns_ops)
7866 struct path ns_path;
7867 struct inode *ns_inode;
7868 int error;
7870 error = ns_get_path(&ns_path, task, ns_ops);
7871 if (!error) {
7872 ns_inode = ns_path.dentry->d_inode;
7873 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7874 ns_link_info->ino = ns_inode->i_ino;
7875 path_put(&ns_path);
7879 void perf_event_namespaces(struct task_struct *task)
7881 struct perf_namespaces_event namespaces_event;
7882 struct perf_ns_link_info *ns_link_info;
7884 if (!atomic_read(&nr_namespaces_events))
7885 return;
7887 namespaces_event = (struct perf_namespaces_event){
7888 .task = task,
7889 .event_id = {
7890 .header = {
7891 .type = PERF_RECORD_NAMESPACES,
7892 .misc = 0,
7893 .size = sizeof(namespaces_event.event_id),
7895 /* .pid */
7896 /* .tid */
7897 .nr_namespaces = NR_NAMESPACES,
7898 /* .link_info[NR_NAMESPACES] */
7902 ns_link_info = namespaces_event.event_id.link_info;
7904 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7905 task, &mntns_operations);
7907 #ifdef CONFIG_USER_NS
7908 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7909 task, &userns_operations);
7910 #endif
7911 #ifdef CONFIG_NET_NS
7912 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7913 task, &netns_operations);
7914 #endif
7915 #ifdef CONFIG_UTS_NS
7916 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7917 task, &utsns_operations);
7918 #endif
7919 #ifdef CONFIG_IPC_NS
7920 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7921 task, &ipcns_operations);
7922 #endif
7923 #ifdef CONFIG_PID_NS
7924 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7925 task, &pidns_operations);
7926 #endif
7927 #ifdef CONFIG_CGROUPS
7928 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7929 task, &cgroupns_operations);
7930 #endif
7932 perf_iterate_sb(perf_event_namespaces_output,
7933 &namespaces_event,
7934 NULL);
7938 * cgroup tracking
7940 #ifdef CONFIG_CGROUP_PERF
7942 struct perf_cgroup_event {
7943 char *path;
7944 int path_size;
7945 struct {
7946 struct perf_event_header header;
7947 u64 id;
7948 char path[];
7949 } event_id;
7952 static int perf_event_cgroup_match(struct perf_event *event)
7954 return event->attr.cgroup;
7957 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7959 struct perf_cgroup_event *cgroup_event = data;
7960 struct perf_output_handle handle;
7961 struct perf_sample_data sample;
7962 u16 header_size = cgroup_event->event_id.header.size;
7963 int ret;
7965 if (!perf_event_cgroup_match(event))
7966 return;
7968 perf_event_header__init_id(&cgroup_event->event_id.header,
7969 &sample, event);
7970 ret = perf_output_begin(&handle, &sample, event,
7971 cgroup_event->event_id.header.size);
7972 if (ret)
7973 goto out;
7975 perf_output_put(&handle, cgroup_event->event_id);
7976 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7978 perf_event__output_id_sample(event, &handle, &sample);
7980 perf_output_end(&handle);
7981 out:
7982 cgroup_event->event_id.header.size = header_size;
7985 static void perf_event_cgroup(struct cgroup *cgrp)
7987 struct perf_cgroup_event cgroup_event;
7988 char path_enomem[16] = "//enomem";
7989 char *pathname;
7990 size_t size;
7992 if (!atomic_read(&nr_cgroup_events))
7993 return;
7995 cgroup_event = (struct perf_cgroup_event){
7996 .event_id = {
7997 .header = {
7998 .type = PERF_RECORD_CGROUP,
7999 .misc = 0,
8000 .size = sizeof(cgroup_event.event_id),
8002 .id = cgroup_id(cgrp),
8006 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8007 if (pathname == NULL) {
8008 cgroup_event.path = path_enomem;
8009 } else {
8010 /* just to be sure to have enough space for alignment */
8011 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8012 cgroup_event.path = pathname;
8016 * Since our buffer works in 8 byte units we need to align our string
8017 * size to a multiple of 8. However, we must guarantee the tail end is
8018 * zero'd out to avoid leaking random bits to userspace.
8020 size = strlen(cgroup_event.path) + 1;
8021 while (!IS_ALIGNED(size, sizeof(u64)))
8022 cgroup_event.path[size++] = '\0';
8024 cgroup_event.event_id.header.size += size;
8025 cgroup_event.path_size = size;
8027 perf_iterate_sb(perf_event_cgroup_output,
8028 &cgroup_event,
8029 NULL);
8031 kfree(pathname);
8034 #endif
8037 * mmap tracking
8040 struct perf_mmap_event {
8041 struct vm_area_struct *vma;
8043 const char *file_name;
8044 int file_size;
8045 int maj, min;
8046 u64 ino;
8047 u64 ino_generation;
8048 u32 prot, flags;
8050 struct {
8051 struct perf_event_header header;
8053 u32 pid;
8054 u32 tid;
8055 u64 start;
8056 u64 len;
8057 u64 pgoff;
8058 } event_id;
8061 static int perf_event_mmap_match(struct perf_event *event,
8062 void *data)
8064 struct perf_mmap_event *mmap_event = data;
8065 struct vm_area_struct *vma = mmap_event->vma;
8066 int executable = vma->vm_flags & VM_EXEC;
8068 return (!executable && event->attr.mmap_data) ||
8069 (executable && (event->attr.mmap || event->attr.mmap2));
8072 static void perf_event_mmap_output(struct perf_event *event,
8073 void *data)
8075 struct perf_mmap_event *mmap_event = data;
8076 struct perf_output_handle handle;
8077 struct perf_sample_data sample;
8078 int size = mmap_event->event_id.header.size;
8079 u32 type = mmap_event->event_id.header.type;
8080 int ret;
8082 if (!perf_event_mmap_match(event, data))
8083 return;
8085 if (event->attr.mmap2) {
8086 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8087 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8088 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8089 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8090 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8091 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8092 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8095 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8096 ret = perf_output_begin(&handle, &sample, event,
8097 mmap_event->event_id.header.size);
8098 if (ret)
8099 goto out;
8101 mmap_event->event_id.pid = perf_event_pid(event, current);
8102 mmap_event->event_id.tid = perf_event_tid(event, current);
8104 perf_output_put(&handle, mmap_event->event_id);
8106 if (event->attr.mmap2) {
8107 perf_output_put(&handle, mmap_event->maj);
8108 perf_output_put(&handle, mmap_event->min);
8109 perf_output_put(&handle, mmap_event->ino);
8110 perf_output_put(&handle, mmap_event->ino_generation);
8111 perf_output_put(&handle, mmap_event->prot);
8112 perf_output_put(&handle, mmap_event->flags);
8115 __output_copy(&handle, mmap_event->file_name,
8116 mmap_event->file_size);
8118 perf_event__output_id_sample(event, &handle, &sample);
8120 perf_output_end(&handle);
8121 out:
8122 mmap_event->event_id.header.size = size;
8123 mmap_event->event_id.header.type = type;
8126 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8128 struct vm_area_struct *vma = mmap_event->vma;
8129 struct file *file = vma->vm_file;
8130 int maj = 0, min = 0;
8131 u64 ino = 0, gen = 0;
8132 u32 prot = 0, flags = 0;
8133 unsigned int size;
8134 char tmp[16];
8135 char *buf = NULL;
8136 char *name;
8138 if (vma->vm_flags & VM_READ)
8139 prot |= PROT_READ;
8140 if (vma->vm_flags & VM_WRITE)
8141 prot |= PROT_WRITE;
8142 if (vma->vm_flags & VM_EXEC)
8143 prot |= PROT_EXEC;
8145 if (vma->vm_flags & VM_MAYSHARE)
8146 flags = MAP_SHARED;
8147 else
8148 flags = MAP_PRIVATE;
8150 if (vma->vm_flags & VM_DENYWRITE)
8151 flags |= MAP_DENYWRITE;
8152 if (vma->vm_flags & VM_MAYEXEC)
8153 flags |= MAP_EXECUTABLE;
8154 if (vma->vm_flags & VM_LOCKED)
8155 flags |= MAP_LOCKED;
8156 if (is_vm_hugetlb_page(vma))
8157 flags |= MAP_HUGETLB;
8159 if (file) {
8160 struct inode *inode;
8161 dev_t dev;
8163 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8164 if (!buf) {
8165 name = "//enomem";
8166 goto cpy_name;
8169 * d_path() works from the end of the rb backwards, so we
8170 * need to add enough zero bytes after the string to handle
8171 * the 64bit alignment we do later.
8173 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8174 if (IS_ERR(name)) {
8175 name = "//toolong";
8176 goto cpy_name;
8178 inode = file_inode(vma->vm_file);
8179 dev = inode->i_sb->s_dev;
8180 ino = inode->i_ino;
8181 gen = inode->i_generation;
8182 maj = MAJOR(dev);
8183 min = MINOR(dev);
8185 goto got_name;
8186 } else {
8187 if (vma->vm_ops && vma->vm_ops->name) {
8188 name = (char *) vma->vm_ops->name(vma);
8189 if (name)
8190 goto cpy_name;
8193 name = (char *)arch_vma_name(vma);
8194 if (name)
8195 goto cpy_name;
8197 if (vma->vm_start <= vma->vm_mm->start_brk &&
8198 vma->vm_end >= vma->vm_mm->brk) {
8199 name = "[heap]";
8200 goto cpy_name;
8202 if (vma->vm_start <= vma->vm_mm->start_stack &&
8203 vma->vm_end >= vma->vm_mm->start_stack) {
8204 name = "[stack]";
8205 goto cpy_name;
8208 name = "//anon";
8209 goto cpy_name;
8212 cpy_name:
8213 strlcpy(tmp, name, sizeof(tmp));
8214 name = tmp;
8215 got_name:
8217 * Since our buffer works in 8 byte units we need to align our string
8218 * size to a multiple of 8. However, we must guarantee the tail end is
8219 * zero'd out to avoid leaking random bits to userspace.
8221 size = strlen(name)+1;
8222 while (!IS_ALIGNED(size, sizeof(u64)))
8223 name[size++] = '\0';
8225 mmap_event->file_name = name;
8226 mmap_event->file_size = size;
8227 mmap_event->maj = maj;
8228 mmap_event->min = min;
8229 mmap_event->ino = ino;
8230 mmap_event->ino_generation = gen;
8231 mmap_event->prot = prot;
8232 mmap_event->flags = flags;
8234 if (!(vma->vm_flags & VM_EXEC))
8235 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8237 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8239 perf_iterate_sb(perf_event_mmap_output,
8240 mmap_event,
8241 NULL);
8243 kfree(buf);
8247 * Check whether inode and address range match filter criteria.
8249 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8250 struct file *file, unsigned long offset,
8251 unsigned long size)
8253 /* d_inode(NULL) won't be equal to any mapped user-space file */
8254 if (!filter->path.dentry)
8255 return false;
8257 if (d_inode(filter->path.dentry) != file_inode(file))
8258 return false;
8260 if (filter->offset > offset + size)
8261 return false;
8263 if (filter->offset + filter->size < offset)
8264 return false;
8266 return true;
8269 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8270 struct vm_area_struct *vma,
8271 struct perf_addr_filter_range *fr)
8273 unsigned long vma_size = vma->vm_end - vma->vm_start;
8274 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8275 struct file *file = vma->vm_file;
8277 if (!perf_addr_filter_match(filter, file, off, vma_size))
8278 return false;
8280 if (filter->offset < off) {
8281 fr->start = vma->vm_start;
8282 fr->size = min(vma_size, filter->size - (off - filter->offset));
8283 } else {
8284 fr->start = vma->vm_start + filter->offset - off;
8285 fr->size = min(vma->vm_end - fr->start, filter->size);
8288 return true;
8291 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8293 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8294 struct vm_area_struct *vma = data;
8295 struct perf_addr_filter *filter;
8296 unsigned int restart = 0, count = 0;
8297 unsigned long flags;
8299 if (!has_addr_filter(event))
8300 return;
8302 if (!vma->vm_file)
8303 return;
8305 raw_spin_lock_irqsave(&ifh->lock, flags);
8306 list_for_each_entry(filter, &ifh->list, entry) {
8307 if (perf_addr_filter_vma_adjust(filter, vma,
8308 &event->addr_filter_ranges[count]))
8309 restart++;
8311 count++;
8314 if (restart)
8315 event->addr_filters_gen++;
8316 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8318 if (restart)
8319 perf_event_stop(event, 1);
8323 * Adjust all task's events' filters to the new vma
8325 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8327 struct perf_event_context *ctx;
8328 int ctxn;
8331 * Data tracing isn't supported yet and as such there is no need
8332 * to keep track of anything that isn't related to executable code:
8334 if (!(vma->vm_flags & VM_EXEC))
8335 return;
8337 rcu_read_lock();
8338 for_each_task_context_nr(ctxn) {
8339 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8340 if (!ctx)
8341 continue;
8343 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8345 rcu_read_unlock();
8348 void perf_event_mmap(struct vm_area_struct *vma)
8350 struct perf_mmap_event mmap_event;
8352 if (!atomic_read(&nr_mmap_events))
8353 return;
8355 mmap_event = (struct perf_mmap_event){
8356 .vma = vma,
8357 /* .file_name */
8358 /* .file_size */
8359 .event_id = {
8360 .header = {
8361 .type = PERF_RECORD_MMAP,
8362 .misc = PERF_RECORD_MISC_USER,
8363 /* .size */
8365 /* .pid */
8366 /* .tid */
8367 .start = vma->vm_start,
8368 .len = vma->vm_end - vma->vm_start,
8369 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8371 /* .maj (attr_mmap2 only) */
8372 /* .min (attr_mmap2 only) */
8373 /* .ino (attr_mmap2 only) */
8374 /* .ino_generation (attr_mmap2 only) */
8375 /* .prot (attr_mmap2 only) */
8376 /* .flags (attr_mmap2 only) */
8379 perf_addr_filters_adjust(vma);
8380 perf_event_mmap_event(&mmap_event);
8383 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8384 unsigned long size, u64 flags)
8386 struct perf_output_handle handle;
8387 struct perf_sample_data sample;
8388 struct perf_aux_event {
8389 struct perf_event_header header;
8390 u64 offset;
8391 u64 size;
8392 u64 flags;
8393 } rec = {
8394 .header = {
8395 .type = PERF_RECORD_AUX,
8396 .misc = 0,
8397 .size = sizeof(rec),
8399 .offset = head,
8400 .size = size,
8401 .flags = flags,
8403 int ret;
8405 perf_event_header__init_id(&rec.header, &sample, event);
8406 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8408 if (ret)
8409 return;
8411 perf_output_put(&handle, rec);
8412 perf_event__output_id_sample(event, &handle, &sample);
8414 perf_output_end(&handle);
8418 * Lost/dropped samples logging
8420 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8422 struct perf_output_handle handle;
8423 struct perf_sample_data sample;
8424 int ret;
8426 struct {
8427 struct perf_event_header header;
8428 u64 lost;
8429 } lost_samples_event = {
8430 .header = {
8431 .type = PERF_RECORD_LOST_SAMPLES,
8432 .misc = 0,
8433 .size = sizeof(lost_samples_event),
8435 .lost = lost,
8438 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8440 ret = perf_output_begin(&handle, &sample, event,
8441 lost_samples_event.header.size);
8442 if (ret)
8443 return;
8445 perf_output_put(&handle, lost_samples_event);
8446 perf_event__output_id_sample(event, &handle, &sample);
8447 perf_output_end(&handle);
8451 * context_switch tracking
8454 struct perf_switch_event {
8455 struct task_struct *task;
8456 struct task_struct *next_prev;
8458 struct {
8459 struct perf_event_header header;
8460 u32 next_prev_pid;
8461 u32 next_prev_tid;
8462 } event_id;
8465 static int perf_event_switch_match(struct perf_event *event)
8467 return event->attr.context_switch;
8470 static void perf_event_switch_output(struct perf_event *event, void *data)
8472 struct perf_switch_event *se = data;
8473 struct perf_output_handle handle;
8474 struct perf_sample_data sample;
8475 int ret;
8477 if (!perf_event_switch_match(event))
8478 return;
8480 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8481 if (event->ctx->task) {
8482 se->event_id.header.type = PERF_RECORD_SWITCH;
8483 se->event_id.header.size = sizeof(se->event_id.header);
8484 } else {
8485 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8486 se->event_id.header.size = sizeof(se->event_id);
8487 se->event_id.next_prev_pid =
8488 perf_event_pid(event, se->next_prev);
8489 se->event_id.next_prev_tid =
8490 perf_event_tid(event, se->next_prev);
8493 perf_event_header__init_id(&se->event_id.header, &sample, event);
8495 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8496 if (ret)
8497 return;
8499 if (event->ctx->task)
8500 perf_output_put(&handle, se->event_id.header);
8501 else
8502 perf_output_put(&handle, se->event_id);
8504 perf_event__output_id_sample(event, &handle, &sample);
8506 perf_output_end(&handle);
8509 static void perf_event_switch(struct task_struct *task,
8510 struct task_struct *next_prev, bool sched_in)
8512 struct perf_switch_event switch_event;
8514 /* N.B. caller checks nr_switch_events != 0 */
8516 switch_event = (struct perf_switch_event){
8517 .task = task,
8518 .next_prev = next_prev,
8519 .event_id = {
8520 .header = {
8521 /* .type */
8522 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8523 /* .size */
8525 /* .next_prev_pid */
8526 /* .next_prev_tid */
8530 if (!sched_in && task->state == TASK_RUNNING)
8531 switch_event.event_id.header.misc |=
8532 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8534 perf_iterate_sb(perf_event_switch_output,
8535 &switch_event,
8536 NULL);
8540 * IRQ throttle logging
8543 static void perf_log_throttle(struct perf_event *event, int enable)
8545 struct perf_output_handle handle;
8546 struct perf_sample_data sample;
8547 int ret;
8549 struct {
8550 struct perf_event_header header;
8551 u64 time;
8552 u64 id;
8553 u64 stream_id;
8554 } throttle_event = {
8555 .header = {
8556 .type = PERF_RECORD_THROTTLE,
8557 .misc = 0,
8558 .size = sizeof(throttle_event),
8560 .time = perf_event_clock(event),
8561 .id = primary_event_id(event),
8562 .stream_id = event->id,
8565 if (enable)
8566 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8568 perf_event_header__init_id(&throttle_event.header, &sample, event);
8570 ret = perf_output_begin(&handle, &sample, event,
8571 throttle_event.header.size);
8572 if (ret)
8573 return;
8575 perf_output_put(&handle, throttle_event);
8576 perf_event__output_id_sample(event, &handle, &sample);
8577 perf_output_end(&handle);
8581 * ksymbol register/unregister tracking
8584 struct perf_ksymbol_event {
8585 const char *name;
8586 int name_len;
8587 struct {
8588 struct perf_event_header header;
8589 u64 addr;
8590 u32 len;
8591 u16 ksym_type;
8592 u16 flags;
8593 } event_id;
8596 static int perf_event_ksymbol_match(struct perf_event *event)
8598 return event->attr.ksymbol;
8601 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8603 struct perf_ksymbol_event *ksymbol_event = data;
8604 struct perf_output_handle handle;
8605 struct perf_sample_data sample;
8606 int ret;
8608 if (!perf_event_ksymbol_match(event))
8609 return;
8611 perf_event_header__init_id(&ksymbol_event->event_id.header,
8612 &sample, event);
8613 ret = perf_output_begin(&handle, &sample, event,
8614 ksymbol_event->event_id.header.size);
8615 if (ret)
8616 return;
8618 perf_output_put(&handle, ksymbol_event->event_id);
8619 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8620 perf_event__output_id_sample(event, &handle, &sample);
8622 perf_output_end(&handle);
8625 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8626 const char *sym)
8628 struct perf_ksymbol_event ksymbol_event;
8629 char name[KSYM_NAME_LEN];
8630 u16 flags = 0;
8631 int name_len;
8633 if (!atomic_read(&nr_ksymbol_events))
8634 return;
8636 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8637 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8638 goto err;
8640 strlcpy(name, sym, KSYM_NAME_LEN);
8641 name_len = strlen(name) + 1;
8642 while (!IS_ALIGNED(name_len, sizeof(u64)))
8643 name[name_len++] = '\0';
8644 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8646 if (unregister)
8647 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8649 ksymbol_event = (struct perf_ksymbol_event){
8650 .name = name,
8651 .name_len = name_len,
8652 .event_id = {
8653 .header = {
8654 .type = PERF_RECORD_KSYMBOL,
8655 .size = sizeof(ksymbol_event.event_id) +
8656 name_len,
8658 .addr = addr,
8659 .len = len,
8660 .ksym_type = ksym_type,
8661 .flags = flags,
8665 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8666 return;
8667 err:
8668 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8672 * bpf program load/unload tracking
8675 struct perf_bpf_event {
8676 struct bpf_prog *prog;
8677 struct {
8678 struct perf_event_header header;
8679 u16 type;
8680 u16 flags;
8681 u32 id;
8682 u8 tag[BPF_TAG_SIZE];
8683 } event_id;
8686 static int perf_event_bpf_match(struct perf_event *event)
8688 return event->attr.bpf_event;
8691 static void perf_event_bpf_output(struct perf_event *event, void *data)
8693 struct perf_bpf_event *bpf_event = data;
8694 struct perf_output_handle handle;
8695 struct perf_sample_data sample;
8696 int ret;
8698 if (!perf_event_bpf_match(event))
8699 return;
8701 perf_event_header__init_id(&bpf_event->event_id.header,
8702 &sample, event);
8703 ret = perf_output_begin(&handle, data, event,
8704 bpf_event->event_id.header.size);
8705 if (ret)
8706 return;
8708 perf_output_put(&handle, bpf_event->event_id);
8709 perf_event__output_id_sample(event, &handle, &sample);
8711 perf_output_end(&handle);
8714 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8715 enum perf_bpf_event_type type)
8717 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8718 int i;
8720 if (prog->aux->func_cnt == 0) {
8721 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8722 (u64)(unsigned long)prog->bpf_func,
8723 prog->jited_len, unregister,
8724 prog->aux->ksym.name);
8725 } else {
8726 for (i = 0; i < prog->aux->func_cnt; i++) {
8727 struct bpf_prog *subprog = prog->aux->func[i];
8729 perf_event_ksymbol(
8730 PERF_RECORD_KSYMBOL_TYPE_BPF,
8731 (u64)(unsigned long)subprog->bpf_func,
8732 subprog->jited_len, unregister,
8733 prog->aux->ksym.name);
8738 void perf_event_bpf_event(struct bpf_prog *prog,
8739 enum perf_bpf_event_type type,
8740 u16 flags)
8742 struct perf_bpf_event bpf_event;
8744 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8745 type >= PERF_BPF_EVENT_MAX)
8746 return;
8748 switch (type) {
8749 case PERF_BPF_EVENT_PROG_LOAD:
8750 case PERF_BPF_EVENT_PROG_UNLOAD:
8751 if (atomic_read(&nr_ksymbol_events))
8752 perf_event_bpf_emit_ksymbols(prog, type);
8753 break;
8754 default:
8755 break;
8758 if (!atomic_read(&nr_bpf_events))
8759 return;
8761 bpf_event = (struct perf_bpf_event){
8762 .prog = prog,
8763 .event_id = {
8764 .header = {
8765 .type = PERF_RECORD_BPF_EVENT,
8766 .size = sizeof(bpf_event.event_id),
8768 .type = type,
8769 .flags = flags,
8770 .id = prog->aux->id,
8774 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8776 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8777 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8780 struct perf_text_poke_event {
8781 const void *old_bytes;
8782 const void *new_bytes;
8783 size_t pad;
8784 u16 old_len;
8785 u16 new_len;
8787 struct {
8788 struct perf_event_header header;
8790 u64 addr;
8791 } event_id;
8794 static int perf_event_text_poke_match(struct perf_event *event)
8796 return event->attr.text_poke;
8799 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8801 struct perf_text_poke_event *text_poke_event = data;
8802 struct perf_output_handle handle;
8803 struct perf_sample_data sample;
8804 u64 padding = 0;
8805 int ret;
8807 if (!perf_event_text_poke_match(event))
8808 return;
8810 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8812 ret = perf_output_begin(&handle, &sample, event,
8813 text_poke_event->event_id.header.size);
8814 if (ret)
8815 return;
8817 perf_output_put(&handle, text_poke_event->event_id);
8818 perf_output_put(&handle, text_poke_event->old_len);
8819 perf_output_put(&handle, text_poke_event->new_len);
8821 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8822 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8824 if (text_poke_event->pad)
8825 __output_copy(&handle, &padding, text_poke_event->pad);
8827 perf_event__output_id_sample(event, &handle, &sample);
8829 perf_output_end(&handle);
8832 void perf_event_text_poke(const void *addr, const void *old_bytes,
8833 size_t old_len, const void *new_bytes, size_t new_len)
8835 struct perf_text_poke_event text_poke_event;
8836 size_t tot, pad;
8838 if (!atomic_read(&nr_text_poke_events))
8839 return;
8841 tot = sizeof(text_poke_event.old_len) + old_len;
8842 tot += sizeof(text_poke_event.new_len) + new_len;
8843 pad = ALIGN(tot, sizeof(u64)) - tot;
8845 text_poke_event = (struct perf_text_poke_event){
8846 .old_bytes = old_bytes,
8847 .new_bytes = new_bytes,
8848 .pad = pad,
8849 .old_len = old_len,
8850 .new_len = new_len,
8851 .event_id = {
8852 .header = {
8853 .type = PERF_RECORD_TEXT_POKE,
8854 .misc = PERF_RECORD_MISC_KERNEL,
8855 .size = sizeof(text_poke_event.event_id) + tot + pad,
8857 .addr = (unsigned long)addr,
8861 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8864 void perf_event_itrace_started(struct perf_event *event)
8866 event->attach_state |= PERF_ATTACH_ITRACE;
8869 static void perf_log_itrace_start(struct perf_event *event)
8871 struct perf_output_handle handle;
8872 struct perf_sample_data sample;
8873 struct perf_aux_event {
8874 struct perf_event_header header;
8875 u32 pid;
8876 u32 tid;
8877 } rec;
8878 int ret;
8880 if (event->parent)
8881 event = event->parent;
8883 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8884 event->attach_state & PERF_ATTACH_ITRACE)
8885 return;
8887 rec.header.type = PERF_RECORD_ITRACE_START;
8888 rec.header.misc = 0;
8889 rec.header.size = sizeof(rec);
8890 rec.pid = perf_event_pid(event, current);
8891 rec.tid = perf_event_tid(event, current);
8893 perf_event_header__init_id(&rec.header, &sample, event);
8894 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8896 if (ret)
8897 return;
8899 perf_output_put(&handle, rec);
8900 perf_event__output_id_sample(event, &handle, &sample);
8902 perf_output_end(&handle);
8905 static int
8906 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8908 struct hw_perf_event *hwc = &event->hw;
8909 int ret = 0;
8910 u64 seq;
8912 seq = __this_cpu_read(perf_throttled_seq);
8913 if (seq != hwc->interrupts_seq) {
8914 hwc->interrupts_seq = seq;
8915 hwc->interrupts = 1;
8916 } else {
8917 hwc->interrupts++;
8918 if (unlikely(throttle
8919 && hwc->interrupts >= max_samples_per_tick)) {
8920 __this_cpu_inc(perf_throttled_count);
8921 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8922 hwc->interrupts = MAX_INTERRUPTS;
8923 perf_log_throttle(event, 0);
8924 ret = 1;
8928 if (event->attr.freq) {
8929 u64 now = perf_clock();
8930 s64 delta = now - hwc->freq_time_stamp;
8932 hwc->freq_time_stamp = now;
8934 if (delta > 0 && delta < 2*TICK_NSEC)
8935 perf_adjust_period(event, delta, hwc->last_period, true);
8938 return ret;
8941 int perf_event_account_interrupt(struct perf_event *event)
8943 return __perf_event_account_interrupt(event, 1);
8947 * Generic event overflow handling, sampling.
8950 static int __perf_event_overflow(struct perf_event *event,
8951 int throttle, struct perf_sample_data *data,
8952 struct pt_regs *regs)
8954 int events = atomic_read(&event->event_limit);
8955 int ret = 0;
8958 * Non-sampling counters might still use the PMI to fold short
8959 * hardware counters, ignore those.
8961 if (unlikely(!is_sampling_event(event)))
8962 return 0;
8964 ret = __perf_event_account_interrupt(event, throttle);
8967 * XXX event_limit might not quite work as expected on inherited
8968 * events
8971 event->pending_kill = POLL_IN;
8972 if (events && atomic_dec_and_test(&event->event_limit)) {
8973 ret = 1;
8974 event->pending_kill = POLL_HUP;
8976 perf_event_disable_inatomic(event);
8979 READ_ONCE(event->overflow_handler)(event, data, regs);
8981 if (*perf_event_fasync(event) && event->pending_kill) {
8982 event->pending_wakeup = 1;
8983 irq_work_queue(&event->pending);
8986 return ret;
8989 int perf_event_overflow(struct perf_event *event,
8990 struct perf_sample_data *data,
8991 struct pt_regs *regs)
8993 return __perf_event_overflow(event, 1, data, regs);
8997 * Generic software event infrastructure
9000 struct swevent_htable {
9001 struct swevent_hlist *swevent_hlist;
9002 struct mutex hlist_mutex;
9003 int hlist_refcount;
9005 /* Recursion avoidance in each contexts */
9006 int recursion[PERF_NR_CONTEXTS];
9009 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9012 * We directly increment event->count and keep a second value in
9013 * event->hw.period_left to count intervals. This period event
9014 * is kept in the range [-sample_period, 0] so that we can use the
9015 * sign as trigger.
9018 u64 perf_swevent_set_period(struct perf_event *event)
9020 struct hw_perf_event *hwc = &event->hw;
9021 u64 period = hwc->last_period;
9022 u64 nr, offset;
9023 s64 old, val;
9025 hwc->last_period = hwc->sample_period;
9027 again:
9028 old = val = local64_read(&hwc->period_left);
9029 if (val < 0)
9030 return 0;
9032 nr = div64_u64(period + val, period);
9033 offset = nr * period;
9034 val -= offset;
9035 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9036 goto again;
9038 return nr;
9041 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9042 struct perf_sample_data *data,
9043 struct pt_regs *regs)
9045 struct hw_perf_event *hwc = &event->hw;
9046 int throttle = 0;
9048 if (!overflow)
9049 overflow = perf_swevent_set_period(event);
9051 if (hwc->interrupts == MAX_INTERRUPTS)
9052 return;
9054 for (; overflow; overflow--) {
9055 if (__perf_event_overflow(event, throttle,
9056 data, regs)) {
9058 * We inhibit the overflow from happening when
9059 * hwc->interrupts == MAX_INTERRUPTS.
9061 break;
9063 throttle = 1;
9067 static void perf_swevent_event(struct perf_event *event, u64 nr,
9068 struct perf_sample_data *data,
9069 struct pt_regs *regs)
9071 struct hw_perf_event *hwc = &event->hw;
9073 local64_add(nr, &event->count);
9075 if (!regs)
9076 return;
9078 if (!is_sampling_event(event))
9079 return;
9081 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9082 data->period = nr;
9083 return perf_swevent_overflow(event, 1, data, regs);
9084 } else
9085 data->period = event->hw.last_period;
9087 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9088 return perf_swevent_overflow(event, 1, data, regs);
9090 if (local64_add_negative(nr, &hwc->period_left))
9091 return;
9093 perf_swevent_overflow(event, 0, data, regs);
9096 static int perf_exclude_event(struct perf_event *event,
9097 struct pt_regs *regs)
9099 if (event->hw.state & PERF_HES_STOPPED)
9100 return 1;
9102 if (regs) {
9103 if (event->attr.exclude_user && user_mode(regs))
9104 return 1;
9106 if (event->attr.exclude_kernel && !user_mode(regs))
9107 return 1;
9110 return 0;
9113 static int perf_swevent_match(struct perf_event *event,
9114 enum perf_type_id type,
9115 u32 event_id,
9116 struct perf_sample_data *data,
9117 struct pt_regs *regs)
9119 if (event->attr.type != type)
9120 return 0;
9122 if (event->attr.config != event_id)
9123 return 0;
9125 if (perf_exclude_event(event, regs))
9126 return 0;
9128 return 1;
9131 static inline u64 swevent_hash(u64 type, u32 event_id)
9133 u64 val = event_id | (type << 32);
9135 return hash_64(val, SWEVENT_HLIST_BITS);
9138 static inline struct hlist_head *
9139 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9141 u64 hash = swevent_hash(type, event_id);
9143 return &hlist->heads[hash];
9146 /* For the read side: events when they trigger */
9147 static inline struct hlist_head *
9148 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9150 struct swevent_hlist *hlist;
9152 hlist = rcu_dereference(swhash->swevent_hlist);
9153 if (!hlist)
9154 return NULL;
9156 return __find_swevent_head(hlist, type, event_id);
9159 /* For the event head insertion and removal in the hlist */
9160 static inline struct hlist_head *
9161 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9163 struct swevent_hlist *hlist;
9164 u32 event_id = event->attr.config;
9165 u64 type = event->attr.type;
9168 * Event scheduling is always serialized against hlist allocation
9169 * and release. Which makes the protected version suitable here.
9170 * The context lock guarantees that.
9172 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9173 lockdep_is_held(&event->ctx->lock));
9174 if (!hlist)
9175 return NULL;
9177 return __find_swevent_head(hlist, type, event_id);
9180 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9181 u64 nr,
9182 struct perf_sample_data *data,
9183 struct pt_regs *regs)
9185 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9186 struct perf_event *event;
9187 struct hlist_head *head;
9189 rcu_read_lock();
9190 head = find_swevent_head_rcu(swhash, type, event_id);
9191 if (!head)
9192 goto end;
9194 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9195 if (perf_swevent_match(event, type, event_id, data, regs))
9196 perf_swevent_event(event, nr, data, regs);
9198 end:
9199 rcu_read_unlock();
9202 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9204 int perf_swevent_get_recursion_context(void)
9206 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9208 return get_recursion_context(swhash->recursion);
9210 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9212 void perf_swevent_put_recursion_context(int rctx)
9214 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9216 put_recursion_context(swhash->recursion, rctx);
9219 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9221 struct perf_sample_data data;
9223 if (WARN_ON_ONCE(!regs))
9224 return;
9226 perf_sample_data_init(&data, addr, 0);
9227 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9230 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9232 int rctx;
9234 preempt_disable_notrace();
9235 rctx = perf_swevent_get_recursion_context();
9236 if (unlikely(rctx < 0))
9237 goto fail;
9239 ___perf_sw_event(event_id, nr, regs, addr);
9241 perf_swevent_put_recursion_context(rctx);
9242 fail:
9243 preempt_enable_notrace();
9246 static void perf_swevent_read(struct perf_event *event)
9250 static int perf_swevent_add(struct perf_event *event, int flags)
9252 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9253 struct hw_perf_event *hwc = &event->hw;
9254 struct hlist_head *head;
9256 if (is_sampling_event(event)) {
9257 hwc->last_period = hwc->sample_period;
9258 perf_swevent_set_period(event);
9261 hwc->state = !(flags & PERF_EF_START);
9263 head = find_swevent_head(swhash, event);
9264 if (WARN_ON_ONCE(!head))
9265 return -EINVAL;
9267 hlist_add_head_rcu(&event->hlist_entry, head);
9268 perf_event_update_userpage(event);
9270 return 0;
9273 static void perf_swevent_del(struct perf_event *event, int flags)
9275 hlist_del_rcu(&event->hlist_entry);
9278 static void perf_swevent_start(struct perf_event *event, int flags)
9280 event->hw.state = 0;
9283 static void perf_swevent_stop(struct perf_event *event, int flags)
9285 event->hw.state = PERF_HES_STOPPED;
9288 /* Deref the hlist from the update side */
9289 static inline struct swevent_hlist *
9290 swevent_hlist_deref(struct swevent_htable *swhash)
9292 return rcu_dereference_protected(swhash->swevent_hlist,
9293 lockdep_is_held(&swhash->hlist_mutex));
9296 static void swevent_hlist_release(struct swevent_htable *swhash)
9298 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9300 if (!hlist)
9301 return;
9303 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9304 kfree_rcu(hlist, rcu_head);
9307 static void swevent_hlist_put_cpu(int cpu)
9309 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9311 mutex_lock(&swhash->hlist_mutex);
9313 if (!--swhash->hlist_refcount)
9314 swevent_hlist_release(swhash);
9316 mutex_unlock(&swhash->hlist_mutex);
9319 static void swevent_hlist_put(void)
9321 int cpu;
9323 for_each_possible_cpu(cpu)
9324 swevent_hlist_put_cpu(cpu);
9327 static int swevent_hlist_get_cpu(int cpu)
9329 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9330 int err = 0;
9332 mutex_lock(&swhash->hlist_mutex);
9333 if (!swevent_hlist_deref(swhash) &&
9334 cpumask_test_cpu(cpu, perf_online_mask)) {
9335 struct swevent_hlist *hlist;
9337 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9338 if (!hlist) {
9339 err = -ENOMEM;
9340 goto exit;
9342 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9344 swhash->hlist_refcount++;
9345 exit:
9346 mutex_unlock(&swhash->hlist_mutex);
9348 return err;
9351 static int swevent_hlist_get(void)
9353 int err, cpu, failed_cpu;
9355 mutex_lock(&pmus_lock);
9356 for_each_possible_cpu(cpu) {
9357 err = swevent_hlist_get_cpu(cpu);
9358 if (err) {
9359 failed_cpu = cpu;
9360 goto fail;
9363 mutex_unlock(&pmus_lock);
9364 return 0;
9365 fail:
9366 for_each_possible_cpu(cpu) {
9367 if (cpu == failed_cpu)
9368 break;
9369 swevent_hlist_put_cpu(cpu);
9371 mutex_unlock(&pmus_lock);
9372 return err;
9375 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9377 static void sw_perf_event_destroy(struct perf_event *event)
9379 u64 event_id = event->attr.config;
9381 WARN_ON(event->parent);
9383 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9384 swevent_hlist_put();
9387 static int perf_swevent_init(struct perf_event *event)
9389 u64 event_id = event->attr.config;
9391 if (event->attr.type != PERF_TYPE_SOFTWARE)
9392 return -ENOENT;
9395 * no branch sampling for software events
9397 if (has_branch_stack(event))
9398 return -EOPNOTSUPP;
9400 switch (event_id) {
9401 case PERF_COUNT_SW_CPU_CLOCK:
9402 case PERF_COUNT_SW_TASK_CLOCK:
9403 return -ENOENT;
9405 default:
9406 break;
9409 if (event_id >= PERF_COUNT_SW_MAX)
9410 return -ENOENT;
9412 if (!event->parent) {
9413 int err;
9415 err = swevent_hlist_get();
9416 if (err)
9417 return err;
9419 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9420 event->destroy = sw_perf_event_destroy;
9423 return 0;
9426 static struct pmu perf_swevent = {
9427 .task_ctx_nr = perf_sw_context,
9429 .capabilities = PERF_PMU_CAP_NO_NMI,
9431 .event_init = perf_swevent_init,
9432 .add = perf_swevent_add,
9433 .del = perf_swevent_del,
9434 .start = perf_swevent_start,
9435 .stop = perf_swevent_stop,
9436 .read = perf_swevent_read,
9439 #ifdef CONFIG_EVENT_TRACING
9441 static int perf_tp_filter_match(struct perf_event *event,
9442 struct perf_sample_data *data)
9444 void *record = data->raw->frag.data;
9446 /* only top level events have filters set */
9447 if (event->parent)
9448 event = event->parent;
9450 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9451 return 1;
9452 return 0;
9455 static int perf_tp_event_match(struct perf_event *event,
9456 struct perf_sample_data *data,
9457 struct pt_regs *regs)
9459 if (event->hw.state & PERF_HES_STOPPED)
9460 return 0;
9462 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9464 if (event->attr.exclude_kernel && !user_mode(regs))
9465 return 0;
9467 if (!perf_tp_filter_match(event, data))
9468 return 0;
9470 return 1;
9473 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9474 struct trace_event_call *call, u64 count,
9475 struct pt_regs *regs, struct hlist_head *head,
9476 struct task_struct *task)
9478 if (bpf_prog_array_valid(call)) {
9479 *(struct pt_regs **)raw_data = regs;
9480 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9481 perf_swevent_put_recursion_context(rctx);
9482 return;
9485 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9486 rctx, task);
9488 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9490 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9491 struct pt_regs *regs, struct hlist_head *head, int rctx,
9492 struct task_struct *task)
9494 struct perf_sample_data data;
9495 struct perf_event *event;
9497 struct perf_raw_record raw = {
9498 .frag = {
9499 .size = entry_size,
9500 .data = record,
9504 perf_sample_data_init(&data, 0, 0);
9505 data.raw = &raw;
9507 perf_trace_buf_update(record, event_type);
9509 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9510 if (perf_tp_event_match(event, &data, regs))
9511 perf_swevent_event(event, count, &data, regs);
9515 * If we got specified a target task, also iterate its context and
9516 * deliver this event there too.
9518 if (task && task != current) {
9519 struct perf_event_context *ctx;
9520 struct trace_entry *entry = record;
9522 rcu_read_lock();
9523 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9524 if (!ctx)
9525 goto unlock;
9527 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9528 if (event->cpu != smp_processor_id())
9529 continue;
9530 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9531 continue;
9532 if (event->attr.config != entry->type)
9533 continue;
9534 if (perf_tp_event_match(event, &data, regs))
9535 perf_swevent_event(event, count, &data, regs);
9537 unlock:
9538 rcu_read_unlock();
9541 perf_swevent_put_recursion_context(rctx);
9543 EXPORT_SYMBOL_GPL(perf_tp_event);
9545 static void tp_perf_event_destroy(struct perf_event *event)
9547 perf_trace_destroy(event);
9550 static int perf_tp_event_init(struct perf_event *event)
9552 int err;
9554 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9555 return -ENOENT;
9558 * no branch sampling for tracepoint events
9560 if (has_branch_stack(event))
9561 return -EOPNOTSUPP;
9563 err = perf_trace_init(event);
9564 if (err)
9565 return err;
9567 event->destroy = tp_perf_event_destroy;
9569 return 0;
9572 static struct pmu perf_tracepoint = {
9573 .task_ctx_nr = perf_sw_context,
9575 .event_init = perf_tp_event_init,
9576 .add = perf_trace_add,
9577 .del = perf_trace_del,
9578 .start = perf_swevent_start,
9579 .stop = perf_swevent_stop,
9580 .read = perf_swevent_read,
9583 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9585 * Flags in config, used by dynamic PMU kprobe and uprobe
9586 * The flags should match following PMU_FORMAT_ATTR().
9588 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9589 * if not set, create kprobe/uprobe
9591 * The following values specify a reference counter (or semaphore in the
9592 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9593 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9595 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9596 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9598 enum perf_probe_config {
9599 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9600 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9601 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9604 PMU_FORMAT_ATTR(retprobe, "config:0");
9605 #endif
9607 #ifdef CONFIG_KPROBE_EVENTS
9608 static struct attribute *kprobe_attrs[] = {
9609 &format_attr_retprobe.attr,
9610 NULL,
9613 static struct attribute_group kprobe_format_group = {
9614 .name = "format",
9615 .attrs = kprobe_attrs,
9618 static const struct attribute_group *kprobe_attr_groups[] = {
9619 &kprobe_format_group,
9620 NULL,
9623 static int perf_kprobe_event_init(struct perf_event *event);
9624 static struct pmu perf_kprobe = {
9625 .task_ctx_nr = perf_sw_context,
9626 .event_init = perf_kprobe_event_init,
9627 .add = perf_trace_add,
9628 .del = perf_trace_del,
9629 .start = perf_swevent_start,
9630 .stop = perf_swevent_stop,
9631 .read = perf_swevent_read,
9632 .attr_groups = kprobe_attr_groups,
9635 static int perf_kprobe_event_init(struct perf_event *event)
9637 int err;
9638 bool is_retprobe;
9640 if (event->attr.type != perf_kprobe.type)
9641 return -ENOENT;
9643 if (!perfmon_capable())
9644 return -EACCES;
9647 * no branch sampling for probe events
9649 if (has_branch_stack(event))
9650 return -EOPNOTSUPP;
9652 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9653 err = perf_kprobe_init(event, is_retprobe);
9654 if (err)
9655 return err;
9657 event->destroy = perf_kprobe_destroy;
9659 return 0;
9661 #endif /* CONFIG_KPROBE_EVENTS */
9663 #ifdef CONFIG_UPROBE_EVENTS
9664 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9666 static struct attribute *uprobe_attrs[] = {
9667 &format_attr_retprobe.attr,
9668 &format_attr_ref_ctr_offset.attr,
9669 NULL,
9672 static struct attribute_group uprobe_format_group = {
9673 .name = "format",
9674 .attrs = uprobe_attrs,
9677 static const struct attribute_group *uprobe_attr_groups[] = {
9678 &uprobe_format_group,
9679 NULL,
9682 static int perf_uprobe_event_init(struct perf_event *event);
9683 static struct pmu perf_uprobe = {
9684 .task_ctx_nr = perf_sw_context,
9685 .event_init = perf_uprobe_event_init,
9686 .add = perf_trace_add,
9687 .del = perf_trace_del,
9688 .start = perf_swevent_start,
9689 .stop = perf_swevent_stop,
9690 .read = perf_swevent_read,
9691 .attr_groups = uprobe_attr_groups,
9694 static int perf_uprobe_event_init(struct perf_event *event)
9696 int err;
9697 unsigned long ref_ctr_offset;
9698 bool is_retprobe;
9700 if (event->attr.type != perf_uprobe.type)
9701 return -ENOENT;
9703 if (!perfmon_capable())
9704 return -EACCES;
9707 * no branch sampling for probe events
9709 if (has_branch_stack(event))
9710 return -EOPNOTSUPP;
9712 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9713 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9714 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9715 if (err)
9716 return err;
9718 event->destroy = perf_uprobe_destroy;
9720 return 0;
9722 #endif /* CONFIG_UPROBE_EVENTS */
9724 static inline void perf_tp_register(void)
9726 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9727 #ifdef CONFIG_KPROBE_EVENTS
9728 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9729 #endif
9730 #ifdef CONFIG_UPROBE_EVENTS
9731 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9732 #endif
9735 static void perf_event_free_filter(struct perf_event *event)
9737 ftrace_profile_free_filter(event);
9740 #ifdef CONFIG_BPF_SYSCALL
9741 static void bpf_overflow_handler(struct perf_event *event,
9742 struct perf_sample_data *data,
9743 struct pt_regs *regs)
9745 struct bpf_perf_event_data_kern ctx = {
9746 .data = data,
9747 .event = event,
9749 int ret = 0;
9751 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9752 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9753 goto out;
9754 rcu_read_lock();
9755 ret = BPF_PROG_RUN(event->prog, &ctx);
9756 rcu_read_unlock();
9757 out:
9758 __this_cpu_dec(bpf_prog_active);
9759 if (!ret)
9760 return;
9762 event->orig_overflow_handler(event, data, regs);
9765 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9767 struct bpf_prog *prog;
9769 if (event->overflow_handler_context)
9770 /* hw breakpoint or kernel counter */
9771 return -EINVAL;
9773 if (event->prog)
9774 return -EEXIST;
9776 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9777 if (IS_ERR(prog))
9778 return PTR_ERR(prog);
9780 if (event->attr.precise_ip &&
9781 prog->call_get_stack &&
9782 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9783 event->attr.exclude_callchain_kernel ||
9784 event->attr.exclude_callchain_user)) {
9786 * On perf_event with precise_ip, calling bpf_get_stack()
9787 * may trigger unwinder warnings and occasional crashes.
9788 * bpf_get_[stack|stackid] works around this issue by using
9789 * callchain attached to perf_sample_data. If the
9790 * perf_event does not full (kernel and user) callchain
9791 * attached to perf_sample_data, do not allow attaching BPF
9792 * program that calls bpf_get_[stack|stackid].
9794 bpf_prog_put(prog);
9795 return -EPROTO;
9798 event->prog = prog;
9799 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9800 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9801 return 0;
9804 static void perf_event_free_bpf_handler(struct perf_event *event)
9806 struct bpf_prog *prog = event->prog;
9808 if (!prog)
9809 return;
9811 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9812 event->prog = NULL;
9813 bpf_prog_put(prog);
9815 #else
9816 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9818 return -EOPNOTSUPP;
9820 static void perf_event_free_bpf_handler(struct perf_event *event)
9823 #endif
9826 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9827 * with perf_event_open()
9829 static inline bool perf_event_is_tracing(struct perf_event *event)
9831 if (event->pmu == &perf_tracepoint)
9832 return true;
9833 #ifdef CONFIG_KPROBE_EVENTS
9834 if (event->pmu == &perf_kprobe)
9835 return true;
9836 #endif
9837 #ifdef CONFIG_UPROBE_EVENTS
9838 if (event->pmu == &perf_uprobe)
9839 return true;
9840 #endif
9841 return false;
9844 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9846 bool is_kprobe, is_tracepoint, is_syscall_tp;
9847 struct bpf_prog *prog;
9848 int ret;
9850 if (!perf_event_is_tracing(event))
9851 return perf_event_set_bpf_handler(event, prog_fd);
9853 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9854 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9855 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9856 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9857 /* bpf programs can only be attached to u/kprobe or tracepoint */
9858 return -EINVAL;
9860 prog = bpf_prog_get(prog_fd);
9861 if (IS_ERR(prog))
9862 return PTR_ERR(prog);
9864 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9865 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9866 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9867 /* valid fd, but invalid bpf program type */
9868 bpf_prog_put(prog);
9869 return -EINVAL;
9872 /* Kprobe override only works for kprobes, not uprobes. */
9873 if (prog->kprobe_override &&
9874 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9875 bpf_prog_put(prog);
9876 return -EINVAL;
9879 if (is_tracepoint || is_syscall_tp) {
9880 int off = trace_event_get_offsets(event->tp_event);
9882 if (prog->aux->max_ctx_offset > off) {
9883 bpf_prog_put(prog);
9884 return -EACCES;
9888 ret = perf_event_attach_bpf_prog(event, prog);
9889 if (ret)
9890 bpf_prog_put(prog);
9891 return ret;
9894 static void perf_event_free_bpf_prog(struct perf_event *event)
9896 if (!perf_event_is_tracing(event)) {
9897 perf_event_free_bpf_handler(event);
9898 return;
9900 perf_event_detach_bpf_prog(event);
9903 #else
9905 static inline void perf_tp_register(void)
9909 static void perf_event_free_filter(struct perf_event *event)
9913 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9915 return -ENOENT;
9918 static void perf_event_free_bpf_prog(struct perf_event *event)
9921 #endif /* CONFIG_EVENT_TRACING */
9923 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9924 void perf_bp_event(struct perf_event *bp, void *data)
9926 struct perf_sample_data sample;
9927 struct pt_regs *regs = data;
9929 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9931 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9932 perf_swevent_event(bp, 1, &sample, regs);
9934 #endif
9937 * Allocate a new address filter
9939 static struct perf_addr_filter *
9940 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9942 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9943 struct perf_addr_filter *filter;
9945 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9946 if (!filter)
9947 return NULL;
9949 INIT_LIST_HEAD(&filter->entry);
9950 list_add_tail(&filter->entry, filters);
9952 return filter;
9955 static void free_filters_list(struct list_head *filters)
9957 struct perf_addr_filter *filter, *iter;
9959 list_for_each_entry_safe(filter, iter, filters, entry) {
9960 path_put(&filter->path);
9961 list_del(&filter->entry);
9962 kfree(filter);
9967 * Free existing address filters and optionally install new ones
9969 static void perf_addr_filters_splice(struct perf_event *event,
9970 struct list_head *head)
9972 unsigned long flags;
9973 LIST_HEAD(list);
9975 if (!has_addr_filter(event))
9976 return;
9978 /* don't bother with children, they don't have their own filters */
9979 if (event->parent)
9980 return;
9982 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9984 list_splice_init(&event->addr_filters.list, &list);
9985 if (head)
9986 list_splice(head, &event->addr_filters.list);
9988 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9990 free_filters_list(&list);
9994 * Scan through mm's vmas and see if one of them matches the
9995 * @filter; if so, adjust filter's address range.
9996 * Called with mm::mmap_lock down for reading.
9998 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9999 struct mm_struct *mm,
10000 struct perf_addr_filter_range *fr)
10002 struct vm_area_struct *vma;
10004 for (vma = mm->mmap; vma; vma = vma->vm_next) {
10005 if (!vma->vm_file)
10006 continue;
10008 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10009 return;
10014 * Update event's address range filters based on the
10015 * task's existing mappings, if any.
10017 static void perf_event_addr_filters_apply(struct perf_event *event)
10019 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10020 struct task_struct *task = READ_ONCE(event->ctx->task);
10021 struct perf_addr_filter *filter;
10022 struct mm_struct *mm = NULL;
10023 unsigned int count = 0;
10024 unsigned long flags;
10027 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10028 * will stop on the parent's child_mutex that our caller is also holding
10030 if (task == TASK_TOMBSTONE)
10031 return;
10033 if (ifh->nr_file_filters) {
10034 mm = get_task_mm(event->ctx->task);
10035 if (!mm)
10036 goto restart;
10038 mmap_read_lock(mm);
10041 raw_spin_lock_irqsave(&ifh->lock, flags);
10042 list_for_each_entry(filter, &ifh->list, entry) {
10043 if (filter->path.dentry) {
10045 * Adjust base offset if the filter is associated to a
10046 * binary that needs to be mapped:
10048 event->addr_filter_ranges[count].start = 0;
10049 event->addr_filter_ranges[count].size = 0;
10051 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10052 } else {
10053 event->addr_filter_ranges[count].start = filter->offset;
10054 event->addr_filter_ranges[count].size = filter->size;
10057 count++;
10060 event->addr_filters_gen++;
10061 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10063 if (ifh->nr_file_filters) {
10064 mmap_read_unlock(mm);
10066 mmput(mm);
10069 restart:
10070 perf_event_stop(event, 1);
10074 * Address range filtering: limiting the data to certain
10075 * instruction address ranges. Filters are ioctl()ed to us from
10076 * userspace as ascii strings.
10078 * Filter string format:
10080 * ACTION RANGE_SPEC
10081 * where ACTION is one of the
10082 * * "filter": limit the trace to this region
10083 * * "start": start tracing from this address
10084 * * "stop": stop tracing at this address/region;
10085 * RANGE_SPEC is
10086 * * for kernel addresses: <start address>[/<size>]
10087 * * for object files: <start address>[/<size>]@</path/to/object/file>
10089 * if <size> is not specified or is zero, the range is treated as a single
10090 * address; not valid for ACTION=="filter".
10092 enum {
10093 IF_ACT_NONE = -1,
10094 IF_ACT_FILTER,
10095 IF_ACT_START,
10096 IF_ACT_STOP,
10097 IF_SRC_FILE,
10098 IF_SRC_KERNEL,
10099 IF_SRC_FILEADDR,
10100 IF_SRC_KERNELADDR,
10103 enum {
10104 IF_STATE_ACTION = 0,
10105 IF_STATE_SOURCE,
10106 IF_STATE_END,
10109 static const match_table_t if_tokens = {
10110 { IF_ACT_FILTER, "filter" },
10111 { IF_ACT_START, "start" },
10112 { IF_ACT_STOP, "stop" },
10113 { IF_SRC_FILE, "%u/%u@%s" },
10114 { IF_SRC_KERNEL, "%u/%u" },
10115 { IF_SRC_FILEADDR, "%u@%s" },
10116 { IF_SRC_KERNELADDR, "%u" },
10117 { IF_ACT_NONE, NULL },
10121 * Address filter string parser
10123 static int
10124 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10125 struct list_head *filters)
10127 struct perf_addr_filter *filter = NULL;
10128 char *start, *orig, *filename = NULL;
10129 substring_t args[MAX_OPT_ARGS];
10130 int state = IF_STATE_ACTION, token;
10131 unsigned int kernel = 0;
10132 int ret = -EINVAL;
10134 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10135 if (!fstr)
10136 return -ENOMEM;
10138 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10139 static const enum perf_addr_filter_action_t actions[] = {
10140 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10141 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10142 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10144 ret = -EINVAL;
10146 if (!*start)
10147 continue;
10149 /* filter definition begins */
10150 if (state == IF_STATE_ACTION) {
10151 filter = perf_addr_filter_new(event, filters);
10152 if (!filter)
10153 goto fail;
10156 token = match_token(start, if_tokens, args);
10157 switch (token) {
10158 case IF_ACT_FILTER:
10159 case IF_ACT_START:
10160 case IF_ACT_STOP:
10161 if (state != IF_STATE_ACTION)
10162 goto fail;
10164 filter->action = actions[token];
10165 state = IF_STATE_SOURCE;
10166 break;
10168 case IF_SRC_KERNELADDR:
10169 case IF_SRC_KERNEL:
10170 kernel = 1;
10171 fallthrough;
10173 case IF_SRC_FILEADDR:
10174 case IF_SRC_FILE:
10175 if (state != IF_STATE_SOURCE)
10176 goto fail;
10178 *args[0].to = 0;
10179 ret = kstrtoul(args[0].from, 0, &filter->offset);
10180 if (ret)
10181 goto fail;
10183 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10184 *args[1].to = 0;
10185 ret = kstrtoul(args[1].from, 0, &filter->size);
10186 if (ret)
10187 goto fail;
10190 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10191 int fpos = token == IF_SRC_FILE ? 2 : 1;
10193 kfree(filename);
10194 filename = match_strdup(&args[fpos]);
10195 if (!filename) {
10196 ret = -ENOMEM;
10197 goto fail;
10201 state = IF_STATE_END;
10202 break;
10204 default:
10205 goto fail;
10209 * Filter definition is fully parsed, validate and install it.
10210 * Make sure that it doesn't contradict itself or the event's
10211 * attribute.
10213 if (state == IF_STATE_END) {
10214 ret = -EINVAL;
10215 if (kernel && event->attr.exclude_kernel)
10216 goto fail;
10219 * ACTION "filter" must have a non-zero length region
10220 * specified.
10222 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10223 !filter->size)
10224 goto fail;
10226 if (!kernel) {
10227 if (!filename)
10228 goto fail;
10231 * For now, we only support file-based filters
10232 * in per-task events; doing so for CPU-wide
10233 * events requires additional context switching
10234 * trickery, since same object code will be
10235 * mapped at different virtual addresses in
10236 * different processes.
10238 ret = -EOPNOTSUPP;
10239 if (!event->ctx->task)
10240 goto fail;
10242 /* look up the path and grab its inode */
10243 ret = kern_path(filename, LOOKUP_FOLLOW,
10244 &filter->path);
10245 if (ret)
10246 goto fail;
10248 ret = -EINVAL;
10249 if (!filter->path.dentry ||
10250 !S_ISREG(d_inode(filter->path.dentry)
10251 ->i_mode))
10252 goto fail;
10254 event->addr_filters.nr_file_filters++;
10257 /* ready to consume more filters */
10258 state = IF_STATE_ACTION;
10259 filter = NULL;
10263 if (state != IF_STATE_ACTION)
10264 goto fail;
10266 kfree(filename);
10267 kfree(orig);
10269 return 0;
10271 fail:
10272 kfree(filename);
10273 free_filters_list(filters);
10274 kfree(orig);
10276 return ret;
10279 static int
10280 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10282 LIST_HEAD(filters);
10283 int ret;
10286 * Since this is called in perf_ioctl() path, we're already holding
10287 * ctx::mutex.
10289 lockdep_assert_held(&event->ctx->mutex);
10291 if (WARN_ON_ONCE(event->parent))
10292 return -EINVAL;
10294 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10295 if (ret)
10296 goto fail_clear_files;
10298 ret = event->pmu->addr_filters_validate(&filters);
10299 if (ret)
10300 goto fail_free_filters;
10302 /* remove existing filters, if any */
10303 perf_addr_filters_splice(event, &filters);
10305 /* install new filters */
10306 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10308 return ret;
10310 fail_free_filters:
10311 free_filters_list(&filters);
10313 fail_clear_files:
10314 event->addr_filters.nr_file_filters = 0;
10316 return ret;
10319 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10321 int ret = -EINVAL;
10322 char *filter_str;
10324 filter_str = strndup_user(arg, PAGE_SIZE);
10325 if (IS_ERR(filter_str))
10326 return PTR_ERR(filter_str);
10328 #ifdef CONFIG_EVENT_TRACING
10329 if (perf_event_is_tracing(event)) {
10330 struct perf_event_context *ctx = event->ctx;
10333 * Beware, here be dragons!!
10335 * the tracepoint muck will deadlock against ctx->mutex, but
10336 * the tracepoint stuff does not actually need it. So
10337 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10338 * already have a reference on ctx.
10340 * This can result in event getting moved to a different ctx,
10341 * but that does not affect the tracepoint state.
10343 mutex_unlock(&ctx->mutex);
10344 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10345 mutex_lock(&ctx->mutex);
10346 } else
10347 #endif
10348 if (has_addr_filter(event))
10349 ret = perf_event_set_addr_filter(event, filter_str);
10351 kfree(filter_str);
10352 return ret;
10356 * hrtimer based swevent callback
10359 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10361 enum hrtimer_restart ret = HRTIMER_RESTART;
10362 struct perf_sample_data data;
10363 struct pt_regs *regs;
10364 struct perf_event *event;
10365 u64 period;
10367 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10369 if (event->state != PERF_EVENT_STATE_ACTIVE)
10370 return HRTIMER_NORESTART;
10372 event->pmu->read(event);
10374 perf_sample_data_init(&data, 0, event->hw.last_period);
10375 regs = get_irq_regs();
10377 if (regs && !perf_exclude_event(event, regs)) {
10378 if (!(event->attr.exclude_idle && is_idle_task(current)))
10379 if (__perf_event_overflow(event, 1, &data, regs))
10380 ret = HRTIMER_NORESTART;
10383 period = max_t(u64, 10000, event->hw.sample_period);
10384 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10386 return ret;
10389 static void perf_swevent_start_hrtimer(struct perf_event *event)
10391 struct hw_perf_event *hwc = &event->hw;
10392 s64 period;
10394 if (!is_sampling_event(event))
10395 return;
10397 period = local64_read(&hwc->period_left);
10398 if (period) {
10399 if (period < 0)
10400 period = 10000;
10402 local64_set(&hwc->period_left, 0);
10403 } else {
10404 period = max_t(u64, 10000, hwc->sample_period);
10406 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10407 HRTIMER_MODE_REL_PINNED_HARD);
10410 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10412 struct hw_perf_event *hwc = &event->hw;
10414 if (is_sampling_event(event)) {
10415 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10416 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10418 hrtimer_cancel(&hwc->hrtimer);
10422 static void perf_swevent_init_hrtimer(struct perf_event *event)
10424 struct hw_perf_event *hwc = &event->hw;
10426 if (!is_sampling_event(event))
10427 return;
10429 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10430 hwc->hrtimer.function = perf_swevent_hrtimer;
10433 * Since hrtimers have a fixed rate, we can do a static freq->period
10434 * mapping and avoid the whole period adjust feedback stuff.
10436 if (event->attr.freq) {
10437 long freq = event->attr.sample_freq;
10439 event->attr.sample_period = NSEC_PER_SEC / freq;
10440 hwc->sample_period = event->attr.sample_period;
10441 local64_set(&hwc->period_left, hwc->sample_period);
10442 hwc->last_period = hwc->sample_period;
10443 event->attr.freq = 0;
10448 * Software event: cpu wall time clock
10451 static void cpu_clock_event_update(struct perf_event *event)
10453 s64 prev;
10454 u64 now;
10456 now = local_clock();
10457 prev = local64_xchg(&event->hw.prev_count, now);
10458 local64_add(now - prev, &event->count);
10461 static void cpu_clock_event_start(struct perf_event *event, int flags)
10463 local64_set(&event->hw.prev_count, local_clock());
10464 perf_swevent_start_hrtimer(event);
10467 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10469 perf_swevent_cancel_hrtimer(event);
10470 cpu_clock_event_update(event);
10473 static int cpu_clock_event_add(struct perf_event *event, int flags)
10475 if (flags & PERF_EF_START)
10476 cpu_clock_event_start(event, flags);
10477 perf_event_update_userpage(event);
10479 return 0;
10482 static void cpu_clock_event_del(struct perf_event *event, int flags)
10484 cpu_clock_event_stop(event, flags);
10487 static void cpu_clock_event_read(struct perf_event *event)
10489 cpu_clock_event_update(event);
10492 static int cpu_clock_event_init(struct perf_event *event)
10494 if (event->attr.type != PERF_TYPE_SOFTWARE)
10495 return -ENOENT;
10497 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10498 return -ENOENT;
10501 * no branch sampling for software events
10503 if (has_branch_stack(event))
10504 return -EOPNOTSUPP;
10506 perf_swevent_init_hrtimer(event);
10508 return 0;
10511 static struct pmu perf_cpu_clock = {
10512 .task_ctx_nr = perf_sw_context,
10514 .capabilities = PERF_PMU_CAP_NO_NMI,
10516 .event_init = cpu_clock_event_init,
10517 .add = cpu_clock_event_add,
10518 .del = cpu_clock_event_del,
10519 .start = cpu_clock_event_start,
10520 .stop = cpu_clock_event_stop,
10521 .read = cpu_clock_event_read,
10525 * Software event: task time clock
10528 static void task_clock_event_update(struct perf_event *event, u64 now)
10530 u64 prev;
10531 s64 delta;
10533 prev = local64_xchg(&event->hw.prev_count, now);
10534 delta = now - prev;
10535 local64_add(delta, &event->count);
10538 static void task_clock_event_start(struct perf_event *event, int flags)
10540 local64_set(&event->hw.prev_count, event->ctx->time);
10541 perf_swevent_start_hrtimer(event);
10544 static void task_clock_event_stop(struct perf_event *event, int flags)
10546 perf_swevent_cancel_hrtimer(event);
10547 task_clock_event_update(event, event->ctx->time);
10550 static int task_clock_event_add(struct perf_event *event, int flags)
10552 if (flags & PERF_EF_START)
10553 task_clock_event_start(event, flags);
10554 perf_event_update_userpage(event);
10556 return 0;
10559 static void task_clock_event_del(struct perf_event *event, int flags)
10561 task_clock_event_stop(event, PERF_EF_UPDATE);
10564 static void task_clock_event_read(struct perf_event *event)
10566 u64 now = perf_clock();
10567 u64 delta = now - event->ctx->timestamp;
10568 u64 time = event->ctx->time + delta;
10570 task_clock_event_update(event, time);
10573 static int task_clock_event_init(struct perf_event *event)
10575 if (event->attr.type != PERF_TYPE_SOFTWARE)
10576 return -ENOENT;
10578 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10579 return -ENOENT;
10582 * no branch sampling for software events
10584 if (has_branch_stack(event))
10585 return -EOPNOTSUPP;
10587 perf_swevent_init_hrtimer(event);
10589 return 0;
10592 static struct pmu perf_task_clock = {
10593 .task_ctx_nr = perf_sw_context,
10595 .capabilities = PERF_PMU_CAP_NO_NMI,
10597 .event_init = task_clock_event_init,
10598 .add = task_clock_event_add,
10599 .del = task_clock_event_del,
10600 .start = task_clock_event_start,
10601 .stop = task_clock_event_stop,
10602 .read = task_clock_event_read,
10605 static void perf_pmu_nop_void(struct pmu *pmu)
10609 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10613 static int perf_pmu_nop_int(struct pmu *pmu)
10615 return 0;
10618 static int perf_event_nop_int(struct perf_event *event, u64 value)
10620 return 0;
10623 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10625 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10627 __this_cpu_write(nop_txn_flags, flags);
10629 if (flags & ~PERF_PMU_TXN_ADD)
10630 return;
10632 perf_pmu_disable(pmu);
10635 static int perf_pmu_commit_txn(struct pmu *pmu)
10637 unsigned int flags = __this_cpu_read(nop_txn_flags);
10639 __this_cpu_write(nop_txn_flags, 0);
10641 if (flags & ~PERF_PMU_TXN_ADD)
10642 return 0;
10644 perf_pmu_enable(pmu);
10645 return 0;
10648 static void perf_pmu_cancel_txn(struct pmu *pmu)
10650 unsigned int flags = __this_cpu_read(nop_txn_flags);
10652 __this_cpu_write(nop_txn_flags, 0);
10654 if (flags & ~PERF_PMU_TXN_ADD)
10655 return;
10657 perf_pmu_enable(pmu);
10660 static int perf_event_idx_default(struct perf_event *event)
10662 return 0;
10666 * Ensures all contexts with the same task_ctx_nr have the same
10667 * pmu_cpu_context too.
10669 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10671 struct pmu *pmu;
10673 if (ctxn < 0)
10674 return NULL;
10676 list_for_each_entry(pmu, &pmus, entry) {
10677 if (pmu->task_ctx_nr == ctxn)
10678 return pmu->pmu_cpu_context;
10681 return NULL;
10684 static void free_pmu_context(struct pmu *pmu)
10687 * Static contexts such as perf_sw_context have a global lifetime
10688 * and may be shared between different PMUs. Avoid freeing them
10689 * when a single PMU is going away.
10691 if (pmu->task_ctx_nr > perf_invalid_context)
10692 return;
10694 free_percpu(pmu->pmu_cpu_context);
10698 * Let userspace know that this PMU supports address range filtering:
10700 static ssize_t nr_addr_filters_show(struct device *dev,
10701 struct device_attribute *attr,
10702 char *page)
10704 struct pmu *pmu = dev_get_drvdata(dev);
10706 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10708 DEVICE_ATTR_RO(nr_addr_filters);
10710 static struct idr pmu_idr;
10712 static ssize_t
10713 type_show(struct device *dev, struct device_attribute *attr, char *page)
10715 struct pmu *pmu = dev_get_drvdata(dev);
10717 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10719 static DEVICE_ATTR_RO(type);
10721 static ssize_t
10722 perf_event_mux_interval_ms_show(struct device *dev,
10723 struct device_attribute *attr,
10724 char *page)
10726 struct pmu *pmu = dev_get_drvdata(dev);
10728 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10731 static DEFINE_MUTEX(mux_interval_mutex);
10733 static ssize_t
10734 perf_event_mux_interval_ms_store(struct device *dev,
10735 struct device_attribute *attr,
10736 const char *buf, size_t count)
10738 struct pmu *pmu = dev_get_drvdata(dev);
10739 int timer, cpu, ret;
10741 ret = kstrtoint(buf, 0, &timer);
10742 if (ret)
10743 return ret;
10745 if (timer < 1)
10746 return -EINVAL;
10748 /* same value, noting to do */
10749 if (timer == pmu->hrtimer_interval_ms)
10750 return count;
10752 mutex_lock(&mux_interval_mutex);
10753 pmu->hrtimer_interval_ms = timer;
10755 /* update all cpuctx for this PMU */
10756 cpus_read_lock();
10757 for_each_online_cpu(cpu) {
10758 struct perf_cpu_context *cpuctx;
10759 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10760 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10762 cpu_function_call(cpu,
10763 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10765 cpus_read_unlock();
10766 mutex_unlock(&mux_interval_mutex);
10768 return count;
10770 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10772 static struct attribute *pmu_dev_attrs[] = {
10773 &dev_attr_type.attr,
10774 &dev_attr_perf_event_mux_interval_ms.attr,
10775 NULL,
10777 ATTRIBUTE_GROUPS(pmu_dev);
10779 static int pmu_bus_running;
10780 static struct bus_type pmu_bus = {
10781 .name = "event_source",
10782 .dev_groups = pmu_dev_groups,
10785 static void pmu_dev_release(struct device *dev)
10787 kfree(dev);
10790 static int pmu_dev_alloc(struct pmu *pmu)
10792 int ret = -ENOMEM;
10794 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10795 if (!pmu->dev)
10796 goto out;
10798 pmu->dev->groups = pmu->attr_groups;
10799 device_initialize(pmu->dev);
10800 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10801 if (ret)
10802 goto free_dev;
10804 dev_set_drvdata(pmu->dev, pmu);
10805 pmu->dev->bus = &pmu_bus;
10806 pmu->dev->release = pmu_dev_release;
10807 ret = device_add(pmu->dev);
10808 if (ret)
10809 goto free_dev;
10811 /* For PMUs with address filters, throw in an extra attribute: */
10812 if (pmu->nr_addr_filters)
10813 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10815 if (ret)
10816 goto del_dev;
10818 if (pmu->attr_update)
10819 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10821 if (ret)
10822 goto del_dev;
10824 out:
10825 return ret;
10827 del_dev:
10828 device_del(pmu->dev);
10830 free_dev:
10831 put_device(pmu->dev);
10832 goto out;
10835 static struct lock_class_key cpuctx_mutex;
10836 static struct lock_class_key cpuctx_lock;
10838 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10840 int cpu, ret, max = PERF_TYPE_MAX;
10842 mutex_lock(&pmus_lock);
10843 ret = -ENOMEM;
10844 pmu->pmu_disable_count = alloc_percpu(int);
10845 if (!pmu->pmu_disable_count)
10846 goto unlock;
10848 pmu->type = -1;
10849 if (!name)
10850 goto skip_type;
10851 pmu->name = name;
10853 if (type != PERF_TYPE_SOFTWARE) {
10854 if (type >= 0)
10855 max = type;
10857 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10858 if (ret < 0)
10859 goto free_pdc;
10861 WARN_ON(type >= 0 && ret != type);
10863 type = ret;
10865 pmu->type = type;
10867 if (pmu_bus_running) {
10868 ret = pmu_dev_alloc(pmu);
10869 if (ret)
10870 goto free_idr;
10873 skip_type:
10874 if (pmu->task_ctx_nr == perf_hw_context) {
10875 static int hw_context_taken = 0;
10878 * Other than systems with heterogeneous CPUs, it never makes
10879 * sense for two PMUs to share perf_hw_context. PMUs which are
10880 * uncore must use perf_invalid_context.
10882 if (WARN_ON_ONCE(hw_context_taken &&
10883 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10884 pmu->task_ctx_nr = perf_invalid_context;
10886 hw_context_taken = 1;
10889 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10890 if (pmu->pmu_cpu_context)
10891 goto got_cpu_context;
10893 ret = -ENOMEM;
10894 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10895 if (!pmu->pmu_cpu_context)
10896 goto free_dev;
10898 for_each_possible_cpu(cpu) {
10899 struct perf_cpu_context *cpuctx;
10901 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10902 __perf_event_init_context(&cpuctx->ctx);
10903 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10904 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10905 cpuctx->ctx.pmu = pmu;
10906 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10908 __perf_mux_hrtimer_init(cpuctx, cpu);
10910 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10911 cpuctx->heap = cpuctx->heap_default;
10914 got_cpu_context:
10915 if (!pmu->start_txn) {
10916 if (pmu->pmu_enable) {
10918 * If we have pmu_enable/pmu_disable calls, install
10919 * transaction stubs that use that to try and batch
10920 * hardware accesses.
10922 pmu->start_txn = perf_pmu_start_txn;
10923 pmu->commit_txn = perf_pmu_commit_txn;
10924 pmu->cancel_txn = perf_pmu_cancel_txn;
10925 } else {
10926 pmu->start_txn = perf_pmu_nop_txn;
10927 pmu->commit_txn = perf_pmu_nop_int;
10928 pmu->cancel_txn = perf_pmu_nop_void;
10932 if (!pmu->pmu_enable) {
10933 pmu->pmu_enable = perf_pmu_nop_void;
10934 pmu->pmu_disable = perf_pmu_nop_void;
10937 if (!pmu->check_period)
10938 pmu->check_period = perf_event_nop_int;
10940 if (!pmu->event_idx)
10941 pmu->event_idx = perf_event_idx_default;
10944 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10945 * since these cannot be in the IDR. This way the linear search
10946 * is fast, provided a valid software event is provided.
10948 if (type == PERF_TYPE_SOFTWARE || !name)
10949 list_add_rcu(&pmu->entry, &pmus);
10950 else
10951 list_add_tail_rcu(&pmu->entry, &pmus);
10953 atomic_set(&pmu->exclusive_cnt, 0);
10954 ret = 0;
10955 unlock:
10956 mutex_unlock(&pmus_lock);
10958 return ret;
10960 free_dev:
10961 device_del(pmu->dev);
10962 put_device(pmu->dev);
10964 free_idr:
10965 if (pmu->type != PERF_TYPE_SOFTWARE)
10966 idr_remove(&pmu_idr, pmu->type);
10968 free_pdc:
10969 free_percpu(pmu->pmu_disable_count);
10970 goto unlock;
10972 EXPORT_SYMBOL_GPL(perf_pmu_register);
10974 void perf_pmu_unregister(struct pmu *pmu)
10976 mutex_lock(&pmus_lock);
10977 list_del_rcu(&pmu->entry);
10980 * We dereference the pmu list under both SRCU and regular RCU, so
10981 * synchronize against both of those.
10983 synchronize_srcu(&pmus_srcu);
10984 synchronize_rcu();
10986 free_percpu(pmu->pmu_disable_count);
10987 if (pmu->type != PERF_TYPE_SOFTWARE)
10988 idr_remove(&pmu_idr, pmu->type);
10989 if (pmu_bus_running) {
10990 if (pmu->nr_addr_filters)
10991 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10992 device_del(pmu->dev);
10993 put_device(pmu->dev);
10995 free_pmu_context(pmu);
10996 mutex_unlock(&pmus_lock);
10998 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11000 static inline bool has_extended_regs(struct perf_event *event)
11002 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11003 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11006 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11008 struct perf_event_context *ctx = NULL;
11009 int ret;
11011 if (!try_module_get(pmu->module))
11012 return -ENODEV;
11015 * A number of pmu->event_init() methods iterate the sibling_list to,
11016 * for example, validate if the group fits on the PMU. Therefore,
11017 * if this is a sibling event, acquire the ctx->mutex to protect
11018 * the sibling_list.
11020 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11022 * This ctx->mutex can nest when we're called through
11023 * inheritance. See the perf_event_ctx_lock_nested() comment.
11025 ctx = perf_event_ctx_lock_nested(event->group_leader,
11026 SINGLE_DEPTH_NESTING);
11027 BUG_ON(!ctx);
11030 event->pmu = pmu;
11031 ret = pmu->event_init(event);
11033 if (ctx)
11034 perf_event_ctx_unlock(event->group_leader, ctx);
11036 if (!ret) {
11037 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11038 has_extended_regs(event))
11039 ret = -EOPNOTSUPP;
11041 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11042 event_has_any_exclude_flag(event))
11043 ret = -EINVAL;
11045 if (ret && event->destroy)
11046 event->destroy(event);
11049 if (ret)
11050 module_put(pmu->module);
11052 return ret;
11055 static struct pmu *perf_init_event(struct perf_event *event)
11057 int idx, type, ret;
11058 struct pmu *pmu;
11060 idx = srcu_read_lock(&pmus_srcu);
11062 /* Try parent's PMU first: */
11063 if (event->parent && event->parent->pmu) {
11064 pmu = event->parent->pmu;
11065 ret = perf_try_init_event(pmu, event);
11066 if (!ret)
11067 goto unlock;
11071 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11072 * are often aliases for PERF_TYPE_RAW.
11074 type = event->attr.type;
11075 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11076 type = PERF_TYPE_RAW;
11078 again:
11079 rcu_read_lock();
11080 pmu = idr_find(&pmu_idr, type);
11081 rcu_read_unlock();
11082 if (pmu) {
11083 ret = perf_try_init_event(pmu, event);
11084 if (ret == -ENOENT && event->attr.type != type) {
11085 type = event->attr.type;
11086 goto again;
11089 if (ret)
11090 pmu = ERR_PTR(ret);
11092 goto unlock;
11095 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11096 ret = perf_try_init_event(pmu, event);
11097 if (!ret)
11098 goto unlock;
11100 if (ret != -ENOENT) {
11101 pmu = ERR_PTR(ret);
11102 goto unlock;
11105 pmu = ERR_PTR(-ENOENT);
11106 unlock:
11107 srcu_read_unlock(&pmus_srcu, idx);
11109 return pmu;
11112 static void attach_sb_event(struct perf_event *event)
11114 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11116 raw_spin_lock(&pel->lock);
11117 list_add_rcu(&event->sb_list, &pel->list);
11118 raw_spin_unlock(&pel->lock);
11122 * We keep a list of all !task (and therefore per-cpu) events
11123 * that need to receive side-band records.
11125 * This avoids having to scan all the various PMU per-cpu contexts
11126 * looking for them.
11128 static void account_pmu_sb_event(struct perf_event *event)
11130 if (is_sb_event(event))
11131 attach_sb_event(event);
11134 static void account_event_cpu(struct perf_event *event, int cpu)
11136 if (event->parent)
11137 return;
11139 if (is_cgroup_event(event))
11140 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11143 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11144 static void account_freq_event_nohz(void)
11146 #ifdef CONFIG_NO_HZ_FULL
11147 /* Lock so we don't race with concurrent unaccount */
11148 spin_lock(&nr_freq_lock);
11149 if (atomic_inc_return(&nr_freq_events) == 1)
11150 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11151 spin_unlock(&nr_freq_lock);
11152 #endif
11155 static void account_freq_event(void)
11157 if (tick_nohz_full_enabled())
11158 account_freq_event_nohz();
11159 else
11160 atomic_inc(&nr_freq_events);
11164 static void account_event(struct perf_event *event)
11166 bool inc = false;
11168 if (event->parent)
11169 return;
11171 if (event->attach_state & PERF_ATTACH_TASK)
11172 inc = true;
11173 if (event->attr.mmap || event->attr.mmap_data)
11174 atomic_inc(&nr_mmap_events);
11175 if (event->attr.comm)
11176 atomic_inc(&nr_comm_events);
11177 if (event->attr.namespaces)
11178 atomic_inc(&nr_namespaces_events);
11179 if (event->attr.cgroup)
11180 atomic_inc(&nr_cgroup_events);
11181 if (event->attr.task)
11182 atomic_inc(&nr_task_events);
11183 if (event->attr.freq)
11184 account_freq_event();
11185 if (event->attr.context_switch) {
11186 atomic_inc(&nr_switch_events);
11187 inc = true;
11189 if (has_branch_stack(event))
11190 inc = true;
11191 if (is_cgroup_event(event))
11192 inc = true;
11193 if (event->attr.ksymbol)
11194 atomic_inc(&nr_ksymbol_events);
11195 if (event->attr.bpf_event)
11196 atomic_inc(&nr_bpf_events);
11197 if (event->attr.text_poke)
11198 atomic_inc(&nr_text_poke_events);
11200 if (inc) {
11202 * We need the mutex here because static_branch_enable()
11203 * must complete *before* the perf_sched_count increment
11204 * becomes visible.
11206 if (atomic_inc_not_zero(&perf_sched_count))
11207 goto enabled;
11209 mutex_lock(&perf_sched_mutex);
11210 if (!atomic_read(&perf_sched_count)) {
11211 static_branch_enable(&perf_sched_events);
11213 * Guarantee that all CPUs observe they key change and
11214 * call the perf scheduling hooks before proceeding to
11215 * install events that need them.
11217 synchronize_rcu();
11220 * Now that we have waited for the sync_sched(), allow further
11221 * increments to by-pass the mutex.
11223 atomic_inc(&perf_sched_count);
11224 mutex_unlock(&perf_sched_mutex);
11226 enabled:
11228 account_event_cpu(event, event->cpu);
11230 account_pmu_sb_event(event);
11234 * Allocate and initialize an event structure
11236 static struct perf_event *
11237 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11238 struct task_struct *task,
11239 struct perf_event *group_leader,
11240 struct perf_event *parent_event,
11241 perf_overflow_handler_t overflow_handler,
11242 void *context, int cgroup_fd)
11244 struct pmu *pmu;
11245 struct perf_event *event;
11246 struct hw_perf_event *hwc;
11247 long err = -EINVAL;
11249 if ((unsigned)cpu >= nr_cpu_ids) {
11250 if (!task || cpu != -1)
11251 return ERR_PTR(-EINVAL);
11254 event = kzalloc(sizeof(*event), GFP_KERNEL);
11255 if (!event)
11256 return ERR_PTR(-ENOMEM);
11259 * Single events are their own group leaders, with an
11260 * empty sibling list:
11262 if (!group_leader)
11263 group_leader = event;
11265 mutex_init(&event->child_mutex);
11266 INIT_LIST_HEAD(&event->child_list);
11268 INIT_LIST_HEAD(&event->event_entry);
11269 INIT_LIST_HEAD(&event->sibling_list);
11270 INIT_LIST_HEAD(&event->active_list);
11271 init_event_group(event);
11272 INIT_LIST_HEAD(&event->rb_entry);
11273 INIT_LIST_HEAD(&event->active_entry);
11274 INIT_LIST_HEAD(&event->addr_filters.list);
11275 INIT_HLIST_NODE(&event->hlist_entry);
11278 init_waitqueue_head(&event->waitq);
11279 event->pending_disable = -1;
11280 init_irq_work(&event->pending, perf_pending_event);
11282 mutex_init(&event->mmap_mutex);
11283 raw_spin_lock_init(&event->addr_filters.lock);
11285 atomic_long_set(&event->refcount, 1);
11286 event->cpu = cpu;
11287 event->attr = *attr;
11288 event->group_leader = group_leader;
11289 event->pmu = NULL;
11290 event->oncpu = -1;
11292 event->parent = parent_event;
11294 event->ns = get_pid_ns(task_active_pid_ns(current));
11295 event->id = atomic64_inc_return(&perf_event_id);
11297 event->state = PERF_EVENT_STATE_INACTIVE;
11299 if (task) {
11300 event->attach_state = PERF_ATTACH_TASK;
11302 * XXX pmu::event_init needs to know what task to account to
11303 * and we cannot use the ctx information because we need the
11304 * pmu before we get a ctx.
11306 event->hw.target = get_task_struct(task);
11309 event->clock = &local_clock;
11310 if (parent_event)
11311 event->clock = parent_event->clock;
11313 if (!overflow_handler && parent_event) {
11314 overflow_handler = parent_event->overflow_handler;
11315 context = parent_event->overflow_handler_context;
11316 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11317 if (overflow_handler == bpf_overflow_handler) {
11318 struct bpf_prog *prog = parent_event->prog;
11320 bpf_prog_inc(prog);
11321 event->prog = prog;
11322 event->orig_overflow_handler =
11323 parent_event->orig_overflow_handler;
11325 #endif
11328 if (overflow_handler) {
11329 event->overflow_handler = overflow_handler;
11330 event->overflow_handler_context = context;
11331 } else if (is_write_backward(event)){
11332 event->overflow_handler = perf_event_output_backward;
11333 event->overflow_handler_context = NULL;
11334 } else {
11335 event->overflow_handler = perf_event_output_forward;
11336 event->overflow_handler_context = NULL;
11339 perf_event__state_init(event);
11341 pmu = NULL;
11343 hwc = &event->hw;
11344 hwc->sample_period = attr->sample_period;
11345 if (attr->freq && attr->sample_freq)
11346 hwc->sample_period = 1;
11347 hwc->last_period = hwc->sample_period;
11349 local64_set(&hwc->period_left, hwc->sample_period);
11352 * We currently do not support PERF_SAMPLE_READ on inherited events.
11353 * See perf_output_read().
11355 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11356 goto err_ns;
11358 if (!has_branch_stack(event))
11359 event->attr.branch_sample_type = 0;
11361 pmu = perf_init_event(event);
11362 if (IS_ERR(pmu)) {
11363 err = PTR_ERR(pmu);
11364 goto err_ns;
11368 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11369 * be different on other CPUs in the uncore mask.
11371 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11372 err = -EINVAL;
11373 goto err_pmu;
11376 if (event->attr.aux_output &&
11377 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11378 err = -EOPNOTSUPP;
11379 goto err_pmu;
11382 if (cgroup_fd != -1) {
11383 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11384 if (err)
11385 goto err_pmu;
11388 err = exclusive_event_init(event);
11389 if (err)
11390 goto err_pmu;
11392 if (has_addr_filter(event)) {
11393 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11394 sizeof(struct perf_addr_filter_range),
11395 GFP_KERNEL);
11396 if (!event->addr_filter_ranges) {
11397 err = -ENOMEM;
11398 goto err_per_task;
11402 * Clone the parent's vma offsets: they are valid until exec()
11403 * even if the mm is not shared with the parent.
11405 if (event->parent) {
11406 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11408 raw_spin_lock_irq(&ifh->lock);
11409 memcpy(event->addr_filter_ranges,
11410 event->parent->addr_filter_ranges,
11411 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11412 raw_spin_unlock_irq(&ifh->lock);
11415 /* force hw sync on the address filters */
11416 event->addr_filters_gen = 1;
11419 if (!event->parent) {
11420 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11421 err = get_callchain_buffers(attr->sample_max_stack);
11422 if (err)
11423 goto err_addr_filters;
11427 err = security_perf_event_alloc(event);
11428 if (err)
11429 goto err_callchain_buffer;
11431 /* symmetric to unaccount_event() in _free_event() */
11432 account_event(event);
11434 return event;
11436 err_callchain_buffer:
11437 if (!event->parent) {
11438 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11439 put_callchain_buffers();
11441 err_addr_filters:
11442 kfree(event->addr_filter_ranges);
11444 err_per_task:
11445 exclusive_event_destroy(event);
11447 err_pmu:
11448 if (is_cgroup_event(event))
11449 perf_detach_cgroup(event);
11450 if (event->destroy)
11451 event->destroy(event);
11452 module_put(pmu->module);
11453 err_ns:
11454 if (event->ns)
11455 put_pid_ns(event->ns);
11456 if (event->hw.target)
11457 put_task_struct(event->hw.target);
11458 kfree(event);
11460 return ERR_PTR(err);
11463 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11464 struct perf_event_attr *attr)
11466 u32 size;
11467 int ret;
11469 /* Zero the full structure, so that a short copy will be nice. */
11470 memset(attr, 0, sizeof(*attr));
11472 ret = get_user(size, &uattr->size);
11473 if (ret)
11474 return ret;
11476 /* ABI compatibility quirk: */
11477 if (!size)
11478 size = PERF_ATTR_SIZE_VER0;
11479 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11480 goto err_size;
11482 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11483 if (ret) {
11484 if (ret == -E2BIG)
11485 goto err_size;
11486 return ret;
11489 attr->size = size;
11491 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11492 return -EINVAL;
11494 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11495 return -EINVAL;
11497 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11498 return -EINVAL;
11500 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11501 u64 mask = attr->branch_sample_type;
11503 /* only using defined bits */
11504 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11505 return -EINVAL;
11507 /* at least one branch bit must be set */
11508 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11509 return -EINVAL;
11511 /* propagate priv level, when not set for branch */
11512 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11514 /* exclude_kernel checked on syscall entry */
11515 if (!attr->exclude_kernel)
11516 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11518 if (!attr->exclude_user)
11519 mask |= PERF_SAMPLE_BRANCH_USER;
11521 if (!attr->exclude_hv)
11522 mask |= PERF_SAMPLE_BRANCH_HV;
11524 * adjust user setting (for HW filter setup)
11526 attr->branch_sample_type = mask;
11528 /* privileged levels capture (kernel, hv): check permissions */
11529 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11530 ret = perf_allow_kernel(attr);
11531 if (ret)
11532 return ret;
11536 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11537 ret = perf_reg_validate(attr->sample_regs_user);
11538 if (ret)
11539 return ret;
11542 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11543 if (!arch_perf_have_user_stack_dump())
11544 return -ENOSYS;
11547 * We have __u32 type for the size, but so far
11548 * we can only use __u16 as maximum due to the
11549 * __u16 sample size limit.
11551 if (attr->sample_stack_user >= USHRT_MAX)
11552 return -EINVAL;
11553 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11554 return -EINVAL;
11557 if (!attr->sample_max_stack)
11558 attr->sample_max_stack = sysctl_perf_event_max_stack;
11560 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11561 ret = perf_reg_validate(attr->sample_regs_intr);
11563 #ifndef CONFIG_CGROUP_PERF
11564 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11565 return -EINVAL;
11566 #endif
11568 out:
11569 return ret;
11571 err_size:
11572 put_user(sizeof(*attr), &uattr->size);
11573 ret = -E2BIG;
11574 goto out;
11577 static int
11578 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11580 struct perf_buffer *rb = NULL;
11581 int ret = -EINVAL;
11583 if (!output_event)
11584 goto set;
11586 /* don't allow circular references */
11587 if (event == output_event)
11588 goto out;
11591 * Don't allow cross-cpu buffers
11593 if (output_event->cpu != event->cpu)
11594 goto out;
11597 * If its not a per-cpu rb, it must be the same task.
11599 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11600 goto out;
11603 * Mixing clocks in the same buffer is trouble you don't need.
11605 if (output_event->clock != event->clock)
11606 goto out;
11609 * Either writing ring buffer from beginning or from end.
11610 * Mixing is not allowed.
11612 if (is_write_backward(output_event) != is_write_backward(event))
11613 goto out;
11616 * If both events generate aux data, they must be on the same PMU
11618 if (has_aux(event) && has_aux(output_event) &&
11619 event->pmu != output_event->pmu)
11620 goto out;
11622 set:
11623 mutex_lock(&event->mmap_mutex);
11624 /* Can't redirect output if we've got an active mmap() */
11625 if (atomic_read(&event->mmap_count))
11626 goto unlock;
11628 if (output_event) {
11629 /* get the rb we want to redirect to */
11630 rb = ring_buffer_get(output_event);
11631 if (!rb)
11632 goto unlock;
11635 ring_buffer_attach(event, rb);
11637 ret = 0;
11638 unlock:
11639 mutex_unlock(&event->mmap_mutex);
11641 out:
11642 return ret;
11645 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11647 if (b < a)
11648 swap(a, b);
11650 mutex_lock(a);
11651 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11654 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11656 bool nmi_safe = false;
11658 switch (clk_id) {
11659 case CLOCK_MONOTONIC:
11660 event->clock = &ktime_get_mono_fast_ns;
11661 nmi_safe = true;
11662 break;
11664 case CLOCK_MONOTONIC_RAW:
11665 event->clock = &ktime_get_raw_fast_ns;
11666 nmi_safe = true;
11667 break;
11669 case CLOCK_REALTIME:
11670 event->clock = &ktime_get_real_ns;
11671 break;
11673 case CLOCK_BOOTTIME:
11674 event->clock = &ktime_get_boottime_ns;
11675 break;
11677 case CLOCK_TAI:
11678 event->clock = &ktime_get_clocktai_ns;
11679 break;
11681 default:
11682 return -EINVAL;
11685 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11686 return -EINVAL;
11688 return 0;
11692 * Variation on perf_event_ctx_lock_nested(), except we take two context
11693 * mutexes.
11695 static struct perf_event_context *
11696 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11697 struct perf_event_context *ctx)
11699 struct perf_event_context *gctx;
11701 again:
11702 rcu_read_lock();
11703 gctx = READ_ONCE(group_leader->ctx);
11704 if (!refcount_inc_not_zero(&gctx->refcount)) {
11705 rcu_read_unlock();
11706 goto again;
11708 rcu_read_unlock();
11710 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11712 if (group_leader->ctx != gctx) {
11713 mutex_unlock(&ctx->mutex);
11714 mutex_unlock(&gctx->mutex);
11715 put_ctx(gctx);
11716 goto again;
11719 return gctx;
11723 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11725 * @attr_uptr: event_id type attributes for monitoring/sampling
11726 * @pid: target pid
11727 * @cpu: target cpu
11728 * @group_fd: group leader event fd
11730 SYSCALL_DEFINE5(perf_event_open,
11731 struct perf_event_attr __user *, attr_uptr,
11732 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11734 struct perf_event *group_leader = NULL, *output_event = NULL;
11735 struct perf_event *event, *sibling;
11736 struct perf_event_attr attr;
11737 struct perf_event_context *ctx, *gctx;
11738 struct file *event_file = NULL;
11739 struct fd group = {NULL, 0};
11740 struct task_struct *task = NULL;
11741 struct pmu *pmu;
11742 int event_fd;
11743 int move_group = 0;
11744 int err;
11745 int f_flags = O_RDWR;
11746 int cgroup_fd = -1;
11748 /* for future expandability... */
11749 if (flags & ~PERF_FLAG_ALL)
11750 return -EINVAL;
11752 /* Do we allow access to perf_event_open(2) ? */
11753 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11754 if (err)
11755 return err;
11757 err = perf_copy_attr(attr_uptr, &attr);
11758 if (err)
11759 return err;
11761 if (!attr.exclude_kernel) {
11762 err = perf_allow_kernel(&attr);
11763 if (err)
11764 return err;
11767 if (attr.namespaces) {
11768 if (!perfmon_capable())
11769 return -EACCES;
11772 if (attr.freq) {
11773 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11774 return -EINVAL;
11775 } else {
11776 if (attr.sample_period & (1ULL << 63))
11777 return -EINVAL;
11780 /* Only privileged users can get physical addresses */
11781 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11782 err = perf_allow_kernel(&attr);
11783 if (err)
11784 return err;
11787 err = security_locked_down(LOCKDOWN_PERF);
11788 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11789 /* REGS_INTR can leak data, lockdown must prevent this */
11790 return err;
11792 err = 0;
11795 * In cgroup mode, the pid argument is used to pass the fd
11796 * opened to the cgroup directory in cgroupfs. The cpu argument
11797 * designates the cpu on which to monitor threads from that
11798 * cgroup.
11800 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11801 return -EINVAL;
11803 if (flags & PERF_FLAG_FD_CLOEXEC)
11804 f_flags |= O_CLOEXEC;
11806 event_fd = get_unused_fd_flags(f_flags);
11807 if (event_fd < 0)
11808 return event_fd;
11810 if (group_fd != -1) {
11811 err = perf_fget_light(group_fd, &group);
11812 if (err)
11813 goto err_fd;
11814 group_leader = group.file->private_data;
11815 if (flags & PERF_FLAG_FD_OUTPUT)
11816 output_event = group_leader;
11817 if (flags & PERF_FLAG_FD_NO_GROUP)
11818 group_leader = NULL;
11821 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11822 task = find_lively_task_by_vpid(pid);
11823 if (IS_ERR(task)) {
11824 err = PTR_ERR(task);
11825 goto err_group_fd;
11829 if (task && group_leader &&
11830 group_leader->attr.inherit != attr.inherit) {
11831 err = -EINVAL;
11832 goto err_task;
11835 if (flags & PERF_FLAG_PID_CGROUP)
11836 cgroup_fd = pid;
11838 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11839 NULL, NULL, cgroup_fd);
11840 if (IS_ERR(event)) {
11841 err = PTR_ERR(event);
11842 goto err_task;
11845 if (is_sampling_event(event)) {
11846 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11847 err = -EOPNOTSUPP;
11848 goto err_alloc;
11853 * Special case software events and allow them to be part of
11854 * any hardware group.
11856 pmu = event->pmu;
11858 if (attr.use_clockid) {
11859 err = perf_event_set_clock(event, attr.clockid);
11860 if (err)
11861 goto err_alloc;
11864 if (pmu->task_ctx_nr == perf_sw_context)
11865 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11867 if (group_leader) {
11868 if (is_software_event(event) &&
11869 !in_software_context(group_leader)) {
11871 * If the event is a sw event, but the group_leader
11872 * is on hw context.
11874 * Allow the addition of software events to hw
11875 * groups, this is safe because software events
11876 * never fail to schedule.
11878 pmu = group_leader->ctx->pmu;
11879 } else if (!is_software_event(event) &&
11880 is_software_event(group_leader) &&
11881 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11883 * In case the group is a pure software group, and we
11884 * try to add a hardware event, move the whole group to
11885 * the hardware context.
11887 move_group = 1;
11892 * Get the target context (task or percpu):
11894 ctx = find_get_context(pmu, task, event);
11895 if (IS_ERR(ctx)) {
11896 err = PTR_ERR(ctx);
11897 goto err_alloc;
11901 * Look up the group leader (we will attach this event to it):
11903 if (group_leader) {
11904 err = -EINVAL;
11907 * Do not allow a recursive hierarchy (this new sibling
11908 * becoming part of another group-sibling):
11910 if (group_leader->group_leader != group_leader)
11911 goto err_context;
11913 /* All events in a group should have the same clock */
11914 if (group_leader->clock != event->clock)
11915 goto err_context;
11918 * Make sure we're both events for the same CPU;
11919 * grouping events for different CPUs is broken; since
11920 * you can never concurrently schedule them anyhow.
11922 if (group_leader->cpu != event->cpu)
11923 goto err_context;
11926 * Make sure we're both on the same task, or both
11927 * per-CPU events.
11929 if (group_leader->ctx->task != ctx->task)
11930 goto err_context;
11933 * Do not allow to attach to a group in a different task
11934 * or CPU context. If we're moving SW events, we'll fix
11935 * this up later, so allow that.
11937 if (!move_group && group_leader->ctx != ctx)
11938 goto err_context;
11941 * Only a group leader can be exclusive or pinned
11943 if (attr.exclusive || attr.pinned)
11944 goto err_context;
11947 if (output_event) {
11948 err = perf_event_set_output(event, output_event);
11949 if (err)
11950 goto err_context;
11953 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11954 f_flags);
11955 if (IS_ERR(event_file)) {
11956 err = PTR_ERR(event_file);
11957 event_file = NULL;
11958 goto err_context;
11961 if (task) {
11962 err = down_read_interruptible(&task->signal->exec_update_lock);
11963 if (err)
11964 goto err_file;
11967 * Preserve ptrace permission check for backwards compatibility.
11969 * We must hold exec_update_lock across this and any potential
11970 * perf_install_in_context() call for this new event to
11971 * serialize against exec() altering our credentials (and the
11972 * perf_event_exit_task() that could imply).
11974 err = -EACCES;
11975 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11976 goto err_cred;
11979 if (move_group) {
11980 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11982 if (gctx->task == TASK_TOMBSTONE) {
11983 err = -ESRCH;
11984 goto err_locked;
11988 * Check if we raced against another sys_perf_event_open() call
11989 * moving the software group underneath us.
11991 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11993 * If someone moved the group out from under us, check
11994 * if this new event wound up on the same ctx, if so
11995 * its the regular !move_group case, otherwise fail.
11997 if (gctx != ctx) {
11998 err = -EINVAL;
11999 goto err_locked;
12000 } else {
12001 perf_event_ctx_unlock(group_leader, gctx);
12002 move_group = 0;
12007 * Failure to create exclusive events returns -EBUSY.
12009 err = -EBUSY;
12010 if (!exclusive_event_installable(group_leader, ctx))
12011 goto err_locked;
12013 for_each_sibling_event(sibling, group_leader) {
12014 if (!exclusive_event_installable(sibling, ctx))
12015 goto err_locked;
12017 } else {
12018 mutex_lock(&ctx->mutex);
12021 if (ctx->task == TASK_TOMBSTONE) {
12022 err = -ESRCH;
12023 goto err_locked;
12026 if (!perf_event_validate_size(event)) {
12027 err = -E2BIG;
12028 goto err_locked;
12031 if (!task) {
12033 * Check if the @cpu we're creating an event for is online.
12035 * We use the perf_cpu_context::ctx::mutex to serialize against
12036 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12038 struct perf_cpu_context *cpuctx =
12039 container_of(ctx, struct perf_cpu_context, ctx);
12041 if (!cpuctx->online) {
12042 err = -ENODEV;
12043 goto err_locked;
12047 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12048 err = -EINVAL;
12049 goto err_locked;
12053 * Must be under the same ctx::mutex as perf_install_in_context(),
12054 * because we need to serialize with concurrent event creation.
12056 if (!exclusive_event_installable(event, ctx)) {
12057 err = -EBUSY;
12058 goto err_locked;
12061 WARN_ON_ONCE(ctx->parent_ctx);
12064 * This is the point on no return; we cannot fail hereafter. This is
12065 * where we start modifying current state.
12068 if (move_group) {
12070 * See perf_event_ctx_lock() for comments on the details
12071 * of swizzling perf_event::ctx.
12073 perf_remove_from_context(group_leader, 0);
12074 put_ctx(gctx);
12076 for_each_sibling_event(sibling, group_leader) {
12077 perf_remove_from_context(sibling, 0);
12078 put_ctx(gctx);
12082 * Wait for everybody to stop referencing the events through
12083 * the old lists, before installing it on new lists.
12085 synchronize_rcu();
12088 * Install the group siblings before the group leader.
12090 * Because a group leader will try and install the entire group
12091 * (through the sibling list, which is still in-tact), we can
12092 * end up with siblings installed in the wrong context.
12094 * By installing siblings first we NO-OP because they're not
12095 * reachable through the group lists.
12097 for_each_sibling_event(sibling, group_leader) {
12098 perf_event__state_init(sibling);
12099 perf_install_in_context(ctx, sibling, sibling->cpu);
12100 get_ctx(ctx);
12104 * Removing from the context ends up with disabled
12105 * event. What we want here is event in the initial
12106 * startup state, ready to be add into new context.
12108 perf_event__state_init(group_leader);
12109 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12110 get_ctx(ctx);
12114 * Precalculate sample_data sizes; do while holding ctx::mutex such
12115 * that we're serialized against further additions and before
12116 * perf_install_in_context() which is the point the event is active and
12117 * can use these values.
12119 perf_event__header_size(event);
12120 perf_event__id_header_size(event);
12122 event->owner = current;
12124 perf_install_in_context(ctx, event, event->cpu);
12125 perf_unpin_context(ctx);
12127 if (move_group)
12128 perf_event_ctx_unlock(group_leader, gctx);
12129 mutex_unlock(&ctx->mutex);
12131 if (task) {
12132 up_read(&task->signal->exec_update_lock);
12133 put_task_struct(task);
12136 mutex_lock(&current->perf_event_mutex);
12137 list_add_tail(&event->owner_entry, &current->perf_event_list);
12138 mutex_unlock(&current->perf_event_mutex);
12141 * Drop the reference on the group_event after placing the
12142 * new event on the sibling_list. This ensures destruction
12143 * of the group leader will find the pointer to itself in
12144 * perf_group_detach().
12146 fdput(group);
12147 fd_install(event_fd, event_file);
12148 return event_fd;
12150 err_locked:
12151 if (move_group)
12152 perf_event_ctx_unlock(group_leader, gctx);
12153 mutex_unlock(&ctx->mutex);
12154 err_cred:
12155 if (task)
12156 up_read(&task->signal->exec_update_lock);
12157 err_file:
12158 fput(event_file);
12159 err_context:
12160 perf_unpin_context(ctx);
12161 put_ctx(ctx);
12162 err_alloc:
12164 * If event_file is set, the fput() above will have called ->release()
12165 * and that will take care of freeing the event.
12167 if (!event_file)
12168 free_event(event);
12169 err_task:
12170 if (task)
12171 put_task_struct(task);
12172 err_group_fd:
12173 fdput(group);
12174 err_fd:
12175 put_unused_fd(event_fd);
12176 return err;
12180 * perf_event_create_kernel_counter
12182 * @attr: attributes of the counter to create
12183 * @cpu: cpu in which the counter is bound
12184 * @task: task to profile (NULL for percpu)
12186 struct perf_event *
12187 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12188 struct task_struct *task,
12189 perf_overflow_handler_t overflow_handler,
12190 void *context)
12192 struct perf_event_context *ctx;
12193 struct perf_event *event;
12194 int err;
12197 * Grouping is not supported for kernel events, neither is 'AUX',
12198 * make sure the caller's intentions are adjusted.
12200 if (attr->aux_output)
12201 return ERR_PTR(-EINVAL);
12203 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12204 overflow_handler, context, -1);
12205 if (IS_ERR(event)) {
12206 err = PTR_ERR(event);
12207 goto err;
12210 /* Mark owner so we could distinguish it from user events. */
12211 event->owner = TASK_TOMBSTONE;
12214 * Get the target context (task or percpu):
12216 ctx = find_get_context(event->pmu, task, event);
12217 if (IS_ERR(ctx)) {
12218 err = PTR_ERR(ctx);
12219 goto err_free;
12222 WARN_ON_ONCE(ctx->parent_ctx);
12223 mutex_lock(&ctx->mutex);
12224 if (ctx->task == TASK_TOMBSTONE) {
12225 err = -ESRCH;
12226 goto err_unlock;
12229 if (!task) {
12231 * Check if the @cpu we're creating an event for is online.
12233 * We use the perf_cpu_context::ctx::mutex to serialize against
12234 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12236 struct perf_cpu_context *cpuctx =
12237 container_of(ctx, struct perf_cpu_context, ctx);
12238 if (!cpuctx->online) {
12239 err = -ENODEV;
12240 goto err_unlock;
12244 if (!exclusive_event_installable(event, ctx)) {
12245 err = -EBUSY;
12246 goto err_unlock;
12249 perf_install_in_context(ctx, event, event->cpu);
12250 perf_unpin_context(ctx);
12251 mutex_unlock(&ctx->mutex);
12253 return event;
12255 err_unlock:
12256 mutex_unlock(&ctx->mutex);
12257 perf_unpin_context(ctx);
12258 put_ctx(ctx);
12259 err_free:
12260 free_event(event);
12261 err:
12262 return ERR_PTR(err);
12264 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12266 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12268 struct perf_event_context *src_ctx;
12269 struct perf_event_context *dst_ctx;
12270 struct perf_event *event, *tmp;
12271 LIST_HEAD(events);
12273 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12274 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12277 * See perf_event_ctx_lock() for comments on the details
12278 * of swizzling perf_event::ctx.
12280 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12281 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12282 event_entry) {
12283 perf_remove_from_context(event, 0);
12284 unaccount_event_cpu(event, src_cpu);
12285 put_ctx(src_ctx);
12286 list_add(&event->migrate_entry, &events);
12290 * Wait for the events to quiesce before re-instating them.
12292 synchronize_rcu();
12295 * Re-instate events in 2 passes.
12297 * Skip over group leaders and only install siblings on this first
12298 * pass, siblings will not get enabled without a leader, however a
12299 * leader will enable its siblings, even if those are still on the old
12300 * context.
12302 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12303 if (event->group_leader == event)
12304 continue;
12306 list_del(&event->migrate_entry);
12307 if (event->state >= PERF_EVENT_STATE_OFF)
12308 event->state = PERF_EVENT_STATE_INACTIVE;
12309 account_event_cpu(event, dst_cpu);
12310 perf_install_in_context(dst_ctx, event, dst_cpu);
12311 get_ctx(dst_ctx);
12315 * Once all the siblings are setup properly, install the group leaders
12316 * to make it go.
12318 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12319 list_del(&event->migrate_entry);
12320 if (event->state >= PERF_EVENT_STATE_OFF)
12321 event->state = PERF_EVENT_STATE_INACTIVE;
12322 account_event_cpu(event, dst_cpu);
12323 perf_install_in_context(dst_ctx, event, dst_cpu);
12324 get_ctx(dst_ctx);
12326 mutex_unlock(&dst_ctx->mutex);
12327 mutex_unlock(&src_ctx->mutex);
12329 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12331 static void sync_child_event(struct perf_event *child_event,
12332 struct task_struct *child)
12334 struct perf_event *parent_event = child_event->parent;
12335 u64 child_val;
12337 if (child_event->attr.inherit_stat)
12338 perf_event_read_event(child_event, child);
12340 child_val = perf_event_count(child_event);
12343 * Add back the child's count to the parent's count:
12345 atomic64_add(child_val, &parent_event->child_count);
12346 atomic64_add(child_event->total_time_enabled,
12347 &parent_event->child_total_time_enabled);
12348 atomic64_add(child_event->total_time_running,
12349 &parent_event->child_total_time_running);
12352 static void
12353 perf_event_exit_event(struct perf_event *child_event,
12354 struct perf_event_context *child_ctx,
12355 struct task_struct *child)
12357 struct perf_event *parent_event = child_event->parent;
12360 * Do not destroy the 'original' grouping; because of the context
12361 * switch optimization the original events could've ended up in a
12362 * random child task.
12364 * If we were to destroy the original group, all group related
12365 * operations would cease to function properly after this random
12366 * child dies.
12368 * Do destroy all inherited groups, we don't care about those
12369 * and being thorough is better.
12371 raw_spin_lock_irq(&child_ctx->lock);
12372 WARN_ON_ONCE(child_ctx->is_active);
12374 if (parent_event)
12375 perf_group_detach(child_event);
12376 list_del_event(child_event, child_ctx);
12377 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12378 raw_spin_unlock_irq(&child_ctx->lock);
12381 * Parent events are governed by their filedesc, retain them.
12383 if (!parent_event) {
12384 perf_event_wakeup(child_event);
12385 return;
12388 * Child events can be cleaned up.
12391 sync_child_event(child_event, child);
12394 * Remove this event from the parent's list
12396 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12397 mutex_lock(&parent_event->child_mutex);
12398 list_del_init(&child_event->child_list);
12399 mutex_unlock(&parent_event->child_mutex);
12402 * Kick perf_poll() for is_event_hup().
12404 perf_event_wakeup(parent_event);
12405 free_event(child_event);
12406 put_event(parent_event);
12409 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12411 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12412 struct perf_event *child_event, *next;
12414 WARN_ON_ONCE(child != current);
12416 child_ctx = perf_pin_task_context(child, ctxn);
12417 if (!child_ctx)
12418 return;
12421 * In order to reduce the amount of tricky in ctx tear-down, we hold
12422 * ctx::mutex over the entire thing. This serializes against almost
12423 * everything that wants to access the ctx.
12425 * The exception is sys_perf_event_open() /
12426 * perf_event_create_kernel_count() which does find_get_context()
12427 * without ctx::mutex (it cannot because of the move_group double mutex
12428 * lock thing). See the comments in perf_install_in_context().
12430 mutex_lock(&child_ctx->mutex);
12433 * In a single ctx::lock section, de-schedule the events and detach the
12434 * context from the task such that we cannot ever get it scheduled back
12435 * in.
12437 raw_spin_lock_irq(&child_ctx->lock);
12438 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12441 * Now that the context is inactive, destroy the task <-> ctx relation
12442 * and mark the context dead.
12444 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12445 put_ctx(child_ctx); /* cannot be last */
12446 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12447 put_task_struct(current); /* cannot be last */
12449 clone_ctx = unclone_ctx(child_ctx);
12450 raw_spin_unlock_irq(&child_ctx->lock);
12452 if (clone_ctx)
12453 put_ctx(clone_ctx);
12456 * Report the task dead after unscheduling the events so that we
12457 * won't get any samples after PERF_RECORD_EXIT. We can however still
12458 * get a few PERF_RECORD_READ events.
12460 perf_event_task(child, child_ctx, 0);
12462 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12463 perf_event_exit_event(child_event, child_ctx, child);
12465 mutex_unlock(&child_ctx->mutex);
12467 put_ctx(child_ctx);
12471 * When a child task exits, feed back event values to parent events.
12473 * Can be called with exec_update_lock held when called from
12474 * setup_new_exec().
12476 void perf_event_exit_task(struct task_struct *child)
12478 struct perf_event *event, *tmp;
12479 int ctxn;
12481 mutex_lock(&child->perf_event_mutex);
12482 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12483 owner_entry) {
12484 list_del_init(&event->owner_entry);
12487 * Ensure the list deletion is visible before we clear
12488 * the owner, closes a race against perf_release() where
12489 * we need to serialize on the owner->perf_event_mutex.
12491 smp_store_release(&event->owner, NULL);
12493 mutex_unlock(&child->perf_event_mutex);
12495 for_each_task_context_nr(ctxn)
12496 perf_event_exit_task_context(child, ctxn);
12499 * The perf_event_exit_task_context calls perf_event_task
12500 * with child's task_ctx, which generates EXIT events for
12501 * child contexts and sets child->perf_event_ctxp[] to NULL.
12502 * At this point we need to send EXIT events to cpu contexts.
12504 perf_event_task(child, NULL, 0);
12507 static void perf_free_event(struct perf_event *event,
12508 struct perf_event_context *ctx)
12510 struct perf_event *parent = event->parent;
12512 if (WARN_ON_ONCE(!parent))
12513 return;
12515 mutex_lock(&parent->child_mutex);
12516 list_del_init(&event->child_list);
12517 mutex_unlock(&parent->child_mutex);
12519 put_event(parent);
12521 raw_spin_lock_irq(&ctx->lock);
12522 perf_group_detach(event);
12523 list_del_event(event, ctx);
12524 raw_spin_unlock_irq(&ctx->lock);
12525 free_event(event);
12529 * Free a context as created by inheritance by perf_event_init_task() below,
12530 * used by fork() in case of fail.
12532 * Even though the task has never lived, the context and events have been
12533 * exposed through the child_list, so we must take care tearing it all down.
12535 void perf_event_free_task(struct task_struct *task)
12537 struct perf_event_context *ctx;
12538 struct perf_event *event, *tmp;
12539 int ctxn;
12541 for_each_task_context_nr(ctxn) {
12542 ctx = task->perf_event_ctxp[ctxn];
12543 if (!ctx)
12544 continue;
12546 mutex_lock(&ctx->mutex);
12547 raw_spin_lock_irq(&ctx->lock);
12549 * Destroy the task <-> ctx relation and mark the context dead.
12551 * This is important because even though the task hasn't been
12552 * exposed yet the context has been (through child_list).
12554 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12555 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12556 put_task_struct(task); /* cannot be last */
12557 raw_spin_unlock_irq(&ctx->lock);
12559 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12560 perf_free_event(event, ctx);
12562 mutex_unlock(&ctx->mutex);
12565 * perf_event_release_kernel() could've stolen some of our
12566 * child events and still have them on its free_list. In that
12567 * case we must wait for these events to have been freed (in
12568 * particular all their references to this task must've been
12569 * dropped).
12571 * Without this copy_process() will unconditionally free this
12572 * task (irrespective of its reference count) and
12573 * _free_event()'s put_task_struct(event->hw.target) will be a
12574 * use-after-free.
12576 * Wait for all events to drop their context reference.
12578 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12579 put_ctx(ctx); /* must be last */
12583 void perf_event_delayed_put(struct task_struct *task)
12585 int ctxn;
12587 for_each_task_context_nr(ctxn)
12588 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12591 struct file *perf_event_get(unsigned int fd)
12593 struct file *file = fget(fd);
12594 if (!file)
12595 return ERR_PTR(-EBADF);
12597 if (file->f_op != &perf_fops) {
12598 fput(file);
12599 return ERR_PTR(-EBADF);
12602 return file;
12605 const struct perf_event *perf_get_event(struct file *file)
12607 if (file->f_op != &perf_fops)
12608 return ERR_PTR(-EINVAL);
12610 return file->private_data;
12613 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12615 if (!event)
12616 return ERR_PTR(-EINVAL);
12618 return &event->attr;
12622 * Inherit an event from parent task to child task.
12624 * Returns:
12625 * - valid pointer on success
12626 * - NULL for orphaned events
12627 * - IS_ERR() on error
12629 static struct perf_event *
12630 inherit_event(struct perf_event *parent_event,
12631 struct task_struct *parent,
12632 struct perf_event_context *parent_ctx,
12633 struct task_struct *child,
12634 struct perf_event *group_leader,
12635 struct perf_event_context *child_ctx)
12637 enum perf_event_state parent_state = parent_event->state;
12638 struct perf_event *child_event;
12639 unsigned long flags;
12642 * Instead of creating recursive hierarchies of events,
12643 * we link inherited events back to the original parent,
12644 * which has a filp for sure, which we use as the reference
12645 * count:
12647 if (parent_event->parent)
12648 parent_event = parent_event->parent;
12650 child_event = perf_event_alloc(&parent_event->attr,
12651 parent_event->cpu,
12652 child,
12653 group_leader, parent_event,
12654 NULL, NULL, -1);
12655 if (IS_ERR(child_event))
12656 return child_event;
12659 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12660 !child_ctx->task_ctx_data) {
12661 struct pmu *pmu = child_event->pmu;
12663 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12664 if (!child_ctx->task_ctx_data) {
12665 free_event(child_event);
12666 return ERR_PTR(-ENOMEM);
12671 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12672 * must be under the same lock in order to serialize against
12673 * perf_event_release_kernel(), such that either we must observe
12674 * is_orphaned_event() or they will observe us on the child_list.
12676 mutex_lock(&parent_event->child_mutex);
12677 if (is_orphaned_event(parent_event) ||
12678 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12679 mutex_unlock(&parent_event->child_mutex);
12680 /* task_ctx_data is freed with child_ctx */
12681 free_event(child_event);
12682 return NULL;
12685 get_ctx(child_ctx);
12688 * Make the child state follow the state of the parent event,
12689 * not its attr.disabled bit. We hold the parent's mutex,
12690 * so we won't race with perf_event_{en, dis}able_family.
12692 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12693 child_event->state = PERF_EVENT_STATE_INACTIVE;
12694 else
12695 child_event->state = PERF_EVENT_STATE_OFF;
12697 if (parent_event->attr.freq) {
12698 u64 sample_period = parent_event->hw.sample_period;
12699 struct hw_perf_event *hwc = &child_event->hw;
12701 hwc->sample_period = sample_period;
12702 hwc->last_period = sample_period;
12704 local64_set(&hwc->period_left, sample_period);
12707 child_event->ctx = child_ctx;
12708 child_event->overflow_handler = parent_event->overflow_handler;
12709 child_event->overflow_handler_context
12710 = parent_event->overflow_handler_context;
12713 * Precalculate sample_data sizes
12715 perf_event__header_size(child_event);
12716 perf_event__id_header_size(child_event);
12719 * Link it up in the child's context:
12721 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12722 add_event_to_ctx(child_event, child_ctx);
12723 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12726 * Link this into the parent event's child list
12728 list_add_tail(&child_event->child_list, &parent_event->child_list);
12729 mutex_unlock(&parent_event->child_mutex);
12731 return child_event;
12735 * Inherits an event group.
12737 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12738 * This matches with perf_event_release_kernel() removing all child events.
12740 * Returns:
12741 * - 0 on success
12742 * - <0 on error
12744 static int inherit_group(struct perf_event *parent_event,
12745 struct task_struct *parent,
12746 struct perf_event_context *parent_ctx,
12747 struct task_struct *child,
12748 struct perf_event_context *child_ctx)
12750 struct perf_event *leader;
12751 struct perf_event *sub;
12752 struct perf_event *child_ctr;
12754 leader = inherit_event(parent_event, parent, parent_ctx,
12755 child, NULL, child_ctx);
12756 if (IS_ERR(leader))
12757 return PTR_ERR(leader);
12759 * @leader can be NULL here because of is_orphaned_event(). In this
12760 * case inherit_event() will create individual events, similar to what
12761 * perf_group_detach() would do anyway.
12763 for_each_sibling_event(sub, parent_event) {
12764 child_ctr = inherit_event(sub, parent, parent_ctx,
12765 child, leader, child_ctx);
12766 if (IS_ERR(child_ctr))
12767 return PTR_ERR(child_ctr);
12769 if (sub->aux_event == parent_event && child_ctr &&
12770 !perf_get_aux_event(child_ctr, leader))
12771 return -EINVAL;
12773 return 0;
12777 * Creates the child task context and tries to inherit the event-group.
12779 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12780 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12781 * consistent with perf_event_release_kernel() removing all child events.
12783 * Returns:
12784 * - 0 on success
12785 * - <0 on error
12787 static int
12788 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12789 struct perf_event_context *parent_ctx,
12790 struct task_struct *child, int ctxn,
12791 int *inherited_all)
12793 int ret;
12794 struct perf_event_context *child_ctx;
12796 if (!event->attr.inherit) {
12797 *inherited_all = 0;
12798 return 0;
12801 child_ctx = child->perf_event_ctxp[ctxn];
12802 if (!child_ctx) {
12804 * This is executed from the parent task context, so
12805 * inherit events that have been marked for cloning.
12806 * First allocate and initialize a context for the
12807 * child.
12809 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12810 if (!child_ctx)
12811 return -ENOMEM;
12813 child->perf_event_ctxp[ctxn] = child_ctx;
12816 ret = inherit_group(event, parent, parent_ctx,
12817 child, child_ctx);
12819 if (ret)
12820 *inherited_all = 0;
12822 return ret;
12826 * Initialize the perf_event context in task_struct
12828 static int perf_event_init_context(struct task_struct *child, int ctxn)
12830 struct perf_event_context *child_ctx, *parent_ctx;
12831 struct perf_event_context *cloned_ctx;
12832 struct perf_event *event;
12833 struct task_struct *parent = current;
12834 int inherited_all = 1;
12835 unsigned long flags;
12836 int ret = 0;
12838 if (likely(!parent->perf_event_ctxp[ctxn]))
12839 return 0;
12842 * If the parent's context is a clone, pin it so it won't get
12843 * swapped under us.
12845 parent_ctx = perf_pin_task_context(parent, ctxn);
12846 if (!parent_ctx)
12847 return 0;
12850 * No need to check if parent_ctx != NULL here; since we saw
12851 * it non-NULL earlier, the only reason for it to become NULL
12852 * is if we exit, and since we're currently in the middle of
12853 * a fork we can't be exiting at the same time.
12857 * Lock the parent list. No need to lock the child - not PID
12858 * hashed yet and not running, so nobody can access it.
12860 mutex_lock(&parent_ctx->mutex);
12863 * We dont have to disable NMIs - we are only looking at
12864 * the list, not manipulating it:
12866 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12867 ret = inherit_task_group(event, parent, parent_ctx,
12868 child, ctxn, &inherited_all);
12869 if (ret)
12870 goto out_unlock;
12874 * We can't hold ctx->lock when iterating the ->flexible_group list due
12875 * to allocations, but we need to prevent rotation because
12876 * rotate_ctx() will change the list from interrupt context.
12878 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12879 parent_ctx->rotate_disable = 1;
12880 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12882 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12883 ret = inherit_task_group(event, parent, parent_ctx,
12884 child, ctxn, &inherited_all);
12885 if (ret)
12886 goto out_unlock;
12889 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12890 parent_ctx->rotate_disable = 0;
12892 child_ctx = child->perf_event_ctxp[ctxn];
12894 if (child_ctx && inherited_all) {
12896 * Mark the child context as a clone of the parent
12897 * context, or of whatever the parent is a clone of.
12899 * Note that if the parent is a clone, the holding of
12900 * parent_ctx->lock avoids it from being uncloned.
12902 cloned_ctx = parent_ctx->parent_ctx;
12903 if (cloned_ctx) {
12904 child_ctx->parent_ctx = cloned_ctx;
12905 child_ctx->parent_gen = parent_ctx->parent_gen;
12906 } else {
12907 child_ctx->parent_ctx = parent_ctx;
12908 child_ctx->parent_gen = parent_ctx->generation;
12910 get_ctx(child_ctx->parent_ctx);
12913 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12914 out_unlock:
12915 mutex_unlock(&parent_ctx->mutex);
12917 perf_unpin_context(parent_ctx);
12918 put_ctx(parent_ctx);
12920 return ret;
12924 * Initialize the perf_event context in task_struct
12926 int perf_event_init_task(struct task_struct *child)
12928 int ctxn, ret;
12930 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12931 mutex_init(&child->perf_event_mutex);
12932 INIT_LIST_HEAD(&child->perf_event_list);
12934 for_each_task_context_nr(ctxn) {
12935 ret = perf_event_init_context(child, ctxn);
12936 if (ret) {
12937 perf_event_free_task(child);
12938 return ret;
12942 return 0;
12945 static void __init perf_event_init_all_cpus(void)
12947 struct swevent_htable *swhash;
12948 int cpu;
12950 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12952 for_each_possible_cpu(cpu) {
12953 swhash = &per_cpu(swevent_htable, cpu);
12954 mutex_init(&swhash->hlist_mutex);
12955 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12957 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12958 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12960 #ifdef CONFIG_CGROUP_PERF
12961 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12962 #endif
12966 static void perf_swevent_init_cpu(unsigned int cpu)
12968 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12970 mutex_lock(&swhash->hlist_mutex);
12971 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12972 struct swevent_hlist *hlist;
12974 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12975 WARN_ON(!hlist);
12976 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12978 mutex_unlock(&swhash->hlist_mutex);
12981 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12982 static void __perf_event_exit_context(void *__info)
12984 struct perf_event_context *ctx = __info;
12985 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12986 struct perf_event *event;
12988 raw_spin_lock(&ctx->lock);
12989 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12990 list_for_each_entry(event, &ctx->event_list, event_entry)
12991 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12992 raw_spin_unlock(&ctx->lock);
12995 static void perf_event_exit_cpu_context(int cpu)
12997 struct perf_cpu_context *cpuctx;
12998 struct perf_event_context *ctx;
12999 struct pmu *pmu;
13001 mutex_lock(&pmus_lock);
13002 list_for_each_entry(pmu, &pmus, entry) {
13003 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13004 ctx = &cpuctx->ctx;
13006 mutex_lock(&ctx->mutex);
13007 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13008 cpuctx->online = 0;
13009 mutex_unlock(&ctx->mutex);
13011 cpumask_clear_cpu(cpu, perf_online_mask);
13012 mutex_unlock(&pmus_lock);
13014 #else
13016 static void perf_event_exit_cpu_context(int cpu) { }
13018 #endif
13020 int perf_event_init_cpu(unsigned int cpu)
13022 struct perf_cpu_context *cpuctx;
13023 struct perf_event_context *ctx;
13024 struct pmu *pmu;
13026 perf_swevent_init_cpu(cpu);
13028 mutex_lock(&pmus_lock);
13029 cpumask_set_cpu(cpu, perf_online_mask);
13030 list_for_each_entry(pmu, &pmus, entry) {
13031 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13032 ctx = &cpuctx->ctx;
13034 mutex_lock(&ctx->mutex);
13035 cpuctx->online = 1;
13036 mutex_unlock(&ctx->mutex);
13038 mutex_unlock(&pmus_lock);
13040 return 0;
13043 int perf_event_exit_cpu(unsigned int cpu)
13045 perf_event_exit_cpu_context(cpu);
13046 return 0;
13049 static int
13050 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13052 int cpu;
13054 for_each_online_cpu(cpu)
13055 perf_event_exit_cpu(cpu);
13057 return NOTIFY_OK;
13061 * Run the perf reboot notifier at the very last possible moment so that
13062 * the generic watchdog code runs as long as possible.
13064 static struct notifier_block perf_reboot_notifier = {
13065 .notifier_call = perf_reboot,
13066 .priority = INT_MIN,
13069 void __init perf_event_init(void)
13071 int ret;
13073 idr_init(&pmu_idr);
13075 perf_event_init_all_cpus();
13076 init_srcu_struct(&pmus_srcu);
13077 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13078 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13079 perf_pmu_register(&perf_task_clock, NULL, -1);
13080 perf_tp_register();
13081 perf_event_init_cpu(smp_processor_id());
13082 register_reboot_notifier(&perf_reboot_notifier);
13084 ret = init_hw_breakpoint();
13085 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13088 * Build time assertion that we keep the data_head at the intended
13089 * location. IOW, validation we got the __reserved[] size right.
13091 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13092 != 1024);
13095 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13096 char *page)
13098 struct perf_pmu_events_attr *pmu_attr =
13099 container_of(attr, struct perf_pmu_events_attr, attr);
13101 if (pmu_attr->event_str)
13102 return sprintf(page, "%s\n", pmu_attr->event_str);
13104 return 0;
13106 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13108 static int __init perf_event_sysfs_init(void)
13110 struct pmu *pmu;
13111 int ret;
13113 mutex_lock(&pmus_lock);
13115 ret = bus_register(&pmu_bus);
13116 if (ret)
13117 goto unlock;
13119 list_for_each_entry(pmu, &pmus, entry) {
13120 if (!pmu->name || pmu->type < 0)
13121 continue;
13123 ret = pmu_dev_alloc(pmu);
13124 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13126 pmu_bus_running = 1;
13127 ret = 0;
13129 unlock:
13130 mutex_unlock(&pmus_lock);
13132 return ret;
13134 device_initcall(perf_event_sysfs_init);
13136 #ifdef CONFIG_CGROUP_PERF
13137 static struct cgroup_subsys_state *
13138 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13140 struct perf_cgroup *jc;
13142 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13143 if (!jc)
13144 return ERR_PTR(-ENOMEM);
13146 jc->info = alloc_percpu(struct perf_cgroup_info);
13147 if (!jc->info) {
13148 kfree(jc);
13149 return ERR_PTR(-ENOMEM);
13152 return &jc->css;
13155 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13157 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13159 free_percpu(jc->info);
13160 kfree(jc);
13163 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13165 perf_event_cgroup(css->cgroup);
13166 return 0;
13169 static int __perf_cgroup_move(void *info)
13171 struct task_struct *task = info;
13172 rcu_read_lock();
13173 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13174 rcu_read_unlock();
13175 return 0;
13178 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13180 struct task_struct *task;
13181 struct cgroup_subsys_state *css;
13183 cgroup_taskset_for_each(task, css, tset)
13184 task_function_call(task, __perf_cgroup_move, task);
13187 struct cgroup_subsys perf_event_cgrp_subsys = {
13188 .css_alloc = perf_cgroup_css_alloc,
13189 .css_free = perf_cgroup_css_free,
13190 .css_online = perf_cgroup_css_online,
13191 .attach = perf_cgroup_attach,
13193 * Implicitly enable on dfl hierarchy so that perf events can
13194 * always be filtered by cgroup2 path as long as perf_event
13195 * controller is not mounted on a legacy hierarchy.
13197 .implicit_on_dfl = true,
13198 .threaded = true,
13200 #endif /* CONFIG_CGROUP_PERF */