1 // SPDX-License-Identifier: GPL-2.0
3 * Performance events core code:
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
61 #include <asm/irq_regs.h>
63 typedef int (*remote_function_f)(void *);
65 struct remote_function_call {
66 struct task_struct *p;
67 remote_function_f func;
72 static void remote_function(void *data)
74 struct remote_function_call *tfc = data;
75 struct task_struct *p = tfc->p;
79 if (task_cpu(p) != smp_processor_id())
83 * Now that we're on right CPU with IRQs disabled, we can test
84 * if we hit the right task without races.
87 tfc->ret = -ESRCH; /* No such (running) process */
92 tfc->ret = tfc->func(tfc->info);
96 * task_function_call - call a function on the cpu on which a task runs
97 * @p: the task to evaluate
98 * @func: the function to be called
99 * @info: the function call argument
101 * Calls the function @func when the task is currently running. This might
102 * be on the current CPU, which just calls the function directly. This will
103 * retry due to any failures in smp_call_function_single(), such as if the
104 * task_cpu() goes offline concurrently.
106 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
109 task_function_call(struct task_struct *p, remote_function_f func, void *info)
111 struct remote_function_call data = {
120 ret = smp_call_function_single(task_cpu(p), remote_function,
135 * cpu_function_call - call a function on the cpu
136 * @cpu: target cpu to queue this function
137 * @func: the function to be called
138 * @info: the function call argument
140 * Calls the function @func on the remote cpu.
142 * returns: @func return value or -ENXIO when the cpu is offline
144 static int cpu_function_call(int cpu, remote_function_f func, void *info)
146 struct remote_function_call data = {
150 .ret = -ENXIO, /* No such CPU */
153 smp_call_function_single(cpu, remote_function, &data, 1);
158 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
159 struct perf_event_context *ctx)
161 raw_spin_lock(&cpuctx->ctx.lock);
163 raw_spin_lock(&ctx->lock);
166 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
167 struct perf_event_context *ctx)
170 raw_spin_unlock(&ctx->lock);
171 raw_spin_unlock(&cpuctx->ctx.lock);
174 #define TASK_TOMBSTONE ((void *)-1L)
176 static bool is_kernel_event(struct perf_event *event)
178 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
181 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
183 struct perf_event_context *perf_cpu_task_ctx(void)
185 lockdep_assert_irqs_disabled();
186 return this_cpu_ptr(&perf_cpu_context)->task_ctx;
190 * On task ctx scheduling...
192 * When !ctx->nr_events a task context will not be scheduled. This means
193 * we can disable the scheduler hooks (for performance) without leaving
194 * pending task ctx state.
196 * This however results in two special cases:
198 * - removing the last event from a task ctx; this is relatively straight
199 * forward and is done in __perf_remove_from_context.
201 * - adding the first event to a task ctx; this is tricky because we cannot
202 * rely on ctx->is_active and therefore cannot use event_function_call().
203 * See perf_install_in_context().
205 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
208 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
209 struct perf_event_context *, void *);
211 struct event_function_struct {
212 struct perf_event *event;
217 static int event_function(void *info)
219 struct event_function_struct *efs = info;
220 struct perf_event *event = efs->event;
221 struct perf_event_context *ctx = event->ctx;
222 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
223 struct perf_event_context *task_ctx = cpuctx->task_ctx;
226 lockdep_assert_irqs_disabled();
228 perf_ctx_lock(cpuctx, task_ctx);
230 * Since we do the IPI call without holding ctx->lock things can have
231 * changed, double check we hit the task we set out to hit.
234 if (ctx->task != current) {
240 * We only use event_function_call() on established contexts,
241 * and event_function() is only ever called when active (or
242 * rather, we'll have bailed in task_function_call() or the
243 * above ctx->task != current test), therefore we must have
244 * ctx->is_active here.
246 WARN_ON_ONCE(!ctx->is_active);
248 * And since we have ctx->is_active, cpuctx->task_ctx must
251 WARN_ON_ONCE(task_ctx != ctx);
253 WARN_ON_ONCE(&cpuctx->ctx != ctx);
256 efs->func(event, cpuctx, ctx, efs->data);
258 perf_ctx_unlock(cpuctx, task_ctx);
263 static void event_function_call(struct perf_event *event, event_f func, void *data)
265 struct perf_event_context *ctx = event->ctx;
266 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
267 struct event_function_struct efs = {
273 if (!event->parent) {
275 * If this is a !child event, we must hold ctx::mutex to
276 * stabilize the event->ctx relation. See
277 * perf_event_ctx_lock().
279 lockdep_assert_held(&ctx->mutex);
283 cpu_function_call(event->cpu, event_function, &efs);
287 if (task == TASK_TOMBSTONE)
291 if (!task_function_call(task, event_function, &efs))
294 raw_spin_lock_irq(&ctx->lock);
296 * Reload the task pointer, it might have been changed by
297 * a concurrent perf_event_context_sched_out().
300 if (task == TASK_TOMBSTONE) {
301 raw_spin_unlock_irq(&ctx->lock);
304 if (ctx->is_active) {
305 raw_spin_unlock_irq(&ctx->lock);
308 func(event, NULL, ctx, data);
309 raw_spin_unlock_irq(&ctx->lock);
313 * Similar to event_function_call() + event_function(), but hard assumes IRQs
314 * are already disabled and we're on the right CPU.
316 static void event_function_local(struct perf_event *event, event_f func, void *data)
318 struct perf_event_context *ctx = event->ctx;
319 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
320 struct task_struct *task = READ_ONCE(ctx->task);
321 struct perf_event_context *task_ctx = NULL;
323 lockdep_assert_irqs_disabled();
326 if (task == TASK_TOMBSTONE)
332 perf_ctx_lock(cpuctx, task_ctx);
335 if (task == TASK_TOMBSTONE)
340 * We must be either inactive or active and the right task,
341 * otherwise we're screwed, since we cannot IPI to somewhere
344 if (ctx->is_active) {
345 if (WARN_ON_ONCE(task != current))
348 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
352 WARN_ON_ONCE(&cpuctx->ctx != ctx);
355 func(event, cpuctx, ctx, data);
357 perf_ctx_unlock(cpuctx, task_ctx);
360 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
361 PERF_FLAG_FD_OUTPUT |\
362 PERF_FLAG_PID_CGROUP |\
363 PERF_FLAG_FD_CLOEXEC)
366 * branch priv levels that need permission checks
368 #define PERF_SAMPLE_BRANCH_PERM_PLM \
369 (PERF_SAMPLE_BRANCH_KERNEL |\
370 PERF_SAMPLE_BRANCH_HV)
373 EVENT_FLEXIBLE = 0x1,
376 /* see ctx_resched() for details */
379 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
383 * perf_sched_events : >0 events exist
386 static void perf_sched_delayed(struct work_struct *work);
387 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
388 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
389 static DEFINE_MUTEX(perf_sched_mutex);
390 static atomic_t perf_sched_count;
392 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
394 static atomic_t nr_mmap_events __read_mostly;
395 static atomic_t nr_comm_events __read_mostly;
396 static atomic_t nr_namespaces_events __read_mostly;
397 static atomic_t nr_task_events __read_mostly;
398 static atomic_t nr_freq_events __read_mostly;
399 static atomic_t nr_switch_events __read_mostly;
400 static atomic_t nr_ksymbol_events __read_mostly;
401 static atomic_t nr_bpf_events __read_mostly;
402 static atomic_t nr_cgroup_events __read_mostly;
403 static atomic_t nr_text_poke_events __read_mostly;
404 static atomic_t nr_build_id_events __read_mostly;
406 static LIST_HEAD(pmus);
407 static DEFINE_MUTEX(pmus_lock);
408 static struct srcu_struct pmus_srcu;
409 static cpumask_var_t perf_online_mask;
410 static struct kmem_cache *perf_event_cache;
413 * perf event paranoia level:
414 * -1 - not paranoid at all
415 * 0 - disallow raw tracepoint access for unpriv
416 * 1 - disallow cpu events for unpriv
417 * 2 - disallow kernel profiling for unpriv
419 int sysctl_perf_event_paranoid __read_mostly = 2;
421 /* Minimum for 512 kiB + 1 user control page */
422 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
425 * max perf event sample rate
427 #define DEFAULT_MAX_SAMPLE_RATE 100000
428 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
429 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
431 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
433 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
434 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
436 static int perf_sample_allowed_ns __read_mostly =
437 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
439 static void update_perf_cpu_limits(void)
441 u64 tmp = perf_sample_period_ns;
443 tmp *= sysctl_perf_cpu_time_max_percent;
444 tmp = div_u64(tmp, 100);
448 WRITE_ONCE(perf_sample_allowed_ns, tmp);
451 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
453 int perf_proc_update_handler(struct ctl_table *table, int write,
454 void *buffer, size_t *lenp, loff_t *ppos)
457 int perf_cpu = sysctl_perf_cpu_time_max_percent;
459 * If throttling is disabled don't allow the write:
461 if (write && (perf_cpu == 100 || perf_cpu == 0))
464 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
468 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
469 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
470 update_perf_cpu_limits();
475 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
477 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
478 void *buffer, size_t *lenp, loff_t *ppos)
480 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
485 if (sysctl_perf_cpu_time_max_percent == 100 ||
486 sysctl_perf_cpu_time_max_percent == 0) {
488 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
489 WRITE_ONCE(perf_sample_allowed_ns, 0);
491 update_perf_cpu_limits();
498 * perf samples are done in some very critical code paths (NMIs).
499 * If they take too much CPU time, the system can lock up and not
500 * get any real work done. This will drop the sample rate when
501 * we detect that events are taking too long.
503 #define NR_ACCUMULATED_SAMPLES 128
504 static DEFINE_PER_CPU(u64, running_sample_length);
506 static u64 __report_avg;
507 static u64 __report_allowed;
509 static void perf_duration_warn(struct irq_work *w)
511 printk_ratelimited(KERN_INFO
512 "perf: interrupt took too long (%lld > %lld), lowering "
513 "kernel.perf_event_max_sample_rate to %d\n",
514 __report_avg, __report_allowed,
515 sysctl_perf_event_sample_rate);
518 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
520 void perf_sample_event_took(u64 sample_len_ns)
522 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
530 /* Decay the counter by 1 average sample. */
531 running_len = __this_cpu_read(running_sample_length);
532 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
533 running_len += sample_len_ns;
534 __this_cpu_write(running_sample_length, running_len);
537 * Note: this will be biased artifically low until we have
538 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
539 * from having to maintain a count.
541 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
542 if (avg_len <= max_len)
545 __report_avg = avg_len;
546 __report_allowed = max_len;
549 * Compute a throttle threshold 25% below the current duration.
551 avg_len += avg_len / 4;
552 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
558 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
559 WRITE_ONCE(max_samples_per_tick, max);
561 sysctl_perf_event_sample_rate = max * HZ;
562 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
564 if (!irq_work_queue(&perf_duration_work)) {
565 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
566 "kernel.perf_event_max_sample_rate to %d\n",
567 __report_avg, __report_allowed,
568 sysctl_perf_event_sample_rate);
572 static atomic64_t perf_event_id;
574 static void update_context_time(struct perf_event_context *ctx);
575 static u64 perf_event_time(struct perf_event *event);
577 void __weak perf_event_print_debug(void) { }
579 static inline u64 perf_clock(void)
581 return local_clock();
584 static inline u64 perf_event_clock(struct perf_event *event)
586 return event->clock();
590 * State based event timekeeping...
592 * The basic idea is to use event->state to determine which (if any) time
593 * fields to increment with the current delta. This means we only need to
594 * update timestamps when we change state or when they are explicitly requested
597 * Event groups make things a little more complicated, but not terribly so. The
598 * rules for a group are that if the group leader is OFF the entire group is
599 * OFF, irrespecive of what the group member states are. This results in
600 * __perf_effective_state().
602 * A futher ramification is that when a group leader flips between OFF and
603 * !OFF, we need to update all group member times.
606 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
607 * need to make sure the relevant context time is updated before we try and
608 * update our timestamps.
611 static __always_inline enum perf_event_state
612 __perf_effective_state(struct perf_event *event)
614 struct perf_event *leader = event->group_leader;
616 if (leader->state <= PERF_EVENT_STATE_OFF)
617 return leader->state;
622 static __always_inline void
623 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
625 enum perf_event_state state = __perf_effective_state(event);
626 u64 delta = now - event->tstamp;
628 *enabled = event->total_time_enabled;
629 if (state >= PERF_EVENT_STATE_INACTIVE)
632 *running = event->total_time_running;
633 if (state >= PERF_EVENT_STATE_ACTIVE)
637 static void perf_event_update_time(struct perf_event *event)
639 u64 now = perf_event_time(event);
641 __perf_update_times(event, now, &event->total_time_enabled,
642 &event->total_time_running);
646 static void perf_event_update_sibling_time(struct perf_event *leader)
648 struct perf_event *sibling;
650 for_each_sibling_event(sibling, leader)
651 perf_event_update_time(sibling);
655 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
657 if (event->state == state)
660 perf_event_update_time(event);
662 * If a group leader gets enabled/disabled all its siblings
665 if ((event->state < 0) ^ (state < 0))
666 perf_event_update_sibling_time(event);
668 WRITE_ONCE(event->state, state);
672 * UP store-release, load-acquire
675 #define __store_release(ptr, val) \
678 WRITE_ONCE(*(ptr), (val)); \
681 #define __load_acquire(ptr) \
683 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
688 static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
690 struct perf_event_pmu_context *pmu_ctx;
692 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
693 if (cgroup && !pmu_ctx->nr_cgroups)
695 perf_pmu_disable(pmu_ctx->pmu);
699 static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
701 struct perf_event_pmu_context *pmu_ctx;
703 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
704 if (cgroup && !pmu_ctx->nr_cgroups)
706 perf_pmu_enable(pmu_ctx->pmu);
710 static void ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type);
711 static void ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type);
713 #ifdef CONFIG_CGROUP_PERF
716 perf_cgroup_match(struct perf_event *event)
718 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
720 /* @event doesn't care about cgroup */
724 /* wants specific cgroup scope but @cpuctx isn't associated with any */
729 * Cgroup scoping is recursive. An event enabled for a cgroup is
730 * also enabled for all its descendant cgroups. If @cpuctx's
731 * cgroup is a descendant of @event's (the test covers identity
732 * case), it's a match.
734 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
735 event->cgrp->css.cgroup);
738 static inline void perf_detach_cgroup(struct perf_event *event)
740 css_put(&event->cgrp->css);
744 static inline int is_cgroup_event(struct perf_event *event)
746 return event->cgrp != NULL;
749 static inline u64 perf_cgroup_event_time(struct perf_event *event)
751 struct perf_cgroup_info *t;
753 t = per_cpu_ptr(event->cgrp->info, event->cpu);
757 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
759 struct perf_cgroup_info *t;
761 t = per_cpu_ptr(event->cgrp->info, event->cpu);
762 if (!__load_acquire(&t->active))
764 now += READ_ONCE(t->timeoffset);
768 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
771 info->time += now - info->timestamp;
772 info->timestamp = now;
774 * see update_context_time()
776 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
779 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
781 struct perf_cgroup *cgrp = cpuctx->cgrp;
782 struct cgroup_subsys_state *css;
783 struct perf_cgroup_info *info;
786 u64 now = perf_clock();
788 for (css = &cgrp->css; css; css = css->parent) {
789 cgrp = container_of(css, struct perf_cgroup, css);
790 info = this_cpu_ptr(cgrp->info);
792 __update_cgrp_time(info, now, true);
794 __store_release(&info->active, 0);
799 static inline void update_cgrp_time_from_event(struct perf_event *event)
801 struct perf_cgroup_info *info;
804 * ensure we access cgroup data only when needed and
805 * when we know the cgroup is pinned (css_get)
807 if (!is_cgroup_event(event))
810 info = this_cpu_ptr(event->cgrp->info);
812 * Do not update time when cgroup is not active
815 __update_cgrp_time(info, perf_clock(), true);
819 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
821 struct perf_event_context *ctx = &cpuctx->ctx;
822 struct perf_cgroup *cgrp = cpuctx->cgrp;
823 struct perf_cgroup_info *info;
824 struct cgroup_subsys_state *css;
827 * ctx->lock held by caller
828 * ensure we do not access cgroup data
829 * unless we have the cgroup pinned (css_get)
834 WARN_ON_ONCE(!ctx->nr_cgroups);
836 for (css = &cgrp->css; css; css = css->parent) {
837 cgrp = container_of(css, struct perf_cgroup, css);
838 info = this_cpu_ptr(cgrp->info);
839 __update_cgrp_time(info, ctx->timestamp, false);
840 __store_release(&info->active, 1);
845 * reschedule events based on the cgroup constraint of task.
847 static void perf_cgroup_switch(struct task_struct *task)
849 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
850 struct perf_cgroup *cgrp;
853 * cpuctx->cgrp is set when the first cgroup event enabled,
854 * and is cleared when the last cgroup event disabled.
856 if (READ_ONCE(cpuctx->cgrp) == NULL)
859 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
861 cgrp = perf_cgroup_from_task(task, NULL);
862 if (READ_ONCE(cpuctx->cgrp) == cgrp)
865 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
866 perf_ctx_disable(&cpuctx->ctx, true);
868 ctx_sched_out(&cpuctx->ctx, EVENT_ALL|EVENT_CGROUP);
870 * must not be done before ctxswout due
871 * to update_cgrp_time_from_cpuctx() in
876 * set cgrp before ctxsw in to allow
877 * perf_cgroup_set_timestamp() in ctx_sched_in()
878 * to not have to pass task around
880 ctx_sched_in(&cpuctx->ctx, EVENT_ALL|EVENT_CGROUP);
882 perf_ctx_enable(&cpuctx->ctx, true);
883 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
886 static int perf_cgroup_ensure_storage(struct perf_event *event,
887 struct cgroup_subsys_state *css)
889 struct perf_cpu_context *cpuctx;
890 struct perf_event **storage;
891 int cpu, heap_size, ret = 0;
894 * Allow storage to have sufficent space for an iterator for each
895 * possibly nested cgroup plus an iterator for events with no cgroup.
897 for (heap_size = 1; css; css = css->parent)
900 for_each_possible_cpu(cpu) {
901 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
902 if (heap_size <= cpuctx->heap_size)
905 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
906 GFP_KERNEL, cpu_to_node(cpu));
912 raw_spin_lock_irq(&cpuctx->ctx.lock);
913 if (cpuctx->heap_size < heap_size) {
914 swap(cpuctx->heap, storage);
915 if (storage == cpuctx->heap_default)
917 cpuctx->heap_size = heap_size;
919 raw_spin_unlock_irq(&cpuctx->ctx.lock);
927 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
928 struct perf_event_attr *attr,
929 struct perf_event *group_leader)
931 struct perf_cgroup *cgrp;
932 struct cgroup_subsys_state *css;
933 struct fd f = fdget(fd);
939 css = css_tryget_online_from_dir(f.file->f_path.dentry,
940 &perf_event_cgrp_subsys);
946 ret = perf_cgroup_ensure_storage(event, css);
950 cgrp = container_of(css, struct perf_cgroup, css);
954 * all events in a group must monitor
955 * the same cgroup because a task belongs
956 * to only one perf cgroup at a time
958 if (group_leader && group_leader->cgrp != cgrp) {
959 perf_detach_cgroup(event);
968 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
970 struct perf_cpu_context *cpuctx;
972 if (!is_cgroup_event(event))
975 event->pmu_ctx->nr_cgroups++;
978 * Because cgroup events are always per-cpu events,
979 * @ctx == &cpuctx->ctx.
981 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
983 if (ctx->nr_cgroups++)
986 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
990 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
992 struct perf_cpu_context *cpuctx;
994 if (!is_cgroup_event(event))
997 event->pmu_ctx->nr_cgroups--;
1000 * Because cgroup events are always per-cpu events,
1001 * @ctx == &cpuctx->ctx.
1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1005 if (--ctx->nr_cgroups)
1008 cpuctx->cgrp = NULL;
1011 #else /* !CONFIG_CGROUP_PERF */
1014 perf_cgroup_match(struct perf_event *event)
1019 static inline void perf_detach_cgroup(struct perf_event *event)
1022 static inline int is_cgroup_event(struct perf_event *event)
1027 static inline void update_cgrp_time_from_event(struct perf_event *event)
1031 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1036 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1037 struct perf_event_attr *attr,
1038 struct perf_event *group_leader)
1044 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1048 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1053 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1059 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1064 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1068 static void perf_cgroup_switch(struct task_struct *task)
1074 * set default to be dependent on timer tick just
1075 * like original code
1077 #define PERF_CPU_HRTIMER (1000 / HZ)
1079 * function must be called with interrupts disabled
1081 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1083 struct perf_cpu_pmu_context *cpc;
1086 lockdep_assert_irqs_disabled();
1088 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1089 rotations = perf_rotate_context(cpc);
1091 raw_spin_lock(&cpc->hrtimer_lock);
1093 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1095 cpc->hrtimer_active = 0;
1096 raw_spin_unlock(&cpc->hrtimer_lock);
1098 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1101 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1103 struct hrtimer *timer = &cpc->hrtimer;
1104 struct pmu *pmu = cpc->epc.pmu;
1108 * check default is sane, if not set then force to
1109 * default interval (1/tick)
1111 interval = pmu->hrtimer_interval_ms;
1113 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1115 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1117 raw_spin_lock_init(&cpc->hrtimer_lock);
1118 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1119 timer->function = perf_mux_hrtimer_handler;
1122 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1124 struct hrtimer *timer = &cpc->hrtimer;
1125 unsigned long flags;
1127 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1128 if (!cpc->hrtimer_active) {
1129 cpc->hrtimer_active = 1;
1130 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1131 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1133 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1138 static int perf_mux_hrtimer_restart_ipi(void *arg)
1140 return perf_mux_hrtimer_restart(arg);
1143 void perf_pmu_disable(struct pmu *pmu)
1145 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1147 pmu->pmu_disable(pmu);
1150 void perf_pmu_enable(struct pmu *pmu)
1152 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1154 pmu->pmu_enable(pmu);
1157 static void perf_assert_pmu_disabled(struct pmu *pmu)
1159 WARN_ON_ONCE(*this_cpu_ptr(pmu->pmu_disable_count) == 0);
1162 static void get_ctx(struct perf_event_context *ctx)
1164 refcount_inc(&ctx->refcount);
1167 static void *alloc_task_ctx_data(struct pmu *pmu)
1169 if (pmu->task_ctx_cache)
1170 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1175 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1177 if (pmu->task_ctx_cache && task_ctx_data)
1178 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1181 static void free_ctx(struct rcu_head *head)
1183 struct perf_event_context *ctx;
1185 ctx = container_of(head, struct perf_event_context, rcu_head);
1189 static void put_ctx(struct perf_event_context *ctx)
1191 if (refcount_dec_and_test(&ctx->refcount)) {
1192 if (ctx->parent_ctx)
1193 put_ctx(ctx->parent_ctx);
1194 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1195 put_task_struct(ctx->task);
1196 call_rcu(&ctx->rcu_head, free_ctx);
1201 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1202 * perf_pmu_migrate_context() we need some magic.
1204 * Those places that change perf_event::ctx will hold both
1205 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1207 * Lock ordering is by mutex address. There are two other sites where
1208 * perf_event_context::mutex nests and those are:
1210 * - perf_event_exit_task_context() [ child , 0 ]
1211 * perf_event_exit_event()
1212 * put_event() [ parent, 1 ]
1214 * - perf_event_init_context() [ parent, 0 ]
1215 * inherit_task_group()
1218 * perf_event_alloc()
1220 * perf_try_init_event() [ child , 1 ]
1222 * While it appears there is an obvious deadlock here -- the parent and child
1223 * nesting levels are inverted between the two. This is in fact safe because
1224 * life-time rules separate them. That is an exiting task cannot fork, and a
1225 * spawning task cannot (yet) exit.
1227 * But remember that these are parent<->child context relations, and
1228 * migration does not affect children, therefore these two orderings should not
1231 * The change in perf_event::ctx does not affect children (as claimed above)
1232 * because the sys_perf_event_open() case will install a new event and break
1233 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1234 * concerned with cpuctx and that doesn't have children.
1236 * The places that change perf_event::ctx will issue:
1238 * perf_remove_from_context();
1239 * synchronize_rcu();
1240 * perf_install_in_context();
1242 * to affect the change. The remove_from_context() + synchronize_rcu() should
1243 * quiesce the event, after which we can install it in the new location. This
1244 * means that only external vectors (perf_fops, prctl) can perturb the event
1245 * while in transit. Therefore all such accessors should also acquire
1246 * perf_event_context::mutex to serialize against this.
1248 * However; because event->ctx can change while we're waiting to acquire
1249 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1254 * task_struct::perf_event_mutex
1255 * perf_event_context::mutex
1256 * perf_event::child_mutex;
1257 * perf_event_context::lock
1258 * perf_event::mmap_mutex
1260 * perf_addr_filters_head::lock
1264 * cpuctx->mutex / perf_event_context::mutex
1266 static struct perf_event_context *
1267 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1269 struct perf_event_context *ctx;
1273 ctx = READ_ONCE(event->ctx);
1274 if (!refcount_inc_not_zero(&ctx->refcount)) {
1280 mutex_lock_nested(&ctx->mutex, nesting);
1281 if (event->ctx != ctx) {
1282 mutex_unlock(&ctx->mutex);
1290 static inline struct perf_event_context *
1291 perf_event_ctx_lock(struct perf_event *event)
1293 return perf_event_ctx_lock_nested(event, 0);
1296 static void perf_event_ctx_unlock(struct perf_event *event,
1297 struct perf_event_context *ctx)
1299 mutex_unlock(&ctx->mutex);
1304 * This must be done under the ctx->lock, such as to serialize against
1305 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1306 * calling scheduler related locks and ctx->lock nests inside those.
1308 static __must_check struct perf_event_context *
1309 unclone_ctx(struct perf_event_context *ctx)
1311 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1313 lockdep_assert_held(&ctx->lock);
1316 ctx->parent_ctx = NULL;
1322 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1327 * only top level events have the pid namespace they were created in
1330 event = event->parent;
1332 nr = __task_pid_nr_ns(p, type, event->ns);
1333 /* avoid -1 if it is idle thread or runs in another ns */
1334 if (!nr && !pid_alive(p))
1339 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1341 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1344 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1346 return perf_event_pid_type(event, p, PIDTYPE_PID);
1350 * If we inherit events we want to return the parent event id
1353 static u64 primary_event_id(struct perf_event *event)
1358 id = event->parent->id;
1364 * Get the perf_event_context for a task and lock it.
1366 * This has to cope with the fact that until it is locked,
1367 * the context could get moved to another task.
1369 static struct perf_event_context *
1370 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1372 struct perf_event_context *ctx;
1376 * One of the few rules of preemptible RCU is that one cannot do
1377 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1378 * part of the read side critical section was irqs-enabled -- see
1379 * rcu_read_unlock_special().
1381 * Since ctx->lock nests under rq->lock we must ensure the entire read
1382 * side critical section has interrupts disabled.
1384 local_irq_save(*flags);
1386 ctx = rcu_dereference(task->perf_event_ctxp);
1389 * If this context is a clone of another, it might
1390 * get swapped for another underneath us by
1391 * perf_event_task_sched_out, though the
1392 * rcu_read_lock() protects us from any context
1393 * getting freed. Lock the context and check if it
1394 * got swapped before we could get the lock, and retry
1395 * if so. If we locked the right context, then it
1396 * can't get swapped on us any more.
1398 raw_spin_lock(&ctx->lock);
1399 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1400 raw_spin_unlock(&ctx->lock);
1402 local_irq_restore(*flags);
1406 if (ctx->task == TASK_TOMBSTONE ||
1407 !refcount_inc_not_zero(&ctx->refcount)) {
1408 raw_spin_unlock(&ctx->lock);
1411 WARN_ON_ONCE(ctx->task != task);
1416 local_irq_restore(*flags);
1421 * Get the context for a task and increment its pin_count so it
1422 * can't get swapped to another task. This also increments its
1423 * reference count so that the context can't get freed.
1425 static struct perf_event_context *
1426 perf_pin_task_context(struct task_struct *task)
1428 struct perf_event_context *ctx;
1429 unsigned long flags;
1431 ctx = perf_lock_task_context(task, &flags);
1434 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1439 static void perf_unpin_context(struct perf_event_context *ctx)
1441 unsigned long flags;
1443 raw_spin_lock_irqsave(&ctx->lock, flags);
1445 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1449 * Update the record of the current time in a context.
1451 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1453 u64 now = perf_clock();
1455 lockdep_assert_held(&ctx->lock);
1458 ctx->time += now - ctx->timestamp;
1459 ctx->timestamp = now;
1462 * The above: time' = time + (now - timestamp), can be re-arranged
1463 * into: time` = now + (time - timestamp), which gives a single value
1464 * offset to compute future time without locks on.
1466 * See perf_event_time_now(), which can be used from NMI context where
1467 * it's (obviously) not possible to acquire ctx->lock in order to read
1468 * both the above values in a consistent manner.
1470 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1473 static void update_context_time(struct perf_event_context *ctx)
1475 __update_context_time(ctx, true);
1478 static u64 perf_event_time(struct perf_event *event)
1480 struct perf_event_context *ctx = event->ctx;
1485 if (is_cgroup_event(event))
1486 return perf_cgroup_event_time(event);
1491 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1493 struct perf_event_context *ctx = event->ctx;
1498 if (is_cgroup_event(event))
1499 return perf_cgroup_event_time_now(event, now);
1501 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1504 now += READ_ONCE(ctx->timeoffset);
1508 static enum event_type_t get_event_type(struct perf_event *event)
1510 struct perf_event_context *ctx = event->ctx;
1511 enum event_type_t event_type;
1513 lockdep_assert_held(&ctx->lock);
1516 * It's 'group type', really, because if our group leader is
1517 * pinned, so are we.
1519 if (event->group_leader != event)
1520 event = event->group_leader;
1522 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1524 event_type |= EVENT_CPU;
1530 * Helper function to initialize event group nodes.
1532 static void init_event_group(struct perf_event *event)
1534 RB_CLEAR_NODE(&event->group_node);
1535 event->group_index = 0;
1539 * Extract pinned or flexible groups from the context
1540 * based on event attrs bits.
1542 static struct perf_event_groups *
1543 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1545 if (event->attr.pinned)
1546 return &ctx->pinned_groups;
1548 return &ctx->flexible_groups;
1552 * Helper function to initializes perf_event_group trees.
1554 static void perf_event_groups_init(struct perf_event_groups *groups)
1556 groups->tree = RB_ROOT;
1560 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1562 struct cgroup *cgroup = NULL;
1564 #ifdef CONFIG_CGROUP_PERF
1566 cgroup = event->cgrp->css.cgroup;
1573 * Compare function for event groups;
1575 * Implements complex key that first sorts by CPU and then by virtual index
1576 * which provides ordering when rotating groups for the same CPU.
1578 static __always_inline int
1579 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1580 const struct cgroup *left_cgroup, const u64 left_group_index,
1581 const struct perf_event *right)
1583 if (left_cpu < right->cpu)
1585 if (left_cpu > right->cpu)
1589 if (left_pmu < right->pmu_ctx->pmu)
1591 if (left_pmu > right->pmu_ctx->pmu)
1595 #ifdef CONFIG_CGROUP_PERF
1597 const struct cgroup *right_cgroup = event_cgroup(right);
1599 if (left_cgroup != right_cgroup) {
1602 * Left has no cgroup but right does, no
1603 * cgroups come first.
1607 if (!right_cgroup) {
1609 * Right has no cgroup but left does, no
1610 * cgroups come first.
1614 /* Two dissimilar cgroups, order by id. */
1615 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1623 if (left_group_index < right->group_index)
1625 if (left_group_index > right->group_index)
1631 #define __node_2_pe(node) \
1632 rb_entry((node), struct perf_event, group_node)
1634 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1636 struct perf_event *e = __node_2_pe(a);
1637 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1638 e->group_index, __node_2_pe(b)) < 0;
1641 struct __group_key {
1644 struct cgroup *cgroup;
1647 static inline int __group_cmp(const void *key, const struct rb_node *node)
1649 const struct __group_key *a = key;
1650 const struct perf_event *b = __node_2_pe(node);
1652 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1653 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1657 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1659 const struct __group_key *a = key;
1660 const struct perf_event *b = __node_2_pe(node);
1662 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1663 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1668 * Insert @event into @groups' tree; using
1669 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1670 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1673 perf_event_groups_insert(struct perf_event_groups *groups,
1674 struct perf_event *event)
1676 event->group_index = ++groups->index;
1678 rb_add(&event->group_node, &groups->tree, __group_less);
1682 * Helper function to insert event into the pinned or flexible groups.
1685 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1687 struct perf_event_groups *groups;
1689 groups = get_event_groups(event, ctx);
1690 perf_event_groups_insert(groups, event);
1694 * Delete a group from a tree.
1697 perf_event_groups_delete(struct perf_event_groups *groups,
1698 struct perf_event *event)
1700 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1701 RB_EMPTY_ROOT(&groups->tree));
1703 rb_erase(&event->group_node, &groups->tree);
1704 init_event_group(event);
1708 * Helper function to delete event from its groups.
1711 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1713 struct perf_event_groups *groups;
1715 groups = get_event_groups(event, ctx);
1716 perf_event_groups_delete(groups, event);
1720 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1722 static struct perf_event *
1723 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1724 struct pmu *pmu, struct cgroup *cgrp)
1726 struct __group_key key = {
1731 struct rb_node *node;
1733 node = rb_find_first(&key, &groups->tree, __group_cmp);
1735 return __node_2_pe(node);
1740 static struct perf_event *
1741 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1743 struct __group_key key = {
1746 .cgroup = event_cgroup(event),
1748 struct rb_node *next;
1750 next = rb_next_match(&key, &event->group_node, __group_cmp);
1752 return __node_2_pe(next);
1757 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1758 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1759 event; event = perf_event_groups_next(event, pmu))
1762 * Iterate through the whole groups tree.
1764 #define perf_event_groups_for_each(event, groups) \
1765 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1766 typeof(*event), group_node); event; \
1767 event = rb_entry_safe(rb_next(&event->group_node), \
1768 typeof(*event), group_node))
1771 * Add an event from the lists for its context.
1772 * Must be called with ctx->mutex and ctx->lock held.
1775 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1777 lockdep_assert_held(&ctx->lock);
1779 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1780 event->attach_state |= PERF_ATTACH_CONTEXT;
1782 event->tstamp = perf_event_time(event);
1785 * If we're a stand alone event or group leader, we go to the context
1786 * list, group events are kept attached to the group so that
1787 * perf_group_detach can, at all times, locate all siblings.
1789 if (event->group_leader == event) {
1790 event->group_caps = event->event_caps;
1791 add_event_to_groups(event, ctx);
1794 list_add_rcu(&event->event_entry, &ctx->event_list);
1796 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1798 if (event->attr.inherit_stat)
1801 if (event->state > PERF_EVENT_STATE_OFF)
1802 perf_cgroup_event_enable(event, ctx);
1805 event->pmu_ctx->nr_events++;
1809 * Initialize event state based on the perf_event_attr::disabled.
1811 static inline void perf_event__state_init(struct perf_event *event)
1813 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1814 PERF_EVENT_STATE_INACTIVE;
1817 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1819 int entry = sizeof(u64); /* value */
1823 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1824 size += sizeof(u64);
1826 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1827 size += sizeof(u64);
1829 if (read_format & PERF_FORMAT_ID)
1830 entry += sizeof(u64);
1832 if (read_format & PERF_FORMAT_LOST)
1833 entry += sizeof(u64);
1835 if (read_format & PERF_FORMAT_GROUP) {
1837 size += sizeof(u64);
1841 * Since perf_event_validate_size() limits this to 16k and inhibits
1842 * adding more siblings, this will never overflow.
1844 return size + nr * entry;
1847 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1849 struct perf_sample_data *data;
1852 if (sample_type & PERF_SAMPLE_IP)
1853 size += sizeof(data->ip);
1855 if (sample_type & PERF_SAMPLE_ADDR)
1856 size += sizeof(data->addr);
1858 if (sample_type & PERF_SAMPLE_PERIOD)
1859 size += sizeof(data->period);
1861 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1862 size += sizeof(data->weight.full);
1864 if (sample_type & PERF_SAMPLE_READ)
1865 size += event->read_size;
1867 if (sample_type & PERF_SAMPLE_DATA_SRC)
1868 size += sizeof(data->data_src.val);
1870 if (sample_type & PERF_SAMPLE_TRANSACTION)
1871 size += sizeof(data->txn);
1873 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1874 size += sizeof(data->phys_addr);
1876 if (sample_type & PERF_SAMPLE_CGROUP)
1877 size += sizeof(data->cgroup);
1879 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1880 size += sizeof(data->data_page_size);
1882 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1883 size += sizeof(data->code_page_size);
1885 event->header_size = size;
1889 * Called at perf_event creation and when events are attached/detached from a
1892 static void perf_event__header_size(struct perf_event *event)
1895 __perf_event_read_size(event->attr.read_format,
1896 event->group_leader->nr_siblings);
1897 __perf_event_header_size(event, event->attr.sample_type);
1900 static void perf_event__id_header_size(struct perf_event *event)
1902 struct perf_sample_data *data;
1903 u64 sample_type = event->attr.sample_type;
1906 if (sample_type & PERF_SAMPLE_TID)
1907 size += sizeof(data->tid_entry);
1909 if (sample_type & PERF_SAMPLE_TIME)
1910 size += sizeof(data->time);
1912 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1913 size += sizeof(data->id);
1915 if (sample_type & PERF_SAMPLE_ID)
1916 size += sizeof(data->id);
1918 if (sample_type & PERF_SAMPLE_STREAM_ID)
1919 size += sizeof(data->stream_id);
1921 if (sample_type & PERF_SAMPLE_CPU)
1922 size += sizeof(data->cpu_entry);
1924 event->id_header_size = size;
1928 * Check that adding an event to the group does not result in anybody
1929 * overflowing the 64k event limit imposed by the output buffer.
1931 * Specifically, check that the read_size for the event does not exceed 16k,
1932 * read_size being the one term that grows with groups size. Since read_size
1933 * depends on per-event read_format, also (re)check the existing events.
1935 * This leaves 48k for the constant size fields and things like callchains,
1936 * branch stacks and register sets.
1938 static bool perf_event_validate_size(struct perf_event *event)
1940 struct perf_event *sibling, *group_leader = event->group_leader;
1942 if (__perf_event_read_size(event->attr.read_format,
1943 group_leader->nr_siblings + 1) > 16*1024)
1946 if (__perf_event_read_size(group_leader->attr.read_format,
1947 group_leader->nr_siblings + 1) > 16*1024)
1950 for_each_sibling_event(sibling, group_leader) {
1951 if (__perf_event_read_size(sibling->attr.read_format,
1952 group_leader->nr_siblings + 1) > 16*1024)
1959 static void perf_group_attach(struct perf_event *event)
1961 struct perf_event *group_leader = event->group_leader, *pos;
1963 lockdep_assert_held(&event->ctx->lock);
1966 * We can have double attach due to group movement (move_group) in
1967 * perf_event_open().
1969 if (event->attach_state & PERF_ATTACH_GROUP)
1972 event->attach_state |= PERF_ATTACH_GROUP;
1974 if (group_leader == event)
1977 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1979 group_leader->group_caps &= event->event_caps;
1981 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1982 group_leader->nr_siblings++;
1983 group_leader->group_generation++;
1985 perf_event__header_size(group_leader);
1987 for_each_sibling_event(pos, group_leader)
1988 perf_event__header_size(pos);
1992 * Remove an event from the lists for its context.
1993 * Must be called with ctx->mutex and ctx->lock held.
1996 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1998 WARN_ON_ONCE(event->ctx != ctx);
1999 lockdep_assert_held(&ctx->lock);
2002 * We can have double detach due to exit/hot-unplug + close.
2004 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2007 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2010 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2012 if (event->attr.inherit_stat)
2015 list_del_rcu(&event->event_entry);
2017 if (event->group_leader == event)
2018 del_event_from_groups(event, ctx);
2021 * If event was in error state, then keep it
2022 * that way, otherwise bogus counts will be
2023 * returned on read(). The only way to get out
2024 * of error state is by explicit re-enabling
2027 if (event->state > PERF_EVENT_STATE_OFF) {
2028 perf_cgroup_event_disable(event, ctx);
2029 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2033 event->pmu_ctx->nr_events--;
2037 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2039 if (!has_aux(aux_event))
2042 if (!event->pmu->aux_output_match)
2045 return event->pmu->aux_output_match(aux_event);
2048 static void put_event(struct perf_event *event);
2049 static void event_sched_out(struct perf_event *event,
2050 struct perf_event_context *ctx);
2052 static void perf_put_aux_event(struct perf_event *event)
2054 struct perf_event_context *ctx = event->ctx;
2055 struct perf_event *iter;
2058 * If event uses aux_event tear down the link
2060 if (event->aux_event) {
2061 iter = event->aux_event;
2062 event->aux_event = NULL;
2068 * If the event is an aux_event, tear down all links to
2069 * it from other events.
2071 for_each_sibling_event(iter, event->group_leader) {
2072 if (iter->aux_event != event)
2075 iter->aux_event = NULL;
2079 * If it's ACTIVE, schedule it out and put it into ERROR
2080 * state so that we don't try to schedule it again. Note
2081 * that perf_event_enable() will clear the ERROR status.
2083 event_sched_out(iter, ctx);
2084 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2088 static bool perf_need_aux_event(struct perf_event *event)
2090 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2093 static int perf_get_aux_event(struct perf_event *event,
2094 struct perf_event *group_leader)
2097 * Our group leader must be an aux event if we want to be
2098 * an aux_output. This way, the aux event will precede its
2099 * aux_output events in the group, and therefore will always
2106 * aux_output and aux_sample_size are mutually exclusive.
2108 if (event->attr.aux_output && event->attr.aux_sample_size)
2111 if (event->attr.aux_output &&
2112 !perf_aux_output_match(event, group_leader))
2115 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2118 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2122 * Link aux_outputs to their aux event; this is undone in
2123 * perf_group_detach() by perf_put_aux_event(). When the
2124 * group in torn down, the aux_output events loose their
2125 * link to the aux_event and can't schedule any more.
2127 event->aux_event = group_leader;
2132 static inline struct list_head *get_event_list(struct perf_event *event)
2134 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2135 &event->pmu_ctx->flexible_active;
2139 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2140 * cannot exist on their own, schedule them out and move them into the ERROR
2141 * state. Also see _perf_event_enable(), it will not be able to recover
2144 static inline void perf_remove_sibling_event(struct perf_event *event)
2146 event_sched_out(event, event->ctx);
2147 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2150 static void perf_group_detach(struct perf_event *event)
2152 struct perf_event *leader = event->group_leader;
2153 struct perf_event *sibling, *tmp;
2154 struct perf_event_context *ctx = event->ctx;
2156 lockdep_assert_held(&ctx->lock);
2159 * We can have double detach due to exit/hot-unplug + close.
2161 if (!(event->attach_state & PERF_ATTACH_GROUP))
2164 event->attach_state &= ~PERF_ATTACH_GROUP;
2166 perf_put_aux_event(event);
2169 * If this is a sibling, remove it from its group.
2171 if (leader != event) {
2172 list_del_init(&event->sibling_list);
2173 event->group_leader->nr_siblings--;
2174 event->group_leader->group_generation++;
2179 * If this was a group event with sibling events then
2180 * upgrade the siblings to singleton events by adding them
2181 * to whatever list we are on.
2183 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2185 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2186 perf_remove_sibling_event(sibling);
2188 sibling->group_leader = sibling;
2189 list_del_init(&sibling->sibling_list);
2191 /* Inherit group flags from the previous leader */
2192 sibling->group_caps = event->group_caps;
2194 if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2195 add_event_to_groups(sibling, event->ctx);
2197 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2198 list_add_tail(&sibling->active_list, get_event_list(sibling));
2201 WARN_ON_ONCE(sibling->ctx != event->ctx);
2205 for_each_sibling_event(tmp, leader)
2206 perf_event__header_size(tmp);
2208 perf_event__header_size(leader);
2211 static void sync_child_event(struct perf_event *child_event);
2213 static void perf_child_detach(struct perf_event *event)
2215 struct perf_event *parent_event = event->parent;
2217 if (!(event->attach_state & PERF_ATTACH_CHILD))
2220 event->attach_state &= ~PERF_ATTACH_CHILD;
2222 if (WARN_ON_ONCE(!parent_event))
2225 lockdep_assert_held(&parent_event->child_mutex);
2227 sync_child_event(event);
2228 list_del_init(&event->child_list);
2231 static bool is_orphaned_event(struct perf_event *event)
2233 return event->state == PERF_EVENT_STATE_DEAD;
2237 event_filter_match(struct perf_event *event)
2239 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2240 perf_cgroup_match(event);
2244 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2246 struct perf_event_pmu_context *epc = event->pmu_ctx;
2247 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2248 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2250 // XXX cpc serialization, probably per-cpu IRQ disabled
2252 WARN_ON_ONCE(event->ctx != ctx);
2253 lockdep_assert_held(&ctx->lock);
2255 if (event->state != PERF_EVENT_STATE_ACTIVE)
2259 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2260 * we can schedule events _OUT_ individually through things like
2261 * __perf_remove_from_context().
2263 list_del_init(&event->active_list);
2265 perf_pmu_disable(event->pmu);
2267 event->pmu->del(event, 0);
2270 if (event->pending_disable) {
2271 event->pending_disable = 0;
2272 perf_cgroup_event_disable(event, ctx);
2273 state = PERF_EVENT_STATE_OFF;
2276 if (event->pending_sigtrap) {
2279 event->pending_sigtrap = 0;
2280 if (state != PERF_EVENT_STATE_OFF &&
2281 !event->pending_work) {
2282 event->pending_work = 1;
2284 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
2285 task_work_add(current, &event->pending_task, TWA_RESUME);
2288 local_dec(&event->ctx->nr_pending);
2291 perf_event_set_state(event, state);
2293 if (!is_software_event(event))
2294 cpc->active_oncpu--;
2295 if (event->attr.freq && event->attr.sample_freq)
2297 if (event->attr.exclusive || !cpc->active_oncpu)
2300 perf_pmu_enable(event->pmu);
2304 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2306 struct perf_event *event;
2308 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2311 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2313 event_sched_out(group_event, ctx);
2316 * Schedule out siblings (if any):
2318 for_each_sibling_event(event, group_event)
2319 event_sched_out(event, ctx);
2322 #define DETACH_GROUP 0x01UL
2323 #define DETACH_CHILD 0x02UL
2324 #define DETACH_DEAD 0x04UL
2327 * Cross CPU call to remove a performance event
2329 * We disable the event on the hardware level first. After that we
2330 * remove it from the context list.
2333 __perf_remove_from_context(struct perf_event *event,
2334 struct perf_cpu_context *cpuctx,
2335 struct perf_event_context *ctx,
2338 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
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, false);
2347 * Ensure event_sched_out() switches to OFF, at the very least
2348 * this avoids raising perf_pending_task() at this time.
2350 if (flags & DETACH_DEAD)
2351 event->pending_disable = 1;
2352 event_sched_out(event, ctx);
2353 if (flags & DETACH_GROUP)
2354 perf_group_detach(event);
2355 if (flags & DETACH_CHILD)
2356 perf_child_detach(event);
2357 list_del_event(event, ctx);
2358 if (flags & DETACH_DEAD)
2359 event->state = PERF_EVENT_STATE_DEAD;
2361 if (!pmu_ctx->nr_events) {
2362 pmu_ctx->rotate_necessary = 0;
2364 if (ctx->task && ctx->is_active) {
2365 struct perf_cpu_pmu_context *cpc;
2367 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
2368 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2369 cpc->task_epc = NULL;
2373 if (!ctx->nr_events && ctx->is_active) {
2374 if (ctx == &cpuctx->ctx)
2375 update_cgrp_time_from_cpuctx(cpuctx, true);
2379 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2380 cpuctx->task_ctx = NULL;
2386 * Remove the event from a task's (or a CPU's) list of events.
2388 * If event->ctx is a cloned context, callers must make sure that
2389 * every task struct that event->ctx->task could possibly point to
2390 * remains valid. This is OK when called from perf_release since
2391 * that only calls us on the top-level context, which can't be a clone.
2392 * When called from perf_event_exit_task, it's OK because the
2393 * context has been detached from its task.
2395 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2397 struct perf_event_context *ctx = event->ctx;
2399 lockdep_assert_held(&ctx->mutex);
2402 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2403 * to work in the face of TASK_TOMBSTONE, unlike every other
2404 * event_function_call() user.
2406 raw_spin_lock_irq(&ctx->lock);
2407 if (!ctx->is_active) {
2408 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2409 ctx, (void *)flags);
2410 raw_spin_unlock_irq(&ctx->lock);
2413 raw_spin_unlock_irq(&ctx->lock);
2415 event_function_call(event, __perf_remove_from_context, (void *)flags);
2419 * Cross CPU call to disable a performance event
2421 static void __perf_event_disable(struct perf_event *event,
2422 struct perf_cpu_context *cpuctx,
2423 struct perf_event_context *ctx,
2426 if (event->state < PERF_EVENT_STATE_INACTIVE)
2429 if (ctx->is_active & EVENT_TIME) {
2430 update_context_time(ctx);
2431 update_cgrp_time_from_event(event);
2434 perf_pmu_disable(event->pmu_ctx->pmu);
2436 if (event == event->group_leader)
2437 group_sched_out(event, ctx);
2439 event_sched_out(event, ctx);
2441 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2442 perf_cgroup_event_disable(event, ctx);
2444 perf_pmu_enable(event->pmu_ctx->pmu);
2450 * If event->ctx is a cloned context, callers must make sure that
2451 * every task struct that event->ctx->task could possibly point to
2452 * remains valid. This condition is satisfied when called through
2453 * perf_event_for_each_child or perf_event_for_each because they
2454 * hold the top-level event's child_mutex, so any descendant that
2455 * goes to exit will block in perf_event_exit_event().
2457 * When called from perf_pending_irq it's OK because event->ctx
2458 * is the current context on this CPU and preemption is disabled,
2459 * hence we can't get into perf_event_task_sched_out for this context.
2461 static void _perf_event_disable(struct perf_event *event)
2463 struct perf_event_context *ctx = event->ctx;
2465 raw_spin_lock_irq(&ctx->lock);
2466 if (event->state <= PERF_EVENT_STATE_OFF) {
2467 raw_spin_unlock_irq(&ctx->lock);
2470 raw_spin_unlock_irq(&ctx->lock);
2472 event_function_call(event, __perf_event_disable, NULL);
2475 void perf_event_disable_local(struct perf_event *event)
2477 event_function_local(event, __perf_event_disable, NULL);
2481 * Strictly speaking kernel users cannot create groups and therefore this
2482 * interface does not need the perf_event_ctx_lock() magic.
2484 void perf_event_disable(struct perf_event *event)
2486 struct perf_event_context *ctx;
2488 ctx = perf_event_ctx_lock(event);
2489 _perf_event_disable(event);
2490 perf_event_ctx_unlock(event, ctx);
2492 EXPORT_SYMBOL_GPL(perf_event_disable);
2494 void perf_event_disable_inatomic(struct perf_event *event)
2496 event->pending_disable = 1;
2497 irq_work_queue(&event->pending_irq);
2500 #define MAX_INTERRUPTS (~0ULL)
2502 static void perf_log_throttle(struct perf_event *event, int enable);
2503 static void perf_log_itrace_start(struct perf_event *event);
2506 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2508 struct perf_event_pmu_context *epc = event->pmu_ctx;
2509 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2512 WARN_ON_ONCE(event->ctx != ctx);
2514 lockdep_assert_held(&ctx->lock);
2516 if (event->state <= PERF_EVENT_STATE_OFF)
2519 WRITE_ONCE(event->oncpu, smp_processor_id());
2521 * Order event::oncpu write to happen before the ACTIVE state is
2522 * visible. This allows perf_event_{stop,read}() to observe the correct
2523 * ->oncpu if it sees ACTIVE.
2526 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2529 * Unthrottle events, since we scheduled we might have missed several
2530 * ticks already, also for a heavily scheduling task there is little
2531 * guarantee it'll get a tick in a timely manner.
2533 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2534 perf_log_throttle(event, 1);
2535 event->hw.interrupts = 0;
2538 perf_pmu_disable(event->pmu);
2540 perf_log_itrace_start(event);
2542 if (event->pmu->add(event, PERF_EF_START)) {
2543 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2549 if (!is_software_event(event))
2550 cpc->active_oncpu++;
2551 if (event->attr.freq && event->attr.sample_freq)
2554 if (event->attr.exclusive)
2558 perf_pmu_enable(event->pmu);
2564 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2566 struct perf_event *event, *partial_group = NULL;
2567 struct pmu *pmu = group_event->pmu_ctx->pmu;
2569 if (group_event->state == PERF_EVENT_STATE_OFF)
2572 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2574 if (event_sched_in(group_event, ctx))
2578 * Schedule in siblings as one group (if any):
2580 for_each_sibling_event(event, group_event) {
2581 if (event_sched_in(event, ctx)) {
2582 partial_group = event;
2587 if (!pmu->commit_txn(pmu))
2592 * Groups can be scheduled in as one unit only, so undo any
2593 * partial group before returning:
2594 * The events up to the failed event are scheduled out normally.
2596 for_each_sibling_event(event, group_event) {
2597 if (event == partial_group)
2600 event_sched_out(event, ctx);
2602 event_sched_out(group_event, ctx);
2605 pmu->cancel_txn(pmu);
2610 * Work out whether we can put this event group on the CPU now.
2612 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2614 struct perf_event_pmu_context *epc = event->pmu_ctx;
2615 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2618 * Groups consisting entirely of software events can always go on.
2620 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2623 * If an exclusive group is already on, no other hardware
2629 * If this group is exclusive and there are already
2630 * events on the CPU, it can't go on.
2632 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2635 * Otherwise, try to add it if all previous groups were able
2641 static void add_event_to_ctx(struct perf_event *event,
2642 struct perf_event_context *ctx)
2644 list_add_event(event, ctx);
2645 perf_group_attach(event);
2648 static void task_ctx_sched_out(struct perf_event_context *ctx,
2649 enum event_type_t event_type)
2651 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2653 if (!cpuctx->task_ctx)
2656 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2659 ctx_sched_out(ctx, event_type);
2662 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2663 struct perf_event_context *ctx)
2665 ctx_sched_in(&cpuctx->ctx, EVENT_PINNED);
2667 ctx_sched_in(ctx, EVENT_PINNED);
2668 ctx_sched_in(&cpuctx->ctx, EVENT_FLEXIBLE);
2670 ctx_sched_in(ctx, EVENT_FLEXIBLE);
2674 * We want to maintain the following priority of scheduling:
2675 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2676 * - task pinned (EVENT_PINNED)
2677 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2678 * - task flexible (EVENT_FLEXIBLE).
2680 * In order to avoid unscheduling and scheduling back in everything every
2681 * time an event is added, only do it for the groups of equal priority and
2684 * This can be called after a batch operation on task events, in which case
2685 * event_type is a bit mask of the types of events involved. For CPU events,
2686 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2689 * XXX: ctx_resched() reschedule entire perf_event_context while adding new
2690 * event to the context or enabling existing event in the context. We can
2691 * probably optimize it by rescheduling only affected pmu_ctx.
2693 static void ctx_resched(struct perf_cpu_context *cpuctx,
2694 struct perf_event_context *task_ctx,
2695 enum event_type_t event_type)
2697 bool cpu_event = !!(event_type & EVENT_CPU);
2700 * If pinned groups are involved, flexible groups also need to be
2703 if (event_type & EVENT_PINNED)
2704 event_type |= EVENT_FLEXIBLE;
2706 event_type &= EVENT_ALL;
2708 perf_ctx_disable(&cpuctx->ctx, false);
2710 perf_ctx_disable(task_ctx, false);
2711 task_ctx_sched_out(task_ctx, event_type);
2715 * Decide which cpu ctx groups to schedule out based on the types
2716 * of events that caused rescheduling:
2717 * - EVENT_CPU: schedule out corresponding groups;
2718 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2719 * - otherwise, do nothing more.
2722 ctx_sched_out(&cpuctx->ctx, event_type);
2723 else if (event_type & EVENT_PINNED)
2724 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
2726 perf_event_sched_in(cpuctx, task_ctx);
2728 perf_ctx_enable(&cpuctx->ctx, false);
2730 perf_ctx_enable(task_ctx, false);
2733 void perf_pmu_resched(struct pmu *pmu)
2735 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2736 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2738 perf_ctx_lock(cpuctx, task_ctx);
2739 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2740 perf_ctx_unlock(cpuctx, task_ctx);
2744 * Cross CPU call to install and enable a performance event
2746 * Very similar to remote_function() + event_function() but cannot assume that
2747 * things like ctx->is_active and cpuctx->task_ctx are set.
2749 static int __perf_install_in_context(void *info)
2751 struct perf_event *event = info;
2752 struct perf_event_context *ctx = event->ctx;
2753 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2754 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2755 bool reprogram = true;
2758 raw_spin_lock(&cpuctx->ctx.lock);
2760 raw_spin_lock(&ctx->lock);
2763 reprogram = (ctx->task == current);
2766 * If the task is running, it must be running on this CPU,
2767 * otherwise we cannot reprogram things.
2769 * If its not running, we don't care, ctx->lock will
2770 * serialize against it becoming runnable.
2772 if (task_curr(ctx->task) && !reprogram) {
2777 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2778 } else if (task_ctx) {
2779 raw_spin_lock(&task_ctx->lock);
2782 #ifdef CONFIG_CGROUP_PERF
2783 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2785 * If the current cgroup doesn't match the event's
2786 * cgroup, we should not try to schedule it.
2788 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2789 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2790 event->cgrp->css.cgroup);
2795 ctx_sched_out(ctx, EVENT_TIME);
2796 add_event_to_ctx(event, ctx);
2797 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2799 add_event_to_ctx(event, ctx);
2803 perf_ctx_unlock(cpuctx, task_ctx);
2808 static bool exclusive_event_installable(struct perf_event *event,
2809 struct perf_event_context *ctx);
2812 * Attach a performance event to a context.
2814 * Very similar to event_function_call, see comment there.
2817 perf_install_in_context(struct perf_event_context *ctx,
2818 struct perf_event *event,
2821 struct task_struct *task = READ_ONCE(ctx->task);
2823 lockdep_assert_held(&ctx->mutex);
2825 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2827 if (event->cpu != -1)
2828 WARN_ON_ONCE(event->cpu != cpu);
2831 * Ensures that if we can observe event->ctx, both the event and ctx
2832 * will be 'complete'. See perf_iterate_sb_cpu().
2834 smp_store_release(&event->ctx, ctx);
2837 * perf_event_attr::disabled events will not run and can be initialized
2838 * without IPI. Except when this is the first event for the context, in
2839 * that case we need the magic of the IPI to set ctx->is_active.
2841 * The IOC_ENABLE that is sure to follow the creation of a disabled
2842 * event will issue the IPI and reprogram the hardware.
2844 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2845 ctx->nr_events && !is_cgroup_event(event)) {
2846 raw_spin_lock_irq(&ctx->lock);
2847 if (ctx->task == TASK_TOMBSTONE) {
2848 raw_spin_unlock_irq(&ctx->lock);
2851 add_event_to_ctx(event, ctx);
2852 raw_spin_unlock_irq(&ctx->lock);
2857 cpu_function_call(cpu, __perf_install_in_context, event);
2862 * Should not happen, we validate the ctx is still alive before calling.
2864 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2868 * Installing events is tricky because we cannot rely on ctx->is_active
2869 * to be set in case this is the nr_events 0 -> 1 transition.
2871 * Instead we use task_curr(), which tells us if the task is running.
2872 * However, since we use task_curr() outside of rq::lock, we can race
2873 * against the actual state. This means the result can be wrong.
2875 * If we get a false positive, we retry, this is harmless.
2877 * If we get a false negative, things are complicated. If we are after
2878 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2879 * value must be correct. If we're before, it doesn't matter since
2880 * perf_event_context_sched_in() will program the counter.
2882 * However, this hinges on the remote context switch having observed
2883 * our task->perf_event_ctxp[] store, such that it will in fact take
2884 * ctx::lock in perf_event_context_sched_in().
2886 * We do this by task_function_call(), if the IPI fails to hit the task
2887 * we know any future context switch of task must see the
2888 * perf_event_ctpx[] store.
2892 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2893 * task_cpu() load, such that if the IPI then does not find the task
2894 * running, a future context switch of that task must observe the
2899 if (!task_function_call(task, __perf_install_in_context, event))
2902 raw_spin_lock_irq(&ctx->lock);
2904 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2906 * Cannot happen because we already checked above (which also
2907 * cannot happen), and we hold ctx->mutex, which serializes us
2908 * against perf_event_exit_task_context().
2910 raw_spin_unlock_irq(&ctx->lock);
2914 * If the task is not running, ctx->lock will avoid it becoming so,
2915 * thus we can safely install the event.
2917 if (task_curr(task)) {
2918 raw_spin_unlock_irq(&ctx->lock);
2921 add_event_to_ctx(event, ctx);
2922 raw_spin_unlock_irq(&ctx->lock);
2926 * Cross CPU call to enable a performance event
2928 static void __perf_event_enable(struct perf_event *event,
2929 struct perf_cpu_context *cpuctx,
2930 struct perf_event_context *ctx,
2933 struct perf_event *leader = event->group_leader;
2934 struct perf_event_context *task_ctx;
2936 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2937 event->state <= PERF_EVENT_STATE_ERROR)
2941 ctx_sched_out(ctx, EVENT_TIME);
2943 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2944 perf_cgroup_event_enable(event, ctx);
2946 if (!ctx->is_active)
2949 if (!event_filter_match(event)) {
2950 ctx_sched_in(ctx, EVENT_TIME);
2955 * If the event is in a group and isn't the group leader,
2956 * then don't put it on unless the group is on.
2958 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2959 ctx_sched_in(ctx, EVENT_TIME);
2963 task_ctx = cpuctx->task_ctx;
2965 WARN_ON_ONCE(task_ctx != ctx);
2967 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2973 * If event->ctx is a cloned context, callers must make sure that
2974 * every task struct that event->ctx->task could possibly point to
2975 * remains valid. This condition is satisfied when called through
2976 * perf_event_for_each_child or perf_event_for_each as described
2977 * for perf_event_disable.
2979 static void _perf_event_enable(struct perf_event *event)
2981 struct perf_event_context *ctx = event->ctx;
2983 raw_spin_lock_irq(&ctx->lock);
2984 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2985 event->state < PERF_EVENT_STATE_ERROR) {
2987 raw_spin_unlock_irq(&ctx->lock);
2992 * If the event is in error state, clear that first.
2994 * That way, if we see the event in error state below, we know that it
2995 * has gone back into error state, as distinct from the task having
2996 * been scheduled away before the cross-call arrived.
2998 if (event->state == PERF_EVENT_STATE_ERROR) {
3000 * Detached SIBLING events cannot leave ERROR state.
3002 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3003 event->group_leader == event)
3006 event->state = PERF_EVENT_STATE_OFF;
3008 raw_spin_unlock_irq(&ctx->lock);
3010 event_function_call(event, __perf_event_enable, NULL);
3014 * See perf_event_disable();
3016 void perf_event_enable(struct perf_event *event)
3018 struct perf_event_context *ctx;
3020 ctx = perf_event_ctx_lock(event);
3021 _perf_event_enable(event);
3022 perf_event_ctx_unlock(event, ctx);
3024 EXPORT_SYMBOL_GPL(perf_event_enable);
3026 struct stop_event_data {
3027 struct perf_event *event;
3028 unsigned int restart;
3031 static int __perf_event_stop(void *info)
3033 struct stop_event_data *sd = info;
3034 struct perf_event *event = sd->event;
3036 /* if it's already INACTIVE, do nothing */
3037 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3040 /* matches smp_wmb() in event_sched_in() */
3044 * There is a window with interrupts enabled before we get here,
3045 * so we need to check again lest we try to stop another CPU's event.
3047 if (READ_ONCE(event->oncpu) != smp_processor_id())
3050 event->pmu->stop(event, PERF_EF_UPDATE);
3053 * May race with the actual stop (through perf_pmu_output_stop()),
3054 * but it is only used for events with AUX ring buffer, and such
3055 * events will refuse to restart because of rb::aux_mmap_count==0,
3056 * see comments in perf_aux_output_begin().
3058 * Since this is happening on an event-local CPU, no trace is lost
3062 event->pmu->start(event, 0);
3067 static int perf_event_stop(struct perf_event *event, int restart)
3069 struct stop_event_data sd = {
3076 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3079 /* matches smp_wmb() in event_sched_in() */
3083 * We only want to restart ACTIVE events, so if the event goes
3084 * inactive here (event->oncpu==-1), there's nothing more to do;
3085 * fall through with ret==-ENXIO.
3087 ret = cpu_function_call(READ_ONCE(event->oncpu),
3088 __perf_event_stop, &sd);
3089 } while (ret == -EAGAIN);
3095 * In order to contain the amount of racy and tricky in the address filter
3096 * configuration management, it is a two part process:
3098 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3099 * we update the addresses of corresponding vmas in
3100 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3101 * (p2) when an event is scheduled in (pmu::add), it calls
3102 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3103 * if the generation has changed since the previous call.
3105 * If (p1) happens while the event is active, we restart it to force (p2).
3107 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3108 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3110 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3111 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3113 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3116 void perf_event_addr_filters_sync(struct perf_event *event)
3118 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3120 if (!has_addr_filter(event))
3123 raw_spin_lock(&ifh->lock);
3124 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3125 event->pmu->addr_filters_sync(event);
3126 event->hw.addr_filters_gen = event->addr_filters_gen;
3128 raw_spin_unlock(&ifh->lock);
3130 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3132 static int _perf_event_refresh(struct perf_event *event, int refresh)
3135 * not supported on inherited events
3137 if (event->attr.inherit || !is_sampling_event(event))
3140 atomic_add(refresh, &event->event_limit);
3141 _perf_event_enable(event);
3147 * See perf_event_disable()
3149 int perf_event_refresh(struct perf_event *event, int refresh)
3151 struct perf_event_context *ctx;
3154 ctx = perf_event_ctx_lock(event);
3155 ret = _perf_event_refresh(event, refresh);
3156 perf_event_ctx_unlock(event, ctx);
3160 EXPORT_SYMBOL_GPL(perf_event_refresh);
3162 static int perf_event_modify_breakpoint(struct perf_event *bp,
3163 struct perf_event_attr *attr)
3167 _perf_event_disable(bp);
3169 err = modify_user_hw_breakpoint_check(bp, attr, true);
3171 if (!bp->attr.disabled)
3172 _perf_event_enable(bp);
3178 * Copy event-type-independent attributes that may be modified.
3180 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3181 const struct perf_event_attr *from)
3183 to->sig_data = from->sig_data;
3186 static int perf_event_modify_attr(struct perf_event *event,
3187 struct perf_event_attr *attr)
3189 int (*func)(struct perf_event *, struct perf_event_attr *);
3190 struct perf_event *child;
3193 if (event->attr.type != attr->type)
3196 switch (event->attr.type) {
3197 case PERF_TYPE_BREAKPOINT:
3198 func = perf_event_modify_breakpoint;
3201 /* Place holder for future additions. */
3205 WARN_ON_ONCE(event->ctx->parent_ctx);
3207 mutex_lock(&event->child_mutex);
3209 * Event-type-independent attributes must be copied before event-type
3210 * modification, which will validate that final attributes match the
3211 * source attributes after all relevant attributes have been copied.
3213 perf_event_modify_copy_attr(&event->attr, attr);
3214 err = func(event, attr);
3217 list_for_each_entry(child, &event->child_list, child_list) {
3218 perf_event_modify_copy_attr(&child->attr, attr);
3219 err = func(child, attr);
3224 mutex_unlock(&event->child_mutex);
3228 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3229 enum event_type_t event_type)
3231 struct perf_event_context *ctx = pmu_ctx->ctx;
3232 struct perf_event *event, *tmp;
3233 struct pmu *pmu = pmu_ctx->pmu;
3235 if (ctx->task && !ctx->is_active) {
3236 struct perf_cpu_pmu_context *cpc;
3238 cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3239 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3240 cpc->task_epc = NULL;
3246 perf_pmu_disable(pmu);
3247 if (event_type & EVENT_PINNED) {
3248 list_for_each_entry_safe(event, tmp,
3249 &pmu_ctx->pinned_active,
3251 group_sched_out(event, ctx);
3254 if (event_type & EVENT_FLEXIBLE) {
3255 list_for_each_entry_safe(event, tmp,
3256 &pmu_ctx->flexible_active,
3258 group_sched_out(event, ctx);
3260 * Since we cleared EVENT_FLEXIBLE, also clear
3261 * rotate_necessary, is will be reset by
3262 * ctx_flexible_sched_in() when needed.
3264 pmu_ctx->rotate_necessary = 0;
3266 perf_pmu_enable(pmu);
3270 ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type)
3272 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3273 struct perf_event_pmu_context *pmu_ctx;
3274 int is_active = ctx->is_active;
3275 bool cgroup = event_type & EVENT_CGROUP;
3277 event_type &= ~EVENT_CGROUP;
3279 lockdep_assert_held(&ctx->lock);
3281 if (likely(!ctx->nr_events)) {
3283 * See __perf_remove_from_context().
3285 WARN_ON_ONCE(ctx->is_active);
3287 WARN_ON_ONCE(cpuctx->task_ctx);
3292 * Always update time if it was set; not only when it changes.
3293 * Otherwise we can 'forget' to update time for any but the last
3294 * context we sched out. For example:
3296 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3297 * ctx_sched_out(.event_type = EVENT_PINNED)
3299 * would only update time for the pinned events.
3301 if (is_active & EVENT_TIME) {
3302 /* update (and stop) ctx time */
3303 update_context_time(ctx);
3304 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3306 * CPU-release for the below ->is_active store,
3307 * see __load_acquire() in perf_event_time_now()
3312 ctx->is_active &= ~event_type;
3313 if (!(ctx->is_active & EVENT_ALL))
3317 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3318 if (!ctx->is_active)
3319 cpuctx->task_ctx = NULL;
3322 is_active ^= ctx->is_active; /* changed bits */
3324 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3325 if (cgroup && !pmu_ctx->nr_cgroups)
3327 __pmu_ctx_sched_out(pmu_ctx, is_active);
3332 * Test whether two contexts are equivalent, i.e. whether they have both been
3333 * cloned from the same version of the same context.
3335 * Equivalence is measured using a generation number in the context that is
3336 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3337 * and list_del_event().
3339 static int context_equiv(struct perf_event_context *ctx1,
3340 struct perf_event_context *ctx2)
3342 lockdep_assert_held(&ctx1->lock);
3343 lockdep_assert_held(&ctx2->lock);
3345 /* Pinning disables the swap optimization */
3346 if (ctx1->pin_count || ctx2->pin_count)
3349 /* If ctx1 is the parent of ctx2 */
3350 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3353 /* If ctx2 is the parent of ctx1 */
3354 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3358 * If ctx1 and ctx2 have the same parent; we flatten the parent
3359 * hierarchy, see perf_event_init_context().
3361 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3362 ctx1->parent_gen == ctx2->parent_gen)
3369 static void __perf_event_sync_stat(struct perf_event *event,
3370 struct perf_event *next_event)
3374 if (!event->attr.inherit_stat)
3378 * Update the event value, we cannot use perf_event_read()
3379 * because we're in the middle of a context switch and have IRQs
3380 * disabled, which upsets smp_call_function_single(), however
3381 * we know the event must be on the current CPU, therefore we
3382 * don't need to use it.
3384 if (event->state == PERF_EVENT_STATE_ACTIVE)
3385 event->pmu->read(event);
3387 perf_event_update_time(event);
3390 * In order to keep per-task stats reliable we need to flip the event
3391 * values when we flip the contexts.
3393 value = local64_read(&next_event->count);
3394 value = local64_xchg(&event->count, value);
3395 local64_set(&next_event->count, value);
3397 swap(event->total_time_enabled, next_event->total_time_enabled);
3398 swap(event->total_time_running, next_event->total_time_running);
3401 * Since we swizzled the values, update the user visible data too.
3403 perf_event_update_userpage(event);
3404 perf_event_update_userpage(next_event);
3407 static void perf_event_sync_stat(struct perf_event_context *ctx,
3408 struct perf_event_context *next_ctx)
3410 struct perf_event *event, *next_event;
3415 update_context_time(ctx);
3417 event = list_first_entry(&ctx->event_list,
3418 struct perf_event, event_entry);
3420 next_event = list_first_entry(&next_ctx->event_list,
3421 struct perf_event, event_entry);
3423 while (&event->event_entry != &ctx->event_list &&
3424 &next_event->event_entry != &next_ctx->event_list) {
3426 __perf_event_sync_stat(event, next_event);
3428 event = list_next_entry(event, event_entry);
3429 next_event = list_next_entry(next_event, event_entry);
3433 #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \
3434 for (pos1 = list_first_entry(head1, typeof(*pos1), member), \
3435 pos2 = list_first_entry(head2, typeof(*pos2), member); \
3436 !list_entry_is_head(pos1, head1, member) && \
3437 !list_entry_is_head(pos2, head2, member); \
3438 pos1 = list_next_entry(pos1, member), \
3439 pos2 = list_next_entry(pos2, member))
3441 static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx,
3442 struct perf_event_context *next_ctx)
3444 struct perf_event_pmu_context *prev_epc, *next_epc;
3446 if (!prev_ctx->nr_task_data)
3449 double_list_for_each_entry(prev_epc, next_epc,
3450 &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list,
3453 if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu))
3457 * PMU specific parts of task perf context can require
3458 * additional synchronization. As an example of such
3459 * synchronization see implementation details of Intel
3460 * LBR call stack data profiling;
3462 if (prev_epc->pmu->swap_task_ctx)
3463 prev_epc->pmu->swap_task_ctx(prev_epc, next_epc);
3465 swap(prev_epc->task_ctx_data, next_epc->task_ctx_data);
3469 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in)
3471 struct perf_event_pmu_context *pmu_ctx;
3472 struct perf_cpu_pmu_context *cpc;
3474 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3475 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3477 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3478 pmu_ctx->pmu->sched_task(pmu_ctx, sched_in);
3483 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3485 struct perf_event_context *ctx = task->perf_event_ctxp;
3486 struct perf_event_context *next_ctx;
3487 struct perf_event_context *parent, *next_parent;
3494 next_ctx = rcu_dereference(next->perf_event_ctxp);
3498 parent = rcu_dereference(ctx->parent_ctx);
3499 next_parent = rcu_dereference(next_ctx->parent_ctx);
3501 /* If neither context have a parent context; they cannot be clones. */
3502 if (!parent && !next_parent)
3505 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3507 * Looks like the two contexts are clones, so we might be
3508 * able to optimize the context switch. We lock both
3509 * contexts and check that they are clones under the
3510 * lock (including re-checking that neither has been
3511 * uncloned in the meantime). It doesn't matter which
3512 * order we take the locks because no other cpu could
3513 * be trying to lock both of these tasks.
3515 raw_spin_lock(&ctx->lock);
3516 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3517 if (context_equiv(ctx, next_ctx)) {
3519 perf_ctx_disable(ctx, false);
3521 /* PMIs are disabled; ctx->nr_pending is stable. */
3522 if (local_read(&ctx->nr_pending) ||
3523 local_read(&next_ctx->nr_pending)) {
3525 * Must not swap out ctx when there's pending
3526 * events that rely on the ctx->task relation.
3528 raw_spin_unlock(&next_ctx->lock);
3533 WRITE_ONCE(ctx->task, next);
3534 WRITE_ONCE(next_ctx->task, task);
3536 perf_ctx_sched_task_cb(ctx, false);
3537 perf_event_swap_task_ctx_data(ctx, next_ctx);
3539 perf_ctx_enable(ctx, false);
3542 * RCU_INIT_POINTER here is safe because we've not
3543 * modified the ctx and the above modification of
3544 * ctx->task and ctx->task_ctx_data are immaterial
3545 * since those values are always verified under
3546 * ctx->lock which we're now holding.
3548 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3549 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3553 perf_event_sync_stat(ctx, next_ctx);
3555 raw_spin_unlock(&next_ctx->lock);
3556 raw_spin_unlock(&ctx->lock);
3562 raw_spin_lock(&ctx->lock);
3563 perf_ctx_disable(ctx, false);
3566 perf_ctx_sched_task_cb(ctx, false);
3567 task_ctx_sched_out(ctx, EVENT_ALL);
3569 perf_ctx_enable(ctx, false);
3570 raw_spin_unlock(&ctx->lock);
3574 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3575 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3577 void perf_sched_cb_dec(struct pmu *pmu)
3579 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3581 this_cpu_dec(perf_sched_cb_usages);
3584 if (!--cpc->sched_cb_usage)
3585 list_del(&cpc->sched_cb_entry);
3589 void perf_sched_cb_inc(struct pmu *pmu)
3591 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3593 if (!cpc->sched_cb_usage++)
3594 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3597 this_cpu_inc(perf_sched_cb_usages);
3601 * This function provides the context switch callback to the lower code
3602 * layer. It is invoked ONLY when the context switch callback is enabled.
3604 * This callback is relevant even to per-cpu events; for example multi event
3605 * PEBS requires this to provide PID/TID information. This requires we flush
3606 * all queued PEBS records before we context switch to a new task.
3608 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in)
3610 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3615 /* software PMUs will not have sched_task */
3616 if (WARN_ON_ONCE(!pmu->sched_task))
3619 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3620 perf_pmu_disable(pmu);
3622 pmu->sched_task(cpc->task_epc, sched_in);
3624 perf_pmu_enable(pmu);
3625 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3628 static void perf_pmu_sched_task(struct task_struct *prev,
3629 struct task_struct *next,
3632 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3633 struct perf_cpu_pmu_context *cpc;
3635 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3636 if (prev == next || cpuctx->task_ctx)
3639 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3640 __perf_pmu_sched_task(cpc, sched_in);
3643 static void perf_event_switch(struct task_struct *task,
3644 struct task_struct *next_prev, bool sched_in);
3647 * Called from scheduler to remove the events of the current task,
3648 * with interrupts disabled.
3650 * We stop each event and update the event value in event->count.
3652 * This does not protect us against NMI, but disable()
3653 * sets the disabled bit in the control field of event _before_
3654 * accessing the event control register. If a NMI hits, then it will
3655 * not restart the event.
3657 void __perf_event_task_sched_out(struct task_struct *task,
3658 struct task_struct *next)
3660 if (__this_cpu_read(perf_sched_cb_usages))
3661 perf_pmu_sched_task(task, next, false);
3663 if (atomic_read(&nr_switch_events))
3664 perf_event_switch(task, next, false);
3666 perf_event_context_sched_out(task, next);
3669 * if cgroup events exist on this CPU, then we need
3670 * to check if we have to switch out PMU state.
3671 * cgroup event are system-wide mode only
3673 perf_cgroup_switch(next);
3676 static bool perf_less_group_idx(const void *l, const void *r)
3678 const struct perf_event *le = *(const struct perf_event **)l;
3679 const struct perf_event *re = *(const struct perf_event **)r;
3681 return le->group_index < re->group_index;
3684 static void swap_ptr(void *l, void *r)
3686 void **lp = l, **rp = r;
3691 static const struct min_heap_callbacks perf_min_heap = {
3692 .elem_size = sizeof(struct perf_event *),
3693 .less = perf_less_group_idx,
3697 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3699 struct perf_event **itrs = heap->data;
3702 itrs[heap->nr] = event;
3707 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3709 struct perf_cpu_pmu_context *cpc;
3711 if (!pmu_ctx->ctx->task)
3714 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3715 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3716 cpc->task_epc = pmu_ctx;
3719 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3720 struct perf_event_groups *groups, int cpu,
3722 int (*func)(struct perf_event *, void *),
3725 #ifdef CONFIG_CGROUP_PERF
3726 struct cgroup_subsys_state *css = NULL;
3728 struct perf_cpu_context *cpuctx = NULL;
3729 /* Space for per CPU and/or any CPU event iterators. */
3730 struct perf_event *itrs[2];
3731 struct min_heap event_heap;
3732 struct perf_event **evt;
3735 if (pmu->filter && pmu->filter(pmu, cpu))
3739 cpuctx = this_cpu_ptr(&perf_cpu_context);
3740 event_heap = (struct min_heap){
3741 .data = cpuctx->heap,
3743 .size = cpuctx->heap_size,
3746 lockdep_assert_held(&cpuctx->ctx.lock);
3748 #ifdef CONFIG_CGROUP_PERF
3750 css = &cpuctx->cgrp->css;
3753 event_heap = (struct min_heap){
3756 .size = ARRAY_SIZE(itrs),
3758 /* Events not within a CPU context may be on any CPU. */
3759 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3761 evt = event_heap.data;
3763 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3765 #ifdef CONFIG_CGROUP_PERF
3766 for (; css; css = css->parent)
3767 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3770 if (event_heap.nr) {
3771 __link_epc((*evt)->pmu_ctx);
3772 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3775 min_heapify_all(&event_heap, &perf_min_heap);
3777 while (event_heap.nr) {
3778 ret = func(*evt, data);
3782 *evt = perf_event_groups_next(*evt, pmu);
3784 min_heapify(&event_heap, 0, &perf_min_heap);
3786 min_heap_pop(&event_heap, &perf_min_heap);
3793 * Because the userpage is strictly per-event (there is no concept of context,
3794 * so there cannot be a context indirection), every userpage must be updated
3795 * when context time starts :-(
3797 * IOW, we must not miss EVENT_TIME edges.
3799 static inline bool event_update_userpage(struct perf_event *event)
3801 if (likely(!atomic_read(&event->mmap_count)))
3804 perf_event_update_time(event);
3805 perf_event_update_userpage(event);
3810 static inline void group_update_userpage(struct perf_event *group_event)
3812 struct perf_event *event;
3814 if (!event_update_userpage(group_event))
3817 for_each_sibling_event(event, group_event)
3818 event_update_userpage(event);
3821 static int merge_sched_in(struct perf_event *event, void *data)
3823 struct perf_event_context *ctx = event->ctx;
3824 int *can_add_hw = data;
3826 if (event->state <= PERF_EVENT_STATE_OFF)
3829 if (!event_filter_match(event))
3832 if (group_can_go_on(event, *can_add_hw)) {
3833 if (!group_sched_in(event, ctx))
3834 list_add_tail(&event->active_list, get_event_list(event));
3837 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3839 if (event->attr.pinned) {
3840 perf_cgroup_event_disable(event, ctx);
3841 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3843 struct perf_cpu_pmu_context *cpc;
3845 event->pmu_ctx->rotate_necessary = 1;
3846 cpc = this_cpu_ptr(event->pmu_ctx->pmu->cpu_pmu_context);
3847 perf_mux_hrtimer_restart(cpc);
3848 group_update_userpage(event);
3855 static void pmu_groups_sched_in(struct perf_event_context *ctx,
3856 struct perf_event_groups *groups,
3860 visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
3861 merge_sched_in, &can_add_hw);
3864 static void ctx_groups_sched_in(struct perf_event_context *ctx,
3865 struct perf_event_groups *groups,
3868 struct perf_event_pmu_context *pmu_ctx;
3870 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3871 if (cgroup && !pmu_ctx->nr_cgroups)
3873 pmu_groups_sched_in(ctx, groups, pmu_ctx->pmu);
3877 static void __pmu_ctx_sched_in(struct perf_event_context *ctx,
3880 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu);
3884 ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type)
3886 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3887 int is_active = ctx->is_active;
3888 bool cgroup = event_type & EVENT_CGROUP;
3890 event_type &= ~EVENT_CGROUP;
3892 lockdep_assert_held(&ctx->lock);
3894 if (likely(!ctx->nr_events))
3897 if (!(is_active & EVENT_TIME)) {
3898 /* start ctx time */
3899 __update_context_time(ctx, false);
3900 perf_cgroup_set_timestamp(cpuctx);
3902 * CPU-release for the below ->is_active store,
3903 * see __load_acquire() in perf_event_time_now()
3908 ctx->is_active |= (event_type | EVENT_TIME);
3911 cpuctx->task_ctx = ctx;
3913 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3916 is_active ^= ctx->is_active; /* changed bits */
3919 * First go through the list and put on any pinned groups
3920 * in order to give them the best chance of going on.
3922 if (is_active & EVENT_PINNED)
3923 ctx_groups_sched_in(ctx, &ctx->pinned_groups, cgroup);
3925 /* Then walk through the lower prio flexible groups */
3926 if (is_active & EVENT_FLEXIBLE)
3927 ctx_groups_sched_in(ctx, &ctx->flexible_groups, cgroup);
3930 static void perf_event_context_sched_in(struct task_struct *task)
3932 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3933 struct perf_event_context *ctx;
3936 ctx = rcu_dereference(task->perf_event_ctxp);
3940 if (cpuctx->task_ctx == ctx) {
3941 perf_ctx_lock(cpuctx, ctx);
3942 perf_ctx_disable(ctx, false);
3944 perf_ctx_sched_task_cb(ctx, true);
3946 perf_ctx_enable(ctx, false);
3947 perf_ctx_unlock(cpuctx, ctx);
3951 perf_ctx_lock(cpuctx, ctx);
3953 * We must check ctx->nr_events while holding ctx->lock, such
3954 * that we serialize against perf_install_in_context().
3956 if (!ctx->nr_events)
3959 perf_ctx_disable(ctx, false);
3961 * We want to keep the following priority order:
3962 * cpu pinned (that don't need to move), task pinned,
3963 * cpu flexible, task flexible.
3965 * However, if task's ctx is not carrying any pinned
3966 * events, no need to flip the cpuctx's events around.
3968 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
3969 perf_ctx_disable(&cpuctx->ctx, false);
3970 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
3973 perf_event_sched_in(cpuctx, ctx);
3975 perf_ctx_sched_task_cb(cpuctx->task_ctx, true);
3977 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3978 perf_ctx_enable(&cpuctx->ctx, false);
3980 perf_ctx_enable(ctx, false);
3983 perf_ctx_unlock(cpuctx, ctx);
3989 * Called from scheduler to add the events of the current task
3990 * with interrupts disabled.
3992 * We restore the event value and then enable it.
3994 * This does not protect us against NMI, but enable()
3995 * sets the enabled bit in the control field of event _before_
3996 * accessing the event control register. If a NMI hits, then it will
3997 * keep the event running.
3999 void __perf_event_task_sched_in(struct task_struct *prev,
4000 struct task_struct *task)
4002 perf_event_context_sched_in(task);
4004 if (atomic_read(&nr_switch_events))
4005 perf_event_switch(task, prev, true);
4007 if (__this_cpu_read(perf_sched_cb_usages))
4008 perf_pmu_sched_task(prev, task, true);
4011 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4013 u64 frequency = event->attr.sample_freq;
4014 u64 sec = NSEC_PER_SEC;
4015 u64 divisor, dividend;
4017 int count_fls, nsec_fls, frequency_fls, sec_fls;
4019 count_fls = fls64(count);
4020 nsec_fls = fls64(nsec);
4021 frequency_fls = fls64(frequency);
4025 * We got @count in @nsec, with a target of sample_freq HZ
4026 * the target period becomes:
4029 * period = -------------------
4030 * @nsec * sample_freq
4035 * Reduce accuracy by one bit such that @a and @b converge
4036 * to a similar magnitude.
4038 #define REDUCE_FLS(a, b) \
4040 if (a##_fls > b##_fls) { \
4050 * Reduce accuracy until either term fits in a u64, then proceed with
4051 * the other, so that finally we can do a u64/u64 division.
4053 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4054 REDUCE_FLS(nsec, frequency);
4055 REDUCE_FLS(sec, count);
4058 if (count_fls + sec_fls > 64) {
4059 divisor = nsec * frequency;
4061 while (count_fls + sec_fls > 64) {
4062 REDUCE_FLS(count, sec);
4066 dividend = count * sec;
4068 dividend = count * sec;
4070 while (nsec_fls + frequency_fls > 64) {
4071 REDUCE_FLS(nsec, frequency);
4075 divisor = nsec * frequency;
4081 return div64_u64(dividend, divisor);
4084 static DEFINE_PER_CPU(int, perf_throttled_count);
4085 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4087 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4089 struct hw_perf_event *hwc = &event->hw;
4090 s64 period, sample_period;
4093 period = perf_calculate_period(event, nsec, count);
4095 delta = (s64)(period - hwc->sample_period);
4096 delta = (delta + 7) / 8; /* low pass filter */
4098 sample_period = hwc->sample_period + delta;
4103 hwc->sample_period = sample_period;
4105 if (local64_read(&hwc->period_left) > 8*sample_period) {
4107 event->pmu->stop(event, PERF_EF_UPDATE);
4109 local64_set(&hwc->period_left, 0);
4112 event->pmu->start(event, PERF_EF_RELOAD);
4117 * combine freq adjustment with unthrottling to avoid two passes over the
4118 * events. At the same time, make sure, having freq events does not change
4119 * the rate of unthrottling as that would introduce bias.
4122 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4124 struct perf_event *event;
4125 struct hw_perf_event *hwc;
4126 u64 now, period = TICK_NSEC;
4130 * only need to iterate over all events iff:
4131 * - context have events in frequency mode (needs freq adjust)
4132 * - there are events to unthrottle on this cpu
4134 if (!(ctx->nr_freq || unthrottle))
4137 raw_spin_lock(&ctx->lock);
4139 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4140 if (event->state != PERF_EVENT_STATE_ACTIVE)
4143 // XXX use visit thingy to avoid the -1,cpu match
4144 if (!event_filter_match(event))
4147 perf_pmu_disable(event->pmu);
4151 if (hwc->interrupts == MAX_INTERRUPTS) {
4152 hwc->interrupts = 0;
4153 perf_log_throttle(event, 1);
4154 event->pmu->start(event, 0);
4157 if (!event->attr.freq || !event->attr.sample_freq)
4161 * stop the event and update event->count
4163 event->pmu->stop(event, PERF_EF_UPDATE);
4165 now = local64_read(&event->count);
4166 delta = now - hwc->freq_count_stamp;
4167 hwc->freq_count_stamp = now;
4171 * reload only if value has changed
4172 * we have stopped the event so tell that
4173 * to perf_adjust_period() to avoid stopping it
4177 perf_adjust_period(event, period, delta, false);
4179 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4181 perf_pmu_enable(event->pmu);
4184 raw_spin_unlock(&ctx->lock);
4188 * Move @event to the tail of the @ctx's elegible events.
4190 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4193 * Rotate the first entry last of non-pinned groups. Rotation might be
4194 * disabled by the inheritance code.
4196 if (ctx->rotate_disable)
4199 perf_event_groups_delete(&ctx->flexible_groups, event);
4200 perf_event_groups_insert(&ctx->flexible_groups, event);
4203 /* pick an event from the flexible_groups to rotate */
4204 static inline struct perf_event *
4205 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4207 struct perf_event *event;
4208 struct rb_node *node;
4209 struct rb_root *tree;
4210 struct __group_key key = {
4211 .pmu = pmu_ctx->pmu,
4214 /* pick the first active flexible event */
4215 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4216 struct perf_event, active_list);
4220 /* if no active flexible event, pick the first event */
4221 tree = &pmu_ctx->ctx->flexible_groups.tree;
4223 if (!pmu_ctx->ctx->task) {
4224 key.cpu = smp_processor_id();
4226 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4228 event = __node_2_pe(node);
4233 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4235 event = __node_2_pe(node);
4239 key.cpu = smp_processor_id();
4240 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4242 event = __node_2_pe(node);
4246 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4247 * finds there are unschedulable events, it will set it again.
4249 pmu_ctx->rotate_necessary = 0;
4254 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4256 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4257 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4258 struct perf_event *cpu_event = NULL, *task_event = NULL;
4259 int cpu_rotate, task_rotate;
4263 * Since we run this from IRQ context, nobody can install new
4264 * events, thus the event count values are stable.
4267 cpu_epc = &cpc->epc;
4269 task_epc = cpc->task_epc;
4271 cpu_rotate = cpu_epc->rotate_necessary;
4272 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4274 if (!(cpu_rotate || task_rotate))
4277 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4278 perf_pmu_disable(pmu);
4281 task_event = ctx_event_to_rotate(task_epc);
4283 cpu_event = ctx_event_to_rotate(cpu_epc);
4286 * As per the order given at ctx_resched() first 'pop' task flexible
4287 * and then, if needed CPU flexible.
4289 if (task_event || (task_epc && cpu_event)) {
4290 update_context_time(task_epc->ctx);
4291 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4295 update_context_time(&cpuctx->ctx);
4296 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4297 rotate_ctx(&cpuctx->ctx, cpu_event);
4298 __pmu_ctx_sched_in(&cpuctx->ctx, pmu);
4302 rotate_ctx(task_epc->ctx, task_event);
4304 if (task_event || (task_epc && cpu_event))
4305 __pmu_ctx_sched_in(task_epc->ctx, pmu);
4307 perf_pmu_enable(pmu);
4308 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4313 void perf_event_task_tick(void)
4315 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4316 struct perf_event_context *ctx;
4319 lockdep_assert_irqs_disabled();
4321 __this_cpu_inc(perf_throttled_seq);
4322 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4323 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4325 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4328 ctx = rcu_dereference(current->perf_event_ctxp);
4330 perf_adjust_freq_unthr_context(ctx, !!throttled);
4334 static int event_enable_on_exec(struct perf_event *event,
4335 struct perf_event_context *ctx)
4337 if (!event->attr.enable_on_exec)
4340 event->attr.enable_on_exec = 0;
4341 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4344 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4350 * Enable all of a task's events that have been marked enable-on-exec.
4351 * This expects task == current.
4353 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4355 struct perf_event_context *clone_ctx = NULL;
4356 enum event_type_t event_type = 0;
4357 struct perf_cpu_context *cpuctx;
4358 struct perf_event *event;
4359 unsigned long flags;
4362 local_irq_save(flags);
4363 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4366 if (!ctx->nr_events)
4369 cpuctx = this_cpu_ptr(&perf_cpu_context);
4370 perf_ctx_lock(cpuctx, ctx);
4371 ctx_sched_out(ctx, EVENT_TIME);
4373 list_for_each_entry(event, &ctx->event_list, event_entry) {
4374 enabled |= event_enable_on_exec(event, ctx);
4375 event_type |= get_event_type(event);
4379 * Unclone and reschedule this context if we enabled any event.
4382 clone_ctx = unclone_ctx(ctx);
4383 ctx_resched(cpuctx, ctx, event_type);
4385 ctx_sched_in(ctx, EVENT_TIME);
4387 perf_ctx_unlock(cpuctx, ctx);
4390 local_irq_restore(flags);
4396 static void perf_remove_from_owner(struct perf_event *event);
4397 static void perf_event_exit_event(struct perf_event *event,
4398 struct perf_event_context *ctx);
4401 * Removes all events from the current task that have been marked
4402 * remove-on-exec, and feeds their values back to parent events.
4404 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4406 struct perf_event_context *clone_ctx = NULL;
4407 struct perf_event *event, *next;
4408 unsigned long flags;
4409 bool modified = false;
4411 mutex_lock(&ctx->mutex);
4413 if (WARN_ON_ONCE(ctx->task != current))
4416 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4417 if (!event->attr.remove_on_exec)
4420 if (!is_kernel_event(event))
4421 perf_remove_from_owner(event);
4425 perf_event_exit_event(event, ctx);
4428 raw_spin_lock_irqsave(&ctx->lock, flags);
4430 clone_ctx = unclone_ctx(ctx);
4431 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4434 mutex_unlock(&ctx->mutex);
4440 struct perf_read_data {
4441 struct perf_event *event;
4446 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4448 u16 local_pkg, event_pkg;
4450 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4451 int local_cpu = smp_processor_id();
4453 event_pkg = topology_physical_package_id(event_cpu);
4454 local_pkg = topology_physical_package_id(local_cpu);
4456 if (event_pkg == local_pkg)
4464 * Cross CPU call to read the hardware event
4466 static void __perf_event_read(void *info)
4468 struct perf_read_data *data = info;
4469 struct perf_event *sub, *event = data->event;
4470 struct perf_event_context *ctx = event->ctx;
4471 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4472 struct pmu *pmu = event->pmu;
4475 * If this is a task context, we need to check whether it is
4476 * the current task context of this cpu. If not it has been
4477 * scheduled out before the smp call arrived. In that case
4478 * event->count would have been updated to a recent sample
4479 * when the event was scheduled out.
4481 if (ctx->task && cpuctx->task_ctx != ctx)
4484 raw_spin_lock(&ctx->lock);
4485 if (ctx->is_active & EVENT_TIME) {
4486 update_context_time(ctx);
4487 update_cgrp_time_from_event(event);
4490 perf_event_update_time(event);
4492 perf_event_update_sibling_time(event);
4494 if (event->state != PERF_EVENT_STATE_ACTIVE)
4503 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4507 for_each_sibling_event(sub, event) {
4508 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4510 * Use sibling's PMU rather than @event's since
4511 * sibling could be on different (eg: software) PMU.
4513 sub->pmu->read(sub);
4517 data->ret = pmu->commit_txn(pmu);
4520 raw_spin_unlock(&ctx->lock);
4523 static inline u64 perf_event_count(struct perf_event *event)
4525 return local64_read(&event->count) + atomic64_read(&event->child_count);
4528 static void calc_timer_values(struct perf_event *event,
4535 *now = perf_clock();
4536 ctx_time = perf_event_time_now(event, *now);
4537 __perf_update_times(event, ctx_time, enabled, running);
4541 * NMI-safe method to read a local event, that is an event that
4543 * - either for the current task, or for this CPU
4544 * - does not have inherit set, for inherited task events
4545 * will not be local and we cannot read them atomically
4546 * - must not have a pmu::count method
4548 int perf_event_read_local(struct perf_event *event, u64 *value,
4549 u64 *enabled, u64 *running)
4551 unsigned long flags;
4555 * Disabling interrupts avoids all counter scheduling (context
4556 * switches, timer based rotation and IPIs).
4558 local_irq_save(flags);
4561 * It must not be an event with inherit set, we cannot read
4562 * all child counters from atomic context.
4564 if (event->attr.inherit) {
4569 /* If this is a per-task event, it must be for current */
4570 if ((event->attach_state & PERF_ATTACH_TASK) &&
4571 event->hw.target != current) {
4576 /* If this is a per-CPU event, it must be for this CPU */
4577 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4578 event->cpu != smp_processor_id()) {
4583 /* If this is a pinned event it must be running on this CPU */
4584 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4590 * If the event is currently on this CPU, its either a per-task event,
4591 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4594 if (event->oncpu == smp_processor_id())
4595 event->pmu->read(event);
4597 *value = local64_read(&event->count);
4598 if (enabled || running) {
4599 u64 __enabled, __running, __now;
4601 calc_timer_values(event, &__now, &__enabled, &__running);
4603 *enabled = __enabled;
4605 *running = __running;
4608 local_irq_restore(flags);
4613 static int perf_event_read(struct perf_event *event, bool group)
4615 enum perf_event_state state = READ_ONCE(event->state);
4616 int event_cpu, ret = 0;
4619 * If event is enabled and currently active on a CPU, update the
4620 * value in the event structure:
4623 if (state == PERF_EVENT_STATE_ACTIVE) {
4624 struct perf_read_data data;
4627 * Orders the ->state and ->oncpu loads such that if we see
4628 * ACTIVE we must also see the right ->oncpu.
4630 * Matches the smp_wmb() from event_sched_in().
4634 event_cpu = READ_ONCE(event->oncpu);
4635 if ((unsigned)event_cpu >= nr_cpu_ids)
4638 data = (struct perf_read_data){
4645 event_cpu = __perf_event_read_cpu(event, event_cpu);
4648 * Purposely ignore the smp_call_function_single() return
4651 * If event_cpu isn't a valid CPU it means the event got
4652 * scheduled out and that will have updated the event count.
4654 * Therefore, either way, we'll have an up-to-date event count
4657 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4661 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4662 struct perf_event_context *ctx = event->ctx;
4663 unsigned long flags;
4665 raw_spin_lock_irqsave(&ctx->lock, flags);
4666 state = event->state;
4667 if (state != PERF_EVENT_STATE_INACTIVE) {
4668 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4673 * May read while context is not active (e.g., thread is
4674 * blocked), in that case we cannot update context time
4676 if (ctx->is_active & EVENT_TIME) {
4677 update_context_time(ctx);
4678 update_cgrp_time_from_event(event);
4681 perf_event_update_time(event);
4683 perf_event_update_sibling_time(event);
4684 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4691 * Initialize the perf_event context in a task_struct:
4693 static void __perf_event_init_context(struct perf_event_context *ctx)
4695 raw_spin_lock_init(&ctx->lock);
4696 mutex_init(&ctx->mutex);
4697 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4698 perf_event_groups_init(&ctx->pinned_groups);
4699 perf_event_groups_init(&ctx->flexible_groups);
4700 INIT_LIST_HEAD(&ctx->event_list);
4701 refcount_set(&ctx->refcount, 1);
4705 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4708 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4709 INIT_LIST_HEAD(&epc->pinned_active);
4710 INIT_LIST_HEAD(&epc->flexible_active);
4711 atomic_set(&epc->refcount, 1);
4714 static struct perf_event_context *
4715 alloc_perf_context(struct task_struct *task)
4717 struct perf_event_context *ctx;
4719 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4723 __perf_event_init_context(ctx);
4725 ctx->task = get_task_struct(task);
4730 static struct task_struct *
4731 find_lively_task_by_vpid(pid_t vpid)
4733 struct task_struct *task;
4739 task = find_task_by_vpid(vpid);
4741 get_task_struct(task);
4745 return ERR_PTR(-ESRCH);
4751 * Returns a matching context with refcount and pincount.
4753 static struct perf_event_context *
4754 find_get_context(struct task_struct *task, struct perf_event *event)
4756 struct perf_event_context *ctx, *clone_ctx = NULL;
4757 struct perf_cpu_context *cpuctx;
4758 unsigned long flags;
4762 /* Must be root to operate on a CPU event: */
4763 err = perf_allow_cpu(&event->attr);
4765 return ERR_PTR(err);
4767 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4770 raw_spin_lock_irqsave(&ctx->lock, flags);
4772 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4779 ctx = perf_lock_task_context(task, &flags);
4781 clone_ctx = unclone_ctx(ctx);
4784 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4789 ctx = alloc_perf_context(task);
4795 mutex_lock(&task->perf_event_mutex);
4797 * If it has already passed perf_event_exit_task().
4798 * we must see PF_EXITING, it takes this mutex too.
4800 if (task->flags & PF_EXITING)
4802 else if (task->perf_event_ctxp)
4807 rcu_assign_pointer(task->perf_event_ctxp, ctx);
4809 mutex_unlock(&task->perf_event_mutex);
4811 if (unlikely(err)) {
4823 return ERR_PTR(err);
4826 static struct perf_event_pmu_context *
4827 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
4828 struct perf_event *event)
4830 struct perf_event_pmu_context *new = NULL, *epc;
4831 void *task_ctx_data = NULL;
4835 * perf_pmu_migrate_context() / __perf_pmu_install_event()
4836 * relies on the fact that find_get_pmu_context() cannot fail
4839 struct perf_cpu_pmu_context *cpc;
4841 cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
4843 raw_spin_lock_irq(&ctx->lock);
4845 atomic_set(&epc->refcount, 1);
4847 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4850 WARN_ON_ONCE(epc->ctx != ctx);
4851 atomic_inc(&epc->refcount);
4853 raw_spin_unlock_irq(&ctx->lock);
4857 new = kzalloc(sizeof(*epc), GFP_KERNEL);
4859 return ERR_PTR(-ENOMEM);
4861 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4862 task_ctx_data = alloc_task_ctx_data(pmu);
4863 if (!task_ctx_data) {
4865 return ERR_PTR(-ENOMEM);
4869 __perf_init_event_pmu_context(new, pmu);
4874 * lockdep_assert_held(&ctx->mutex);
4876 * can't because perf_event_init_task() doesn't actually hold the
4880 raw_spin_lock_irq(&ctx->lock);
4881 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4882 if (epc->pmu == pmu) {
4883 WARN_ON_ONCE(epc->ctx != ctx);
4884 atomic_inc(&epc->refcount);
4892 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4896 if (task_ctx_data && !epc->task_ctx_data) {
4897 epc->task_ctx_data = task_ctx_data;
4898 task_ctx_data = NULL;
4899 ctx->nr_task_data++;
4901 raw_spin_unlock_irq(&ctx->lock);
4903 free_task_ctx_data(pmu, task_ctx_data);
4909 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
4911 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
4914 static void free_epc_rcu(struct rcu_head *head)
4916 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
4918 kfree(epc->task_ctx_data);
4922 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
4924 struct perf_event_context *ctx = epc->ctx;
4925 unsigned long flags;
4930 * lockdep_assert_held(&ctx->mutex);
4932 * can't because of the call-site in _free_event()/put_event()
4933 * which isn't always called under ctx->mutex.
4935 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
4938 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
4940 list_del_init(&epc->pmu_ctx_entry);
4943 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
4944 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
4946 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4951 call_rcu(&epc->rcu_head, free_epc_rcu);
4954 static void perf_event_free_filter(struct perf_event *event);
4956 static void free_event_rcu(struct rcu_head *head)
4958 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
4961 put_pid_ns(event->ns);
4962 perf_event_free_filter(event);
4963 kmem_cache_free(perf_event_cache, event);
4966 static void ring_buffer_attach(struct perf_event *event,
4967 struct perf_buffer *rb);
4969 static void detach_sb_event(struct perf_event *event)
4971 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4973 raw_spin_lock(&pel->lock);
4974 list_del_rcu(&event->sb_list);
4975 raw_spin_unlock(&pel->lock);
4978 static bool is_sb_event(struct perf_event *event)
4980 struct perf_event_attr *attr = &event->attr;
4985 if (event->attach_state & PERF_ATTACH_TASK)
4988 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4989 attr->comm || attr->comm_exec ||
4990 attr->task || attr->ksymbol ||
4991 attr->context_switch || attr->text_poke ||
4997 static void unaccount_pmu_sb_event(struct perf_event *event)
4999 if (is_sb_event(event))
5000 detach_sb_event(event);
5003 #ifdef CONFIG_NO_HZ_FULL
5004 static DEFINE_SPINLOCK(nr_freq_lock);
5007 static void unaccount_freq_event_nohz(void)
5009 #ifdef CONFIG_NO_HZ_FULL
5010 spin_lock(&nr_freq_lock);
5011 if (atomic_dec_and_test(&nr_freq_events))
5012 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5013 spin_unlock(&nr_freq_lock);
5017 static void unaccount_freq_event(void)
5019 if (tick_nohz_full_enabled())
5020 unaccount_freq_event_nohz();
5022 atomic_dec(&nr_freq_events);
5025 static void unaccount_event(struct perf_event *event)
5032 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5034 if (event->attr.mmap || event->attr.mmap_data)
5035 atomic_dec(&nr_mmap_events);
5036 if (event->attr.build_id)
5037 atomic_dec(&nr_build_id_events);
5038 if (event->attr.comm)
5039 atomic_dec(&nr_comm_events);
5040 if (event->attr.namespaces)
5041 atomic_dec(&nr_namespaces_events);
5042 if (event->attr.cgroup)
5043 atomic_dec(&nr_cgroup_events);
5044 if (event->attr.task)
5045 atomic_dec(&nr_task_events);
5046 if (event->attr.freq)
5047 unaccount_freq_event();
5048 if (event->attr.context_switch) {
5050 atomic_dec(&nr_switch_events);
5052 if (is_cgroup_event(event))
5054 if (has_branch_stack(event))
5056 if (event->attr.ksymbol)
5057 atomic_dec(&nr_ksymbol_events);
5058 if (event->attr.bpf_event)
5059 atomic_dec(&nr_bpf_events);
5060 if (event->attr.text_poke)
5061 atomic_dec(&nr_text_poke_events);
5064 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5065 schedule_delayed_work(&perf_sched_work, HZ);
5068 unaccount_pmu_sb_event(event);
5071 static void perf_sched_delayed(struct work_struct *work)
5073 mutex_lock(&perf_sched_mutex);
5074 if (atomic_dec_and_test(&perf_sched_count))
5075 static_branch_disable(&perf_sched_events);
5076 mutex_unlock(&perf_sched_mutex);
5080 * The following implement mutual exclusion of events on "exclusive" pmus
5081 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5082 * at a time, so we disallow creating events that might conflict, namely:
5084 * 1) cpu-wide events in the presence of per-task events,
5085 * 2) per-task events in the presence of cpu-wide events,
5086 * 3) two matching events on the same perf_event_context.
5088 * The former two cases are handled in the allocation path (perf_event_alloc(),
5089 * _free_event()), the latter -- before the first perf_install_in_context().
5091 static int exclusive_event_init(struct perf_event *event)
5093 struct pmu *pmu = event->pmu;
5095 if (!is_exclusive_pmu(pmu))
5099 * Prevent co-existence of per-task and cpu-wide events on the
5100 * same exclusive pmu.
5102 * Negative pmu::exclusive_cnt means there are cpu-wide
5103 * events on this "exclusive" pmu, positive means there are
5106 * Since this is called in perf_event_alloc() path, event::ctx
5107 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5108 * to mean "per-task event", because unlike other attach states it
5109 * never gets cleared.
5111 if (event->attach_state & PERF_ATTACH_TASK) {
5112 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5115 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5122 static void exclusive_event_destroy(struct perf_event *event)
5124 struct pmu *pmu = event->pmu;
5126 if (!is_exclusive_pmu(pmu))
5129 /* see comment in exclusive_event_init() */
5130 if (event->attach_state & PERF_ATTACH_TASK)
5131 atomic_dec(&pmu->exclusive_cnt);
5133 atomic_inc(&pmu->exclusive_cnt);
5136 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5138 if ((e1->pmu == e2->pmu) &&
5139 (e1->cpu == e2->cpu ||
5146 static bool exclusive_event_installable(struct perf_event *event,
5147 struct perf_event_context *ctx)
5149 struct perf_event *iter_event;
5150 struct pmu *pmu = event->pmu;
5152 lockdep_assert_held(&ctx->mutex);
5154 if (!is_exclusive_pmu(pmu))
5157 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5158 if (exclusive_event_match(iter_event, event))
5165 static void perf_addr_filters_splice(struct perf_event *event,
5166 struct list_head *head);
5168 static void _free_event(struct perf_event *event)
5170 irq_work_sync(&event->pending_irq);
5172 unaccount_event(event);
5174 security_perf_event_free(event);
5178 * Can happen when we close an event with re-directed output.
5180 * Since we have a 0 refcount, perf_mmap_close() will skip
5181 * over us; possibly making our ring_buffer_put() the last.
5183 mutex_lock(&event->mmap_mutex);
5184 ring_buffer_attach(event, NULL);
5185 mutex_unlock(&event->mmap_mutex);
5188 if (is_cgroup_event(event))
5189 perf_detach_cgroup(event);
5191 if (!event->parent) {
5192 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
5193 put_callchain_buffers();
5196 perf_event_free_bpf_prog(event);
5197 perf_addr_filters_splice(event, NULL);
5198 kfree(event->addr_filter_ranges);
5201 event->destroy(event);
5204 * Must be after ->destroy(), due to uprobe_perf_close() using
5207 if (event->hw.target)
5208 put_task_struct(event->hw.target);
5211 put_pmu_ctx(event->pmu_ctx);
5214 * perf_event_free_task() relies on put_ctx() being 'last', in particular
5215 * all task references must be cleaned up.
5218 put_ctx(event->ctx);
5220 exclusive_event_destroy(event);
5221 module_put(event->pmu->module);
5223 call_rcu(&event->rcu_head, free_event_rcu);
5227 * Used to free events which have a known refcount of 1, such as in error paths
5228 * where the event isn't exposed yet and inherited events.
5230 static void free_event(struct perf_event *event)
5232 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5233 "unexpected event refcount: %ld; ptr=%p\n",
5234 atomic_long_read(&event->refcount), event)) {
5235 /* leak to avoid use-after-free */
5243 * Remove user event from the owner task.
5245 static void perf_remove_from_owner(struct perf_event *event)
5247 struct task_struct *owner;
5251 * Matches the smp_store_release() in perf_event_exit_task(). If we
5252 * observe !owner it means the list deletion is complete and we can
5253 * indeed free this event, otherwise we need to serialize on
5254 * owner->perf_event_mutex.
5256 owner = READ_ONCE(event->owner);
5259 * Since delayed_put_task_struct() also drops the last
5260 * task reference we can safely take a new reference
5261 * while holding the rcu_read_lock().
5263 get_task_struct(owner);
5269 * If we're here through perf_event_exit_task() we're already
5270 * holding ctx->mutex which would be an inversion wrt. the
5271 * normal lock order.
5273 * However we can safely take this lock because its the child
5276 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5279 * We have to re-check the event->owner field, if it is cleared
5280 * we raced with perf_event_exit_task(), acquiring the mutex
5281 * ensured they're done, and we can proceed with freeing the
5285 list_del_init(&event->owner_entry);
5286 smp_store_release(&event->owner, NULL);
5288 mutex_unlock(&owner->perf_event_mutex);
5289 put_task_struct(owner);
5293 static void put_event(struct perf_event *event)
5295 if (!atomic_long_dec_and_test(&event->refcount))
5302 * Kill an event dead; while event:refcount will preserve the event
5303 * object, it will not preserve its functionality. Once the last 'user'
5304 * gives up the object, we'll destroy the thing.
5306 int perf_event_release_kernel(struct perf_event *event)
5308 struct perf_event_context *ctx = event->ctx;
5309 struct perf_event *child, *tmp;
5310 LIST_HEAD(free_list);
5313 * If we got here through err_alloc: free_event(event); we will not
5314 * have attached to a context yet.
5317 WARN_ON_ONCE(event->attach_state &
5318 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5322 if (!is_kernel_event(event))
5323 perf_remove_from_owner(event);
5325 ctx = perf_event_ctx_lock(event);
5326 WARN_ON_ONCE(ctx->parent_ctx);
5329 * Mark this event as STATE_DEAD, there is no external reference to it
5332 * Anybody acquiring event->child_mutex after the below loop _must_
5333 * also see this, most importantly inherit_event() which will avoid
5334 * placing more children on the list.
5336 * Thus this guarantees that we will in fact observe and kill _ALL_
5339 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5341 perf_event_ctx_unlock(event, ctx);
5344 mutex_lock(&event->child_mutex);
5345 list_for_each_entry(child, &event->child_list, child_list) {
5348 * Cannot change, child events are not migrated, see the
5349 * comment with perf_event_ctx_lock_nested().
5351 ctx = READ_ONCE(child->ctx);
5353 * Since child_mutex nests inside ctx::mutex, we must jump
5354 * through hoops. We start by grabbing a reference on the ctx.
5356 * Since the event cannot get freed while we hold the
5357 * child_mutex, the context must also exist and have a !0
5363 * Now that we have a ctx ref, we can drop child_mutex, and
5364 * acquire ctx::mutex without fear of it going away. Then we
5365 * can re-acquire child_mutex.
5367 mutex_unlock(&event->child_mutex);
5368 mutex_lock(&ctx->mutex);
5369 mutex_lock(&event->child_mutex);
5372 * Now that we hold ctx::mutex and child_mutex, revalidate our
5373 * state, if child is still the first entry, it didn't get freed
5374 * and we can continue doing so.
5376 tmp = list_first_entry_or_null(&event->child_list,
5377 struct perf_event, child_list);
5379 perf_remove_from_context(child, DETACH_GROUP);
5380 list_move(&child->child_list, &free_list);
5382 * This matches the refcount bump in inherit_event();
5383 * this can't be the last reference.
5388 mutex_unlock(&event->child_mutex);
5389 mutex_unlock(&ctx->mutex);
5393 mutex_unlock(&event->child_mutex);
5395 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5396 void *var = &child->ctx->refcount;
5398 list_del(&child->child_list);
5402 * Wake any perf_event_free_task() waiting for this event to be
5405 smp_mb(); /* pairs with wait_var_event() */
5410 put_event(event); /* Must be the 'last' reference */
5413 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5416 * Called when the last reference to the file is gone.
5418 static int perf_release(struct inode *inode, struct file *file)
5420 perf_event_release_kernel(file->private_data);
5424 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5426 struct perf_event *child;
5432 mutex_lock(&event->child_mutex);
5434 (void)perf_event_read(event, false);
5435 total += perf_event_count(event);
5437 *enabled += event->total_time_enabled +
5438 atomic64_read(&event->child_total_time_enabled);
5439 *running += event->total_time_running +
5440 atomic64_read(&event->child_total_time_running);
5442 list_for_each_entry(child, &event->child_list, child_list) {
5443 (void)perf_event_read(child, false);
5444 total += perf_event_count(child);
5445 *enabled += child->total_time_enabled;
5446 *running += child->total_time_running;
5448 mutex_unlock(&event->child_mutex);
5453 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5455 struct perf_event_context *ctx;
5458 ctx = perf_event_ctx_lock(event);
5459 count = __perf_event_read_value(event, enabled, running);
5460 perf_event_ctx_unlock(event, ctx);
5464 EXPORT_SYMBOL_GPL(perf_event_read_value);
5466 static int __perf_read_group_add(struct perf_event *leader,
5467 u64 read_format, u64 *values)
5469 struct perf_event_context *ctx = leader->ctx;
5470 struct perf_event *sub, *parent;
5471 unsigned long flags;
5472 int n = 1; /* skip @nr */
5475 ret = perf_event_read(leader, true);
5479 raw_spin_lock_irqsave(&ctx->lock, flags);
5481 * Verify the grouping between the parent and child (inherited)
5482 * events is still in tact.
5485 * - leader->ctx->lock pins leader->sibling_list
5486 * - parent->child_mutex pins parent->child_list
5487 * - parent->ctx->mutex pins parent->sibling_list
5489 * Because parent->ctx != leader->ctx (and child_list nests inside
5490 * ctx->mutex), group destruction is not atomic between children, also
5491 * see perf_event_release_kernel(). Additionally, parent can grow the
5494 * Therefore it is possible to have parent and child groups in a
5495 * different configuration and summing over such a beast makes no sense
5500 parent = leader->parent;
5502 (parent->group_generation != leader->group_generation ||
5503 parent->nr_siblings != leader->nr_siblings)) {
5509 * Since we co-schedule groups, {enabled,running} times of siblings
5510 * will be identical to those of the leader, so we only publish one
5513 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5514 values[n++] += leader->total_time_enabled +
5515 atomic64_read(&leader->child_total_time_enabled);
5518 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5519 values[n++] += leader->total_time_running +
5520 atomic64_read(&leader->child_total_time_running);
5524 * Write {count,id} tuples for every sibling.
5526 values[n++] += perf_event_count(leader);
5527 if (read_format & PERF_FORMAT_ID)
5528 values[n++] = primary_event_id(leader);
5529 if (read_format & PERF_FORMAT_LOST)
5530 values[n++] = atomic64_read(&leader->lost_samples);
5532 for_each_sibling_event(sub, leader) {
5533 values[n++] += perf_event_count(sub);
5534 if (read_format & PERF_FORMAT_ID)
5535 values[n++] = primary_event_id(sub);
5536 if (read_format & PERF_FORMAT_LOST)
5537 values[n++] = atomic64_read(&sub->lost_samples);
5541 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5545 static int perf_read_group(struct perf_event *event,
5546 u64 read_format, char __user *buf)
5548 struct perf_event *leader = event->group_leader, *child;
5549 struct perf_event_context *ctx = leader->ctx;
5553 lockdep_assert_held(&ctx->mutex);
5555 values = kzalloc(event->read_size, GFP_KERNEL);
5559 values[0] = 1 + leader->nr_siblings;
5561 mutex_lock(&leader->child_mutex);
5563 ret = __perf_read_group_add(leader, read_format, values);
5567 list_for_each_entry(child, &leader->child_list, child_list) {
5568 ret = __perf_read_group_add(child, read_format, values);
5573 mutex_unlock(&leader->child_mutex);
5575 ret = event->read_size;
5576 if (copy_to_user(buf, values, event->read_size))
5581 mutex_unlock(&leader->child_mutex);
5587 static int perf_read_one(struct perf_event *event,
5588 u64 read_format, char __user *buf)
5590 u64 enabled, running;
5594 values[n++] = __perf_event_read_value(event, &enabled, &running);
5595 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5596 values[n++] = enabled;
5597 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5598 values[n++] = running;
5599 if (read_format & PERF_FORMAT_ID)
5600 values[n++] = primary_event_id(event);
5601 if (read_format & PERF_FORMAT_LOST)
5602 values[n++] = atomic64_read(&event->lost_samples);
5604 if (copy_to_user(buf, values, n * sizeof(u64)))
5607 return n * sizeof(u64);
5610 static bool is_event_hup(struct perf_event *event)
5614 if (event->state > PERF_EVENT_STATE_EXIT)
5617 mutex_lock(&event->child_mutex);
5618 no_children = list_empty(&event->child_list);
5619 mutex_unlock(&event->child_mutex);
5624 * Read the performance event - simple non blocking version for now
5627 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5629 u64 read_format = event->attr.read_format;
5633 * Return end-of-file for a read on an event that is in
5634 * error state (i.e. because it was pinned but it couldn't be
5635 * scheduled on to the CPU at some point).
5637 if (event->state == PERF_EVENT_STATE_ERROR)
5640 if (count < event->read_size)
5643 WARN_ON_ONCE(event->ctx->parent_ctx);
5644 if (read_format & PERF_FORMAT_GROUP)
5645 ret = perf_read_group(event, read_format, buf);
5647 ret = perf_read_one(event, read_format, buf);
5653 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5655 struct perf_event *event = file->private_data;
5656 struct perf_event_context *ctx;
5659 ret = security_perf_event_read(event);
5663 ctx = perf_event_ctx_lock(event);
5664 ret = __perf_read(event, buf, count);
5665 perf_event_ctx_unlock(event, ctx);
5670 static __poll_t perf_poll(struct file *file, poll_table *wait)
5672 struct perf_event *event = file->private_data;
5673 struct perf_buffer *rb;
5674 __poll_t events = EPOLLHUP;
5676 poll_wait(file, &event->waitq, wait);
5678 if (is_event_hup(event))
5682 * Pin the event->rb by taking event->mmap_mutex; otherwise
5683 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5685 mutex_lock(&event->mmap_mutex);
5688 events = atomic_xchg(&rb->poll, 0);
5689 mutex_unlock(&event->mmap_mutex);
5693 static void _perf_event_reset(struct perf_event *event)
5695 (void)perf_event_read(event, false);
5696 local64_set(&event->count, 0);
5697 perf_event_update_userpage(event);
5700 /* Assume it's not an event with inherit set. */
5701 u64 perf_event_pause(struct perf_event *event, bool reset)
5703 struct perf_event_context *ctx;
5706 ctx = perf_event_ctx_lock(event);
5707 WARN_ON_ONCE(event->attr.inherit);
5708 _perf_event_disable(event);
5709 count = local64_read(&event->count);
5711 local64_set(&event->count, 0);
5712 perf_event_ctx_unlock(event, ctx);
5716 EXPORT_SYMBOL_GPL(perf_event_pause);
5719 * Holding the top-level event's child_mutex means that any
5720 * descendant process that has inherited this event will block
5721 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5722 * task existence requirements of perf_event_enable/disable.
5724 static void perf_event_for_each_child(struct perf_event *event,
5725 void (*func)(struct perf_event *))
5727 struct perf_event *child;
5729 WARN_ON_ONCE(event->ctx->parent_ctx);
5731 mutex_lock(&event->child_mutex);
5733 list_for_each_entry(child, &event->child_list, child_list)
5735 mutex_unlock(&event->child_mutex);
5738 static void perf_event_for_each(struct perf_event *event,
5739 void (*func)(struct perf_event *))
5741 struct perf_event_context *ctx = event->ctx;
5742 struct perf_event *sibling;
5744 lockdep_assert_held(&ctx->mutex);
5746 event = event->group_leader;
5748 perf_event_for_each_child(event, func);
5749 for_each_sibling_event(sibling, event)
5750 perf_event_for_each_child(sibling, func);
5753 static void __perf_event_period(struct perf_event *event,
5754 struct perf_cpu_context *cpuctx,
5755 struct perf_event_context *ctx,
5758 u64 value = *((u64 *)info);
5761 if (event->attr.freq) {
5762 event->attr.sample_freq = value;
5764 event->attr.sample_period = value;
5765 event->hw.sample_period = value;
5768 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5770 perf_pmu_disable(event->pmu);
5772 * We could be throttled; unthrottle now to avoid the tick
5773 * trying to unthrottle while we already re-started the event.
5775 if (event->hw.interrupts == MAX_INTERRUPTS) {
5776 event->hw.interrupts = 0;
5777 perf_log_throttle(event, 1);
5779 event->pmu->stop(event, PERF_EF_UPDATE);
5782 local64_set(&event->hw.period_left, 0);
5785 event->pmu->start(event, PERF_EF_RELOAD);
5786 perf_pmu_enable(event->pmu);
5790 static int perf_event_check_period(struct perf_event *event, u64 value)
5792 return event->pmu->check_period(event, value);
5795 static int _perf_event_period(struct perf_event *event, u64 value)
5797 if (!is_sampling_event(event))
5803 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5806 if (perf_event_check_period(event, value))
5809 if (!event->attr.freq && (value & (1ULL << 63)))
5812 event_function_call(event, __perf_event_period, &value);
5817 int perf_event_period(struct perf_event *event, u64 value)
5819 struct perf_event_context *ctx;
5822 ctx = perf_event_ctx_lock(event);
5823 ret = _perf_event_period(event, value);
5824 perf_event_ctx_unlock(event, ctx);
5828 EXPORT_SYMBOL_GPL(perf_event_period);
5830 static const struct file_operations perf_fops;
5832 static inline int perf_fget_light(int fd, struct fd *p)
5834 struct fd f = fdget(fd);
5838 if (f.file->f_op != &perf_fops) {
5846 static int perf_event_set_output(struct perf_event *event,
5847 struct perf_event *output_event);
5848 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5849 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5850 struct perf_event_attr *attr);
5852 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5854 void (*func)(struct perf_event *);
5858 case PERF_EVENT_IOC_ENABLE:
5859 func = _perf_event_enable;
5861 case PERF_EVENT_IOC_DISABLE:
5862 func = _perf_event_disable;
5864 case PERF_EVENT_IOC_RESET:
5865 func = _perf_event_reset;
5868 case PERF_EVENT_IOC_REFRESH:
5869 return _perf_event_refresh(event, arg);
5871 case PERF_EVENT_IOC_PERIOD:
5875 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5878 return _perf_event_period(event, value);
5880 case PERF_EVENT_IOC_ID:
5882 u64 id = primary_event_id(event);
5884 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5889 case PERF_EVENT_IOC_SET_OUTPUT:
5893 struct perf_event *output_event;
5895 ret = perf_fget_light(arg, &output);
5898 output_event = output.file->private_data;
5899 ret = perf_event_set_output(event, output_event);
5902 ret = perf_event_set_output(event, NULL);
5907 case PERF_EVENT_IOC_SET_FILTER:
5908 return perf_event_set_filter(event, (void __user *)arg);
5910 case PERF_EVENT_IOC_SET_BPF:
5912 struct bpf_prog *prog;
5915 prog = bpf_prog_get(arg);
5917 return PTR_ERR(prog);
5919 err = perf_event_set_bpf_prog(event, prog, 0);
5928 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5929 struct perf_buffer *rb;
5932 rb = rcu_dereference(event->rb);
5933 if (!rb || !rb->nr_pages) {
5937 rb_toggle_paused(rb, !!arg);
5942 case PERF_EVENT_IOC_QUERY_BPF:
5943 return perf_event_query_prog_array(event, (void __user *)arg);
5945 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5946 struct perf_event_attr new_attr;
5947 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5953 return perf_event_modify_attr(event, &new_attr);
5959 if (flags & PERF_IOC_FLAG_GROUP)
5960 perf_event_for_each(event, func);
5962 perf_event_for_each_child(event, func);
5967 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5969 struct perf_event *event = file->private_data;
5970 struct perf_event_context *ctx;
5973 /* Treat ioctl like writes as it is likely a mutating operation. */
5974 ret = security_perf_event_write(event);
5978 ctx = perf_event_ctx_lock(event);
5979 ret = _perf_ioctl(event, cmd, arg);
5980 perf_event_ctx_unlock(event, ctx);
5985 #ifdef CONFIG_COMPAT
5986 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5989 switch (_IOC_NR(cmd)) {
5990 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5991 case _IOC_NR(PERF_EVENT_IOC_ID):
5992 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5993 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5994 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5995 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5996 cmd &= ~IOCSIZE_MASK;
5997 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6001 return perf_ioctl(file, cmd, arg);
6004 # define perf_compat_ioctl NULL
6007 int perf_event_task_enable(void)
6009 struct perf_event_context *ctx;
6010 struct perf_event *event;
6012 mutex_lock(¤t->perf_event_mutex);
6013 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6014 ctx = perf_event_ctx_lock(event);
6015 perf_event_for_each_child(event, _perf_event_enable);
6016 perf_event_ctx_unlock(event, ctx);
6018 mutex_unlock(¤t->perf_event_mutex);
6023 int perf_event_task_disable(void)
6025 struct perf_event_context *ctx;
6026 struct perf_event *event;
6028 mutex_lock(¤t->perf_event_mutex);
6029 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6030 ctx = perf_event_ctx_lock(event);
6031 perf_event_for_each_child(event, _perf_event_disable);
6032 perf_event_ctx_unlock(event, ctx);
6034 mutex_unlock(¤t->perf_event_mutex);
6039 static int perf_event_index(struct perf_event *event)
6041 if (event->hw.state & PERF_HES_STOPPED)
6044 if (event->state != PERF_EVENT_STATE_ACTIVE)
6047 return event->pmu->event_idx(event);
6050 static void perf_event_init_userpage(struct perf_event *event)
6052 struct perf_event_mmap_page *userpg;
6053 struct perf_buffer *rb;
6056 rb = rcu_dereference(event->rb);
6060 userpg = rb->user_page;
6062 /* Allow new userspace to detect that bit 0 is deprecated */
6063 userpg->cap_bit0_is_deprecated = 1;
6064 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6065 userpg->data_offset = PAGE_SIZE;
6066 userpg->data_size = perf_data_size(rb);
6072 void __weak arch_perf_update_userpage(
6073 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6078 * Callers need to ensure there can be no nesting of this function, otherwise
6079 * the seqlock logic goes bad. We can not serialize this because the arch
6080 * code calls this from NMI context.
6082 void perf_event_update_userpage(struct perf_event *event)
6084 struct perf_event_mmap_page *userpg;
6085 struct perf_buffer *rb;
6086 u64 enabled, running, now;
6089 rb = rcu_dereference(event->rb);
6094 * compute total_time_enabled, total_time_running
6095 * based on snapshot values taken when the event
6096 * was last scheduled in.
6098 * we cannot simply called update_context_time()
6099 * because of locking issue as we can be called in
6102 calc_timer_values(event, &now, &enabled, &running);
6104 userpg = rb->user_page;
6106 * Disable preemption to guarantee consistent time stamps are stored to
6112 userpg->index = perf_event_index(event);
6113 userpg->offset = perf_event_count(event);
6115 userpg->offset -= local64_read(&event->hw.prev_count);
6117 userpg->time_enabled = enabled +
6118 atomic64_read(&event->child_total_time_enabled);
6120 userpg->time_running = running +
6121 atomic64_read(&event->child_total_time_running);
6123 arch_perf_update_userpage(event, userpg, now);
6131 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6133 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
6135 struct perf_event *event = vmf->vma->vm_file->private_data;
6136 struct perf_buffer *rb;
6137 vm_fault_t ret = VM_FAULT_SIGBUS;
6139 if (vmf->flags & FAULT_FLAG_MKWRITE) {
6140 if (vmf->pgoff == 0)
6146 rb = rcu_dereference(event->rb);
6150 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
6153 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
6157 get_page(vmf->page);
6158 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
6159 vmf->page->index = vmf->pgoff;
6168 static void ring_buffer_attach(struct perf_event *event,
6169 struct perf_buffer *rb)
6171 struct perf_buffer *old_rb = NULL;
6172 unsigned long flags;
6174 WARN_ON_ONCE(event->parent);
6178 * Should be impossible, we set this when removing
6179 * event->rb_entry and wait/clear when adding event->rb_entry.
6181 WARN_ON_ONCE(event->rcu_pending);
6184 spin_lock_irqsave(&old_rb->event_lock, flags);
6185 list_del_rcu(&event->rb_entry);
6186 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6188 event->rcu_batches = get_state_synchronize_rcu();
6189 event->rcu_pending = 1;
6193 if (event->rcu_pending) {
6194 cond_synchronize_rcu(event->rcu_batches);
6195 event->rcu_pending = 0;
6198 spin_lock_irqsave(&rb->event_lock, flags);
6199 list_add_rcu(&event->rb_entry, &rb->event_list);
6200 spin_unlock_irqrestore(&rb->event_lock, flags);
6204 * Avoid racing with perf_mmap_close(AUX): stop the event
6205 * before swizzling the event::rb pointer; if it's getting
6206 * unmapped, its aux_mmap_count will be 0 and it won't
6207 * restart. See the comment in __perf_pmu_output_stop().
6209 * Data will inevitably be lost when set_output is done in
6210 * mid-air, but then again, whoever does it like this is
6211 * not in for the data anyway.
6214 perf_event_stop(event, 0);
6216 rcu_assign_pointer(event->rb, rb);
6219 ring_buffer_put(old_rb);
6221 * Since we detached before setting the new rb, so that we
6222 * could attach the new rb, we could have missed a wakeup.
6225 wake_up_all(&event->waitq);
6229 static void ring_buffer_wakeup(struct perf_event *event)
6231 struct perf_buffer *rb;
6234 event = event->parent;
6237 rb = rcu_dereference(event->rb);
6239 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6240 wake_up_all(&event->waitq);
6245 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6247 struct perf_buffer *rb;
6250 event = event->parent;
6253 rb = rcu_dereference(event->rb);
6255 if (!refcount_inc_not_zero(&rb->refcount))
6263 void ring_buffer_put(struct perf_buffer *rb)
6265 if (!refcount_dec_and_test(&rb->refcount))
6268 WARN_ON_ONCE(!list_empty(&rb->event_list));
6270 call_rcu(&rb->rcu_head, rb_free_rcu);
6273 static void perf_mmap_open(struct vm_area_struct *vma)
6275 struct perf_event *event = vma->vm_file->private_data;
6277 atomic_inc(&event->mmap_count);
6278 atomic_inc(&event->rb->mmap_count);
6281 atomic_inc(&event->rb->aux_mmap_count);
6283 if (event->pmu->event_mapped)
6284 event->pmu->event_mapped(event, vma->vm_mm);
6287 static void perf_pmu_output_stop(struct perf_event *event);
6290 * A buffer can be mmap()ed multiple times; either directly through the same
6291 * event, or through other events by use of perf_event_set_output().
6293 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6294 * the buffer here, where we still have a VM context. This means we need
6295 * to detach all events redirecting to us.
6297 static void perf_mmap_close(struct vm_area_struct *vma)
6299 struct perf_event *event = vma->vm_file->private_data;
6300 struct perf_buffer *rb = ring_buffer_get(event);
6301 struct user_struct *mmap_user = rb->mmap_user;
6302 int mmap_locked = rb->mmap_locked;
6303 unsigned long size = perf_data_size(rb);
6304 bool detach_rest = false;
6306 if (event->pmu->event_unmapped)
6307 event->pmu->event_unmapped(event, vma->vm_mm);
6310 * rb->aux_mmap_count will always drop before rb->mmap_count and
6311 * event->mmap_count, so it is ok to use event->mmap_mutex to
6312 * serialize with perf_mmap here.
6314 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6315 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6317 * Stop all AUX events that are writing to this buffer,
6318 * so that we can free its AUX pages and corresponding PMU
6319 * data. Note that after rb::aux_mmap_count dropped to zero,
6320 * they won't start any more (see perf_aux_output_begin()).
6322 perf_pmu_output_stop(event);
6324 /* now it's safe to free the pages */
6325 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6326 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6328 /* this has to be the last one */
6330 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6332 mutex_unlock(&event->mmap_mutex);
6335 if (atomic_dec_and_test(&rb->mmap_count))
6338 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6341 ring_buffer_attach(event, NULL);
6342 mutex_unlock(&event->mmap_mutex);
6344 /* If there's still other mmap()s of this buffer, we're done. */
6349 * No other mmap()s, detach from all other events that might redirect
6350 * into the now unreachable buffer. Somewhat complicated by the
6351 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6355 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6356 if (!atomic_long_inc_not_zero(&event->refcount)) {
6358 * This event is en-route to free_event() which will
6359 * detach it and remove it from the list.
6365 mutex_lock(&event->mmap_mutex);
6367 * Check we didn't race with perf_event_set_output() which can
6368 * swizzle the rb from under us while we were waiting to
6369 * acquire mmap_mutex.
6371 * If we find a different rb; ignore this event, a next
6372 * iteration will no longer find it on the list. We have to
6373 * still restart the iteration to make sure we're not now
6374 * iterating the wrong list.
6376 if (event->rb == rb)
6377 ring_buffer_attach(event, NULL);
6379 mutex_unlock(&event->mmap_mutex);
6383 * Restart the iteration; either we're on the wrong list or
6384 * destroyed its integrity by doing a deletion.
6391 * It could be there's still a few 0-ref events on the list; they'll
6392 * get cleaned up by free_event() -- they'll also still have their
6393 * ref on the rb and will free it whenever they are done with it.
6395 * Aside from that, this buffer is 'fully' detached and unmapped,
6396 * undo the VM accounting.
6399 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6400 &mmap_user->locked_vm);
6401 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6402 free_uid(mmap_user);
6405 ring_buffer_put(rb); /* could be last */
6408 static const struct vm_operations_struct perf_mmap_vmops = {
6409 .open = perf_mmap_open,
6410 .close = perf_mmap_close, /* non mergeable */
6411 .fault = perf_mmap_fault,
6412 .page_mkwrite = perf_mmap_fault,
6415 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6417 struct perf_event *event = file->private_data;
6418 unsigned long user_locked, user_lock_limit;
6419 struct user_struct *user = current_user();
6420 struct perf_buffer *rb = NULL;
6421 unsigned long locked, lock_limit;
6422 unsigned long vma_size;
6423 unsigned long nr_pages;
6424 long user_extra = 0, extra = 0;
6425 int ret = 0, flags = 0;
6428 * Don't allow mmap() of inherited per-task counters. This would
6429 * create a performance issue due to all children writing to the
6432 if (event->cpu == -1 && event->attr.inherit)
6435 if (!(vma->vm_flags & VM_SHARED))
6438 ret = security_perf_event_read(event);
6442 vma_size = vma->vm_end - vma->vm_start;
6444 if (vma->vm_pgoff == 0) {
6445 nr_pages = (vma_size / PAGE_SIZE) - 1;
6448 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6449 * mapped, all subsequent mappings should have the same size
6450 * and offset. Must be above the normal perf buffer.
6452 u64 aux_offset, aux_size;
6457 nr_pages = vma_size / PAGE_SIZE;
6459 mutex_lock(&event->mmap_mutex);
6466 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6467 aux_size = READ_ONCE(rb->user_page->aux_size);
6469 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6472 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6475 /* already mapped with a different offset */
6476 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6479 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6482 /* already mapped with a different size */
6483 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6486 if (!is_power_of_2(nr_pages))
6489 if (!atomic_inc_not_zero(&rb->mmap_count))
6492 if (rb_has_aux(rb)) {
6493 atomic_inc(&rb->aux_mmap_count);
6498 atomic_set(&rb->aux_mmap_count, 1);
6499 user_extra = nr_pages;
6505 * If we have rb pages ensure they're a power-of-two number, so we
6506 * can do bitmasks instead of modulo.
6508 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6511 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6514 WARN_ON_ONCE(event->ctx->parent_ctx);
6516 mutex_lock(&event->mmap_mutex);
6518 if (data_page_nr(event->rb) != nr_pages) {
6523 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6525 * Raced against perf_mmap_close(); remove the
6526 * event and try again.
6528 ring_buffer_attach(event, NULL);
6529 mutex_unlock(&event->mmap_mutex);
6536 user_extra = nr_pages + 1;
6539 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6542 * Increase the limit linearly with more CPUs:
6544 user_lock_limit *= num_online_cpus();
6546 user_locked = atomic_long_read(&user->locked_vm);
6549 * sysctl_perf_event_mlock may have changed, so that
6550 * user->locked_vm > user_lock_limit
6552 if (user_locked > user_lock_limit)
6553 user_locked = user_lock_limit;
6554 user_locked += user_extra;
6556 if (user_locked > user_lock_limit) {
6558 * charge locked_vm until it hits user_lock_limit;
6559 * charge the rest from pinned_vm
6561 extra = user_locked - user_lock_limit;
6562 user_extra -= extra;
6565 lock_limit = rlimit(RLIMIT_MEMLOCK);
6566 lock_limit >>= PAGE_SHIFT;
6567 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6569 if ((locked > lock_limit) && perf_is_paranoid() &&
6570 !capable(CAP_IPC_LOCK)) {
6575 WARN_ON(!rb && event->rb);
6577 if (vma->vm_flags & VM_WRITE)
6578 flags |= RING_BUFFER_WRITABLE;
6581 rb = rb_alloc(nr_pages,
6582 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6590 atomic_set(&rb->mmap_count, 1);
6591 rb->mmap_user = get_current_user();
6592 rb->mmap_locked = extra;
6594 ring_buffer_attach(event, rb);
6596 perf_event_update_time(event);
6597 perf_event_init_userpage(event);
6598 perf_event_update_userpage(event);
6600 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6601 event->attr.aux_watermark, flags);
6603 rb->aux_mmap_locked = extra;
6608 atomic_long_add(user_extra, &user->locked_vm);
6609 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6611 atomic_inc(&event->mmap_count);
6613 atomic_dec(&rb->mmap_count);
6616 mutex_unlock(&event->mmap_mutex);
6619 * Since pinned accounting is per vm we cannot allow fork() to copy our
6622 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
6623 vma->vm_ops = &perf_mmap_vmops;
6625 if (event->pmu->event_mapped)
6626 event->pmu->event_mapped(event, vma->vm_mm);
6631 static int perf_fasync(int fd, struct file *filp, int on)
6633 struct inode *inode = file_inode(filp);
6634 struct perf_event *event = filp->private_data;
6638 retval = fasync_helper(fd, filp, on, &event->fasync);
6639 inode_unlock(inode);
6647 static const struct file_operations perf_fops = {
6648 .llseek = no_llseek,
6649 .release = perf_release,
6652 .unlocked_ioctl = perf_ioctl,
6653 .compat_ioctl = perf_compat_ioctl,
6655 .fasync = perf_fasync,
6661 * If there's data, ensure we set the poll() state and publish everything
6662 * to user-space before waking everybody up.
6665 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6667 /* only the parent has fasync state */
6669 event = event->parent;
6670 return &event->fasync;
6673 void perf_event_wakeup(struct perf_event *event)
6675 ring_buffer_wakeup(event);
6677 if (event->pending_kill) {
6678 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6679 event->pending_kill = 0;
6683 static void perf_sigtrap(struct perf_event *event)
6686 * We'd expect this to only occur if the irq_work is delayed and either
6687 * ctx->task or current has changed in the meantime. This can be the
6688 * case on architectures that do not implement arch_irq_work_raise().
6690 if (WARN_ON_ONCE(event->ctx->task != current))
6694 * Both perf_pending_task() and perf_pending_irq() can race with the
6697 if (current->flags & PF_EXITING)
6700 send_sig_perf((void __user *)event->pending_addr,
6701 event->orig_type, event->attr.sig_data);
6705 * Deliver the pending work in-event-context or follow the context.
6707 static void __perf_pending_irq(struct perf_event *event)
6709 int cpu = READ_ONCE(event->oncpu);
6712 * If the event isn't running; we done. event_sched_out() will have
6713 * taken care of things.
6719 * Yay, we hit home and are in the context of the event.
6721 if (cpu == smp_processor_id()) {
6722 if (event->pending_sigtrap) {
6723 event->pending_sigtrap = 0;
6724 perf_sigtrap(event);
6725 local_dec(&event->ctx->nr_pending);
6727 if (event->pending_disable) {
6728 event->pending_disable = 0;
6729 perf_event_disable_local(event);
6737 * perf_event_disable_inatomic()
6738 * @pending_disable = CPU-A;
6742 * @pending_disable = -1;
6745 * perf_event_disable_inatomic()
6746 * @pending_disable = CPU-B;
6747 * irq_work_queue(); // FAILS
6750 * perf_pending_irq()
6752 * But the event runs on CPU-B and wants disabling there.
6754 irq_work_queue_on(&event->pending_irq, cpu);
6757 static void perf_pending_irq(struct irq_work *entry)
6759 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6763 * If we 'fail' here, that's OK, it means recursion is already disabled
6764 * and we won't recurse 'further'.
6766 rctx = perf_swevent_get_recursion_context();
6769 * The wakeup isn't bound to the context of the event -- it can happen
6770 * irrespective of where the event is.
6772 if (event->pending_wakeup) {
6773 event->pending_wakeup = 0;
6774 perf_event_wakeup(event);
6777 __perf_pending_irq(event);
6780 perf_swevent_put_recursion_context(rctx);
6783 static void perf_pending_task(struct callback_head *head)
6785 struct perf_event *event = container_of(head, struct perf_event, pending_task);
6789 * If we 'fail' here, that's OK, it means recursion is already disabled
6790 * and we won't recurse 'further'.
6792 preempt_disable_notrace();
6793 rctx = perf_swevent_get_recursion_context();
6795 if (event->pending_work) {
6796 event->pending_work = 0;
6797 perf_sigtrap(event);
6798 local_dec(&event->ctx->nr_pending);
6802 perf_swevent_put_recursion_context(rctx);
6803 preempt_enable_notrace();
6808 #ifdef CONFIG_GUEST_PERF_EVENTS
6809 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6811 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
6812 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
6813 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
6815 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6817 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6820 rcu_assign_pointer(perf_guest_cbs, cbs);
6821 static_call_update(__perf_guest_state, cbs->state);
6822 static_call_update(__perf_guest_get_ip, cbs->get_ip);
6824 /* Implementing ->handle_intel_pt_intr is optional. */
6825 if (cbs->handle_intel_pt_intr)
6826 static_call_update(__perf_guest_handle_intel_pt_intr,
6827 cbs->handle_intel_pt_intr);
6829 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6831 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6833 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6836 rcu_assign_pointer(perf_guest_cbs, NULL);
6837 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
6838 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
6839 static_call_update(__perf_guest_handle_intel_pt_intr,
6840 (void *)&__static_call_return0);
6843 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6847 perf_output_sample_regs(struct perf_output_handle *handle,
6848 struct pt_regs *regs, u64 mask)
6851 DECLARE_BITMAP(_mask, 64);
6853 bitmap_from_u64(_mask, mask);
6854 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6857 val = perf_reg_value(regs, bit);
6858 perf_output_put(handle, val);
6862 static void perf_sample_regs_user(struct perf_regs *regs_user,
6863 struct pt_regs *regs)
6865 if (user_mode(regs)) {
6866 regs_user->abi = perf_reg_abi(current);
6867 regs_user->regs = regs;
6868 } else if (!(current->flags & PF_KTHREAD)) {
6869 perf_get_regs_user(regs_user, regs);
6871 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6872 regs_user->regs = NULL;
6876 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6877 struct pt_regs *regs)
6879 regs_intr->regs = regs;
6880 regs_intr->abi = perf_reg_abi(current);
6885 * Get remaining task size from user stack pointer.
6887 * It'd be better to take stack vma map and limit this more
6888 * precisely, but there's no way to get it safely under interrupt,
6889 * so using TASK_SIZE as limit.
6891 static u64 perf_ustack_task_size(struct pt_regs *regs)
6893 unsigned long addr = perf_user_stack_pointer(regs);
6895 if (!addr || addr >= TASK_SIZE)
6898 return TASK_SIZE - addr;
6902 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6903 struct pt_regs *regs)
6907 /* No regs, no stack pointer, no dump. */
6912 * Check if we fit in with the requested stack size into the:
6914 * If we don't, we limit the size to the TASK_SIZE.
6916 * - remaining sample size
6917 * If we don't, we customize the stack size to
6918 * fit in to the remaining sample size.
6921 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6922 stack_size = min(stack_size, (u16) task_size);
6924 /* Current header size plus static size and dynamic size. */
6925 header_size += 2 * sizeof(u64);
6927 /* Do we fit in with the current stack dump size? */
6928 if ((u16) (header_size + stack_size) < header_size) {
6930 * If we overflow the maximum size for the sample,
6931 * we customize the stack dump size to fit in.
6933 stack_size = USHRT_MAX - header_size - sizeof(u64);
6934 stack_size = round_up(stack_size, sizeof(u64));
6941 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6942 struct pt_regs *regs)
6944 /* Case of a kernel thread, nothing to dump */
6947 perf_output_put(handle, size);
6956 * - the size requested by user or the best one we can fit
6957 * in to the sample max size
6959 * - user stack dump data
6961 * - the actual dumped size
6965 perf_output_put(handle, dump_size);
6968 sp = perf_user_stack_pointer(regs);
6969 rem = __output_copy_user(handle, (void *) sp, dump_size);
6970 dyn_size = dump_size - rem;
6972 perf_output_skip(handle, rem);
6975 perf_output_put(handle, dyn_size);
6979 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6980 struct perf_sample_data *data,
6983 struct perf_event *sampler = event->aux_event;
6984 struct perf_buffer *rb;
6991 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6994 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6997 rb = ring_buffer_get(sampler);
7002 * If this is an NMI hit inside sampling code, don't take
7003 * the sample. See also perf_aux_sample_output().
7005 if (READ_ONCE(rb->aux_in_sampling)) {
7008 size = min_t(size_t, size, perf_aux_size(rb));
7009 data->aux_size = ALIGN(size, sizeof(u64));
7011 ring_buffer_put(rb);
7014 return data->aux_size;
7017 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
7018 struct perf_event *event,
7019 struct perf_output_handle *handle,
7022 unsigned long flags;
7026 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7027 * paths. If we start calling them in NMI context, they may race with
7028 * the IRQ ones, that is, for example, re-starting an event that's just
7029 * been stopped, which is why we're using a separate callback that
7030 * doesn't change the event state.
7032 * IRQs need to be disabled to prevent IPIs from racing with us.
7034 local_irq_save(flags);
7036 * Guard against NMI hits inside the critical section;
7037 * see also perf_prepare_sample_aux().
7039 WRITE_ONCE(rb->aux_in_sampling, 1);
7042 ret = event->pmu->snapshot_aux(event, handle, size);
7045 WRITE_ONCE(rb->aux_in_sampling, 0);
7046 local_irq_restore(flags);
7051 static void perf_aux_sample_output(struct perf_event *event,
7052 struct perf_output_handle *handle,
7053 struct perf_sample_data *data)
7055 struct perf_event *sampler = event->aux_event;
7056 struct perf_buffer *rb;
7060 if (WARN_ON_ONCE(!sampler || !data->aux_size))
7063 rb = ring_buffer_get(sampler);
7067 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7070 * An error here means that perf_output_copy() failed (returned a
7071 * non-zero surplus that it didn't copy), which in its current
7072 * enlightened implementation is not possible. If that changes, we'd
7075 if (WARN_ON_ONCE(size < 0))
7079 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7080 * perf_prepare_sample_aux(), so should not be more than that.
7082 pad = data->aux_size - size;
7083 if (WARN_ON_ONCE(pad >= sizeof(u64)))
7088 perf_output_copy(handle, &zero, pad);
7092 ring_buffer_put(rb);
7096 * A set of common sample data types saved even for non-sample records
7097 * when event->attr.sample_id_all is set.
7099 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7100 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7101 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7103 static void __perf_event_header__init_id(struct perf_sample_data *data,
7104 struct perf_event *event,
7107 data->type = event->attr.sample_type;
7108 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
7110 if (sample_type & PERF_SAMPLE_TID) {
7111 /* namespace issues */
7112 data->tid_entry.pid = perf_event_pid(event, current);
7113 data->tid_entry.tid = perf_event_tid(event, current);
7116 if (sample_type & PERF_SAMPLE_TIME)
7117 data->time = perf_event_clock(event);
7119 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7120 data->id = primary_event_id(event);
7122 if (sample_type & PERF_SAMPLE_STREAM_ID)
7123 data->stream_id = event->id;
7125 if (sample_type & PERF_SAMPLE_CPU) {
7126 data->cpu_entry.cpu = raw_smp_processor_id();
7127 data->cpu_entry.reserved = 0;
7131 void perf_event_header__init_id(struct perf_event_header *header,
7132 struct perf_sample_data *data,
7133 struct perf_event *event)
7135 if (event->attr.sample_id_all) {
7136 header->size += event->id_header_size;
7137 __perf_event_header__init_id(data, event, event->attr.sample_type);
7141 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7142 struct perf_sample_data *data)
7144 u64 sample_type = data->type;
7146 if (sample_type & PERF_SAMPLE_TID)
7147 perf_output_put(handle, data->tid_entry);
7149 if (sample_type & PERF_SAMPLE_TIME)
7150 perf_output_put(handle, data->time);
7152 if (sample_type & PERF_SAMPLE_ID)
7153 perf_output_put(handle, data->id);
7155 if (sample_type & PERF_SAMPLE_STREAM_ID)
7156 perf_output_put(handle, data->stream_id);
7158 if (sample_type & PERF_SAMPLE_CPU)
7159 perf_output_put(handle, data->cpu_entry);
7161 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7162 perf_output_put(handle, data->id);
7165 void perf_event__output_id_sample(struct perf_event *event,
7166 struct perf_output_handle *handle,
7167 struct perf_sample_data *sample)
7169 if (event->attr.sample_id_all)
7170 __perf_event__output_id_sample(handle, sample);
7173 static void perf_output_read_one(struct perf_output_handle *handle,
7174 struct perf_event *event,
7175 u64 enabled, u64 running)
7177 u64 read_format = event->attr.read_format;
7181 values[n++] = perf_event_count(event);
7182 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7183 values[n++] = enabled +
7184 atomic64_read(&event->child_total_time_enabled);
7186 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7187 values[n++] = running +
7188 atomic64_read(&event->child_total_time_running);
7190 if (read_format & PERF_FORMAT_ID)
7191 values[n++] = primary_event_id(event);
7192 if (read_format & PERF_FORMAT_LOST)
7193 values[n++] = atomic64_read(&event->lost_samples);
7195 __output_copy(handle, values, n * sizeof(u64));
7198 static void perf_output_read_group(struct perf_output_handle *handle,
7199 struct perf_event *event,
7200 u64 enabled, u64 running)
7202 struct perf_event *leader = event->group_leader, *sub;
7203 u64 read_format = event->attr.read_format;
7204 unsigned long flags;
7209 * Disabling interrupts avoids all counter scheduling
7210 * (context switches, timer based rotation and IPIs).
7212 local_irq_save(flags);
7214 values[n++] = 1 + leader->nr_siblings;
7216 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7217 values[n++] = enabled;
7219 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7220 values[n++] = running;
7222 if ((leader != event) &&
7223 (leader->state == PERF_EVENT_STATE_ACTIVE))
7224 leader->pmu->read(leader);
7226 values[n++] = perf_event_count(leader);
7227 if (read_format & PERF_FORMAT_ID)
7228 values[n++] = primary_event_id(leader);
7229 if (read_format & PERF_FORMAT_LOST)
7230 values[n++] = atomic64_read(&leader->lost_samples);
7232 __output_copy(handle, values, n * sizeof(u64));
7234 for_each_sibling_event(sub, leader) {
7237 if ((sub != event) &&
7238 (sub->state == PERF_EVENT_STATE_ACTIVE))
7239 sub->pmu->read(sub);
7241 values[n++] = perf_event_count(sub);
7242 if (read_format & PERF_FORMAT_ID)
7243 values[n++] = primary_event_id(sub);
7244 if (read_format & PERF_FORMAT_LOST)
7245 values[n++] = atomic64_read(&sub->lost_samples);
7247 __output_copy(handle, values, n * sizeof(u64));
7250 local_irq_restore(flags);
7253 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7254 PERF_FORMAT_TOTAL_TIME_RUNNING)
7257 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7259 * The problem is that its both hard and excessively expensive to iterate the
7260 * child list, not to mention that its impossible to IPI the children running
7261 * on another CPU, from interrupt/NMI context.
7263 static void perf_output_read(struct perf_output_handle *handle,
7264 struct perf_event *event)
7266 u64 enabled = 0, running = 0, now;
7267 u64 read_format = event->attr.read_format;
7270 * compute total_time_enabled, total_time_running
7271 * based on snapshot values taken when the event
7272 * was last scheduled in.
7274 * we cannot simply called update_context_time()
7275 * because of locking issue as we are called in
7278 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7279 calc_timer_values(event, &now, &enabled, &running);
7281 if (event->attr.read_format & PERF_FORMAT_GROUP)
7282 perf_output_read_group(handle, event, enabled, running);
7284 perf_output_read_one(handle, event, enabled, running);
7287 void perf_output_sample(struct perf_output_handle *handle,
7288 struct perf_event_header *header,
7289 struct perf_sample_data *data,
7290 struct perf_event *event)
7292 u64 sample_type = data->type;
7294 perf_output_put(handle, *header);
7296 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7297 perf_output_put(handle, data->id);
7299 if (sample_type & PERF_SAMPLE_IP)
7300 perf_output_put(handle, data->ip);
7302 if (sample_type & PERF_SAMPLE_TID)
7303 perf_output_put(handle, data->tid_entry);
7305 if (sample_type & PERF_SAMPLE_TIME)
7306 perf_output_put(handle, data->time);
7308 if (sample_type & PERF_SAMPLE_ADDR)
7309 perf_output_put(handle, data->addr);
7311 if (sample_type & PERF_SAMPLE_ID)
7312 perf_output_put(handle, data->id);
7314 if (sample_type & PERF_SAMPLE_STREAM_ID)
7315 perf_output_put(handle, data->stream_id);
7317 if (sample_type & PERF_SAMPLE_CPU)
7318 perf_output_put(handle, data->cpu_entry);
7320 if (sample_type & PERF_SAMPLE_PERIOD)
7321 perf_output_put(handle, data->period);
7323 if (sample_type & PERF_SAMPLE_READ)
7324 perf_output_read(handle, event);
7326 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7329 size += data->callchain->nr;
7330 size *= sizeof(u64);
7331 __output_copy(handle, data->callchain, size);
7334 if (sample_type & PERF_SAMPLE_RAW) {
7335 struct perf_raw_record *raw = data->raw;
7338 struct perf_raw_frag *frag = &raw->frag;
7340 perf_output_put(handle, raw->size);
7343 __output_custom(handle, frag->copy,
7344 frag->data, frag->size);
7346 __output_copy(handle, frag->data,
7349 if (perf_raw_frag_last(frag))
7354 __output_skip(handle, NULL, frag->pad);
7360 .size = sizeof(u32),
7363 perf_output_put(handle, raw);
7367 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7368 if (data->br_stack) {
7371 size = data->br_stack->nr
7372 * sizeof(struct perf_branch_entry);
7374 perf_output_put(handle, data->br_stack->nr);
7375 if (branch_sample_hw_index(event))
7376 perf_output_put(handle, data->br_stack->hw_idx);
7377 perf_output_copy(handle, data->br_stack->entries, size);
7380 * we always store at least the value of nr
7383 perf_output_put(handle, nr);
7387 if (sample_type & PERF_SAMPLE_REGS_USER) {
7388 u64 abi = data->regs_user.abi;
7391 * If there are no regs to dump, notice it through
7392 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7394 perf_output_put(handle, abi);
7397 u64 mask = event->attr.sample_regs_user;
7398 perf_output_sample_regs(handle,
7399 data->regs_user.regs,
7404 if (sample_type & PERF_SAMPLE_STACK_USER) {
7405 perf_output_sample_ustack(handle,
7406 data->stack_user_size,
7407 data->regs_user.regs);
7410 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7411 perf_output_put(handle, data->weight.full);
7413 if (sample_type & PERF_SAMPLE_DATA_SRC)
7414 perf_output_put(handle, data->data_src.val);
7416 if (sample_type & PERF_SAMPLE_TRANSACTION)
7417 perf_output_put(handle, data->txn);
7419 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7420 u64 abi = data->regs_intr.abi;
7422 * If there are no regs to dump, notice it through
7423 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7425 perf_output_put(handle, abi);
7428 u64 mask = event->attr.sample_regs_intr;
7430 perf_output_sample_regs(handle,
7431 data->regs_intr.regs,
7436 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7437 perf_output_put(handle, data->phys_addr);
7439 if (sample_type & PERF_SAMPLE_CGROUP)
7440 perf_output_put(handle, data->cgroup);
7442 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7443 perf_output_put(handle, data->data_page_size);
7445 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7446 perf_output_put(handle, data->code_page_size);
7448 if (sample_type & PERF_SAMPLE_AUX) {
7449 perf_output_put(handle, data->aux_size);
7452 perf_aux_sample_output(event, handle, data);
7455 if (!event->attr.watermark) {
7456 int wakeup_events = event->attr.wakeup_events;
7458 if (wakeup_events) {
7459 struct perf_buffer *rb = handle->rb;
7460 int events = local_inc_return(&rb->events);
7462 if (events >= wakeup_events) {
7463 local_sub(wakeup_events, &rb->events);
7464 local_inc(&rb->wakeup);
7470 static u64 perf_virt_to_phys(u64 virt)
7477 if (virt >= TASK_SIZE) {
7478 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7479 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7480 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7481 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7484 * Walking the pages tables for user address.
7485 * Interrupts are disabled, so it prevents any tear down
7486 * of the page tables.
7487 * Try IRQ-safe get_user_page_fast_only first.
7488 * If failed, leave phys_addr as 0.
7490 if (current->mm != NULL) {
7493 pagefault_disable();
7494 if (get_user_page_fast_only(virt, 0, &p)) {
7495 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7506 * Return the pagetable size of a given virtual address.
7508 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7512 #ifdef CONFIG_HAVE_FAST_GUP
7519 pgdp = pgd_offset(mm, addr);
7520 pgd = READ_ONCE(*pgdp);
7525 return pgd_leaf_size(pgd);
7527 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7528 p4d = READ_ONCE(*p4dp);
7529 if (!p4d_present(p4d))
7533 return p4d_leaf_size(p4d);
7535 pudp = pud_offset_lockless(p4dp, p4d, addr);
7536 pud = READ_ONCE(*pudp);
7537 if (!pud_present(pud))
7541 return pud_leaf_size(pud);
7543 pmdp = pmd_offset_lockless(pudp, pud, addr);
7545 pmd = pmdp_get_lockless(pmdp);
7546 if (!pmd_present(pmd))
7550 return pmd_leaf_size(pmd);
7552 ptep = pte_offset_map(&pmd, addr);
7556 pte = ptep_get_lockless(ptep);
7557 if (pte_present(pte))
7558 size = pte_leaf_size(pte);
7560 #endif /* CONFIG_HAVE_FAST_GUP */
7565 static u64 perf_get_page_size(unsigned long addr)
7567 struct mm_struct *mm;
7568 unsigned long flags;
7575 * Software page-table walkers must disable IRQs,
7576 * which prevents any tear down of the page tables.
7578 local_irq_save(flags);
7583 * For kernel threads and the like, use init_mm so that
7584 * we can find kernel memory.
7589 size = perf_get_pgtable_size(mm, addr);
7591 local_irq_restore(flags);
7596 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7598 struct perf_callchain_entry *
7599 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7601 bool kernel = !event->attr.exclude_callchain_kernel;
7602 bool user = !event->attr.exclude_callchain_user;
7603 /* Disallow cross-task user callchains. */
7604 bool crosstask = event->ctx->task && event->ctx->task != current;
7605 const u32 max_stack = event->attr.sample_max_stack;
7606 struct perf_callchain_entry *callchain;
7608 if (!kernel && !user)
7609 return &__empty_callchain;
7611 callchain = get_perf_callchain(regs, 0, kernel, user,
7612 max_stack, crosstask, true);
7613 return callchain ?: &__empty_callchain;
7616 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
7618 return d * !!(flags & s);
7621 void perf_prepare_sample(struct perf_sample_data *data,
7622 struct perf_event *event,
7623 struct pt_regs *regs)
7625 u64 sample_type = event->attr.sample_type;
7626 u64 filtered_sample_type;
7629 * Add the sample flags that are dependent to others. And clear the
7630 * sample flags that have already been done by the PMU driver.
7632 filtered_sample_type = sample_type;
7633 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
7635 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
7636 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
7637 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
7638 PERF_SAMPLE_REGS_USER);
7639 filtered_sample_type &= ~data->sample_flags;
7641 if (filtered_sample_type == 0) {
7642 /* Make sure it has the correct data->type for output */
7643 data->type = event->attr.sample_type;
7647 __perf_event_header__init_id(data, event, filtered_sample_type);
7649 if (filtered_sample_type & PERF_SAMPLE_IP) {
7650 data->ip = perf_instruction_pointer(regs);
7651 data->sample_flags |= PERF_SAMPLE_IP;
7654 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7655 perf_sample_save_callchain(data, event, regs);
7657 if (filtered_sample_type & PERF_SAMPLE_RAW) {
7659 data->dyn_size += sizeof(u64);
7660 data->sample_flags |= PERF_SAMPLE_RAW;
7663 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
7664 data->br_stack = NULL;
7665 data->dyn_size += sizeof(u64);
7666 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
7669 if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
7670 perf_sample_regs_user(&data->regs_user, regs);
7673 * It cannot use the filtered_sample_type here as REGS_USER can be set
7674 * by STACK_USER (using __cond_set() above) and we don't want to update
7675 * the dyn_size if it's not requested by users.
7677 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
7678 /* regs dump ABI info */
7679 int size = sizeof(u64);
7681 if (data->regs_user.regs) {
7682 u64 mask = event->attr.sample_regs_user;
7683 size += hweight64(mask) * sizeof(u64);
7686 data->dyn_size += size;
7687 data->sample_flags |= PERF_SAMPLE_REGS_USER;
7690 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
7692 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7693 * processed as the last one or have additional check added
7694 * in case new sample type is added, because we could eat
7695 * up the rest of the sample size.
7697 u16 stack_size = event->attr.sample_stack_user;
7698 u16 header_size = perf_sample_data_size(data, event);
7699 u16 size = sizeof(u64);
7701 stack_size = perf_sample_ustack_size(stack_size, header_size,
7702 data->regs_user.regs);
7705 * If there is something to dump, add space for the dump
7706 * itself and for the field that tells the dynamic size,
7707 * which is how many have been actually dumped.
7710 size += sizeof(u64) + stack_size;
7712 data->stack_user_size = stack_size;
7713 data->dyn_size += size;
7714 data->sample_flags |= PERF_SAMPLE_STACK_USER;
7717 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
7718 data->weight.full = 0;
7719 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
7722 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
7723 data->data_src.val = PERF_MEM_NA;
7724 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
7727 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
7729 data->sample_flags |= PERF_SAMPLE_TRANSACTION;
7732 if (filtered_sample_type & PERF_SAMPLE_ADDR) {
7734 data->sample_flags |= PERF_SAMPLE_ADDR;
7737 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
7738 /* regs dump ABI info */
7739 int size = sizeof(u64);
7741 perf_sample_regs_intr(&data->regs_intr, regs);
7743 if (data->regs_intr.regs) {
7744 u64 mask = event->attr.sample_regs_intr;
7746 size += hweight64(mask) * sizeof(u64);
7749 data->dyn_size += size;
7750 data->sample_flags |= PERF_SAMPLE_REGS_INTR;
7753 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
7754 data->phys_addr = perf_virt_to_phys(data->addr);
7755 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
7758 #ifdef CONFIG_CGROUP_PERF
7759 if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
7760 struct cgroup *cgrp;
7762 /* protected by RCU */
7763 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7764 data->cgroup = cgroup_id(cgrp);
7765 data->sample_flags |= PERF_SAMPLE_CGROUP;
7770 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7771 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7772 * but the value will not dump to the userspace.
7774 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
7775 data->data_page_size = perf_get_page_size(data->addr);
7776 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
7779 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
7780 data->code_page_size = perf_get_page_size(data->ip);
7781 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
7784 if (filtered_sample_type & PERF_SAMPLE_AUX) {
7786 u16 header_size = perf_sample_data_size(data, event);
7788 header_size += sizeof(u64); /* size */
7791 * Given the 16bit nature of header::size, an AUX sample can
7792 * easily overflow it, what with all the preceding sample bits.
7793 * Make sure this doesn't happen by using up to U16_MAX bytes
7794 * per sample in total (rounded down to 8 byte boundary).
7796 size = min_t(size_t, U16_MAX - header_size,
7797 event->attr.aux_sample_size);
7798 size = rounddown(size, 8);
7799 size = perf_prepare_sample_aux(event, data, size);
7801 WARN_ON_ONCE(size + header_size > U16_MAX);
7802 data->dyn_size += size + sizeof(u64); /* size above */
7803 data->sample_flags |= PERF_SAMPLE_AUX;
7807 void perf_prepare_header(struct perf_event_header *header,
7808 struct perf_sample_data *data,
7809 struct perf_event *event,
7810 struct pt_regs *regs)
7812 header->type = PERF_RECORD_SAMPLE;
7813 header->size = perf_sample_data_size(data, event);
7814 header->misc = perf_misc_flags(regs);
7817 * If you're adding more sample types here, you likely need to do
7818 * something about the overflowing header::size, like repurpose the
7819 * lowest 3 bits of size, which should be always zero at the moment.
7820 * This raises a more important question, do we really need 512k sized
7821 * samples and why, so good argumentation is in order for whatever you
7824 WARN_ON_ONCE(header->size & 7);
7827 static __always_inline int
7828 __perf_event_output(struct perf_event *event,
7829 struct perf_sample_data *data,
7830 struct pt_regs *regs,
7831 int (*output_begin)(struct perf_output_handle *,
7832 struct perf_sample_data *,
7833 struct perf_event *,
7836 struct perf_output_handle handle;
7837 struct perf_event_header header;
7840 /* protect the callchain buffers */
7843 perf_prepare_sample(data, event, regs);
7844 perf_prepare_header(&header, data, event, regs);
7846 err = output_begin(&handle, data, event, header.size);
7850 perf_output_sample(&handle, &header, data, event);
7852 perf_output_end(&handle);
7860 perf_event_output_forward(struct perf_event *event,
7861 struct perf_sample_data *data,
7862 struct pt_regs *regs)
7864 __perf_event_output(event, data, regs, perf_output_begin_forward);
7868 perf_event_output_backward(struct perf_event *event,
7869 struct perf_sample_data *data,
7870 struct pt_regs *regs)
7872 __perf_event_output(event, data, regs, perf_output_begin_backward);
7876 perf_event_output(struct perf_event *event,
7877 struct perf_sample_data *data,
7878 struct pt_regs *regs)
7880 return __perf_event_output(event, data, regs, perf_output_begin);
7887 struct perf_read_event {
7888 struct perf_event_header header;
7895 perf_event_read_event(struct perf_event *event,
7896 struct task_struct *task)
7898 struct perf_output_handle handle;
7899 struct perf_sample_data sample;
7900 struct perf_read_event read_event = {
7902 .type = PERF_RECORD_READ,
7904 .size = sizeof(read_event) + event->read_size,
7906 .pid = perf_event_pid(event, task),
7907 .tid = perf_event_tid(event, task),
7911 perf_event_header__init_id(&read_event.header, &sample, event);
7912 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7916 perf_output_put(&handle, read_event);
7917 perf_output_read(&handle, event);
7918 perf_event__output_id_sample(event, &handle, &sample);
7920 perf_output_end(&handle);
7923 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7926 perf_iterate_ctx(struct perf_event_context *ctx,
7927 perf_iterate_f output,
7928 void *data, bool all)
7930 struct perf_event *event;
7932 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7934 if (event->state < PERF_EVENT_STATE_INACTIVE)
7936 if (!event_filter_match(event))
7940 output(event, data);
7944 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7946 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7947 struct perf_event *event;
7949 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7951 * Skip events that are not fully formed yet; ensure that
7952 * if we observe event->ctx, both event and ctx will be
7953 * complete enough. See perf_install_in_context().
7955 if (!smp_load_acquire(&event->ctx))
7958 if (event->state < PERF_EVENT_STATE_INACTIVE)
7960 if (!event_filter_match(event))
7962 output(event, data);
7967 * Iterate all events that need to receive side-band events.
7969 * For new callers; ensure that account_pmu_sb_event() includes
7970 * your event, otherwise it might not get delivered.
7973 perf_iterate_sb(perf_iterate_f output, void *data,
7974 struct perf_event_context *task_ctx)
7976 struct perf_event_context *ctx;
7982 * If we have task_ctx != NULL we only notify the task context itself.
7983 * The task_ctx is set only for EXIT events before releasing task
7987 perf_iterate_ctx(task_ctx, output, data, false);
7991 perf_iterate_sb_cpu(output, data);
7993 ctx = rcu_dereference(current->perf_event_ctxp);
7995 perf_iterate_ctx(ctx, output, data, false);
8002 * Clear all file-based filters at exec, they'll have to be
8003 * re-instated when/if these objects are mmapped again.
8005 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
8007 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8008 struct perf_addr_filter *filter;
8009 unsigned int restart = 0, count = 0;
8010 unsigned long flags;
8012 if (!has_addr_filter(event))
8015 raw_spin_lock_irqsave(&ifh->lock, flags);
8016 list_for_each_entry(filter, &ifh->list, entry) {
8017 if (filter->path.dentry) {
8018 event->addr_filter_ranges[count].start = 0;
8019 event->addr_filter_ranges[count].size = 0;
8027 event->addr_filters_gen++;
8028 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8031 perf_event_stop(event, 1);
8034 void perf_event_exec(void)
8036 struct perf_event_context *ctx;
8038 ctx = perf_pin_task_context(current);
8042 perf_event_enable_on_exec(ctx);
8043 perf_event_remove_on_exec(ctx);
8044 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
8046 perf_unpin_context(ctx);
8050 struct remote_output {
8051 struct perf_buffer *rb;
8055 static void __perf_event_output_stop(struct perf_event *event, void *data)
8057 struct perf_event *parent = event->parent;
8058 struct remote_output *ro = data;
8059 struct perf_buffer *rb = ro->rb;
8060 struct stop_event_data sd = {
8064 if (!has_aux(event))
8071 * In case of inheritance, it will be the parent that links to the
8072 * ring-buffer, but it will be the child that's actually using it.
8074 * We are using event::rb to determine if the event should be stopped,
8075 * however this may race with ring_buffer_attach() (through set_output),
8076 * which will make us skip the event that actually needs to be stopped.
8077 * So ring_buffer_attach() has to stop an aux event before re-assigning
8080 if (rcu_dereference(parent->rb) == rb)
8081 ro->err = __perf_event_stop(&sd);
8084 static int __perf_pmu_output_stop(void *info)
8086 struct perf_event *event = info;
8087 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
8088 struct remote_output ro = {
8093 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
8094 if (cpuctx->task_ctx)
8095 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
8102 static void perf_pmu_output_stop(struct perf_event *event)
8104 struct perf_event *iter;
8109 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8111 * For per-CPU events, we need to make sure that neither they
8112 * nor their children are running; for cpu==-1 events it's
8113 * sufficient to stop the event itself if it's active, since
8114 * it can't have children.
8118 cpu = READ_ONCE(iter->oncpu);
8123 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8124 if (err == -EAGAIN) {
8133 * task tracking -- fork/exit
8135 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8138 struct perf_task_event {
8139 struct task_struct *task;
8140 struct perf_event_context *task_ctx;
8143 struct perf_event_header header;
8153 static int perf_event_task_match(struct perf_event *event)
8155 return event->attr.comm || event->attr.mmap ||
8156 event->attr.mmap2 || event->attr.mmap_data ||
8160 static void perf_event_task_output(struct perf_event *event,
8163 struct perf_task_event *task_event = data;
8164 struct perf_output_handle handle;
8165 struct perf_sample_data sample;
8166 struct task_struct *task = task_event->task;
8167 int ret, size = task_event->event_id.header.size;
8169 if (!perf_event_task_match(event))
8172 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8174 ret = perf_output_begin(&handle, &sample, event,
8175 task_event->event_id.header.size);
8179 task_event->event_id.pid = perf_event_pid(event, task);
8180 task_event->event_id.tid = perf_event_tid(event, task);
8182 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8183 task_event->event_id.ppid = perf_event_pid(event,
8185 task_event->event_id.ptid = perf_event_pid(event,
8187 } else { /* PERF_RECORD_FORK */
8188 task_event->event_id.ppid = perf_event_pid(event, current);
8189 task_event->event_id.ptid = perf_event_tid(event, current);
8192 task_event->event_id.time = perf_event_clock(event);
8194 perf_output_put(&handle, task_event->event_id);
8196 perf_event__output_id_sample(event, &handle, &sample);
8198 perf_output_end(&handle);
8200 task_event->event_id.header.size = size;
8203 static void perf_event_task(struct task_struct *task,
8204 struct perf_event_context *task_ctx,
8207 struct perf_task_event task_event;
8209 if (!atomic_read(&nr_comm_events) &&
8210 !atomic_read(&nr_mmap_events) &&
8211 !atomic_read(&nr_task_events))
8214 task_event = (struct perf_task_event){
8216 .task_ctx = task_ctx,
8219 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8221 .size = sizeof(task_event.event_id),
8231 perf_iterate_sb(perf_event_task_output,
8236 void perf_event_fork(struct task_struct *task)
8238 perf_event_task(task, NULL, 1);
8239 perf_event_namespaces(task);
8246 struct perf_comm_event {
8247 struct task_struct *task;
8252 struct perf_event_header header;
8259 static int perf_event_comm_match(struct perf_event *event)
8261 return event->attr.comm;
8264 static void perf_event_comm_output(struct perf_event *event,
8267 struct perf_comm_event *comm_event = data;
8268 struct perf_output_handle handle;
8269 struct perf_sample_data sample;
8270 int size = comm_event->event_id.header.size;
8273 if (!perf_event_comm_match(event))
8276 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8277 ret = perf_output_begin(&handle, &sample, event,
8278 comm_event->event_id.header.size);
8283 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8284 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8286 perf_output_put(&handle, comm_event->event_id);
8287 __output_copy(&handle, comm_event->comm,
8288 comm_event->comm_size);
8290 perf_event__output_id_sample(event, &handle, &sample);
8292 perf_output_end(&handle);
8294 comm_event->event_id.header.size = size;
8297 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8299 char comm[TASK_COMM_LEN];
8302 memset(comm, 0, sizeof(comm));
8303 strscpy(comm, comm_event->task->comm, sizeof(comm));
8304 size = ALIGN(strlen(comm)+1, sizeof(u64));
8306 comm_event->comm = comm;
8307 comm_event->comm_size = size;
8309 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8311 perf_iterate_sb(perf_event_comm_output,
8316 void perf_event_comm(struct task_struct *task, bool exec)
8318 struct perf_comm_event comm_event;
8320 if (!atomic_read(&nr_comm_events))
8323 comm_event = (struct perf_comm_event){
8329 .type = PERF_RECORD_COMM,
8330 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8338 perf_event_comm_event(&comm_event);
8342 * namespaces tracking
8345 struct perf_namespaces_event {
8346 struct task_struct *task;
8349 struct perf_event_header header;
8354 struct perf_ns_link_info link_info[NR_NAMESPACES];
8358 static int perf_event_namespaces_match(struct perf_event *event)
8360 return event->attr.namespaces;
8363 static void perf_event_namespaces_output(struct perf_event *event,
8366 struct perf_namespaces_event *namespaces_event = data;
8367 struct perf_output_handle handle;
8368 struct perf_sample_data sample;
8369 u16 header_size = namespaces_event->event_id.header.size;
8372 if (!perf_event_namespaces_match(event))
8375 perf_event_header__init_id(&namespaces_event->event_id.header,
8377 ret = perf_output_begin(&handle, &sample, event,
8378 namespaces_event->event_id.header.size);
8382 namespaces_event->event_id.pid = perf_event_pid(event,
8383 namespaces_event->task);
8384 namespaces_event->event_id.tid = perf_event_tid(event,
8385 namespaces_event->task);
8387 perf_output_put(&handle, namespaces_event->event_id);
8389 perf_event__output_id_sample(event, &handle, &sample);
8391 perf_output_end(&handle);
8393 namespaces_event->event_id.header.size = header_size;
8396 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8397 struct task_struct *task,
8398 const struct proc_ns_operations *ns_ops)
8400 struct path ns_path;
8401 struct inode *ns_inode;
8404 error = ns_get_path(&ns_path, task, ns_ops);
8406 ns_inode = ns_path.dentry->d_inode;
8407 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8408 ns_link_info->ino = ns_inode->i_ino;
8413 void perf_event_namespaces(struct task_struct *task)
8415 struct perf_namespaces_event namespaces_event;
8416 struct perf_ns_link_info *ns_link_info;
8418 if (!atomic_read(&nr_namespaces_events))
8421 namespaces_event = (struct perf_namespaces_event){
8425 .type = PERF_RECORD_NAMESPACES,
8427 .size = sizeof(namespaces_event.event_id),
8431 .nr_namespaces = NR_NAMESPACES,
8432 /* .link_info[NR_NAMESPACES] */
8436 ns_link_info = namespaces_event.event_id.link_info;
8438 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8439 task, &mntns_operations);
8441 #ifdef CONFIG_USER_NS
8442 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8443 task, &userns_operations);
8445 #ifdef CONFIG_NET_NS
8446 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8447 task, &netns_operations);
8449 #ifdef CONFIG_UTS_NS
8450 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8451 task, &utsns_operations);
8453 #ifdef CONFIG_IPC_NS
8454 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8455 task, &ipcns_operations);
8457 #ifdef CONFIG_PID_NS
8458 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8459 task, &pidns_operations);
8461 #ifdef CONFIG_CGROUPS
8462 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8463 task, &cgroupns_operations);
8466 perf_iterate_sb(perf_event_namespaces_output,
8474 #ifdef CONFIG_CGROUP_PERF
8476 struct perf_cgroup_event {
8480 struct perf_event_header header;
8486 static int perf_event_cgroup_match(struct perf_event *event)
8488 return event->attr.cgroup;
8491 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8493 struct perf_cgroup_event *cgroup_event = data;
8494 struct perf_output_handle handle;
8495 struct perf_sample_data sample;
8496 u16 header_size = cgroup_event->event_id.header.size;
8499 if (!perf_event_cgroup_match(event))
8502 perf_event_header__init_id(&cgroup_event->event_id.header,
8504 ret = perf_output_begin(&handle, &sample, event,
8505 cgroup_event->event_id.header.size);
8509 perf_output_put(&handle, cgroup_event->event_id);
8510 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8512 perf_event__output_id_sample(event, &handle, &sample);
8514 perf_output_end(&handle);
8516 cgroup_event->event_id.header.size = header_size;
8519 static void perf_event_cgroup(struct cgroup *cgrp)
8521 struct perf_cgroup_event cgroup_event;
8522 char path_enomem[16] = "//enomem";
8526 if (!atomic_read(&nr_cgroup_events))
8529 cgroup_event = (struct perf_cgroup_event){
8532 .type = PERF_RECORD_CGROUP,
8534 .size = sizeof(cgroup_event.event_id),
8536 .id = cgroup_id(cgrp),
8540 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8541 if (pathname == NULL) {
8542 cgroup_event.path = path_enomem;
8544 /* just to be sure to have enough space for alignment */
8545 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8546 cgroup_event.path = pathname;
8550 * Since our buffer works in 8 byte units we need to align our string
8551 * size to a multiple of 8. However, we must guarantee the tail end is
8552 * zero'd out to avoid leaking random bits to userspace.
8554 size = strlen(cgroup_event.path) + 1;
8555 while (!IS_ALIGNED(size, sizeof(u64)))
8556 cgroup_event.path[size++] = '\0';
8558 cgroup_event.event_id.header.size += size;
8559 cgroup_event.path_size = size;
8561 perf_iterate_sb(perf_event_cgroup_output,
8574 struct perf_mmap_event {
8575 struct vm_area_struct *vma;
8577 const char *file_name;
8583 u8 build_id[BUILD_ID_SIZE_MAX];
8587 struct perf_event_header header;
8597 static int perf_event_mmap_match(struct perf_event *event,
8600 struct perf_mmap_event *mmap_event = data;
8601 struct vm_area_struct *vma = mmap_event->vma;
8602 int executable = vma->vm_flags & VM_EXEC;
8604 return (!executable && event->attr.mmap_data) ||
8605 (executable && (event->attr.mmap || event->attr.mmap2));
8608 static void perf_event_mmap_output(struct perf_event *event,
8611 struct perf_mmap_event *mmap_event = data;
8612 struct perf_output_handle handle;
8613 struct perf_sample_data sample;
8614 int size = mmap_event->event_id.header.size;
8615 u32 type = mmap_event->event_id.header.type;
8619 if (!perf_event_mmap_match(event, data))
8622 if (event->attr.mmap2) {
8623 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8624 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8625 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8626 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8627 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8628 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8629 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8632 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8633 ret = perf_output_begin(&handle, &sample, event,
8634 mmap_event->event_id.header.size);
8638 mmap_event->event_id.pid = perf_event_pid(event, current);
8639 mmap_event->event_id.tid = perf_event_tid(event, current);
8641 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8643 if (event->attr.mmap2 && use_build_id)
8644 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8646 perf_output_put(&handle, mmap_event->event_id);
8648 if (event->attr.mmap2) {
8650 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8652 __output_copy(&handle, size, 4);
8653 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8655 perf_output_put(&handle, mmap_event->maj);
8656 perf_output_put(&handle, mmap_event->min);
8657 perf_output_put(&handle, mmap_event->ino);
8658 perf_output_put(&handle, mmap_event->ino_generation);
8660 perf_output_put(&handle, mmap_event->prot);
8661 perf_output_put(&handle, mmap_event->flags);
8664 __output_copy(&handle, mmap_event->file_name,
8665 mmap_event->file_size);
8667 perf_event__output_id_sample(event, &handle, &sample);
8669 perf_output_end(&handle);
8671 mmap_event->event_id.header.size = size;
8672 mmap_event->event_id.header.type = type;
8675 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8677 struct vm_area_struct *vma = mmap_event->vma;
8678 struct file *file = vma->vm_file;
8679 int maj = 0, min = 0;
8680 u64 ino = 0, gen = 0;
8681 u32 prot = 0, flags = 0;
8687 if (vma->vm_flags & VM_READ)
8689 if (vma->vm_flags & VM_WRITE)
8691 if (vma->vm_flags & VM_EXEC)
8694 if (vma->vm_flags & VM_MAYSHARE)
8697 flags = MAP_PRIVATE;
8699 if (vma->vm_flags & VM_LOCKED)
8700 flags |= MAP_LOCKED;
8701 if (is_vm_hugetlb_page(vma))
8702 flags |= MAP_HUGETLB;
8705 struct inode *inode;
8708 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8714 * d_path() works from the end of the rb backwards, so we
8715 * need to add enough zero bytes after the string to handle
8716 * the 64bit alignment we do later.
8718 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8723 inode = file_inode(vma->vm_file);
8724 dev = inode->i_sb->s_dev;
8726 gen = inode->i_generation;
8732 if (vma->vm_ops && vma->vm_ops->name)
8733 name = (char *) vma->vm_ops->name(vma);
8735 name = (char *)arch_vma_name(vma);
8737 if (vma_is_initial_heap(vma))
8739 else if (vma_is_initial_stack(vma))
8747 strscpy(tmp, name, sizeof(tmp));
8751 * Since our buffer works in 8 byte units we need to align our string
8752 * size to a multiple of 8. However, we must guarantee the tail end is
8753 * zero'd out to avoid leaking random bits to userspace.
8755 size = strlen(name)+1;
8756 while (!IS_ALIGNED(size, sizeof(u64)))
8757 name[size++] = '\0';
8759 mmap_event->file_name = name;
8760 mmap_event->file_size = size;
8761 mmap_event->maj = maj;
8762 mmap_event->min = min;
8763 mmap_event->ino = ino;
8764 mmap_event->ino_generation = gen;
8765 mmap_event->prot = prot;
8766 mmap_event->flags = flags;
8768 if (!(vma->vm_flags & VM_EXEC))
8769 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8771 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8773 if (atomic_read(&nr_build_id_events))
8774 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8776 perf_iterate_sb(perf_event_mmap_output,
8784 * Check whether inode and address range match filter criteria.
8786 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8787 struct file *file, unsigned long offset,
8790 /* d_inode(NULL) won't be equal to any mapped user-space file */
8791 if (!filter->path.dentry)
8794 if (d_inode(filter->path.dentry) != file_inode(file))
8797 if (filter->offset > offset + size)
8800 if (filter->offset + filter->size < offset)
8806 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8807 struct vm_area_struct *vma,
8808 struct perf_addr_filter_range *fr)
8810 unsigned long vma_size = vma->vm_end - vma->vm_start;
8811 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8812 struct file *file = vma->vm_file;
8814 if (!perf_addr_filter_match(filter, file, off, vma_size))
8817 if (filter->offset < off) {
8818 fr->start = vma->vm_start;
8819 fr->size = min(vma_size, filter->size - (off - filter->offset));
8821 fr->start = vma->vm_start + filter->offset - off;
8822 fr->size = min(vma->vm_end - fr->start, filter->size);
8828 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8830 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8831 struct vm_area_struct *vma = data;
8832 struct perf_addr_filter *filter;
8833 unsigned int restart = 0, count = 0;
8834 unsigned long flags;
8836 if (!has_addr_filter(event))
8842 raw_spin_lock_irqsave(&ifh->lock, flags);
8843 list_for_each_entry(filter, &ifh->list, entry) {
8844 if (perf_addr_filter_vma_adjust(filter, vma,
8845 &event->addr_filter_ranges[count]))
8852 event->addr_filters_gen++;
8853 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8856 perf_event_stop(event, 1);
8860 * Adjust all task's events' filters to the new vma
8862 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8864 struct perf_event_context *ctx;
8867 * Data tracing isn't supported yet and as such there is no need
8868 * to keep track of anything that isn't related to executable code:
8870 if (!(vma->vm_flags & VM_EXEC))
8874 ctx = rcu_dereference(current->perf_event_ctxp);
8876 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8880 void perf_event_mmap(struct vm_area_struct *vma)
8882 struct perf_mmap_event mmap_event;
8884 if (!atomic_read(&nr_mmap_events))
8887 mmap_event = (struct perf_mmap_event){
8893 .type = PERF_RECORD_MMAP,
8894 .misc = PERF_RECORD_MISC_USER,
8899 .start = vma->vm_start,
8900 .len = vma->vm_end - vma->vm_start,
8901 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8903 /* .maj (attr_mmap2 only) */
8904 /* .min (attr_mmap2 only) */
8905 /* .ino (attr_mmap2 only) */
8906 /* .ino_generation (attr_mmap2 only) */
8907 /* .prot (attr_mmap2 only) */
8908 /* .flags (attr_mmap2 only) */
8911 perf_addr_filters_adjust(vma);
8912 perf_event_mmap_event(&mmap_event);
8915 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8916 unsigned long size, u64 flags)
8918 struct perf_output_handle handle;
8919 struct perf_sample_data sample;
8920 struct perf_aux_event {
8921 struct perf_event_header header;
8927 .type = PERF_RECORD_AUX,
8929 .size = sizeof(rec),
8937 perf_event_header__init_id(&rec.header, &sample, event);
8938 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8943 perf_output_put(&handle, rec);
8944 perf_event__output_id_sample(event, &handle, &sample);
8946 perf_output_end(&handle);
8950 * Lost/dropped samples logging
8952 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8954 struct perf_output_handle handle;
8955 struct perf_sample_data sample;
8959 struct perf_event_header header;
8961 } lost_samples_event = {
8963 .type = PERF_RECORD_LOST_SAMPLES,
8965 .size = sizeof(lost_samples_event),
8970 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8972 ret = perf_output_begin(&handle, &sample, event,
8973 lost_samples_event.header.size);
8977 perf_output_put(&handle, lost_samples_event);
8978 perf_event__output_id_sample(event, &handle, &sample);
8979 perf_output_end(&handle);
8983 * context_switch tracking
8986 struct perf_switch_event {
8987 struct task_struct *task;
8988 struct task_struct *next_prev;
8991 struct perf_event_header header;
8997 static int perf_event_switch_match(struct perf_event *event)
8999 return event->attr.context_switch;
9002 static void perf_event_switch_output(struct perf_event *event, void *data)
9004 struct perf_switch_event *se = data;
9005 struct perf_output_handle handle;
9006 struct perf_sample_data sample;
9009 if (!perf_event_switch_match(event))
9012 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9013 if (event->ctx->task) {
9014 se->event_id.header.type = PERF_RECORD_SWITCH;
9015 se->event_id.header.size = sizeof(se->event_id.header);
9017 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
9018 se->event_id.header.size = sizeof(se->event_id);
9019 se->event_id.next_prev_pid =
9020 perf_event_pid(event, se->next_prev);
9021 se->event_id.next_prev_tid =
9022 perf_event_tid(event, se->next_prev);
9025 perf_event_header__init_id(&se->event_id.header, &sample, event);
9027 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
9031 if (event->ctx->task)
9032 perf_output_put(&handle, se->event_id.header);
9034 perf_output_put(&handle, se->event_id);
9036 perf_event__output_id_sample(event, &handle, &sample);
9038 perf_output_end(&handle);
9041 static void perf_event_switch(struct task_struct *task,
9042 struct task_struct *next_prev, bool sched_in)
9044 struct perf_switch_event switch_event;
9046 /* N.B. caller checks nr_switch_events != 0 */
9048 switch_event = (struct perf_switch_event){
9050 .next_prev = next_prev,
9054 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
9057 /* .next_prev_pid */
9058 /* .next_prev_tid */
9062 if (!sched_in && task->on_rq) {
9063 switch_event.event_id.header.misc |=
9064 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
9067 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
9071 * IRQ throttle logging
9074 static void perf_log_throttle(struct perf_event *event, int enable)
9076 struct perf_output_handle handle;
9077 struct perf_sample_data sample;
9081 struct perf_event_header header;
9085 } throttle_event = {
9087 .type = PERF_RECORD_THROTTLE,
9089 .size = sizeof(throttle_event),
9091 .time = perf_event_clock(event),
9092 .id = primary_event_id(event),
9093 .stream_id = event->id,
9097 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9099 perf_event_header__init_id(&throttle_event.header, &sample, event);
9101 ret = perf_output_begin(&handle, &sample, event,
9102 throttle_event.header.size);
9106 perf_output_put(&handle, throttle_event);
9107 perf_event__output_id_sample(event, &handle, &sample);
9108 perf_output_end(&handle);
9112 * ksymbol register/unregister tracking
9115 struct perf_ksymbol_event {
9119 struct perf_event_header header;
9127 static int perf_event_ksymbol_match(struct perf_event *event)
9129 return event->attr.ksymbol;
9132 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9134 struct perf_ksymbol_event *ksymbol_event = data;
9135 struct perf_output_handle handle;
9136 struct perf_sample_data sample;
9139 if (!perf_event_ksymbol_match(event))
9142 perf_event_header__init_id(&ksymbol_event->event_id.header,
9144 ret = perf_output_begin(&handle, &sample, event,
9145 ksymbol_event->event_id.header.size);
9149 perf_output_put(&handle, ksymbol_event->event_id);
9150 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9151 perf_event__output_id_sample(event, &handle, &sample);
9153 perf_output_end(&handle);
9156 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9159 struct perf_ksymbol_event ksymbol_event;
9160 char name[KSYM_NAME_LEN];
9164 if (!atomic_read(&nr_ksymbol_events))
9167 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9168 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9171 strscpy(name, sym, KSYM_NAME_LEN);
9172 name_len = strlen(name) + 1;
9173 while (!IS_ALIGNED(name_len, sizeof(u64)))
9174 name[name_len++] = '\0';
9175 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9178 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9180 ksymbol_event = (struct perf_ksymbol_event){
9182 .name_len = name_len,
9185 .type = PERF_RECORD_KSYMBOL,
9186 .size = sizeof(ksymbol_event.event_id) +
9191 .ksym_type = ksym_type,
9196 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9199 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9203 * bpf program load/unload tracking
9206 struct perf_bpf_event {
9207 struct bpf_prog *prog;
9209 struct perf_event_header header;
9213 u8 tag[BPF_TAG_SIZE];
9217 static int perf_event_bpf_match(struct perf_event *event)
9219 return event->attr.bpf_event;
9222 static void perf_event_bpf_output(struct perf_event *event, void *data)
9224 struct perf_bpf_event *bpf_event = data;
9225 struct perf_output_handle handle;
9226 struct perf_sample_data sample;
9229 if (!perf_event_bpf_match(event))
9232 perf_event_header__init_id(&bpf_event->event_id.header,
9234 ret = perf_output_begin(&handle, &sample, event,
9235 bpf_event->event_id.header.size);
9239 perf_output_put(&handle, bpf_event->event_id);
9240 perf_event__output_id_sample(event, &handle, &sample);
9242 perf_output_end(&handle);
9245 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9246 enum perf_bpf_event_type type)
9248 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9251 if (prog->aux->func_cnt == 0) {
9252 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9253 (u64)(unsigned long)prog->bpf_func,
9254 prog->jited_len, unregister,
9255 prog->aux->ksym.name);
9257 for (i = 0; i < prog->aux->func_cnt; i++) {
9258 struct bpf_prog *subprog = prog->aux->func[i];
9261 PERF_RECORD_KSYMBOL_TYPE_BPF,
9262 (u64)(unsigned long)subprog->bpf_func,
9263 subprog->jited_len, unregister,
9264 subprog->aux->ksym.name);
9269 void perf_event_bpf_event(struct bpf_prog *prog,
9270 enum perf_bpf_event_type type,
9273 struct perf_bpf_event bpf_event;
9275 if (type <= PERF_BPF_EVENT_UNKNOWN ||
9276 type >= PERF_BPF_EVENT_MAX)
9280 case PERF_BPF_EVENT_PROG_LOAD:
9281 case PERF_BPF_EVENT_PROG_UNLOAD:
9282 if (atomic_read(&nr_ksymbol_events))
9283 perf_event_bpf_emit_ksymbols(prog, type);
9289 if (!atomic_read(&nr_bpf_events))
9292 bpf_event = (struct perf_bpf_event){
9296 .type = PERF_RECORD_BPF_EVENT,
9297 .size = sizeof(bpf_event.event_id),
9301 .id = prog->aux->id,
9305 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9307 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9308 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9311 struct perf_text_poke_event {
9312 const void *old_bytes;
9313 const void *new_bytes;
9319 struct perf_event_header header;
9325 static int perf_event_text_poke_match(struct perf_event *event)
9327 return event->attr.text_poke;
9330 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9332 struct perf_text_poke_event *text_poke_event = data;
9333 struct perf_output_handle handle;
9334 struct perf_sample_data sample;
9338 if (!perf_event_text_poke_match(event))
9341 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9343 ret = perf_output_begin(&handle, &sample, event,
9344 text_poke_event->event_id.header.size);
9348 perf_output_put(&handle, text_poke_event->event_id);
9349 perf_output_put(&handle, text_poke_event->old_len);
9350 perf_output_put(&handle, text_poke_event->new_len);
9352 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9353 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9355 if (text_poke_event->pad)
9356 __output_copy(&handle, &padding, text_poke_event->pad);
9358 perf_event__output_id_sample(event, &handle, &sample);
9360 perf_output_end(&handle);
9363 void perf_event_text_poke(const void *addr, const void *old_bytes,
9364 size_t old_len, const void *new_bytes, size_t new_len)
9366 struct perf_text_poke_event text_poke_event;
9369 if (!atomic_read(&nr_text_poke_events))
9372 tot = sizeof(text_poke_event.old_len) + old_len;
9373 tot += sizeof(text_poke_event.new_len) + new_len;
9374 pad = ALIGN(tot, sizeof(u64)) - tot;
9376 text_poke_event = (struct perf_text_poke_event){
9377 .old_bytes = old_bytes,
9378 .new_bytes = new_bytes,
9384 .type = PERF_RECORD_TEXT_POKE,
9385 .misc = PERF_RECORD_MISC_KERNEL,
9386 .size = sizeof(text_poke_event.event_id) + tot + pad,
9388 .addr = (unsigned long)addr,
9392 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9395 void perf_event_itrace_started(struct perf_event *event)
9397 event->attach_state |= PERF_ATTACH_ITRACE;
9400 static void perf_log_itrace_start(struct perf_event *event)
9402 struct perf_output_handle handle;
9403 struct perf_sample_data sample;
9404 struct perf_aux_event {
9405 struct perf_event_header header;
9412 event = event->parent;
9414 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9415 event->attach_state & PERF_ATTACH_ITRACE)
9418 rec.header.type = PERF_RECORD_ITRACE_START;
9419 rec.header.misc = 0;
9420 rec.header.size = sizeof(rec);
9421 rec.pid = perf_event_pid(event, current);
9422 rec.tid = perf_event_tid(event, current);
9424 perf_event_header__init_id(&rec.header, &sample, event);
9425 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9430 perf_output_put(&handle, rec);
9431 perf_event__output_id_sample(event, &handle, &sample);
9433 perf_output_end(&handle);
9436 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9438 struct perf_output_handle handle;
9439 struct perf_sample_data sample;
9440 struct perf_aux_event {
9441 struct perf_event_header header;
9447 event = event->parent;
9449 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9450 rec.header.misc = 0;
9451 rec.header.size = sizeof(rec);
9454 perf_event_header__init_id(&rec.header, &sample, event);
9455 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9460 perf_output_put(&handle, rec);
9461 perf_event__output_id_sample(event, &handle, &sample);
9463 perf_output_end(&handle);
9465 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
9468 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9470 struct hw_perf_event *hwc = &event->hw;
9474 seq = __this_cpu_read(perf_throttled_seq);
9475 if (seq != hwc->interrupts_seq) {
9476 hwc->interrupts_seq = seq;
9477 hwc->interrupts = 1;
9480 if (unlikely(throttle &&
9481 hwc->interrupts > max_samples_per_tick)) {
9482 __this_cpu_inc(perf_throttled_count);
9483 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9484 hwc->interrupts = MAX_INTERRUPTS;
9485 perf_log_throttle(event, 0);
9490 if (event->attr.freq) {
9491 u64 now = perf_clock();
9492 s64 delta = now - hwc->freq_time_stamp;
9494 hwc->freq_time_stamp = now;
9496 if (delta > 0 && delta < 2*TICK_NSEC)
9497 perf_adjust_period(event, delta, hwc->last_period, true);
9503 int perf_event_account_interrupt(struct perf_event *event)
9505 return __perf_event_account_interrupt(event, 1);
9508 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
9511 * Due to interrupt latency (AKA "skid"), we may enter the
9512 * kernel before taking an overflow, even if the PMU is only
9513 * counting user events.
9515 if (event->attr.exclude_kernel && !user_mode(regs))
9522 * Generic event overflow handling, sampling.
9525 static int __perf_event_overflow(struct perf_event *event,
9526 int throttle, struct perf_sample_data *data,
9527 struct pt_regs *regs)
9529 int events = atomic_read(&event->event_limit);
9533 * Non-sampling counters might still use the PMI to fold short
9534 * hardware counters, ignore those.
9536 if (unlikely(!is_sampling_event(event)))
9539 ret = __perf_event_account_interrupt(event, throttle);
9542 * XXX event_limit might not quite work as expected on inherited
9546 event->pending_kill = POLL_IN;
9547 if (events && atomic_dec_and_test(&event->event_limit)) {
9549 event->pending_kill = POLL_HUP;
9550 perf_event_disable_inatomic(event);
9553 if (event->attr.sigtrap) {
9555 * The desired behaviour of sigtrap vs invalid samples is a bit
9556 * tricky; on the one hand, one should not loose the SIGTRAP if
9557 * it is the first event, on the other hand, we should also not
9558 * trigger the WARN or override the data address.
9560 bool valid_sample = sample_is_allowed(event, regs);
9561 unsigned int pending_id = 1;
9564 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
9565 if (!event->pending_sigtrap) {
9566 event->pending_sigtrap = pending_id;
9567 local_inc(&event->ctx->nr_pending);
9568 } else if (event->attr.exclude_kernel && valid_sample) {
9570 * Should not be able to return to user space without
9571 * consuming pending_sigtrap; with exceptions:
9573 * 1. Where !exclude_kernel, events can overflow again
9574 * in the kernel without returning to user space.
9576 * 2. Events that can overflow again before the IRQ-
9577 * work without user space progress (e.g. hrtimer).
9578 * To approximate progress (with false negatives),
9579 * check 32-bit hash of the current IP.
9581 WARN_ON_ONCE(event->pending_sigtrap != pending_id);
9584 event->pending_addr = 0;
9585 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
9586 event->pending_addr = data->addr;
9587 irq_work_queue(&event->pending_irq);
9590 READ_ONCE(event->overflow_handler)(event, data, regs);
9592 if (*perf_event_fasync(event) && event->pending_kill) {
9593 event->pending_wakeup = 1;
9594 irq_work_queue(&event->pending_irq);
9600 int perf_event_overflow(struct perf_event *event,
9601 struct perf_sample_data *data,
9602 struct pt_regs *regs)
9604 return __perf_event_overflow(event, 1, data, regs);
9608 * Generic software event infrastructure
9611 struct swevent_htable {
9612 struct swevent_hlist *swevent_hlist;
9613 struct mutex hlist_mutex;
9616 /* Recursion avoidance in each contexts */
9617 int recursion[PERF_NR_CONTEXTS];
9620 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9623 * We directly increment event->count and keep a second value in
9624 * event->hw.period_left to count intervals. This period event
9625 * is kept in the range [-sample_period, 0] so that we can use the
9629 u64 perf_swevent_set_period(struct perf_event *event)
9631 struct hw_perf_event *hwc = &event->hw;
9632 u64 period = hwc->last_period;
9636 hwc->last_period = hwc->sample_period;
9638 old = local64_read(&hwc->period_left);
9644 nr = div64_u64(period + val, period);
9645 offset = nr * period;
9647 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
9652 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9653 struct perf_sample_data *data,
9654 struct pt_regs *regs)
9656 struct hw_perf_event *hwc = &event->hw;
9660 overflow = perf_swevent_set_period(event);
9662 if (hwc->interrupts == MAX_INTERRUPTS)
9665 for (; overflow; overflow--) {
9666 if (__perf_event_overflow(event, throttle,
9669 * We inhibit the overflow from happening when
9670 * hwc->interrupts == MAX_INTERRUPTS.
9678 static void perf_swevent_event(struct perf_event *event, u64 nr,
9679 struct perf_sample_data *data,
9680 struct pt_regs *regs)
9682 struct hw_perf_event *hwc = &event->hw;
9684 local64_add(nr, &event->count);
9689 if (!is_sampling_event(event))
9692 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9694 return perf_swevent_overflow(event, 1, data, regs);
9696 data->period = event->hw.last_period;
9698 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9699 return perf_swevent_overflow(event, 1, data, regs);
9701 if (local64_add_negative(nr, &hwc->period_left))
9704 perf_swevent_overflow(event, 0, data, regs);
9707 static int perf_exclude_event(struct perf_event *event,
9708 struct pt_regs *regs)
9710 if (event->hw.state & PERF_HES_STOPPED)
9714 if (event->attr.exclude_user && user_mode(regs))
9717 if (event->attr.exclude_kernel && !user_mode(regs))
9724 static int perf_swevent_match(struct perf_event *event,
9725 enum perf_type_id type,
9727 struct perf_sample_data *data,
9728 struct pt_regs *regs)
9730 if (event->attr.type != type)
9733 if (event->attr.config != event_id)
9736 if (perf_exclude_event(event, regs))
9742 static inline u64 swevent_hash(u64 type, u32 event_id)
9744 u64 val = event_id | (type << 32);
9746 return hash_64(val, SWEVENT_HLIST_BITS);
9749 static inline struct hlist_head *
9750 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9752 u64 hash = swevent_hash(type, event_id);
9754 return &hlist->heads[hash];
9757 /* For the read side: events when they trigger */
9758 static inline struct hlist_head *
9759 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9761 struct swevent_hlist *hlist;
9763 hlist = rcu_dereference(swhash->swevent_hlist);
9767 return __find_swevent_head(hlist, type, event_id);
9770 /* For the event head insertion and removal in the hlist */
9771 static inline struct hlist_head *
9772 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9774 struct swevent_hlist *hlist;
9775 u32 event_id = event->attr.config;
9776 u64 type = event->attr.type;
9779 * Event scheduling is always serialized against hlist allocation
9780 * and release. Which makes the protected version suitable here.
9781 * The context lock guarantees that.
9783 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9784 lockdep_is_held(&event->ctx->lock));
9788 return __find_swevent_head(hlist, type, event_id);
9791 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9793 struct perf_sample_data *data,
9794 struct pt_regs *regs)
9796 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9797 struct perf_event *event;
9798 struct hlist_head *head;
9801 head = find_swevent_head_rcu(swhash, type, event_id);
9805 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9806 if (perf_swevent_match(event, type, event_id, data, regs))
9807 perf_swevent_event(event, nr, data, regs);
9813 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9815 int perf_swevent_get_recursion_context(void)
9817 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9819 return get_recursion_context(swhash->recursion);
9821 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9823 void perf_swevent_put_recursion_context(int rctx)
9825 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9827 put_recursion_context(swhash->recursion, rctx);
9830 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9832 struct perf_sample_data data;
9834 if (WARN_ON_ONCE(!regs))
9837 perf_sample_data_init(&data, addr, 0);
9838 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9841 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9845 preempt_disable_notrace();
9846 rctx = perf_swevent_get_recursion_context();
9847 if (unlikely(rctx < 0))
9850 ___perf_sw_event(event_id, nr, regs, addr);
9852 perf_swevent_put_recursion_context(rctx);
9854 preempt_enable_notrace();
9857 static void perf_swevent_read(struct perf_event *event)
9861 static int perf_swevent_add(struct perf_event *event, int flags)
9863 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9864 struct hw_perf_event *hwc = &event->hw;
9865 struct hlist_head *head;
9867 if (is_sampling_event(event)) {
9868 hwc->last_period = hwc->sample_period;
9869 perf_swevent_set_period(event);
9872 hwc->state = !(flags & PERF_EF_START);
9874 head = find_swevent_head(swhash, event);
9875 if (WARN_ON_ONCE(!head))
9878 hlist_add_head_rcu(&event->hlist_entry, head);
9879 perf_event_update_userpage(event);
9884 static void perf_swevent_del(struct perf_event *event, int flags)
9886 hlist_del_rcu(&event->hlist_entry);
9889 static void perf_swevent_start(struct perf_event *event, int flags)
9891 event->hw.state = 0;
9894 static void perf_swevent_stop(struct perf_event *event, int flags)
9896 event->hw.state = PERF_HES_STOPPED;
9899 /* Deref the hlist from the update side */
9900 static inline struct swevent_hlist *
9901 swevent_hlist_deref(struct swevent_htable *swhash)
9903 return rcu_dereference_protected(swhash->swevent_hlist,
9904 lockdep_is_held(&swhash->hlist_mutex));
9907 static void swevent_hlist_release(struct swevent_htable *swhash)
9909 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9914 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9915 kfree_rcu(hlist, rcu_head);
9918 static void swevent_hlist_put_cpu(int cpu)
9920 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9922 mutex_lock(&swhash->hlist_mutex);
9924 if (!--swhash->hlist_refcount)
9925 swevent_hlist_release(swhash);
9927 mutex_unlock(&swhash->hlist_mutex);
9930 static void swevent_hlist_put(void)
9934 for_each_possible_cpu(cpu)
9935 swevent_hlist_put_cpu(cpu);
9938 static int swevent_hlist_get_cpu(int cpu)
9940 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9943 mutex_lock(&swhash->hlist_mutex);
9944 if (!swevent_hlist_deref(swhash) &&
9945 cpumask_test_cpu(cpu, perf_online_mask)) {
9946 struct swevent_hlist *hlist;
9948 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9953 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9955 swhash->hlist_refcount++;
9957 mutex_unlock(&swhash->hlist_mutex);
9962 static int swevent_hlist_get(void)
9964 int err, cpu, failed_cpu;
9966 mutex_lock(&pmus_lock);
9967 for_each_possible_cpu(cpu) {
9968 err = swevent_hlist_get_cpu(cpu);
9974 mutex_unlock(&pmus_lock);
9977 for_each_possible_cpu(cpu) {
9978 if (cpu == failed_cpu)
9980 swevent_hlist_put_cpu(cpu);
9982 mutex_unlock(&pmus_lock);
9986 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9988 static void sw_perf_event_destroy(struct perf_event *event)
9990 u64 event_id = event->attr.config;
9992 WARN_ON(event->parent);
9994 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9995 swevent_hlist_put();
9998 static struct pmu perf_cpu_clock; /* fwd declaration */
9999 static struct pmu perf_task_clock;
10001 static int perf_swevent_init(struct perf_event *event)
10003 u64 event_id = event->attr.config;
10005 if (event->attr.type != PERF_TYPE_SOFTWARE)
10009 * no branch sampling for software events
10011 if (has_branch_stack(event))
10012 return -EOPNOTSUPP;
10014 switch (event_id) {
10015 case PERF_COUNT_SW_CPU_CLOCK:
10016 event->attr.type = perf_cpu_clock.type;
10018 case PERF_COUNT_SW_TASK_CLOCK:
10019 event->attr.type = perf_task_clock.type;
10026 if (event_id >= PERF_COUNT_SW_MAX)
10029 if (!event->parent) {
10032 err = swevent_hlist_get();
10036 static_key_slow_inc(&perf_swevent_enabled[event_id]);
10037 event->destroy = sw_perf_event_destroy;
10043 static struct pmu perf_swevent = {
10044 .task_ctx_nr = perf_sw_context,
10046 .capabilities = PERF_PMU_CAP_NO_NMI,
10048 .event_init = perf_swevent_init,
10049 .add = perf_swevent_add,
10050 .del = perf_swevent_del,
10051 .start = perf_swevent_start,
10052 .stop = perf_swevent_stop,
10053 .read = perf_swevent_read,
10056 #ifdef CONFIG_EVENT_TRACING
10058 static void tp_perf_event_destroy(struct perf_event *event)
10060 perf_trace_destroy(event);
10063 static int perf_tp_event_init(struct perf_event *event)
10067 if (event->attr.type != PERF_TYPE_TRACEPOINT)
10071 * no branch sampling for tracepoint events
10073 if (has_branch_stack(event))
10074 return -EOPNOTSUPP;
10076 err = perf_trace_init(event);
10080 event->destroy = tp_perf_event_destroy;
10085 static struct pmu perf_tracepoint = {
10086 .task_ctx_nr = perf_sw_context,
10088 .event_init = perf_tp_event_init,
10089 .add = perf_trace_add,
10090 .del = perf_trace_del,
10091 .start = perf_swevent_start,
10092 .stop = perf_swevent_stop,
10093 .read = perf_swevent_read,
10096 static int perf_tp_filter_match(struct perf_event *event,
10097 struct perf_sample_data *data)
10099 void *record = data->raw->frag.data;
10101 /* only top level events have filters set */
10103 event = event->parent;
10105 if (likely(!event->filter) || filter_match_preds(event->filter, record))
10110 static int perf_tp_event_match(struct perf_event *event,
10111 struct perf_sample_data *data,
10112 struct pt_regs *regs)
10114 if (event->hw.state & PERF_HES_STOPPED)
10117 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10119 if (event->attr.exclude_kernel && !user_mode(regs))
10122 if (!perf_tp_filter_match(event, data))
10128 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10129 struct trace_event_call *call, u64 count,
10130 struct pt_regs *regs, struct hlist_head *head,
10131 struct task_struct *task)
10133 if (bpf_prog_array_valid(call)) {
10134 *(struct pt_regs **)raw_data = regs;
10135 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10136 perf_swevent_put_recursion_context(rctx);
10140 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10143 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10145 static void __perf_tp_event_target_task(u64 count, void *record,
10146 struct pt_regs *regs,
10147 struct perf_sample_data *data,
10148 struct perf_event *event)
10150 struct trace_entry *entry = record;
10152 if (event->attr.config != entry->type)
10154 /* Cannot deliver synchronous signal to other task. */
10155 if (event->attr.sigtrap)
10157 if (perf_tp_event_match(event, data, regs))
10158 perf_swevent_event(event, count, data, regs);
10161 static void perf_tp_event_target_task(u64 count, void *record,
10162 struct pt_regs *regs,
10163 struct perf_sample_data *data,
10164 struct perf_event_context *ctx)
10166 unsigned int cpu = smp_processor_id();
10167 struct pmu *pmu = &perf_tracepoint;
10168 struct perf_event *event, *sibling;
10170 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10171 __perf_tp_event_target_task(count, record, regs, data, event);
10172 for_each_sibling_event(sibling, event)
10173 __perf_tp_event_target_task(count, record, regs, data, sibling);
10176 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10177 __perf_tp_event_target_task(count, record, regs, data, event);
10178 for_each_sibling_event(sibling, event)
10179 __perf_tp_event_target_task(count, record, regs, data, sibling);
10183 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10184 struct pt_regs *regs, struct hlist_head *head, int rctx,
10185 struct task_struct *task)
10187 struct perf_sample_data data;
10188 struct perf_event *event;
10190 struct perf_raw_record raw = {
10192 .size = entry_size,
10197 perf_sample_data_init(&data, 0, 0);
10198 perf_sample_save_raw_data(&data, &raw);
10200 perf_trace_buf_update(record, event_type);
10202 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10203 if (perf_tp_event_match(event, &data, regs)) {
10204 perf_swevent_event(event, count, &data, regs);
10207 * Here use the same on-stack perf_sample_data,
10208 * some members in data are event-specific and
10209 * need to be re-computed for different sweveents.
10210 * Re-initialize data->sample_flags safely to avoid
10211 * the problem that next event skips preparing data
10212 * because data->sample_flags is set.
10214 perf_sample_data_init(&data, 0, 0);
10215 perf_sample_save_raw_data(&data, &raw);
10220 * If we got specified a target task, also iterate its context and
10221 * deliver this event there too.
10223 if (task && task != current) {
10224 struct perf_event_context *ctx;
10227 ctx = rcu_dereference(task->perf_event_ctxp);
10231 raw_spin_lock(&ctx->lock);
10232 perf_tp_event_target_task(count, record, regs, &data, ctx);
10233 raw_spin_unlock(&ctx->lock);
10238 perf_swevent_put_recursion_context(rctx);
10240 EXPORT_SYMBOL_GPL(perf_tp_event);
10242 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10244 * Flags in config, used by dynamic PMU kprobe and uprobe
10245 * The flags should match following PMU_FORMAT_ATTR().
10247 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10248 * if not set, create kprobe/uprobe
10250 * The following values specify a reference counter (or semaphore in the
10251 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10252 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10254 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
10255 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
10257 enum perf_probe_config {
10258 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
10259 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
10260 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
10263 PMU_FORMAT_ATTR(retprobe, "config:0");
10266 #ifdef CONFIG_KPROBE_EVENTS
10267 static struct attribute *kprobe_attrs[] = {
10268 &format_attr_retprobe.attr,
10272 static struct attribute_group kprobe_format_group = {
10274 .attrs = kprobe_attrs,
10277 static const struct attribute_group *kprobe_attr_groups[] = {
10278 &kprobe_format_group,
10282 static int perf_kprobe_event_init(struct perf_event *event);
10283 static struct pmu perf_kprobe = {
10284 .task_ctx_nr = perf_sw_context,
10285 .event_init = perf_kprobe_event_init,
10286 .add = perf_trace_add,
10287 .del = perf_trace_del,
10288 .start = perf_swevent_start,
10289 .stop = perf_swevent_stop,
10290 .read = perf_swevent_read,
10291 .attr_groups = kprobe_attr_groups,
10294 static int perf_kprobe_event_init(struct perf_event *event)
10299 if (event->attr.type != perf_kprobe.type)
10302 if (!perfmon_capable())
10306 * no branch sampling for probe events
10308 if (has_branch_stack(event))
10309 return -EOPNOTSUPP;
10311 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10312 err = perf_kprobe_init(event, is_retprobe);
10316 event->destroy = perf_kprobe_destroy;
10320 #endif /* CONFIG_KPROBE_EVENTS */
10322 #ifdef CONFIG_UPROBE_EVENTS
10323 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10325 static struct attribute *uprobe_attrs[] = {
10326 &format_attr_retprobe.attr,
10327 &format_attr_ref_ctr_offset.attr,
10331 static struct attribute_group uprobe_format_group = {
10333 .attrs = uprobe_attrs,
10336 static const struct attribute_group *uprobe_attr_groups[] = {
10337 &uprobe_format_group,
10341 static int perf_uprobe_event_init(struct perf_event *event);
10342 static struct pmu perf_uprobe = {
10343 .task_ctx_nr = perf_sw_context,
10344 .event_init = perf_uprobe_event_init,
10345 .add = perf_trace_add,
10346 .del = perf_trace_del,
10347 .start = perf_swevent_start,
10348 .stop = perf_swevent_stop,
10349 .read = perf_swevent_read,
10350 .attr_groups = uprobe_attr_groups,
10353 static int perf_uprobe_event_init(struct perf_event *event)
10356 unsigned long ref_ctr_offset;
10359 if (event->attr.type != perf_uprobe.type)
10362 if (!perfmon_capable())
10366 * no branch sampling for probe events
10368 if (has_branch_stack(event))
10369 return -EOPNOTSUPP;
10371 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10372 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10373 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10377 event->destroy = perf_uprobe_destroy;
10381 #endif /* CONFIG_UPROBE_EVENTS */
10383 static inline void perf_tp_register(void)
10385 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10386 #ifdef CONFIG_KPROBE_EVENTS
10387 perf_pmu_register(&perf_kprobe, "kprobe", -1);
10389 #ifdef CONFIG_UPROBE_EVENTS
10390 perf_pmu_register(&perf_uprobe, "uprobe", -1);
10394 static void perf_event_free_filter(struct perf_event *event)
10396 ftrace_profile_free_filter(event);
10399 #ifdef CONFIG_BPF_SYSCALL
10400 static void bpf_overflow_handler(struct perf_event *event,
10401 struct perf_sample_data *data,
10402 struct pt_regs *regs)
10404 struct bpf_perf_event_data_kern ctx = {
10408 struct bpf_prog *prog;
10411 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10412 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10415 prog = READ_ONCE(event->prog);
10417 perf_prepare_sample(data, event, regs);
10418 ret = bpf_prog_run(prog, &ctx);
10422 __this_cpu_dec(bpf_prog_active);
10426 event->orig_overflow_handler(event, data, regs);
10429 static int perf_event_set_bpf_handler(struct perf_event *event,
10430 struct bpf_prog *prog,
10433 if (event->overflow_handler_context)
10434 /* hw breakpoint or kernel counter */
10440 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10443 if (event->attr.precise_ip &&
10444 prog->call_get_stack &&
10445 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10446 event->attr.exclude_callchain_kernel ||
10447 event->attr.exclude_callchain_user)) {
10449 * On perf_event with precise_ip, calling bpf_get_stack()
10450 * may trigger unwinder warnings and occasional crashes.
10451 * bpf_get_[stack|stackid] works around this issue by using
10452 * callchain attached to perf_sample_data. If the
10453 * perf_event does not full (kernel and user) callchain
10454 * attached to perf_sample_data, do not allow attaching BPF
10455 * program that calls bpf_get_[stack|stackid].
10460 event->prog = prog;
10461 event->bpf_cookie = bpf_cookie;
10462 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
10463 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
10467 static void perf_event_free_bpf_handler(struct perf_event *event)
10469 struct bpf_prog *prog = event->prog;
10474 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
10475 event->prog = NULL;
10476 bpf_prog_put(prog);
10479 static int perf_event_set_bpf_handler(struct perf_event *event,
10480 struct bpf_prog *prog,
10483 return -EOPNOTSUPP;
10485 static void perf_event_free_bpf_handler(struct perf_event *event)
10491 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10492 * with perf_event_open()
10494 static inline bool perf_event_is_tracing(struct perf_event *event)
10496 if (event->pmu == &perf_tracepoint)
10498 #ifdef CONFIG_KPROBE_EVENTS
10499 if (event->pmu == &perf_kprobe)
10502 #ifdef CONFIG_UPROBE_EVENTS
10503 if (event->pmu == &perf_uprobe)
10509 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10512 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10514 if (!perf_event_is_tracing(event))
10515 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10517 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10518 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10519 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10520 is_syscall_tp = is_syscall_trace_event(event->tp_event);
10521 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10522 /* bpf programs can only be attached to u/kprobe or tracepoint */
10525 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10526 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10527 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10530 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->aux->sleepable && !is_uprobe)
10531 /* only uprobe programs are allowed to be sleepable */
10534 /* Kprobe override only works for kprobes, not uprobes. */
10535 if (prog->kprobe_override && !is_kprobe)
10538 if (is_tracepoint || is_syscall_tp) {
10539 int off = trace_event_get_offsets(event->tp_event);
10541 if (prog->aux->max_ctx_offset > off)
10545 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10548 void perf_event_free_bpf_prog(struct perf_event *event)
10550 if (!perf_event_is_tracing(event)) {
10551 perf_event_free_bpf_handler(event);
10554 perf_event_detach_bpf_prog(event);
10559 static inline void perf_tp_register(void)
10563 static void perf_event_free_filter(struct perf_event *event)
10567 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10573 void perf_event_free_bpf_prog(struct perf_event *event)
10576 #endif /* CONFIG_EVENT_TRACING */
10578 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10579 void perf_bp_event(struct perf_event *bp, void *data)
10581 struct perf_sample_data sample;
10582 struct pt_regs *regs = data;
10584 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10586 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10587 perf_swevent_event(bp, 1, &sample, regs);
10592 * Allocate a new address filter
10594 static struct perf_addr_filter *
10595 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10597 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10598 struct perf_addr_filter *filter;
10600 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10604 INIT_LIST_HEAD(&filter->entry);
10605 list_add_tail(&filter->entry, filters);
10610 static void free_filters_list(struct list_head *filters)
10612 struct perf_addr_filter *filter, *iter;
10614 list_for_each_entry_safe(filter, iter, filters, entry) {
10615 path_put(&filter->path);
10616 list_del(&filter->entry);
10622 * Free existing address filters and optionally install new ones
10624 static void perf_addr_filters_splice(struct perf_event *event,
10625 struct list_head *head)
10627 unsigned long flags;
10630 if (!has_addr_filter(event))
10633 /* don't bother with children, they don't have their own filters */
10637 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10639 list_splice_init(&event->addr_filters.list, &list);
10641 list_splice(head, &event->addr_filters.list);
10643 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10645 free_filters_list(&list);
10649 * Scan through mm's vmas and see if one of them matches the
10650 * @filter; if so, adjust filter's address range.
10651 * Called with mm::mmap_lock down for reading.
10653 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10654 struct mm_struct *mm,
10655 struct perf_addr_filter_range *fr)
10657 struct vm_area_struct *vma;
10658 VMA_ITERATOR(vmi, mm, 0);
10660 for_each_vma(vmi, vma) {
10664 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10670 * Update event's address range filters based on the
10671 * task's existing mappings, if any.
10673 static void perf_event_addr_filters_apply(struct perf_event *event)
10675 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10676 struct task_struct *task = READ_ONCE(event->ctx->task);
10677 struct perf_addr_filter *filter;
10678 struct mm_struct *mm = NULL;
10679 unsigned int count = 0;
10680 unsigned long flags;
10683 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10684 * will stop on the parent's child_mutex that our caller is also holding
10686 if (task == TASK_TOMBSTONE)
10689 if (ifh->nr_file_filters) {
10690 mm = get_task_mm(task);
10694 mmap_read_lock(mm);
10697 raw_spin_lock_irqsave(&ifh->lock, flags);
10698 list_for_each_entry(filter, &ifh->list, entry) {
10699 if (filter->path.dentry) {
10701 * Adjust base offset if the filter is associated to a
10702 * binary that needs to be mapped:
10704 event->addr_filter_ranges[count].start = 0;
10705 event->addr_filter_ranges[count].size = 0;
10707 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10709 event->addr_filter_ranges[count].start = filter->offset;
10710 event->addr_filter_ranges[count].size = filter->size;
10716 event->addr_filters_gen++;
10717 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10719 if (ifh->nr_file_filters) {
10720 mmap_read_unlock(mm);
10726 perf_event_stop(event, 1);
10730 * Address range filtering: limiting the data to certain
10731 * instruction address ranges. Filters are ioctl()ed to us from
10732 * userspace as ascii strings.
10734 * Filter string format:
10736 * ACTION RANGE_SPEC
10737 * where ACTION is one of the
10738 * * "filter": limit the trace to this region
10739 * * "start": start tracing from this address
10740 * * "stop": stop tracing at this address/region;
10742 * * for kernel addresses: <start address>[/<size>]
10743 * * for object files: <start address>[/<size>]@</path/to/object/file>
10745 * if <size> is not specified or is zero, the range is treated as a single
10746 * address; not valid for ACTION=="filter".
10760 IF_STATE_ACTION = 0,
10765 static const match_table_t if_tokens = {
10766 { IF_ACT_FILTER, "filter" },
10767 { IF_ACT_START, "start" },
10768 { IF_ACT_STOP, "stop" },
10769 { IF_SRC_FILE, "%u/%u@%s" },
10770 { IF_SRC_KERNEL, "%u/%u" },
10771 { IF_SRC_FILEADDR, "%u@%s" },
10772 { IF_SRC_KERNELADDR, "%u" },
10773 { IF_ACT_NONE, NULL },
10777 * Address filter string parser
10780 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10781 struct list_head *filters)
10783 struct perf_addr_filter *filter = NULL;
10784 char *start, *orig, *filename = NULL;
10785 substring_t args[MAX_OPT_ARGS];
10786 int state = IF_STATE_ACTION, token;
10787 unsigned int kernel = 0;
10790 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10794 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10795 static const enum perf_addr_filter_action_t actions[] = {
10796 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10797 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10798 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10805 /* filter definition begins */
10806 if (state == IF_STATE_ACTION) {
10807 filter = perf_addr_filter_new(event, filters);
10812 token = match_token(start, if_tokens, args);
10814 case IF_ACT_FILTER:
10817 if (state != IF_STATE_ACTION)
10820 filter->action = actions[token];
10821 state = IF_STATE_SOURCE;
10824 case IF_SRC_KERNELADDR:
10825 case IF_SRC_KERNEL:
10829 case IF_SRC_FILEADDR:
10831 if (state != IF_STATE_SOURCE)
10835 ret = kstrtoul(args[0].from, 0, &filter->offset);
10839 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10841 ret = kstrtoul(args[1].from, 0, &filter->size);
10846 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10847 int fpos = token == IF_SRC_FILE ? 2 : 1;
10850 filename = match_strdup(&args[fpos]);
10857 state = IF_STATE_END;
10865 * Filter definition is fully parsed, validate and install it.
10866 * Make sure that it doesn't contradict itself or the event's
10869 if (state == IF_STATE_END) {
10873 * ACTION "filter" must have a non-zero length region
10876 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10885 * For now, we only support file-based filters
10886 * in per-task events; doing so for CPU-wide
10887 * events requires additional context switching
10888 * trickery, since same object code will be
10889 * mapped at different virtual addresses in
10890 * different processes.
10893 if (!event->ctx->task)
10896 /* look up the path and grab its inode */
10897 ret = kern_path(filename, LOOKUP_FOLLOW,
10903 if (!filter->path.dentry ||
10904 !S_ISREG(d_inode(filter->path.dentry)
10908 event->addr_filters.nr_file_filters++;
10911 /* ready to consume more filters */
10914 state = IF_STATE_ACTION;
10920 if (state != IF_STATE_ACTION)
10930 free_filters_list(filters);
10937 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10939 LIST_HEAD(filters);
10943 * Since this is called in perf_ioctl() path, we're already holding
10946 lockdep_assert_held(&event->ctx->mutex);
10948 if (WARN_ON_ONCE(event->parent))
10951 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10953 goto fail_clear_files;
10955 ret = event->pmu->addr_filters_validate(&filters);
10957 goto fail_free_filters;
10959 /* remove existing filters, if any */
10960 perf_addr_filters_splice(event, &filters);
10962 /* install new filters */
10963 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10968 free_filters_list(&filters);
10971 event->addr_filters.nr_file_filters = 0;
10976 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10981 filter_str = strndup_user(arg, PAGE_SIZE);
10982 if (IS_ERR(filter_str))
10983 return PTR_ERR(filter_str);
10985 #ifdef CONFIG_EVENT_TRACING
10986 if (perf_event_is_tracing(event)) {
10987 struct perf_event_context *ctx = event->ctx;
10990 * Beware, here be dragons!!
10992 * the tracepoint muck will deadlock against ctx->mutex, but
10993 * the tracepoint stuff does not actually need it. So
10994 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10995 * already have a reference on ctx.
10997 * This can result in event getting moved to a different ctx,
10998 * but that does not affect the tracepoint state.
11000 mutex_unlock(&ctx->mutex);
11001 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
11002 mutex_lock(&ctx->mutex);
11005 if (has_addr_filter(event))
11006 ret = perf_event_set_addr_filter(event, filter_str);
11013 * hrtimer based swevent callback
11016 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
11018 enum hrtimer_restart ret = HRTIMER_RESTART;
11019 struct perf_sample_data data;
11020 struct pt_regs *regs;
11021 struct perf_event *event;
11024 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
11026 if (event->state != PERF_EVENT_STATE_ACTIVE)
11027 return HRTIMER_NORESTART;
11029 event->pmu->read(event);
11031 perf_sample_data_init(&data, 0, event->hw.last_period);
11032 regs = get_irq_regs();
11034 if (regs && !perf_exclude_event(event, regs)) {
11035 if (!(event->attr.exclude_idle && is_idle_task(current)))
11036 if (__perf_event_overflow(event, 1, &data, regs))
11037 ret = HRTIMER_NORESTART;
11040 period = max_t(u64, 10000, event->hw.sample_period);
11041 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
11046 static void perf_swevent_start_hrtimer(struct perf_event *event)
11048 struct hw_perf_event *hwc = &event->hw;
11051 if (!is_sampling_event(event))
11054 period = local64_read(&hwc->period_left);
11059 local64_set(&hwc->period_left, 0);
11061 period = max_t(u64, 10000, hwc->sample_period);
11063 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
11064 HRTIMER_MODE_REL_PINNED_HARD);
11067 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
11069 struct hw_perf_event *hwc = &event->hw;
11071 if (is_sampling_event(event)) {
11072 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
11073 local64_set(&hwc->period_left, ktime_to_ns(remaining));
11075 hrtimer_cancel(&hwc->hrtimer);
11079 static void perf_swevent_init_hrtimer(struct perf_event *event)
11081 struct hw_perf_event *hwc = &event->hw;
11083 if (!is_sampling_event(event))
11086 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
11087 hwc->hrtimer.function = perf_swevent_hrtimer;
11090 * Since hrtimers have a fixed rate, we can do a static freq->period
11091 * mapping and avoid the whole period adjust feedback stuff.
11093 if (event->attr.freq) {
11094 long freq = event->attr.sample_freq;
11096 event->attr.sample_period = NSEC_PER_SEC / freq;
11097 hwc->sample_period = event->attr.sample_period;
11098 local64_set(&hwc->period_left, hwc->sample_period);
11099 hwc->last_period = hwc->sample_period;
11100 event->attr.freq = 0;
11105 * Software event: cpu wall time clock
11108 static void cpu_clock_event_update(struct perf_event *event)
11113 now = local_clock();
11114 prev = local64_xchg(&event->hw.prev_count, now);
11115 local64_add(now - prev, &event->count);
11118 static void cpu_clock_event_start(struct perf_event *event, int flags)
11120 local64_set(&event->hw.prev_count, local_clock());
11121 perf_swevent_start_hrtimer(event);
11124 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11126 perf_swevent_cancel_hrtimer(event);
11127 cpu_clock_event_update(event);
11130 static int cpu_clock_event_add(struct perf_event *event, int flags)
11132 if (flags & PERF_EF_START)
11133 cpu_clock_event_start(event, flags);
11134 perf_event_update_userpage(event);
11139 static void cpu_clock_event_del(struct perf_event *event, int flags)
11141 cpu_clock_event_stop(event, flags);
11144 static void cpu_clock_event_read(struct perf_event *event)
11146 cpu_clock_event_update(event);
11149 static int cpu_clock_event_init(struct perf_event *event)
11151 if (event->attr.type != perf_cpu_clock.type)
11154 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11158 * no branch sampling for software events
11160 if (has_branch_stack(event))
11161 return -EOPNOTSUPP;
11163 perf_swevent_init_hrtimer(event);
11168 static struct pmu perf_cpu_clock = {
11169 .task_ctx_nr = perf_sw_context,
11171 .capabilities = PERF_PMU_CAP_NO_NMI,
11172 .dev = PMU_NULL_DEV,
11174 .event_init = cpu_clock_event_init,
11175 .add = cpu_clock_event_add,
11176 .del = cpu_clock_event_del,
11177 .start = cpu_clock_event_start,
11178 .stop = cpu_clock_event_stop,
11179 .read = cpu_clock_event_read,
11183 * Software event: task time clock
11186 static void task_clock_event_update(struct perf_event *event, u64 now)
11191 prev = local64_xchg(&event->hw.prev_count, now);
11192 delta = now - prev;
11193 local64_add(delta, &event->count);
11196 static void task_clock_event_start(struct perf_event *event, int flags)
11198 local64_set(&event->hw.prev_count, event->ctx->time);
11199 perf_swevent_start_hrtimer(event);
11202 static void task_clock_event_stop(struct perf_event *event, int flags)
11204 perf_swevent_cancel_hrtimer(event);
11205 task_clock_event_update(event, event->ctx->time);
11208 static int task_clock_event_add(struct perf_event *event, int flags)
11210 if (flags & PERF_EF_START)
11211 task_clock_event_start(event, flags);
11212 perf_event_update_userpage(event);
11217 static void task_clock_event_del(struct perf_event *event, int flags)
11219 task_clock_event_stop(event, PERF_EF_UPDATE);
11222 static void task_clock_event_read(struct perf_event *event)
11224 u64 now = perf_clock();
11225 u64 delta = now - event->ctx->timestamp;
11226 u64 time = event->ctx->time + delta;
11228 task_clock_event_update(event, time);
11231 static int task_clock_event_init(struct perf_event *event)
11233 if (event->attr.type != perf_task_clock.type)
11236 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11240 * no branch sampling for software events
11242 if (has_branch_stack(event))
11243 return -EOPNOTSUPP;
11245 perf_swevent_init_hrtimer(event);
11250 static struct pmu perf_task_clock = {
11251 .task_ctx_nr = perf_sw_context,
11253 .capabilities = PERF_PMU_CAP_NO_NMI,
11254 .dev = PMU_NULL_DEV,
11256 .event_init = task_clock_event_init,
11257 .add = task_clock_event_add,
11258 .del = task_clock_event_del,
11259 .start = task_clock_event_start,
11260 .stop = task_clock_event_stop,
11261 .read = task_clock_event_read,
11264 static void perf_pmu_nop_void(struct pmu *pmu)
11268 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11272 static int perf_pmu_nop_int(struct pmu *pmu)
11277 static int perf_event_nop_int(struct perf_event *event, u64 value)
11282 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11284 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11286 __this_cpu_write(nop_txn_flags, flags);
11288 if (flags & ~PERF_PMU_TXN_ADD)
11291 perf_pmu_disable(pmu);
11294 static int perf_pmu_commit_txn(struct pmu *pmu)
11296 unsigned int flags = __this_cpu_read(nop_txn_flags);
11298 __this_cpu_write(nop_txn_flags, 0);
11300 if (flags & ~PERF_PMU_TXN_ADD)
11303 perf_pmu_enable(pmu);
11307 static void perf_pmu_cancel_txn(struct pmu *pmu)
11309 unsigned int flags = __this_cpu_read(nop_txn_flags);
11311 __this_cpu_write(nop_txn_flags, 0);
11313 if (flags & ~PERF_PMU_TXN_ADD)
11316 perf_pmu_enable(pmu);
11319 static int perf_event_idx_default(struct perf_event *event)
11324 static void free_pmu_context(struct pmu *pmu)
11326 free_percpu(pmu->cpu_pmu_context);
11330 * Let userspace know that this PMU supports address range filtering:
11332 static ssize_t nr_addr_filters_show(struct device *dev,
11333 struct device_attribute *attr,
11336 struct pmu *pmu = dev_get_drvdata(dev);
11338 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11340 DEVICE_ATTR_RO(nr_addr_filters);
11342 static struct idr pmu_idr;
11345 type_show(struct device *dev, struct device_attribute *attr, char *page)
11347 struct pmu *pmu = dev_get_drvdata(dev);
11349 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11351 static DEVICE_ATTR_RO(type);
11354 perf_event_mux_interval_ms_show(struct device *dev,
11355 struct device_attribute *attr,
11358 struct pmu *pmu = dev_get_drvdata(dev);
11360 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11363 static DEFINE_MUTEX(mux_interval_mutex);
11366 perf_event_mux_interval_ms_store(struct device *dev,
11367 struct device_attribute *attr,
11368 const char *buf, size_t count)
11370 struct pmu *pmu = dev_get_drvdata(dev);
11371 int timer, cpu, ret;
11373 ret = kstrtoint(buf, 0, &timer);
11380 /* same value, noting to do */
11381 if (timer == pmu->hrtimer_interval_ms)
11384 mutex_lock(&mux_interval_mutex);
11385 pmu->hrtimer_interval_ms = timer;
11387 /* update all cpuctx for this PMU */
11389 for_each_online_cpu(cpu) {
11390 struct perf_cpu_pmu_context *cpc;
11391 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11392 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11394 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
11396 cpus_read_unlock();
11397 mutex_unlock(&mux_interval_mutex);
11401 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11403 static struct attribute *pmu_dev_attrs[] = {
11404 &dev_attr_type.attr,
11405 &dev_attr_perf_event_mux_interval_ms.attr,
11408 ATTRIBUTE_GROUPS(pmu_dev);
11410 static int pmu_bus_running;
11411 static struct bus_type pmu_bus = {
11412 .name = "event_source",
11413 .dev_groups = pmu_dev_groups,
11416 static void pmu_dev_release(struct device *dev)
11421 static int pmu_dev_alloc(struct pmu *pmu)
11425 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11429 pmu->dev->groups = pmu->attr_groups;
11430 device_initialize(pmu->dev);
11432 dev_set_drvdata(pmu->dev, pmu);
11433 pmu->dev->bus = &pmu_bus;
11434 pmu->dev->parent = pmu->parent;
11435 pmu->dev->release = pmu_dev_release;
11437 ret = dev_set_name(pmu->dev, "%s", pmu->name);
11441 ret = device_add(pmu->dev);
11445 /* For PMUs with address filters, throw in an extra attribute: */
11446 if (pmu->nr_addr_filters)
11447 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
11452 if (pmu->attr_update)
11453 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11462 device_del(pmu->dev);
11465 put_device(pmu->dev);
11469 static struct lock_class_key cpuctx_mutex;
11470 static struct lock_class_key cpuctx_lock;
11472 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11474 int cpu, ret, max = PERF_TYPE_MAX;
11476 mutex_lock(&pmus_lock);
11478 pmu->pmu_disable_count = alloc_percpu(int);
11479 if (!pmu->pmu_disable_count)
11483 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) {
11493 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
11497 WARN_ON(type >= 0 && ret != type);
11502 if (pmu_bus_running && !pmu->dev) {
11503 ret = pmu_dev_alloc(pmu);
11509 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context);
11510 if (!pmu->cpu_pmu_context)
11513 for_each_possible_cpu(cpu) {
11514 struct perf_cpu_pmu_context *cpc;
11516 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11517 __perf_init_event_pmu_context(&cpc->epc, pmu);
11518 __perf_mux_hrtimer_init(cpc, cpu);
11521 if (!pmu->start_txn) {
11522 if (pmu->pmu_enable) {
11524 * If we have pmu_enable/pmu_disable calls, install
11525 * transaction stubs that use that to try and batch
11526 * hardware accesses.
11528 pmu->start_txn = perf_pmu_start_txn;
11529 pmu->commit_txn = perf_pmu_commit_txn;
11530 pmu->cancel_txn = perf_pmu_cancel_txn;
11532 pmu->start_txn = perf_pmu_nop_txn;
11533 pmu->commit_txn = perf_pmu_nop_int;
11534 pmu->cancel_txn = perf_pmu_nop_void;
11538 if (!pmu->pmu_enable) {
11539 pmu->pmu_enable = perf_pmu_nop_void;
11540 pmu->pmu_disable = perf_pmu_nop_void;
11543 if (!pmu->check_period)
11544 pmu->check_period = perf_event_nop_int;
11546 if (!pmu->event_idx)
11547 pmu->event_idx = perf_event_idx_default;
11549 list_add_rcu(&pmu->entry, &pmus);
11550 atomic_set(&pmu->exclusive_cnt, 0);
11553 mutex_unlock(&pmus_lock);
11558 if (pmu->dev && pmu->dev != PMU_NULL_DEV) {
11559 device_del(pmu->dev);
11560 put_device(pmu->dev);
11564 idr_remove(&pmu_idr, pmu->type);
11567 free_percpu(pmu->pmu_disable_count);
11570 EXPORT_SYMBOL_GPL(perf_pmu_register);
11572 void perf_pmu_unregister(struct pmu *pmu)
11574 mutex_lock(&pmus_lock);
11575 list_del_rcu(&pmu->entry);
11578 * We dereference the pmu list under both SRCU and regular RCU, so
11579 * synchronize against both of those.
11581 synchronize_srcu(&pmus_srcu);
11584 free_percpu(pmu->pmu_disable_count);
11585 idr_remove(&pmu_idr, pmu->type);
11586 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
11587 if (pmu->nr_addr_filters)
11588 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11589 device_del(pmu->dev);
11590 put_device(pmu->dev);
11592 free_pmu_context(pmu);
11593 mutex_unlock(&pmus_lock);
11595 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11597 static inline bool has_extended_regs(struct perf_event *event)
11599 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11600 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11603 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11605 struct perf_event_context *ctx = NULL;
11608 if (!try_module_get(pmu->module))
11612 * A number of pmu->event_init() methods iterate the sibling_list to,
11613 * for example, validate if the group fits on the PMU. Therefore,
11614 * if this is a sibling event, acquire the ctx->mutex to protect
11615 * the sibling_list.
11617 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11619 * This ctx->mutex can nest when we're called through
11620 * inheritance. See the perf_event_ctx_lock_nested() comment.
11622 ctx = perf_event_ctx_lock_nested(event->group_leader,
11623 SINGLE_DEPTH_NESTING);
11628 ret = pmu->event_init(event);
11631 perf_event_ctx_unlock(event->group_leader, ctx);
11634 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11635 has_extended_regs(event))
11638 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11639 event_has_any_exclude_flag(event))
11642 if (ret && event->destroy)
11643 event->destroy(event);
11647 module_put(pmu->module);
11652 static struct pmu *perf_init_event(struct perf_event *event)
11654 bool extended_type = false;
11655 int idx, type, ret;
11658 idx = srcu_read_lock(&pmus_srcu);
11661 * Save original type before calling pmu->event_init() since certain
11662 * pmus overwrites event->attr.type to forward event to another pmu.
11664 event->orig_type = event->attr.type;
11666 /* Try parent's PMU first: */
11667 if (event->parent && event->parent->pmu) {
11668 pmu = event->parent->pmu;
11669 ret = perf_try_init_event(pmu, event);
11675 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11676 * are often aliases for PERF_TYPE_RAW.
11678 type = event->attr.type;
11679 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
11680 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
11682 type = PERF_TYPE_RAW;
11684 extended_type = true;
11685 event->attr.config &= PERF_HW_EVENT_MASK;
11691 pmu = idr_find(&pmu_idr, type);
11694 if (event->attr.type != type && type != PERF_TYPE_RAW &&
11695 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
11698 ret = perf_try_init_event(pmu, event);
11699 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
11700 type = event->attr.type;
11705 pmu = ERR_PTR(ret);
11710 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11711 ret = perf_try_init_event(pmu, event);
11715 if (ret != -ENOENT) {
11716 pmu = ERR_PTR(ret);
11721 pmu = ERR_PTR(-ENOENT);
11723 srcu_read_unlock(&pmus_srcu, idx);
11728 static void attach_sb_event(struct perf_event *event)
11730 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11732 raw_spin_lock(&pel->lock);
11733 list_add_rcu(&event->sb_list, &pel->list);
11734 raw_spin_unlock(&pel->lock);
11738 * We keep a list of all !task (and therefore per-cpu) events
11739 * that need to receive side-band records.
11741 * This avoids having to scan all the various PMU per-cpu contexts
11742 * looking for them.
11744 static void account_pmu_sb_event(struct perf_event *event)
11746 if (is_sb_event(event))
11747 attach_sb_event(event);
11750 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11751 static void account_freq_event_nohz(void)
11753 #ifdef CONFIG_NO_HZ_FULL
11754 /* Lock so we don't race with concurrent unaccount */
11755 spin_lock(&nr_freq_lock);
11756 if (atomic_inc_return(&nr_freq_events) == 1)
11757 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11758 spin_unlock(&nr_freq_lock);
11762 static void account_freq_event(void)
11764 if (tick_nohz_full_enabled())
11765 account_freq_event_nohz();
11767 atomic_inc(&nr_freq_events);
11771 static void account_event(struct perf_event *event)
11778 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11780 if (event->attr.mmap || event->attr.mmap_data)
11781 atomic_inc(&nr_mmap_events);
11782 if (event->attr.build_id)
11783 atomic_inc(&nr_build_id_events);
11784 if (event->attr.comm)
11785 atomic_inc(&nr_comm_events);
11786 if (event->attr.namespaces)
11787 atomic_inc(&nr_namespaces_events);
11788 if (event->attr.cgroup)
11789 atomic_inc(&nr_cgroup_events);
11790 if (event->attr.task)
11791 atomic_inc(&nr_task_events);
11792 if (event->attr.freq)
11793 account_freq_event();
11794 if (event->attr.context_switch) {
11795 atomic_inc(&nr_switch_events);
11798 if (has_branch_stack(event))
11800 if (is_cgroup_event(event))
11802 if (event->attr.ksymbol)
11803 atomic_inc(&nr_ksymbol_events);
11804 if (event->attr.bpf_event)
11805 atomic_inc(&nr_bpf_events);
11806 if (event->attr.text_poke)
11807 atomic_inc(&nr_text_poke_events);
11811 * We need the mutex here because static_branch_enable()
11812 * must complete *before* the perf_sched_count increment
11815 if (atomic_inc_not_zero(&perf_sched_count))
11818 mutex_lock(&perf_sched_mutex);
11819 if (!atomic_read(&perf_sched_count)) {
11820 static_branch_enable(&perf_sched_events);
11822 * Guarantee that all CPUs observe they key change and
11823 * call the perf scheduling hooks before proceeding to
11824 * install events that need them.
11829 * Now that we have waited for the sync_sched(), allow further
11830 * increments to by-pass the mutex.
11832 atomic_inc(&perf_sched_count);
11833 mutex_unlock(&perf_sched_mutex);
11837 account_pmu_sb_event(event);
11841 * Allocate and initialize an event structure
11843 static struct perf_event *
11844 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11845 struct task_struct *task,
11846 struct perf_event *group_leader,
11847 struct perf_event *parent_event,
11848 perf_overflow_handler_t overflow_handler,
11849 void *context, int cgroup_fd)
11852 struct perf_event *event;
11853 struct hw_perf_event *hwc;
11854 long err = -EINVAL;
11857 if ((unsigned)cpu >= nr_cpu_ids) {
11858 if (!task || cpu != -1)
11859 return ERR_PTR(-EINVAL);
11861 if (attr->sigtrap && !task) {
11862 /* Requires a task: avoid signalling random tasks. */
11863 return ERR_PTR(-EINVAL);
11866 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11867 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11870 return ERR_PTR(-ENOMEM);
11873 * Single events are their own group leaders, with an
11874 * empty sibling list:
11877 group_leader = event;
11879 mutex_init(&event->child_mutex);
11880 INIT_LIST_HEAD(&event->child_list);
11882 INIT_LIST_HEAD(&event->event_entry);
11883 INIT_LIST_HEAD(&event->sibling_list);
11884 INIT_LIST_HEAD(&event->active_list);
11885 init_event_group(event);
11886 INIT_LIST_HEAD(&event->rb_entry);
11887 INIT_LIST_HEAD(&event->active_entry);
11888 INIT_LIST_HEAD(&event->addr_filters.list);
11889 INIT_HLIST_NODE(&event->hlist_entry);
11892 init_waitqueue_head(&event->waitq);
11893 init_irq_work(&event->pending_irq, perf_pending_irq);
11894 init_task_work(&event->pending_task, perf_pending_task);
11896 mutex_init(&event->mmap_mutex);
11897 raw_spin_lock_init(&event->addr_filters.lock);
11899 atomic_long_set(&event->refcount, 1);
11901 event->attr = *attr;
11902 event->group_leader = group_leader;
11906 event->parent = parent_event;
11908 event->ns = get_pid_ns(task_active_pid_ns(current));
11909 event->id = atomic64_inc_return(&perf_event_id);
11911 event->state = PERF_EVENT_STATE_INACTIVE;
11914 event->event_caps = parent_event->event_caps;
11917 event->attach_state = PERF_ATTACH_TASK;
11919 * XXX pmu::event_init needs to know what task to account to
11920 * and we cannot use the ctx information because we need the
11921 * pmu before we get a ctx.
11923 event->hw.target = get_task_struct(task);
11926 event->clock = &local_clock;
11928 event->clock = parent_event->clock;
11930 if (!overflow_handler && parent_event) {
11931 overflow_handler = parent_event->overflow_handler;
11932 context = parent_event->overflow_handler_context;
11933 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11934 if (overflow_handler == bpf_overflow_handler) {
11935 struct bpf_prog *prog = parent_event->prog;
11937 bpf_prog_inc(prog);
11938 event->prog = prog;
11939 event->orig_overflow_handler =
11940 parent_event->orig_overflow_handler;
11945 if (overflow_handler) {
11946 event->overflow_handler = overflow_handler;
11947 event->overflow_handler_context = context;
11948 } else if (is_write_backward(event)){
11949 event->overflow_handler = perf_event_output_backward;
11950 event->overflow_handler_context = NULL;
11952 event->overflow_handler = perf_event_output_forward;
11953 event->overflow_handler_context = NULL;
11956 perf_event__state_init(event);
11961 hwc->sample_period = attr->sample_period;
11962 if (attr->freq && attr->sample_freq)
11963 hwc->sample_period = 1;
11964 hwc->last_period = hwc->sample_period;
11966 local64_set(&hwc->period_left, hwc->sample_period);
11969 * We currently do not support PERF_SAMPLE_READ on inherited events.
11970 * See perf_output_read().
11972 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11975 if (!has_branch_stack(event))
11976 event->attr.branch_sample_type = 0;
11978 pmu = perf_init_event(event);
11980 err = PTR_ERR(pmu);
11985 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
11986 * events (they don't make sense as the cgroup will be different
11987 * on other CPUs in the uncore mask).
11989 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) {
11994 if (event->attr.aux_output &&
11995 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
12000 if (cgroup_fd != -1) {
12001 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
12006 err = exclusive_event_init(event);
12010 if (has_addr_filter(event)) {
12011 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
12012 sizeof(struct perf_addr_filter_range),
12014 if (!event->addr_filter_ranges) {
12020 * Clone the parent's vma offsets: they are valid until exec()
12021 * even if the mm is not shared with the parent.
12023 if (event->parent) {
12024 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
12026 raw_spin_lock_irq(&ifh->lock);
12027 memcpy(event->addr_filter_ranges,
12028 event->parent->addr_filter_ranges,
12029 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
12030 raw_spin_unlock_irq(&ifh->lock);
12033 /* force hw sync on the address filters */
12034 event->addr_filters_gen = 1;
12037 if (!event->parent) {
12038 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
12039 err = get_callchain_buffers(attr->sample_max_stack);
12041 goto err_addr_filters;
12045 err = security_perf_event_alloc(event);
12047 goto err_callchain_buffer;
12049 /* symmetric to unaccount_event() in _free_event() */
12050 account_event(event);
12054 err_callchain_buffer:
12055 if (!event->parent) {
12056 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
12057 put_callchain_buffers();
12060 kfree(event->addr_filter_ranges);
12063 exclusive_event_destroy(event);
12066 if (is_cgroup_event(event))
12067 perf_detach_cgroup(event);
12068 if (event->destroy)
12069 event->destroy(event);
12070 module_put(pmu->module);
12072 if (event->hw.target)
12073 put_task_struct(event->hw.target);
12074 call_rcu(&event->rcu_head, free_event_rcu);
12076 return ERR_PTR(err);
12079 static int perf_copy_attr(struct perf_event_attr __user *uattr,
12080 struct perf_event_attr *attr)
12085 /* Zero the full structure, so that a short copy will be nice. */
12086 memset(attr, 0, sizeof(*attr));
12088 ret = get_user(size, &uattr->size);
12092 /* ABI compatibility quirk: */
12094 size = PERF_ATTR_SIZE_VER0;
12095 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
12098 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
12107 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
12110 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
12113 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
12116 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
12117 u64 mask = attr->branch_sample_type;
12119 /* only using defined bits */
12120 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
12123 /* at least one branch bit must be set */
12124 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
12127 /* propagate priv level, when not set for branch */
12128 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
12130 /* exclude_kernel checked on syscall entry */
12131 if (!attr->exclude_kernel)
12132 mask |= PERF_SAMPLE_BRANCH_KERNEL;
12134 if (!attr->exclude_user)
12135 mask |= PERF_SAMPLE_BRANCH_USER;
12137 if (!attr->exclude_hv)
12138 mask |= PERF_SAMPLE_BRANCH_HV;
12140 * adjust user setting (for HW filter setup)
12142 attr->branch_sample_type = mask;
12144 /* privileged levels capture (kernel, hv): check permissions */
12145 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
12146 ret = perf_allow_kernel(attr);
12152 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
12153 ret = perf_reg_validate(attr->sample_regs_user);
12158 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
12159 if (!arch_perf_have_user_stack_dump())
12163 * We have __u32 type for the size, but so far
12164 * we can only use __u16 as maximum due to the
12165 * __u16 sample size limit.
12167 if (attr->sample_stack_user >= USHRT_MAX)
12169 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
12173 if (!attr->sample_max_stack)
12174 attr->sample_max_stack = sysctl_perf_event_max_stack;
12176 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
12177 ret = perf_reg_validate(attr->sample_regs_intr);
12179 #ifndef CONFIG_CGROUP_PERF
12180 if (attr->sample_type & PERF_SAMPLE_CGROUP)
12183 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
12184 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
12187 if (!attr->inherit && attr->inherit_thread)
12190 if (attr->remove_on_exec && attr->enable_on_exec)
12193 if (attr->sigtrap && !attr->remove_on_exec)
12200 put_user(sizeof(*attr), &uattr->size);
12205 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12211 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12215 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12217 struct perf_buffer *rb = NULL;
12220 if (!output_event) {
12221 mutex_lock(&event->mmap_mutex);
12225 /* don't allow circular references */
12226 if (event == output_event)
12230 * Don't allow cross-cpu buffers
12232 if (output_event->cpu != event->cpu)
12236 * If its not a per-cpu rb, it must be the same task.
12238 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
12242 * Mixing clocks in the same buffer is trouble you don't need.
12244 if (output_event->clock != event->clock)
12248 * Either writing ring buffer from beginning or from end.
12249 * Mixing is not allowed.
12251 if (is_write_backward(output_event) != is_write_backward(event))
12255 * If both events generate aux data, they must be on the same PMU
12257 if (has_aux(event) && has_aux(output_event) &&
12258 event->pmu != output_event->pmu)
12262 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12263 * output_event is already on rb->event_list, and the list iteration
12264 * restarts after every removal, it is guaranteed this new event is
12265 * observed *OR* if output_event is already removed, it's guaranteed we
12266 * observe !rb->mmap_count.
12268 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12270 /* Can't redirect output if we've got an active mmap() */
12271 if (atomic_read(&event->mmap_count))
12274 if (output_event) {
12275 /* get the rb we want to redirect to */
12276 rb = ring_buffer_get(output_event);
12280 /* did we race against perf_mmap_close() */
12281 if (!atomic_read(&rb->mmap_count)) {
12282 ring_buffer_put(rb);
12287 ring_buffer_attach(event, rb);
12291 mutex_unlock(&event->mmap_mutex);
12293 mutex_unlock(&output_event->mmap_mutex);
12299 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12301 bool nmi_safe = false;
12304 case CLOCK_MONOTONIC:
12305 event->clock = &ktime_get_mono_fast_ns;
12309 case CLOCK_MONOTONIC_RAW:
12310 event->clock = &ktime_get_raw_fast_ns;
12314 case CLOCK_REALTIME:
12315 event->clock = &ktime_get_real_ns;
12318 case CLOCK_BOOTTIME:
12319 event->clock = &ktime_get_boottime_ns;
12323 event->clock = &ktime_get_clocktai_ns;
12330 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12337 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12339 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12340 bool is_capable = perfmon_capable();
12342 if (attr->sigtrap) {
12344 * perf_event_attr::sigtrap sends signals to the other task.
12345 * Require the current task to also have CAP_KILL.
12348 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12352 * If the required capabilities aren't available, checks for
12353 * ptrace permissions: upgrade to ATTACH, since sending signals
12354 * can effectively change the target task.
12356 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12360 * Preserve ptrace permission check for backwards compatibility. The
12361 * ptrace check also includes checks that the current task and other
12362 * task have matching uids, and is therefore not done here explicitly.
12364 return is_capable || ptrace_may_access(task, ptrace_mode);
12368 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12370 * @attr_uptr: event_id type attributes for monitoring/sampling
12373 * @group_fd: group leader event fd
12374 * @flags: perf event open flags
12376 SYSCALL_DEFINE5(perf_event_open,
12377 struct perf_event_attr __user *, attr_uptr,
12378 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12380 struct perf_event *group_leader = NULL, *output_event = NULL;
12381 struct perf_event_pmu_context *pmu_ctx;
12382 struct perf_event *event, *sibling;
12383 struct perf_event_attr attr;
12384 struct perf_event_context *ctx;
12385 struct file *event_file = NULL;
12386 struct fd group = {NULL, 0};
12387 struct task_struct *task = NULL;
12390 int move_group = 0;
12392 int f_flags = O_RDWR;
12393 int cgroup_fd = -1;
12395 /* for future expandability... */
12396 if (flags & ~PERF_FLAG_ALL)
12399 err = perf_copy_attr(attr_uptr, &attr);
12403 /* Do we allow access to perf_event_open(2) ? */
12404 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12408 if (!attr.exclude_kernel) {
12409 err = perf_allow_kernel(&attr);
12414 if (attr.namespaces) {
12415 if (!perfmon_capable())
12420 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12423 if (attr.sample_period & (1ULL << 63))
12427 /* Only privileged users can get physical addresses */
12428 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12429 err = perf_allow_kernel(&attr);
12434 /* REGS_INTR can leak data, lockdown must prevent this */
12435 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12436 err = security_locked_down(LOCKDOWN_PERF);
12442 * In cgroup mode, the pid argument is used to pass the fd
12443 * opened to the cgroup directory in cgroupfs. The cpu argument
12444 * designates the cpu on which to monitor threads from that
12447 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12450 if (flags & PERF_FLAG_FD_CLOEXEC)
12451 f_flags |= O_CLOEXEC;
12453 event_fd = get_unused_fd_flags(f_flags);
12457 if (group_fd != -1) {
12458 err = perf_fget_light(group_fd, &group);
12461 group_leader = group.file->private_data;
12462 if (flags & PERF_FLAG_FD_OUTPUT)
12463 output_event = group_leader;
12464 if (flags & PERF_FLAG_FD_NO_GROUP)
12465 group_leader = NULL;
12468 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12469 task = find_lively_task_by_vpid(pid);
12470 if (IS_ERR(task)) {
12471 err = PTR_ERR(task);
12476 if (task && group_leader &&
12477 group_leader->attr.inherit != attr.inherit) {
12482 if (flags & PERF_FLAG_PID_CGROUP)
12485 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12486 NULL, NULL, cgroup_fd);
12487 if (IS_ERR(event)) {
12488 err = PTR_ERR(event);
12492 if (is_sampling_event(event)) {
12493 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12500 * Special case software events and allow them to be part of
12501 * any hardware group.
12505 if (attr.use_clockid) {
12506 err = perf_event_set_clock(event, attr.clockid);
12511 if (pmu->task_ctx_nr == perf_sw_context)
12512 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12515 err = down_read_interruptible(&task->signal->exec_update_lock);
12520 * We must hold exec_update_lock across this and any potential
12521 * perf_install_in_context() call for this new event to
12522 * serialize against exec() altering our credentials (and the
12523 * perf_event_exit_task() that could imply).
12526 if (!perf_check_permission(&attr, task))
12531 * Get the target context (task or percpu):
12533 ctx = find_get_context(task, event);
12535 err = PTR_ERR(ctx);
12539 mutex_lock(&ctx->mutex);
12541 if (ctx->task == TASK_TOMBSTONE) {
12548 * Check if the @cpu we're creating an event for is online.
12550 * We use the perf_cpu_context::ctx::mutex to serialize against
12551 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12553 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
12555 if (!cpuctx->online) {
12561 if (group_leader) {
12565 * Do not allow a recursive hierarchy (this new sibling
12566 * becoming part of another group-sibling):
12568 if (group_leader->group_leader != group_leader)
12571 /* All events in a group should have the same clock */
12572 if (group_leader->clock != event->clock)
12576 * Make sure we're both events for the same CPU;
12577 * grouping events for different CPUs is broken; since
12578 * you can never concurrently schedule them anyhow.
12580 if (group_leader->cpu != event->cpu)
12584 * Make sure we're both on the same context; either task or cpu.
12586 if (group_leader->ctx != ctx)
12590 * Only a group leader can be exclusive or pinned
12592 if (attr.exclusive || attr.pinned)
12595 if (is_software_event(event) &&
12596 !in_software_context(group_leader)) {
12598 * If the event is a sw event, but the group_leader
12599 * is on hw context.
12601 * Allow the addition of software events to hw
12602 * groups, this is safe because software events
12603 * never fail to schedule.
12605 * Note the comment that goes with struct
12606 * perf_event_pmu_context.
12608 pmu = group_leader->pmu_ctx->pmu;
12609 } else if (!is_software_event(event)) {
12610 if (is_software_event(group_leader) &&
12611 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12613 * In case the group is a pure software group, and we
12614 * try to add a hardware event, move the whole group to
12615 * the hardware context.
12620 /* Don't allow group of multiple hw events from different pmus */
12621 if (!in_software_context(group_leader) &&
12622 group_leader->pmu_ctx->pmu != pmu)
12628 * Now that we're certain of the pmu; find the pmu_ctx.
12630 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12631 if (IS_ERR(pmu_ctx)) {
12632 err = PTR_ERR(pmu_ctx);
12635 event->pmu_ctx = pmu_ctx;
12637 if (output_event) {
12638 err = perf_event_set_output(event, output_event);
12643 if (!perf_event_validate_size(event)) {
12648 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12654 * Must be under the same ctx::mutex as perf_install_in_context(),
12655 * because we need to serialize with concurrent event creation.
12657 if (!exclusive_event_installable(event, ctx)) {
12662 WARN_ON_ONCE(ctx->parent_ctx);
12664 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
12665 if (IS_ERR(event_file)) {
12666 err = PTR_ERR(event_file);
12672 * This is the point on no return; we cannot fail hereafter. This is
12673 * where we start modifying current state.
12677 perf_remove_from_context(group_leader, 0);
12678 put_pmu_ctx(group_leader->pmu_ctx);
12680 for_each_sibling_event(sibling, group_leader) {
12681 perf_remove_from_context(sibling, 0);
12682 put_pmu_ctx(sibling->pmu_ctx);
12686 * Install the group siblings before the group leader.
12688 * Because a group leader will try and install the entire group
12689 * (through the sibling list, which is still in-tact), we can
12690 * end up with siblings installed in the wrong context.
12692 * By installing siblings first we NO-OP because they're not
12693 * reachable through the group lists.
12695 for_each_sibling_event(sibling, group_leader) {
12696 sibling->pmu_ctx = pmu_ctx;
12697 get_pmu_ctx(pmu_ctx);
12698 perf_event__state_init(sibling);
12699 perf_install_in_context(ctx, sibling, sibling->cpu);
12703 * Removing from the context ends up with disabled
12704 * event. What we want here is event in the initial
12705 * startup state, ready to be add into new context.
12707 group_leader->pmu_ctx = pmu_ctx;
12708 get_pmu_ctx(pmu_ctx);
12709 perf_event__state_init(group_leader);
12710 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12714 * Precalculate sample_data sizes; do while holding ctx::mutex such
12715 * that we're serialized against further additions and before
12716 * perf_install_in_context() which is the point the event is active and
12717 * can use these values.
12719 perf_event__header_size(event);
12720 perf_event__id_header_size(event);
12722 event->owner = current;
12724 perf_install_in_context(ctx, event, event->cpu);
12725 perf_unpin_context(ctx);
12727 mutex_unlock(&ctx->mutex);
12730 up_read(&task->signal->exec_update_lock);
12731 put_task_struct(task);
12734 mutex_lock(¤t->perf_event_mutex);
12735 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12736 mutex_unlock(¤t->perf_event_mutex);
12739 * Drop the reference on the group_event after placing the
12740 * new event on the sibling_list. This ensures destruction
12741 * of the group leader will find the pointer to itself in
12742 * perf_group_detach().
12745 fd_install(event_fd, event_file);
12749 put_pmu_ctx(event->pmu_ctx);
12750 event->pmu_ctx = NULL; /* _free_event() */
12752 mutex_unlock(&ctx->mutex);
12753 perf_unpin_context(ctx);
12757 up_read(&task->signal->exec_update_lock);
12762 put_task_struct(task);
12766 put_unused_fd(event_fd);
12771 * perf_event_create_kernel_counter
12773 * @attr: attributes of the counter to create
12774 * @cpu: cpu in which the counter is bound
12775 * @task: task to profile (NULL for percpu)
12776 * @overflow_handler: callback to trigger when we hit the event
12777 * @context: context data could be used in overflow_handler callback
12779 struct perf_event *
12780 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12781 struct task_struct *task,
12782 perf_overflow_handler_t overflow_handler,
12785 struct perf_event_pmu_context *pmu_ctx;
12786 struct perf_event_context *ctx;
12787 struct perf_event *event;
12792 * Grouping is not supported for kernel events, neither is 'AUX',
12793 * make sure the caller's intentions are adjusted.
12795 if (attr->aux_output)
12796 return ERR_PTR(-EINVAL);
12798 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12799 overflow_handler, context, -1);
12800 if (IS_ERR(event)) {
12801 err = PTR_ERR(event);
12805 /* Mark owner so we could distinguish it from user events. */
12806 event->owner = TASK_TOMBSTONE;
12809 if (pmu->task_ctx_nr == perf_sw_context)
12810 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12813 * Get the target context (task or percpu):
12815 ctx = find_get_context(task, event);
12817 err = PTR_ERR(ctx);
12821 WARN_ON_ONCE(ctx->parent_ctx);
12822 mutex_lock(&ctx->mutex);
12823 if (ctx->task == TASK_TOMBSTONE) {
12828 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12829 if (IS_ERR(pmu_ctx)) {
12830 err = PTR_ERR(pmu_ctx);
12833 event->pmu_ctx = pmu_ctx;
12837 * Check if the @cpu we're creating an event for is online.
12839 * We use the perf_cpu_context::ctx::mutex to serialize against
12840 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12842 struct perf_cpu_context *cpuctx =
12843 container_of(ctx, struct perf_cpu_context, ctx);
12844 if (!cpuctx->online) {
12850 if (!exclusive_event_installable(event, ctx)) {
12855 perf_install_in_context(ctx, event, event->cpu);
12856 perf_unpin_context(ctx);
12857 mutex_unlock(&ctx->mutex);
12862 put_pmu_ctx(pmu_ctx);
12863 event->pmu_ctx = NULL; /* _free_event() */
12865 mutex_unlock(&ctx->mutex);
12866 perf_unpin_context(ctx);
12871 return ERR_PTR(err);
12873 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12875 static void __perf_pmu_remove(struct perf_event_context *ctx,
12876 int cpu, struct pmu *pmu,
12877 struct perf_event_groups *groups,
12878 struct list_head *events)
12880 struct perf_event *event, *sibling;
12882 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
12883 perf_remove_from_context(event, 0);
12884 put_pmu_ctx(event->pmu_ctx);
12885 list_add(&event->migrate_entry, events);
12887 for_each_sibling_event(sibling, event) {
12888 perf_remove_from_context(sibling, 0);
12889 put_pmu_ctx(sibling->pmu_ctx);
12890 list_add(&sibling->migrate_entry, events);
12895 static void __perf_pmu_install_event(struct pmu *pmu,
12896 struct perf_event_context *ctx,
12897 int cpu, struct perf_event *event)
12899 struct perf_event_pmu_context *epc;
12900 struct perf_event_context *old_ctx = event->ctx;
12902 get_ctx(ctx); /* normally find_get_context() */
12905 epc = find_get_pmu_context(pmu, ctx, event);
12906 event->pmu_ctx = epc;
12908 if (event->state >= PERF_EVENT_STATE_OFF)
12909 event->state = PERF_EVENT_STATE_INACTIVE;
12910 perf_install_in_context(ctx, event, cpu);
12913 * Now that event->ctx is updated and visible, put the old ctx.
12918 static void __perf_pmu_install(struct perf_event_context *ctx,
12919 int cpu, struct pmu *pmu, struct list_head *events)
12921 struct perf_event *event, *tmp;
12924 * Re-instate events in 2 passes.
12926 * Skip over group leaders and only install siblings on this first
12927 * pass, siblings will not get enabled without a leader, however a
12928 * leader will enable its siblings, even if those are still on the old
12931 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12932 if (event->group_leader == event)
12935 list_del(&event->migrate_entry);
12936 __perf_pmu_install_event(pmu, ctx, cpu, event);
12940 * Once all the siblings are setup properly, install the group leaders
12943 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12944 list_del(&event->migrate_entry);
12945 __perf_pmu_install_event(pmu, ctx, cpu, event);
12949 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12951 struct perf_event_context *src_ctx, *dst_ctx;
12955 * Since per-cpu context is persistent, no need to grab an extra
12958 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
12959 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
12962 * See perf_event_ctx_lock() for comments on the details
12963 * of swizzling perf_event::ctx.
12965 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12967 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
12968 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
12970 if (!list_empty(&events)) {
12972 * Wait for the events to quiesce before re-instating them.
12976 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
12979 mutex_unlock(&dst_ctx->mutex);
12980 mutex_unlock(&src_ctx->mutex);
12982 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12984 static void sync_child_event(struct perf_event *child_event)
12986 struct perf_event *parent_event = child_event->parent;
12989 if (child_event->attr.inherit_stat) {
12990 struct task_struct *task = child_event->ctx->task;
12992 if (task && task != TASK_TOMBSTONE)
12993 perf_event_read_event(child_event, task);
12996 child_val = perf_event_count(child_event);
12999 * Add back the child's count to the parent's count:
13001 atomic64_add(child_val, &parent_event->child_count);
13002 atomic64_add(child_event->total_time_enabled,
13003 &parent_event->child_total_time_enabled);
13004 atomic64_add(child_event->total_time_running,
13005 &parent_event->child_total_time_running);
13009 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
13011 struct perf_event *parent_event = event->parent;
13012 unsigned long detach_flags = 0;
13014 if (parent_event) {
13016 * Do not destroy the 'original' grouping; because of the
13017 * context switch optimization the original events could've
13018 * ended up in a random child task.
13020 * If we were to destroy the original group, all group related
13021 * operations would cease to function properly after this
13022 * random child dies.
13024 * Do destroy all inherited groups, we don't care about those
13025 * and being thorough is better.
13027 detach_flags = DETACH_GROUP | DETACH_CHILD;
13028 mutex_lock(&parent_event->child_mutex);
13031 perf_remove_from_context(event, detach_flags);
13033 raw_spin_lock_irq(&ctx->lock);
13034 if (event->state > PERF_EVENT_STATE_EXIT)
13035 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
13036 raw_spin_unlock_irq(&ctx->lock);
13039 * Child events can be freed.
13041 if (parent_event) {
13042 mutex_unlock(&parent_event->child_mutex);
13044 * Kick perf_poll() for is_event_hup();
13046 perf_event_wakeup(parent_event);
13048 put_event(parent_event);
13053 * Parent events are governed by their filedesc, retain them.
13055 perf_event_wakeup(event);
13058 static void perf_event_exit_task_context(struct task_struct *child)
13060 struct perf_event_context *child_ctx, *clone_ctx = NULL;
13061 struct perf_event *child_event, *next;
13063 WARN_ON_ONCE(child != current);
13065 child_ctx = perf_pin_task_context(child);
13070 * In order to reduce the amount of tricky in ctx tear-down, we hold
13071 * ctx::mutex over the entire thing. This serializes against almost
13072 * everything that wants to access the ctx.
13074 * The exception is sys_perf_event_open() /
13075 * perf_event_create_kernel_count() which does find_get_context()
13076 * without ctx::mutex (it cannot because of the move_group double mutex
13077 * lock thing). See the comments in perf_install_in_context().
13079 mutex_lock(&child_ctx->mutex);
13082 * In a single ctx::lock section, de-schedule the events and detach the
13083 * context from the task such that we cannot ever get it scheduled back
13086 raw_spin_lock_irq(&child_ctx->lock);
13087 task_ctx_sched_out(child_ctx, EVENT_ALL);
13090 * Now that the context is inactive, destroy the task <-> ctx relation
13091 * and mark the context dead.
13093 RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
13094 put_ctx(child_ctx); /* cannot be last */
13095 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
13096 put_task_struct(current); /* cannot be last */
13098 clone_ctx = unclone_ctx(child_ctx);
13099 raw_spin_unlock_irq(&child_ctx->lock);
13102 put_ctx(clone_ctx);
13105 * Report the task dead after unscheduling the events so that we
13106 * won't get any samples after PERF_RECORD_EXIT. We can however still
13107 * get a few PERF_RECORD_READ events.
13109 perf_event_task(child, child_ctx, 0);
13111 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
13112 perf_event_exit_event(child_event, child_ctx);
13114 mutex_unlock(&child_ctx->mutex);
13116 put_ctx(child_ctx);
13120 * When a child task exits, feed back event values to parent events.
13122 * Can be called with exec_update_lock held when called from
13123 * setup_new_exec().
13125 void perf_event_exit_task(struct task_struct *child)
13127 struct perf_event *event, *tmp;
13129 mutex_lock(&child->perf_event_mutex);
13130 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
13132 list_del_init(&event->owner_entry);
13135 * Ensure the list deletion is visible before we clear
13136 * the owner, closes a race against perf_release() where
13137 * we need to serialize on the owner->perf_event_mutex.
13139 smp_store_release(&event->owner, NULL);
13141 mutex_unlock(&child->perf_event_mutex);
13143 perf_event_exit_task_context(child);
13146 * The perf_event_exit_task_context calls perf_event_task
13147 * with child's task_ctx, which generates EXIT events for
13148 * child contexts and sets child->perf_event_ctxp[] to NULL.
13149 * At this point we need to send EXIT events to cpu contexts.
13151 perf_event_task(child, NULL, 0);
13154 static void perf_free_event(struct perf_event *event,
13155 struct perf_event_context *ctx)
13157 struct perf_event *parent = event->parent;
13159 if (WARN_ON_ONCE(!parent))
13162 mutex_lock(&parent->child_mutex);
13163 list_del_init(&event->child_list);
13164 mutex_unlock(&parent->child_mutex);
13168 raw_spin_lock_irq(&ctx->lock);
13169 perf_group_detach(event);
13170 list_del_event(event, ctx);
13171 raw_spin_unlock_irq(&ctx->lock);
13176 * Free a context as created by inheritance by perf_event_init_task() below,
13177 * used by fork() in case of fail.
13179 * Even though the task has never lived, the context and events have been
13180 * exposed through the child_list, so we must take care tearing it all down.
13182 void perf_event_free_task(struct task_struct *task)
13184 struct perf_event_context *ctx;
13185 struct perf_event *event, *tmp;
13187 ctx = rcu_access_pointer(task->perf_event_ctxp);
13191 mutex_lock(&ctx->mutex);
13192 raw_spin_lock_irq(&ctx->lock);
13194 * Destroy the task <-> ctx relation and mark the context dead.
13196 * This is important because even though the task hasn't been
13197 * exposed yet the context has been (through child_list).
13199 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
13200 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13201 put_task_struct(task); /* cannot be last */
13202 raw_spin_unlock_irq(&ctx->lock);
13205 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13206 perf_free_event(event, ctx);
13208 mutex_unlock(&ctx->mutex);
13211 * perf_event_release_kernel() could've stolen some of our
13212 * child events and still have them on its free_list. In that
13213 * case we must wait for these events to have been freed (in
13214 * particular all their references to this task must've been
13217 * Without this copy_process() will unconditionally free this
13218 * task (irrespective of its reference count) and
13219 * _free_event()'s put_task_struct(event->hw.target) will be a
13222 * Wait for all events to drop their context reference.
13224 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13225 put_ctx(ctx); /* must be last */
13228 void perf_event_delayed_put(struct task_struct *task)
13230 WARN_ON_ONCE(task->perf_event_ctxp);
13233 struct file *perf_event_get(unsigned int fd)
13235 struct file *file = fget(fd);
13237 return ERR_PTR(-EBADF);
13239 if (file->f_op != &perf_fops) {
13241 return ERR_PTR(-EBADF);
13247 const struct perf_event *perf_get_event(struct file *file)
13249 if (file->f_op != &perf_fops)
13250 return ERR_PTR(-EINVAL);
13252 return file->private_data;
13255 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13258 return ERR_PTR(-EINVAL);
13260 return &event->attr;
13264 * Inherit an event from parent task to child task.
13267 * - valid pointer on success
13268 * - NULL for orphaned events
13269 * - IS_ERR() on error
13271 static struct perf_event *
13272 inherit_event(struct perf_event *parent_event,
13273 struct task_struct *parent,
13274 struct perf_event_context *parent_ctx,
13275 struct task_struct *child,
13276 struct perf_event *group_leader,
13277 struct perf_event_context *child_ctx)
13279 enum perf_event_state parent_state = parent_event->state;
13280 struct perf_event_pmu_context *pmu_ctx;
13281 struct perf_event *child_event;
13282 unsigned long flags;
13285 * Instead of creating recursive hierarchies of events,
13286 * we link inherited events back to the original parent,
13287 * which has a filp for sure, which we use as the reference
13290 if (parent_event->parent)
13291 parent_event = parent_event->parent;
13293 child_event = perf_event_alloc(&parent_event->attr,
13296 group_leader, parent_event,
13298 if (IS_ERR(child_event))
13299 return child_event;
13301 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
13302 if (IS_ERR(pmu_ctx)) {
13303 free_event(child_event);
13304 return ERR_CAST(pmu_ctx);
13306 child_event->pmu_ctx = pmu_ctx;
13309 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13310 * must be under the same lock in order to serialize against
13311 * perf_event_release_kernel(), such that either we must observe
13312 * is_orphaned_event() or they will observe us on the child_list.
13314 mutex_lock(&parent_event->child_mutex);
13315 if (is_orphaned_event(parent_event) ||
13316 !atomic_long_inc_not_zero(&parent_event->refcount)) {
13317 mutex_unlock(&parent_event->child_mutex);
13318 /* task_ctx_data is freed with child_ctx */
13319 free_event(child_event);
13323 get_ctx(child_ctx);
13326 * Make the child state follow the state of the parent event,
13327 * not its attr.disabled bit. We hold the parent's mutex,
13328 * so we won't race with perf_event_{en, dis}able_family.
13330 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13331 child_event->state = PERF_EVENT_STATE_INACTIVE;
13333 child_event->state = PERF_EVENT_STATE_OFF;
13335 if (parent_event->attr.freq) {
13336 u64 sample_period = parent_event->hw.sample_period;
13337 struct hw_perf_event *hwc = &child_event->hw;
13339 hwc->sample_period = sample_period;
13340 hwc->last_period = sample_period;
13342 local64_set(&hwc->period_left, sample_period);
13345 child_event->ctx = child_ctx;
13346 child_event->overflow_handler = parent_event->overflow_handler;
13347 child_event->overflow_handler_context
13348 = parent_event->overflow_handler_context;
13351 * Precalculate sample_data sizes
13353 perf_event__header_size(child_event);
13354 perf_event__id_header_size(child_event);
13357 * Link it up in the child's context:
13359 raw_spin_lock_irqsave(&child_ctx->lock, flags);
13360 add_event_to_ctx(child_event, child_ctx);
13361 child_event->attach_state |= PERF_ATTACH_CHILD;
13362 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13365 * Link this into the parent event's child list
13367 list_add_tail(&child_event->child_list, &parent_event->child_list);
13368 mutex_unlock(&parent_event->child_mutex);
13370 return child_event;
13374 * Inherits an event group.
13376 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13377 * This matches with perf_event_release_kernel() removing all child events.
13383 static int inherit_group(struct perf_event *parent_event,
13384 struct task_struct *parent,
13385 struct perf_event_context *parent_ctx,
13386 struct task_struct *child,
13387 struct perf_event_context *child_ctx)
13389 struct perf_event *leader;
13390 struct perf_event *sub;
13391 struct perf_event *child_ctr;
13393 leader = inherit_event(parent_event, parent, parent_ctx,
13394 child, NULL, child_ctx);
13395 if (IS_ERR(leader))
13396 return PTR_ERR(leader);
13398 * @leader can be NULL here because of is_orphaned_event(). In this
13399 * case inherit_event() will create individual events, similar to what
13400 * perf_group_detach() would do anyway.
13402 for_each_sibling_event(sub, parent_event) {
13403 child_ctr = inherit_event(sub, parent, parent_ctx,
13404 child, leader, child_ctx);
13405 if (IS_ERR(child_ctr))
13406 return PTR_ERR(child_ctr);
13408 if (sub->aux_event == parent_event && child_ctr &&
13409 !perf_get_aux_event(child_ctr, leader))
13413 leader->group_generation = parent_event->group_generation;
13418 * Creates the child task context and tries to inherit the event-group.
13420 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13421 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13422 * consistent with perf_event_release_kernel() removing all child events.
13429 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13430 struct perf_event_context *parent_ctx,
13431 struct task_struct *child,
13432 u64 clone_flags, int *inherited_all)
13434 struct perf_event_context *child_ctx;
13437 if (!event->attr.inherit ||
13438 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13439 /* Do not inherit if sigtrap and signal handlers were cleared. */
13440 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13441 *inherited_all = 0;
13445 child_ctx = child->perf_event_ctxp;
13448 * This is executed from the parent task context, so
13449 * inherit events that have been marked for cloning.
13450 * First allocate and initialize a context for the
13453 child_ctx = alloc_perf_context(child);
13457 child->perf_event_ctxp = child_ctx;
13460 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
13462 *inherited_all = 0;
13468 * Initialize the perf_event context in task_struct
13470 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
13472 struct perf_event_context *child_ctx, *parent_ctx;
13473 struct perf_event_context *cloned_ctx;
13474 struct perf_event *event;
13475 struct task_struct *parent = current;
13476 int inherited_all = 1;
13477 unsigned long flags;
13480 if (likely(!parent->perf_event_ctxp))
13484 * If the parent's context is a clone, pin it so it won't get
13485 * swapped under us.
13487 parent_ctx = perf_pin_task_context(parent);
13492 * No need to check if parent_ctx != NULL here; since we saw
13493 * it non-NULL earlier, the only reason for it to become NULL
13494 * is if we exit, and since we're currently in the middle of
13495 * a fork we can't be exiting at the same time.
13499 * Lock the parent list. No need to lock the child - not PID
13500 * hashed yet and not running, so nobody can access it.
13502 mutex_lock(&parent_ctx->mutex);
13505 * We dont have to disable NMIs - we are only looking at
13506 * the list, not manipulating it:
13508 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13509 ret = inherit_task_group(event, parent, parent_ctx,
13510 child, clone_flags, &inherited_all);
13516 * We can't hold ctx->lock when iterating the ->flexible_group list due
13517 * to allocations, but we need to prevent rotation because
13518 * rotate_ctx() will change the list from interrupt context.
13520 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13521 parent_ctx->rotate_disable = 1;
13522 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13524 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13525 ret = inherit_task_group(event, parent, parent_ctx,
13526 child, clone_flags, &inherited_all);
13531 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13532 parent_ctx->rotate_disable = 0;
13534 child_ctx = child->perf_event_ctxp;
13536 if (child_ctx && inherited_all) {
13538 * Mark the child context as a clone of the parent
13539 * context, or of whatever the parent is a clone of.
13541 * Note that if the parent is a clone, the holding of
13542 * parent_ctx->lock avoids it from being uncloned.
13544 cloned_ctx = parent_ctx->parent_ctx;
13546 child_ctx->parent_ctx = cloned_ctx;
13547 child_ctx->parent_gen = parent_ctx->parent_gen;
13549 child_ctx->parent_ctx = parent_ctx;
13550 child_ctx->parent_gen = parent_ctx->generation;
13552 get_ctx(child_ctx->parent_ctx);
13555 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13557 mutex_unlock(&parent_ctx->mutex);
13559 perf_unpin_context(parent_ctx);
13560 put_ctx(parent_ctx);
13566 * Initialize the perf_event context in task_struct
13568 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
13572 child->perf_event_ctxp = NULL;
13573 mutex_init(&child->perf_event_mutex);
13574 INIT_LIST_HEAD(&child->perf_event_list);
13576 ret = perf_event_init_context(child, clone_flags);
13578 perf_event_free_task(child);
13585 static void __init perf_event_init_all_cpus(void)
13587 struct swevent_htable *swhash;
13588 struct perf_cpu_context *cpuctx;
13591 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13593 for_each_possible_cpu(cpu) {
13594 swhash = &per_cpu(swevent_htable, cpu);
13595 mutex_init(&swhash->hlist_mutex);
13597 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13598 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13600 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13602 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13603 __perf_event_init_context(&cpuctx->ctx);
13604 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
13605 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
13606 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
13607 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
13608 cpuctx->heap = cpuctx->heap_default;
13612 static void perf_swevent_init_cpu(unsigned int cpu)
13614 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13616 mutex_lock(&swhash->hlist_mutex);
13617 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13618 struct swevent_hlist *hlist;
13620 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13622 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13624 mutex_unlock(&swhash->hlist_mutex);
13627 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13628 static void __perf_event_exit_context(void *__info)
13630 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
13631 struct perf_event_context *ctx = __info;
13632 struct perf_event *event;
13634 raw_spin_lock(&ctx->lock);
13635 ctx_sched_out(ctx, EVENT_TIME);
13636 list_for_each_entry(event, &ctx->event_list, event_entry)
13637 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13638 raw_spin_unlock(&ctx->lock);
13641 static void perf_event_exit_cpu_context(int cpu)
13643 struct perf_cpu_context *cpuctx;
13644 struct perf_event_context *ctx;
13646 // XXX simplify cpuctx->online
13647 mutex_lock(&pmus_lock);
13648 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13649 ctx = &cpuctx->ctx;
13651 mutex_lock(&ctx->mutex);
13652 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13653 cpuctx->online = 0;
13654 mutex_unlock(&ctx->mutex);
13655 cpumask_clear_cpu(cpu, perf_online_mask);
13656 mutex_unlock(&pmus_lock);
13660 static void perf_event_exit_cpu_context(int cpu) { }
13664 int perf_event_init_cpu(unsigned int cpu)
13666 struct perf_cpu_context *cpuctx;
13667 struct perf_event_context *ctx;
13669 perf_swevent_init_cpu(cpu);
13671 mutex_lock(&pmus_lock);
13672 cpumask_set_cpu(cpu, perf_online_mask);
13673 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13674 ctx = &cpuctx->ctx;
13676 mutex_lock(&ctx->mutex);
13677 cpuctx->online = 1;
13678 mutex_unlock(&ctx->mutex);
13679 mutex_unlock(&pmus_lock);
13684 int perf_event_exit_cpu(unsigned int cpu)
13686 perf_event_exit_cpu_context(cpu);
13691 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13695 for_each_online_cpu(cpu)
13696 perf_event_exit_cpu(cpu);
13702 * Run the perf reboot notifier at the very last possible moment so that
13703 * the generic watchdog code runs as long as possible.
13705 static struct notifier_block perf_reboot_notifier = {
13706 .notifier_call = perf_reboot,
13707 .priority = INT_MIN,
13710 void __init perf_event_init(void)
13714 idr_init(&pmu_idr);
13716 perf_event_init_all_cpus();
13717 init_srcu_struct(&pmus_srcu);
13718 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13719 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
13720 perf_pmu_register(&perf_task_clock, "task_clock", -1);
13721 perf_tp_register();
13722 perf_event_init_cpu(smp_processor_id());
13723 register_reboot_notifier(&perf_reboot_notifier);
13725 ret = init_hw_breakpoint();
13726 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13728 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13731 * Build time assertion that we keep the data_head at the intended
13732 * location. IOW, validation we got the __reserved[] size right.
13734 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13738 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13741 struct perf_pmu_events_attr *pmu_attr =
13742 container_of(attr, struct perf_pmu_events_attr, attr);
13744 if (pmu_attr->event_str)
13745 return sprintf(page, "%s\n", pmu_attr->event_str);
13749 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13751 static int __init perf_event_sysfs_init(void)
13756 mutex_lock(&pmus_lock);
13758 ret = bus_register(&pmu_bus);
13762 list_for_each_entry(pmu, &pmus, entry) {
13766 ret = pmu_dev_alloc(pmu);
13767 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13769 pmu_bus_running = 1;
13773 mutex_unlock(&pmus_lock);
13777 device_initcall(perf_event_sysfs_init);
13779 #ifdef CONFIG_CGROUP_PERF
13780 static struct cgroup_subsys_state *
13781 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13783 struct perf_cgroup *jc;
13785 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13787 return ERR_PTR(-ENOMEM);
13789 jc->info = alloc_percpu(struct perf_cgroup_info);
13792 return ERR_PTR(-ENOMEM);
13798 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13800 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13802 free_percpu(jc->info);
13806 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13808 perf_event_cgroup(css->cgroup);
13812 static int __perf_cgroup_move(void *info)
13814 struct task_struct *task = info;
13817 perf_cgroup_switch(task);
13823 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13825 struct task_struct *task;
13826 struct cgroup_subsys_state *css;
13828 cgroup_taskset_for_each(task, css, tset)
13829 task_function_call(task, __perf_cgroup_move, task);
13832 struct cgroup_subsys perf_event_cgrp_subsys = {
13833 .css_alloc = perf_cgroup_css_alloc,
13834 .css_free = perf_cgroup_css_free,
13835 .css_online = perf_cgroup_css_online,
13836 .attach = perf_cgroup_attach,
13838 * Implicitly enable on dfl hierarchy so that perf events can
13839 * always be filtered by cgroup2 path as long as perf_event
13840 * controller is not mounted on a legacy hierarchy.
13842 .implicit_on_dfl = true,
13845 #endif /* CONFIG_CGROUP_PERF */
13847 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);