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 */
378 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
382 * perf_sched_events : >0 events exist
385 static void perf_sched_delayed(struct work_struct *work);
386 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
387 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
388 static DEFINE_MUTEX(perf_sched_mutex);
389 static atomic_t perf_sched_count;
391 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
393 static atomic_t nr_mmap_events __read_mostly;
394 static atomic_t nr_comm_events __read_mostly;
395 static atomic_t nr_namespaces_events __read_mostly;
396 static atomic_t nr_task_events __read_mostly;
397 static atomic_t nr_freq_events __read_mostly;
398 static atomic_t nr_switch_events __read_mostly;
399 static atomic_t nr_ksymbol_events __read_mostly;
400 static atomic_t nr_bpf_events __read_mostly;
401 static atomic_t nr_cgroup_events __read_mostly;
402 static atomic_t nr_text_poke_events __read_mostly;
403 static atomic_t nr_build_id_events __read_mostly;
405 static LIST_HEAD(pmus);
406 static DEFINE_MUTEX(pmus_lock);
407 static struct srcu_struct pmus_srcu;
408 static cpumask_var_t perf_online_mask;
409 static struct kmem_cache *perf_event_cache;
412 * perf event paranoia level:
413 * -1 - not paranoid at all
414 * 0 - disallow raw tracepoint access for unpriv
415 * 1 - disallow cpu events for unpriv
416 * 2 - disallow kernel profiling for unpriv
418 int sysctl_perf_event_paranoid __read_mostly = 2;
420 /* Minimum for 512 kiB + 1 user control page */
421 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
424 * max perf event sample rate
426 #define DEFAULT_MAX_SAMPLE_RATE 100000
427 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
428 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
430 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
432 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
433 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
435 static int perf_sample_allowed_ns __read_mostly =
436 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
438 static void update_perf_cpu_limits(void)
440 u64 tmp = perf_sample_period_ns;
442 tmp *= sysctl_perf_cpu_time_max_percent;
443 tmp = div_u64(tmp, 100);
447 WRITE_ONCE(perf_sample_allowed_ns, tmp);
450 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
452 int perf_proc_update_handler(struct ctl_table *table, int write,
453 void *buffer, size_t *lenp, loff_t *ppos)
456 int perf_cpu = sysctl_perf_cpu_time_max_percent;
458 * If throttling is disabled don't allow the write:
460 if (write && (perf_cpu == 100 || perf_cpu == 0))
463 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
467 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
468 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
469 update_perf_cpu_limits();
474 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
476 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
477 void *buffer, size_t *lenp, loff_t *ppos)
479 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
484 if (sysctl_perf_cpu_time_max_percent == 100 ||
485 sysctl_perf_cpu_time_max_percent == 0) {
487 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
488 WRITE_ONCE(perf_sample_allowed_ns, 0);
490 update_perf_cpu_limits();
497 * perf samples are done in some very critical code paths (NMIs).
498 * If they take too much CPU time, the system can lock up and not
499 * get any real work done. This will drop the sample rate when
500 * we detect that events are taking too long.
502 #define NR_ACCUMULATED_SAMPLES 128
503 static DEFINE_PER_CPU(u64, running_sample_length);
505 static u64 __report_avg;
506 static u64 __report_allowed;
508 static void perf_duration_warn(struct irq_work *w)
510 printk_ratelimited(KERN_INFO
511 "perf: interrupt took too long (%lld > %lld), lowering "
512 "kernel.perf_event_max_sample_rate to %d\n",
513 __report_avg, __report_allowed,
514 sysctl_perf_event_sample_rate);
517 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
519 void perf_sample_event_took(u64 sample_len_ns)
521 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
529 /* Decay the counter by 1 average sample. */
530 running_len = __this_cpu_read(running_sample_length);
531 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
532 running_len += sample_len_ns;
533 __this_cpu_write(running_sample_length, running_len);
536 * Note: this will be biased artifically low until we have
537 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
538 * from having to maintain a count.
540 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
541 if (avg_len <= max_len)
544 __report_avg = avg_len;
545 __report_allowed = max_len;
548 * Compute a throttle threshold 25% below the current duration.
550 avg_len += avg_len / 4;
551 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
557 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
558 WRITE_ONCE(max_samples_per_tick, max);
560 sysctl_perf_event_sample_rate = max * HZ;
561 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
563 if (!irq_work_queue(&perf_duration_work)) {
564 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
565 "kernel.perf_event_max_sample_rate to %d\n",
566 __report_avg, __report_allowed,
567 sysctl_perf_event_sample_rate);
571 static atomic64_t perf_event_id;
573 static void update_context_time(struct perf_event_context *ctx);
574 static u64 perf_event_time(struct perf_event *event);
576 void __weak perf_event_print_debug(void) { }
578 static inline u64 perf_clock(void)
580 return local_clock();
583 static inline u64 perf_event_clock(struct perf_event *event)
585 return event->clock();
589 * State based event timekeeping...
591 * The basic idea is to use event->state to determine which (if any) time
592 * fields to increment with the current delta. This means we only need to
593 * update timestamps when we change state or when they are explicitly requested
596 * Event groups make things a little more complicated, but not terribly so. The
597 * rules for a group are that if the group leader is OFF the entire group is
598 * OFF, irrespecive of what the group member states are. This results in
599 * __perf_effective_state().
601 * A futher ramification is that when a group leader flips between OFF and
602 * !OFF, we need to update all group member times.
605 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
606 * need to make sure the relevant context time is updated before we try and
607 * update our timestamps.
610 static __always_inline enum perf_event_state
611 __perf_effective_state(struct perf_event *event)
613 struct perf_event *leader = event->group_leader;
615 if (leader->state <= PERF_EVENT_STATE_OFF)
616 return leader->state;
621 static __always_inline void
622 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
624 enum perf_event_state state = __perf_effective_state(event);
625 u64 delta = now - event->tstamp;
627 *enabled = event->total_time_enabled;
628 if (state >= PERF_EVENT_STATE_INACTIVE)
631 *running = event->total_time_running;
632 if (state >= PERF_EVENT_STATE_ACTIVE)
636 static void perf_event_update_time(struct perf_event *event)
638 u64 now = perf_event_time(event);
640 __perf_update_times(event, now, &event->total_time_enabled,
641 &event->total_time_running);
645 static void perf_event_update_sibling_time(struct perf_event *leader)
647 struct perf_event *sibling;
649 for_each_sibling_event(sibling, leader)
650 perf_event_update_time(sibling);
654 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
656 if (event->state == state)
659 perf_event_update_time(event);
661 * If a group leader gets enabled/disabled all its siblings
664 if ((event->state < 0) ^ (state < 0))
665 perf_event_update_sibling_time(event);
667 WRITE_ONCE(event->state, state);
671 * UP store-release, load-acquire
674 #define __store_release(ptr, val) \
677 WRITE_ONCE(*(ptr), (val)); \
680 #define __load_acquire(ptr) \
682 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
687 static void perf_ctx_disable(struct perf_event_context *ctx)
689 struct perf_event_pmu_context *pmu_ctx;
691 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry)
692 perf_pmu_disable(pmu_ctx->pmu);
695 static void perf_ctx_enable(struct perf_event_context *ctx)
697 struct perf_event_pmu_context *pmu_ctx;
699 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry)
700 perf_pmu_enable(pmu_ctx->pmu);
703 static void ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type);
704 static void ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type);
706 #ifdef CONFIG_CGROUP_PERF
709 perf_cgroup_match(struct perf_event *event)
711 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
713 /* @event doesn't care about cgroup */
717 /* wants specific cgroup scope but @cpuctx isn't associated with any */
722 * Cgroup scoping is recursive. An event enabled for a cgroup is
723 * also enabled for all its descendant cgroups. If @cpuctx's
724 * cgroup is a descendant of @event's (the test covers identity
725 * case), it's a match.
727 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
728 event->cgrp->css.cgroup);
731 static inline void perf_detach_cgroup(struct perf_event *event)
733 css_put(&event->cgrp->css);
737 static inline int is_cgroup_event(struct perf_event *event)
739 return event->cgrp != NULL;
742 static inline u64 perf_cgroup_event_time(struct perf_event *event)
744 struct perf_cgroup_info *t;
746 t = per_cpu_ptr(event->cgrp->info, event->cpu);
750 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
752 struct perf_cgroup_info *t;
754 t = per_cpu_ptr(event->cgrp->info, event->cpu);
755 if (!__load_acquire(&t->active))
757 now += READ_ONCE(t->timeoffset);
761 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
764 info->time += now - info->timestamp;
765 info->timestamp = now;
767 * see update_context_time()
769 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
772 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
774 struct perf_cgroup *cgrp = cpuctx->cgrp;
775 struct cgroup_subsys_state *css;
776 struct perf_cgroup_info *info;
779 u64 now = perf_clock();
781 for (css = &cgrp->css; css; css = css->parent) {
782 cgrp = container_of(css, struct perf_cgroup, css);
783 info = this_cpu_ptr(cgrp->info);
785 __update_cgrp_time(info, now, true);
787 __store_release(&info->active, 0);
792 static inline void update_cgrp_time_from_event(struct perf_event *event)
794 struct perf_cgroup_info *info;
797 * ensure we access cgroup data only when needed and
798 * when we know the cgroup is pinned (css_get)
800 if (!is_cgroup_event(event))
803 info = this_cpu_ptr(event->cgrp->info);
805 * Do not update time when cgroup is not active
808 __update_cgrp_time(info, perf_clock(), true);
812 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
814 struct perf_event_context *ctx = &cpuctx->ctx;
815 struct perf_cgroup *cgrp = cpuctx->cgrp;
816 struct perf_cgroup_info *info;
817 struct cgroup_subsys_state *css;
820 * ctx->lock held by caller
821 * ensure we do not access cgroup data
822 * unless we have the cgroup pinned (css_get)
827 WARN_ON_ONCE(!ctx->nr_cgroups);
829 for (css = &cgrp->css; css; css = css->parent) {
830 cgrp = container_of(css, struct perf_cgroup, css);
831 info = this_cpu_ptr(cgrp->info);
832 __update_cgrp_time(info, ctx->timestamp, false);
833 __store_release(&info->active, 1);
838 * reschedule events based on the cgroup constraint of task.
840 static void perf_cgroup_switch(struct task_struct *task)
842 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
843 struct perf_cgroup *cgrp;
846 * cpuctx->cgrp is set when the first cgroup event enabled,
847 * and is cleared when the last cgroup event disabled.
849 if (READ_ONCE(cpuctx->cgrp) == NULL)
852 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
854 cgrp = perf_cgroup_from_task(task, NULL);
855 if (READ_ONCE(cpuctx->cgrp) == cgrp)
858 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
859 perf_ctx_disable(&cpuctx->ctx);
861 ctx_sched_out(&cpuctx->ctx, EVENT_ALL);
863 * must not be done before ctxswout due
864 * to update_cgrp_time_from_cpuctx() in
869 * set cgrp before ctxsw in to allow
870 * perf_cgroup_set_timestamp() in ctx_sched_in()
871 * to not have to pass task around
873 ctx_sched_in(&cpuctx->ctx, EVENT_ALL);
875 perf_ctx_enable(&cpuctx->ctx);
876 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
879 static int perf_cgroup_ensure_storage(struct perf_event *event,
880 struct cgroup_subsys_state *css)
882 struct perf_cpu_context *cpuctx;
883 struct perf_event **storage;
884 int cpu, heap_size, ret = 0;
887 * Allow storage to have sufficent space for an iterator for each
888 * possibly nested cgroup plus an iterator for events with no cgroup.
890 for (heap_size = 1; css; css = css->parent)
893 for_each_possible_cpu(cpu) {
894 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
895 if (heap_size <= cpuctx->heap_size)
898 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
899 GFP_KERNEL, cpu_to_node(cpu));
905 raw_spin_lock_irq(&cpuctx->ctx.lock);
906 if (cpuctx->heap_size < heap_size) {
907 swap(cpuctx->heap, storage);
908 if (storage == cpuctx->heap_default)
910 cpuctx->heap_size = heap_size;
912 raw_spin_unlock_irq(&cpuctx->ctx.lock);
920 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
921 struct perf_event_attr *attr,
922 struct perf_event *group_leader)
924 struct perf_cgroup *cgrp;
925 struct cgroup_subsys_state *css;
926 struct fd f = fdget(fd);
932 css = css_tryget_online_from_dir(f.file->f_path.dentry,
933 &perf_event_cgrp_subsys);
939 ret = perf_cgroup_ensure_storage(event, css);
943 cgrp = container_of(css, struct perf_cgroup, css);
947 * all events in a group must monitor
948 * the same cgroup because a task belongs
949 * to only one perf cgroup at a time
951 if (group_leader && group_leader->cgrp != cgrp) {
952 perf_detach_cgroup(event);
961 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
963 struct perf_cpu_context *cpuctx;
965 if (!is_cgroup_event(event))
969 * Because cgroup events are always per-cpu events,
970 * @ctx == &cpuctx->ctx.
972 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
974 if (ctx->nr_cgroups++)
977 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
981 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
983 struct perf_cpu_context *cpuctx;
985 if (!is_cgroup_event(event))
989 * Because cgroup events are always per-cpu events,
990 * @ctx == &cpuctx->ctx.
992 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
994 if (--ctx->nr_cgroups)
1000 #else /* !CONFIG_CGROUP_PERF */
1003 perf_cgroup_match(struct perf_event *event)
1008 static inline void perf_detach_cgroup(struct perf_event *event)
1011 static inline int is_cgroup_event(struct perf_event *event)
1016 static inline void update_cgrp_time_from_event(struct perf_event *event)
1020 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1025 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1026 struct perf_event_attr *attr,
1027 struct perf_event *group_leader)
1033 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1037 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1042 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1048 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1053 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1057 static void perf_cgroup_switch(struct task_struct *task)
1063 * set default to be dependent on timer tick just
1064 * like original code
1066 #define PERF_CPU_HRTIMER (1000 / HZ)
1068 * function must be called with interrupts disabled
1070 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1072 struct perf_cpu_pmu_context *cpc;
1075 lockdep_assert_irqs_disabled();
1077 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1078 rotations = perf_rotate_context(cpc);
1080 raw_spin_lock(&cpc->hrtimer_lock);
1082 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1084 cpc->hrtimer_active = 0;
1085 raw_spin_unlock(&cpc->hrtimer_lock);
1087 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1090 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1092 struct hrtimer *timer = &cpc->hrtimer;
1093 struct pmu *pmu = cpc->epc.pmu;
1097 * check default is sane, if not set then force to
1098 * default interval (1/tick)
1100 interval = pmu->hrtimer_interval_ms;
1102 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1104 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1106 raw_spin_lock_init(&cpc->hrtimer_lock);
1107 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1108 timer->function = perf_mux_hrtimer_handler;
1111 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1113 struct hrtimer *timer = &cpc->hrtimer;
1114 unsigned long flags;
1116 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1117 if (!cpc->hrtimer_active) {
1118 cpc->hrtimer_active = 1;
1119 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1120 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1122 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1127 static int perf_mux_hrtimer_restart_ipi(void *arg)
1129 return perf_mux_hrtimer_restart(arg);
1132 void perf_pmu_disable(struct pmu *pmu)
1134 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1136 pmu->pmu_disable(pmu);
1139 void perf_pmu_enable(struct pmu *pmu)
1141 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1143 pmu->pmu_enable(pmu);
1146 static void perf_assert_pmu_disabled(struct pmu *pmu)
1148 WARN_ON_ONCE(*this_cpu_ptr(pmu->pmu_disable_count) == 0);
1151 static void get_ctx(struct perf_event_context *ctx)
1153 refcount_inc(&ctx->refcount);
1156 static void *alloc_task_ctx_data(struct pmu *pmu)
1158 if (pmu->task_ctx_cache)
1159 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1164 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1166 if (pmu->task_ctx_cache && task_ctx_data)
1167 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1170 static void free_ctx(struct rcu_head *head)
1172 struct perf_event_context *ctx;
1174 ctx = container_of(head, struct perf_event_context, rcu_head);
1178 static void put_ctx(struct perf_event_context *ctx)
1180 if (refcount_dec_and_test(&ctx->refcount)) {
1181 if (ctx->parent_ctx)
1182 put_ctx(ctx->parent_ctx);
1183 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1184 put_task_struct(ctx->task);
1185 call_rcu(&ctx->rcu_head, free_ctx);
1190 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1191 * perf_pmu_migrate_context() we need some magic.
1193 * Those places that change perf_event::ctx will hold both
1194 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1196 * Lock ordering is by mutex address. There are two other sites where
1197 * perf_event_context::mutex nests and those are:
1199 * - perf_event_exit_task_context() [ child , 0 ]
1200 * perf_event_exit_event()
1201 * put_event() [ parent, 1 ]
1203 * - perf_event_init_context() [ parent, 0 ]
1204 * inherit_task_group()
1207 * perf_event_alloc()
1209 * perf_try_init_event() [ child , 1 ]
1211 * While it appears there is an obvious deadlock here -- the parent and child
1212 * nesting levels are inverted between the two. This is in fact safe because
1213 * life-time rules separate them. That is an exiting task cannot fork, and a
1214 * spawning task cannot (yet) exit.
1216 * But remember that these are parent<->child context relations, and
1217 * migration does not affect children, therefore these two orderings should not
1220 * The change in perf_event::ctx does not affect children (as claimed above)
1221 * because the sys_perf_event_open() case will install a new event and break
1222 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1223 * concerned with cpuctx and that doesn't have children.
1225 * The places that change perf_event::ctx will issue:
1227 * perf_remove_from_context();
1228 * synchronize_rcu();
1229 * perf_install_in_context();
1231 * to affect the change. The remove_from_context() + synchronize_rcu() should
1232 * quiesce the event, after which we can install it in the new location. This
1233 * means that only external vectors (perf_fops, prctl) can perturb the event
1234 * while in transit. Therefore all such accessors should also acquire
1235 * perf_event_context::mutex to serialize against this.
1237 * However; because event->ctx can change while we're waiting to acquire
1238 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1243 * task_struct::perf_event_mutex
1244 * perf_event_context::mutex
1245 * perf_event::child_mutex;
1246 * perf_event_context::lock
1247 * perf_event::mmap_mutex
1249 * perf_addr_filters_head::lock
1253 * cpuctx->mutex / perf_event_context::mutex
1255 static struct perf_event_context *
1256 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1258 struct perf_event_context *ctx;
1262 ctx = READ_ONCE(event->ctx);
1263 if (!refcount_inc_not_zero(&ctx->refcount)) {
1269 mutex_lock_nested(&ctx->mutex, nesting);
1270 if (event->ctx != ctx) {
1271 mutex_unlock(&ctx->mutex);
1279 static inline struct perf_event_context *
1280 perf_event_ctx_lock(struct perf_event *event)
1282 return perf_event_ctx_lock_nested(event, 0);
1285 static void perf_event_ctx_unlock(struct perf_event *event,
1286 struct perf_event_context *ctx)
1288 mutex_unlock(&ctx->mutex);
1293 * This must be done under the ctx->lock, such as to serialize against
1294 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1295 * calling scheduler related locks and ctx->lock nests inside those.
1297 static __must_check struct perf_event_context *
1298 unclone_ctx(struct perf_event_context *ctx)
1300 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1302 lockdep_assert_held(&ctx->lock);
1305 ctx->parent_ctx = NULL;
1311 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1316 * only top level events have the pid namespace they were created in
1319 event = event->parent;
1321 nr = __task_pid_nr_ns(p, type, event->ns);
1322 /* avoid -1 if it is idle thread or runs in another ns */
1323 if (!nr && !pid_alive(p))
1328 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1330 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1333 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1335 return perf_event_pid_type(event, p, PIDTYPE_PID);
1339 * If we inherit events we want to return the parent event id
1342 static u64 primary_event_id(struct perf_event *event)
1347 id = event->parent->id;
1353 * Get the perf_event_context for a task and lock it.
1355 * This has to cope with the fact that until it is locked,
1356 * the context could get moved to another task.
1358 static struct perf_event_context *
1359 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1361 struct perf_event_context *ctx;
1365 * One of the few rules of preemptible RCU is that one cannot do
1366 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1367 * part of the read side critical section was irqs-enabled -- see
1368 * rcu_read_unlock_special().
1370 * Since ctx->lock nests under rq->lock we must ensure the entire read
1371 * side critical section has interrupts disabled.
1373 local_irq_save(*flags);
1375 ctx = rcu_dereference(task->perf_event_ctxp);
1378 * If this context is a clone of another, it might
1379 * get swapped for another underneath us by
1380 * perf_event_task_sched_out, though the
1381 * rcu_read_lock() protects us from any context
1382 * getting freed. Lock the context and check if it
1383 * got swapped before we could get the lock, and retry
1384 * if so. If we locked the right context, then it
1385 * can't get swapped on us any more.
1387 raw_spin_lock(&ctx->lock);
1388 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1389 raw_spin_unlock(&ctx->lock);
1391 local_irq_restore(*flags);
1395 if (ctx->task == TASK_TOMBSTONE ||
1396 !refcount_inc_not_zero(&ctx->refcount)) {
1397 raw_spin_unlock(&ctx->lock);
1400 WARN_ON_ONCE(ctx->task != task);
1405 local_irq_restore(*flags);
1410 * Get the context for a task and increment its pin_count so it
1411 * can't get swapped to another task. This also increments its
1412 * reference count so that the context can't get freed.
1414 static struct perf_event_context *
1415 perf_pin_task_context(struct task_struct *task)
1417 struct perf_event_context *ctx;
1418 unsigned long flags;
1420 ctx = perf_lock_task_context(task, &flags);
1423 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1428 static void perf_unpin_context(struct perf_event_context *ctx)
1430 unsigned long flags;
1432 raw_spin_lock_irqsave(&ctx->lock, flags);
1434 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1438 * Update the record of the current time in a context.
1440 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1442 u64 now = perf_clock();
1444 lockdep_assert_held(&ctx->lock);
1447 ctx->time += now - ctx->timestamp;
1448 ctx->timestamp = now;
1451 * The above: time' = time + (now - timestamp), can be re-arranged
1452 * into: time` = now + (time - timestamp), which gives a single value
1453 * offset to compute future time without locks on.
1455 * See perf_event_time_now(), which can be used from NMI context where
1456 * it's (obviously) not possible to acquire ctx->lock in order to read
1457 * both the above values in a consistent manner.
1459 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1462 static void update_context_time(struct perf_event_context *ctx)
1464 __update_context_time(ctx, true);
1467 static u64 perf_event_time(struct perf_event *event)
1469 struct perf_event_context *ctx = event->ctx;
1474 if (is_cgroup_event(event))
1475 return perf_cgroup_event_time(event);
1480 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1482 struct perf_event_context *ctx = event->ctx;
1487 if (is_cgroup_event(event))
1488 return perf_cgroup_event_time_now(event, now);
1490 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1493 now += READ_ONCE(ctx->timeoffset);
1497 static enum event_type_t get_event_type(struct perf_event *event)
1499 struct perf_event_context *ctx = event->ctx;
1500 enum event_type_t event_type;
1502 lockdep_assert_held(&ctx->lock);
1505 * It's 'group type', really, because if our group leader is
1506 * pinned, so are we.
1508 if (event->group_leader != event)
1509 event = event->group_leader;
1511 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1513 event_type |= EVENT_CPU;
1519 * Helper function to initialize event group nodes.
1521 static void init_event_group(struct perf_event *event)
1523 RB_CLEAR_NODE(&event->group_node);
1524 event->group_index = 0;
1528 * Extract pinned or flexible groups from the context
1529 * based on event attrs bits.
1531 static struct perf_event_groups *
1532 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1534 if (event->attr.pinned)
1535 return &ctx->pinned_groups;
1537 return &ctx->flexible_groups;
1541 * Helper function to initializes perf_event_group trees.
1543 static void perf_event_groups_init(struct perf_event_groups *groups)
1545 groups->tree = RB_ROOT;
1549 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1551 struct cgroup *cgroup = NULL;
1553 #ifdef CONFIG_CGROUP_PERF
1555 cgroup = event->cgrp->css.cgroup;
1562 * Compare function for event groups;
1564 * Implements complex key that first sorts by CPU and then by virtual index
1565 * which provides ordering when rotating groups for the same CPU.
1567 static __always_inline int
1568 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1569 const struct cgroup *left_cgroup, const u64 left_group_index,
1570 const struct perf_event *right)
1572 if (left_cpu < right->cpu)
1574 if (left_cpu > right->cpu)
1578 if (left_pmu < right->pmu_ctx->pmu)
1580 if (left_pmu > right->pmu_ctx->pmu)
1584 #ifdef CONFIG_CGROUP_PERF
1586 const struct cgroup *right_cgroup = event_cgroup(right);
1588 if (left_cgroup != right_cgroup) {
1591 * Left has no cgroup but right does, no
1592 * cgroups come first.
1596 if (!right_cgroup) {
1598 * Right has no cgroup but left does, no
1599 * cgroups come first.
1603 /* Two dissimilar cgroups, order by id. */
1604 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1612 if (left_group_index < right->group_index)
1614 if (left_group_index > right->group_index)
1620 #define __node_2_pe(node) \
1621 rb_entry((node), struct perf_event, group_node)
1623 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1625 struct perf_event *e = __node_2_pe(a);
1626 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1627 e->group_index, __node_2_pe(b)) < 0;
1630 struct __group_key {
1633 struct cgroup *cgroup;
1636 static inline int __group_cmp(const void *key, const struct rb_node *node)
1638 const struct __group_key *a = key;
1639 const struct perf_event *b = __node_2_pe(node);
1641 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1642 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1646 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1648 const struct __group_key *a = key;
1649 const struct perf_event *b = __node_2_pe(node);
1651 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1652 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1657 * Insert @event into @groups' tree; using
1658 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1659 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1662 perf_event_groups_insert(struct perf_event_groups *groups,
1663 struct perf_event *event)
1665 event->group_index = ++groups->index;
1667 rb_add(&event->group_node, &groups->tree, __group_less);
1671 * Helper function to insert event into the pinned or flexible groups.
1674 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1676 struct perf_event_groups *groups;
1678 groups = get_event_groups(event, ctx);
1679 perf_event_groups_insert(groups, event);
1683 * Delete a group from a tree.
1686 perf_event_groups_delete(struct perf_event_groups *groups,
1687 struct perf_event *event)
1689 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1690 RB_EMPTY_ROOT(&groups->tree));
1692 rb_erase(&event->group_node, &groups->tree);
1693 init_event_group(event);
1697 * Helper function to delete event from its groups.
1700 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1702 struct perf_event_groups *groups;
1704 groups = get_event_groups(event, ctx);
1705 perf_event_groups_delete(groups, event);
1709 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1711 static struct perf_event *
1712 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1713 struct pmu *pmu, struct cgroup *cgrp)
1715 struct __group_key key = {
1720 struct rb_node *node;
1722 node = rb_find_first(&key, &groups->tree, __group_cmp);
1724 return __node_2_pe(node);
1729 static struct perf_event *
1730 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1732 struct __group_key key = {
1735 .cgroup = event_cgroup(event),
1737 struct rb_node *next;
1739 next = rb_next_match(&key, &event->group_node, __group_cmp);
1741 return __node_2_pe(next);
1746 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1747 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1748 event; event = perf_event_groups_next(event, pmu))
1751 * Iterate through the whole groups tree.
1753 #define perf_event_groups_for_each(event, groups) \
1754 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1755 typeof(*event), group_node); event; \
1756 event = rb_entry_safe(rb_next(&event->group_node), \
1757 typeof(*event), group_node))
1760 * Add an event from the lists for its context.
1761 * Must be called with ctx->mutex and ctx->lock held.
1764 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1766 lockdep_assert_held(&ctx->lock);
1768 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1769 event->attach_state |= PERF_ATTACH_CONTEXT;
1771 event->tstamp = perf_event_time(event);
1774 * If we're a stand alone event or group leader, we go to the context
1775 * list, group events are kept attached to the group so that
1776 * perf_group_detach can, at all times, locate all siblings.
1778 if (event->group_leader == event) {
1779 event->group_caps = event->event_caps;
1780 add_event_to_groups(event, ctx);
1783 list_add_rcu(&event->event_entry, &ctx->event_list);
1785 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1787 if (event->attr.inherit_stat)
1790 if (event->state > PERF_EVENT_STATE_OFF)
1791 perf_cgroup_event_enable(event, ctx);
1794 event->pmu_ctx->nr_events++;
1798 * Initialize event state based on the perf_event_attr::disabled.
1800 static inline void perf_event__state_init(struct perf_event *event)
1802 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1803 PERF_EVENT_STATE_INACTIVE;
1806 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1808 int entry = sizeof(u64); /* value */
1812 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1813 size += sizeof(u64);
1815 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1816 size += sizeof(u64);
1818 if (event->attr.read_format & PERF_FORMAT_ID)
1819 entry += sizeof(u64);
1821 if (event->attr.read_format & PERF_FORMAT_LOST)
1822 entry += sizeof(u64);
1824 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1826 size += sizeof(u64);
1830 event->read_size = size;
1833 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1835 struct perf_sample_data *data;
1838 if (sample_type & PERF_SAMPLE_IP)
1839 size += sizeof(data->ip);
1841 if (sample_type & PERF_SAMPLE_ADDR)
1842 size += sizeof(data->addr);
1844 if (sample_type & PERF_SAMPLE_PERIOD)
1845 size += sizeof(data->period);
1847 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1848 size += sizeof(data->weight.full);
1850 if (sample_type & PERF_SAMPLE_READ)
1851 size += event->read_size;
1853 if (sample_type & PERF_SAMPLE_DATA_SRC)
1854 size += sizeof(data->data_src.val);
1856 if (sample_type & PERF_SAMPLE_TRANSACTION)
1857 size += sizeof(data->txn);
1859 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1860 size += sizeof(data->phys_addr);
1862 if (sample_type & PERF_SAMPLE_CGROUP)
1863 size += sizeof(data->cgroup);
1865 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1866 size += sizeof(data->data_page_size);
1868 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1869 size += sizeof(data->code_page_size);
1871 event->header_size = size;
1875 * Called at perf_event creation and when events are attached/detached from a
1878 static void perf_event__header_size(struct perf_event *event)
1880 __perf_event_read_size(event,
1881 event->group_leader->nr_siblings);
1882 __perf_event_header_size(event, event->attr.sample_type);
1885 static void perf_event__id_header_size(struct perf_event *event)
1887 struct perf_sample_data *data;
1888 u64 sample_type = event->attr.sample_type;
1891 if (sample_type & PERF_SAMPLE_TID)
1892 size += sizeof(data->tid_entry);
1894 if (sample_type & PERF_SAMPLE_TIME)
1895 size += sizeof(data->time);
1897 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1898 size += sizeof(data->id);
1900 if (sample_type & PERF_SAMPLE_ID)
1901 size += sizeof(data->id);
1903 if (sample_type & PERF_SAMPLE_STREAM_ID)
1904 size += sizeof(data->stream_id);
1906 if (sample_type & PERF_SAMPLE_CPU)
1907 size += sizeof(data->cpu_entry);
1909 event->id_header_size = size;
1912 static bool perf_event_validate_size(struct perf_event *event)
1915 * The values computed here will be over-written when we actually
1918 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1919 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1920 perf_event__id_header_size(event);
1923 * Sum the lot; should not exceed the 64k limit we have on records.
1924 * Conservative limit to allow for callchains and other variable fields.
1926 if (event->read_size + event->header_size +
1927 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1933 static void perf_group_attach(struct perf_event *event)
1935 struct perf_event *group_leader = event->group_leader, *pos;
1937 lockdep_assert_held(&event->ctx->lock);
1940 * We can have double attach due to group movement (move_group) in
1941 * perf_event_open().
1943 if (event->attach_state & PERF_ATTACH_GROUP)
1946 event->attach_state |= PERF_ATTACH_GROUP;
1948 if (group_leader == event)
1951 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1953 group_leader->group_caps &= event->event_caps;
1955 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1956 group_leader->nr_siblings++;
1958 perf_event__header_size(group_leader);
1960 for_each_sibling_event(pos, group_leader)
1961 perf_event__header_size(pos);
1965 * Remove an event from the lists for its context.
1966 * Must be called with ctx->mutex and ctx->lock held.
1969 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1971 WARN_ON_ONCE(event->ctx != ctx);
1972 lockdep_assert_held(&ctx->lock);
1975 * We can have double detach due to exit/hot-unplug + close.
1977 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1980 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1983 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1985 if (event->attr.inherit_stat)
1988 list_del_rcu(&event->event_entry);
1990 if (event->group_leader == event)
1991 del_event_from_groups(event, ctx);
1994 * If event was in error state, then keep it
1995 * that way, otherwise bogus counts will be
1996 * returned on read(). The only way to get out
1997 * of error state is by explicit re-enabling
2000 if (event->state > PERF_EVENT_STATE_OFF) {
2001 perf_cgroup_event_disable(event, ctx);
2002 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2006 event->pmu_ctx->nr_events--;
2010 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2012 if (!has_aux(aux_event))
2015 if (!event->pmu->aux_output_match)
2018 return event->pmu->aux_output_match(aux_event);
2021 static void put_event(struct perf_event *event);
2022 static void event_sched_out(struct perf_event *event,
2023 struct perf_event_context *ctx);
2025 static void perf_put_aux_event(struct perf_event *event)
2027 struct perf_event_context *ctx = event->ctx;
2028 struct perf_event *iter;
2031 * If event uses aux_event tear down the link
2033 if (event->aux_event) {
2034 iter = event->aux_event;
2035 event->aux_event = NULL;
2041 * If the event is an aux_event, tear down all links to
2042 * it from other events.
2044 for_each_sibling_event(iter, event->group_leader) {
2045 if (iter->aux_event != event)
2048 iter->aux_event = NULL;
2052 * If it's ACTIVE, schedule it out and put it into ERROR
2053 * state so that we don't try to schedule it again. Note
2054 * that perf_event_enable() will clear the ERROR status.
2056 event_sched_out(iter, ctx);
2057 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2061 static bool perf_need_aux_event(struct perf_event *event)
2063 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2066 static int perf_get_aux_event(struct perf_event *event,
2067 struct perf_event *group_leader)
2070 * Our group leader must be an aux event if we want to be
2071 * an aux_output. This way, the aux event will precede its
2072 * aux_output events in the group, and therefore will always
2079 * aux_output and aux_sample_size are mutually exclusive.
2081 if (event->attr.aux_output && event->attr.aux_sample_size)
2084 if (event->attr.aux_output &&
2085 !perf_aux_output_match(event, group_leader))
2088 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2091 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2095 * Link aux_outputs to their aux event; this is undone in
2096 * perf_group_detach() by perf_put_aux_event(). When the
2097 * group in torn down, the aux_output events loose their
2098 * link to the aux_event and can't schedule any more.
2100 event->aux_event = group_leader;
2105 static inline struct list_head *get_event_list(struct perf_event *event)
2107 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2108 &event->pmu_ctx->flexible_active;
2112 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2113 * cannot exist on their own, schedule them out and move them into the ERROR
2114 * state. Also see _perf_event_enable(), it will not be able to recover
2117 static inline void perf_remove_sibling_event(struct perf_event *event)
2119 event_sched_out(event, event->ctx);
2120 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2123 static void perf_group_detach(struct perf_event *event)
2125 struct perf_event *leader = event->group_leader;
2126 struct perf_event *sibling, *tmp;
2127 struct perf_event_context *ctx = event->ctx;
2129 lockdep_assert_held(&ctx->lock);
2132 * We can have double detach due to exit/hot-unplug + close.
2134 if (!(event->attach_state & PERF_ATTACH_GROUP))
2137 event->attach_state &= ~PERF_ATTACH_GROUP;
2139 perf_put_aux_event(event);
2142 * If this is a sibling, remove it from its group.
2144 if (leader != event) {
2145 list_del_init(&event->sibling_list);
2146 event->group_leader->nr_siblings--;
2151 * If this was a group event with sibling events then
2152 * upgrade the siblings to singleton events by adding them
2153 * to whatever list we are on.
2155 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2157 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2158 perf_remove_sibling_event(sibling);
2160 sibling->group_leader = sibling;
2161 list_del_init(&sibling->sibling_list);
2163 /* Inherit group flags from the previous leader */
2164 sibling->group_caps = event->group_caps;
2166 if (!RB_EMPTY_NODE(&event->group_node)) {
2167 add_event_to_groups(sibling, event->ctx);
2169 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2170 list_add_tail(&sibling->active_list, get_event_list(sibling));
2173 WARN_ON_ONCE(sibling->ctx != event->ctx);
2177 for_each_sibling_event(tmp, leader)
2178 perf_event__header_size(tmp);
2180 perf_event__header_size(leader);
2183 static void sync_child_event(struct perf_event *child_event);
2185 static void perf_child_detach(struct perf_event *event)
2187 struct perf_event *parent_event = event->parent;
2189 if (!(event->attach_state & PERF_ATTACH_CHILD))
2192 event->attach_state &= ~PERF_ATTACH_CHILD;
2194 if (WARN_ON_ONCE(!parent_event))
2197 lockdep_assert_held(&parent_event->child_mutex);
2199 sync_child_event(event);
2200 list_del_init(&event->child_list);
2203 static bool is_orphaned_event(struct perf_event *event)
2205 return event->state == PERF_EVENT_STATE_DEAD;
2209 event_filter_match(struct perf_event *event)
2211 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2212 perf_cgroup_match(event);
2216 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2218 struct perf_event_pmu_context *epc = event->pmu_ctx;
2219 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2220 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2222 // XXX cpc serialization, probably per-cpu IRQ disabled
2224 WARN_ON_ONCE(event->ctx != ctx);
2225 lockdep_assert_held(&ctx->lock);
2227 if (event->state != PERF_EVENT_STATE_ACTIVE)
2231 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2232 * we can schedule events _OUT_ individually through things like
2233 * __perf_remove_from_context().
2235 list_del_init(&event->active_list);
2237 perf_pmu_disable(event->pmu);
2239 event->pmu->del(event, 0);
2242 if (event->pending_disable) {
2243 event->pending_disable = 0;
2244 perf_cgroup_event_disable(event, ctx);
2245 state = PERF_EVENT_STATE_OFF;
2248 if (event->pending_sigtrap) {
2251 event->pending_sigtrap = 0;
2252 if (state != PERF_EVENT_STATE_OFF &&
2253 !event->pending_work) {
2254 event->pending_work = 1;
2256 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
2257 task_work_add(current, &event->pending_task, TWA_RESUME);
2260 local_dec(&event->ctx->nr_pending);
2263 perf_event_set_state(event, state);
2265 if (!is_software_event(event))
2266 cpc->active_oncpu--;
2267 if (event->attr.freq && event->attr.sample_freq)
2269 if (event->attr.exclusive || !cpc->active_oncpu)
2272 perf_pmu_enable(event->pmu);
2276 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2278 struct perf_event *event;
2280 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2283 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2285 event_sched_out(group_event, ctx);
2288 * Schedule out siblings (if any):
2290 for_each_sibling_event(event, group_event)
2291 event_sched_out(event, ctx);
2294 #define DETACH_GROUP 0x01UL
2295 #define DETACH_CHILD 0x02UL
2296 #define DETACH_DEAD 0x04UL
2299 * Cross CPU call to remove a performance event
2301 * We disable the event on the hardware level first. After that we
2302 * remove it from the context list.
2305 __perf_remove_from_context(struct perf_event *event,
2306 struct perf_cpu_context *cpuctx,
2307 struct perf_event_context *ctx,
2310 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2311 unsigned long flags = (unsigned long)info;
2313 if (ctx->is_active & EVENT_TIME) {
2314 update_context_time(ctx);
2315 update_cgrp_time_from_cpuctx(cpuctx, false);
2319 * Ensure event_sched_out() switches to OFF, at the very least
2320 * this avoids raising perf_pending_task() at this time.
2322 if (flags & DETACH_DEAD)
2323 event->pending_disable = 1;
2324 event_sched_out(event, ctx);
2325 if (flags & DETACH_GROUP)
2326 perf_group_detach(event);
2327 if (flags & DETACH_CHILD)
2328 perf_child_detach(event);
2329 list_del_event(event, ctx);
2330 if (flags & DETACH_DEAD)
2331 event->state = PERF_EVENT_STATE_DEAD;
2333 if (!pmu_ctx->nr_events) {
2334 pmu_ctx->rotate_necessary = 0;
2336 if (ctx->task && ctx->is_active) {
2337 struct perf_cpu_pmu_context *cpc;
2339 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
2340 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2341 cpc->task_epc = NULL;
2345 if (!ctx->nr_events && ctx->is_active) {
2346 if (ctx == &cpuctx->ctx)
2347 update_cgrp_time_from_cpuctx(cpuctx, true);
2351 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2352 cpuctx->task_ctx = NULL;
2358 * Remove the event from a task's (or a CPU's) list of events.
2360 * If event->ctx is a cloned context, callers must make sure that
2361 * every task struct that event->ctx->task could possibly point to
2362 * remains valid. This is OK when called from perf_release since
2363 * that only calls us on the top-level context, which can't be a clone.
2364 * When called from perf_event_exit_task, it's OK because the
2365 * context has been detached from its task.
2367 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2369 struct perf_event_context *ctx = event->ctx;
2371 lockdep_assert_held(&ctx->mutex);
2374 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2375 * to work in the face of TASK_TOMBSTONE, unlike every other
2376 * event_function_call() user.
2378 raw_spin_lock_irq(&ctx->lock);
2379 if (!ctx->is_active) {
2380 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2381 ctx, (void *)flags);
2382 raw_spin_unlock_irq(&ctx->lock);
2385 raw_spin_unlock_irq(&ctx->lock);
2387 event_function_call(event, __perf_remove_from_context, (void *)flags);
2391 * Cross CPU call to disable a performance event
2393 static void __perf_event_disable(struct perf_event *event,
2394 struct perf_cpu_context *cpuctx,
2395 struct perf_event_context *ctx,
2398 if (event->state < PERF_EVENT_STATE_INACTIVE)
2401 if (ctx->is_active & EVENT_TIME) {
2402 update_context_time(ctx);
2403 update_cgrp_time_from_event(event);
2406 perf_pmu_disable(event->pmu_ctx->pmu);
2408 if (event == event->group_leader)
2409 group_sched_out(event, ctx);
2411 event_sched_out(event, ctx);
2413 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2414 perf_cgroup_event_disable(event, ctx);
2416 perf_pmu_enable(event->pmu_ctx->pmu);
2422 * If event->ctx is a cloned context, callers must make sure that
2423 * every task struct that event->ctx->task could possibly point to
2424 * remains valid. This condition is satisfied when called through
2425 * perf_event_for_each_child or perf_event_for_each because they
2426 * hold the top-level event's child_mutex, so any descendant that
2427 * goes to exit will block in perf_event_exit_event().
2429 * When called from perf_pending_irq it's OK because event->ctx
2430 * is the current context on this CPU and preemption is disabled,
2431 * hence we can't get into perf_event_task_sched_out for this context.
2433 static void _perf_event_disable(struct perf_event *event)
2435 struct perf_event_context *ctx = event->ctx;
2437 raw_spin_lock_irq(&ctx->lock);
2438 if (event->state <= PERF_EVENT_STATE_OFF) {
2439 raw_spin_unlock_irq(&ctx->lock);
2442 raw_spin_unlock_irq(&ctx->lock);
2444 event_function_call(event, __perf_event_disable, NULL);
2447 void perf_event_disable_local(struct perf_event *event)
2449 event_function_local(event, __perf_event_disable, NULL);
2453 * Strictly speaking kernel users cannot create groups and therefore this
2454 * interface does not need the perf_event_ctx_lock() magic.
2456 void perf_event_disable(struct perf_event *event)
2458 struct perf_event_context *ctx;
2460 ctx = perf_event_ctx_lock(event);
2461 _perf_event_disable(event);
2462 perf_event_ctx_unlock(event, ctx);
2464 EXPORT_SYMBOL_GPL(perf_event_disable);
2466 void perf_event_disable_inatomic(struct perf_event *event)
2468 event->pending_disable = 1;
2469 irq_work_queue(&event->pending_irq);
2472 #define MAX_INTERRUPTS (~0ULL)
2474 static void perf_log_throttle(struct perf_event *event, int enable);
2475 static void perf_log_itrace_start(struct perf_event *event);
2478 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2480 struct perf_event_pmu_context *epc = event->pmu_ctx;
2481 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2484 WARN_ON_ONCE(event->ctx != ctx);
2486 lockdep_assert_held(&ctx->lock);
2488 if (event->state <= PERF_EVENT_STATE_OFF)
2491 WRITE_ONCE(event->oncpu, smp_processor_id());
2493 * Order event::oncpu write to happen before the ACTIVE state is
2494 * visible. This allows perf_event_{stop,read}() to observe the correct
2495 * ->oncpu if it sees ACTIVE.
2498 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2501 * Unthrottle events, since we scheduled we might have missed several
2502 * ticks already, also for a heavily scheduling task there is little
2503 * guarantee it'll get a tick in a timely manner.
2505 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2506 perf_log_throttle(event, 1);
2507 event->hw.interrupts = 0;
2510 perf_pmu_disable(event->pmu);
2512 perf_log_itrace_start(event);
2514 if (event->pmu->add(event, PERF_EF_START)) {
2515 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2521 if (!is_software_event(event))
2522 cpc->active_oncpu++;
2523 if (event->attr.freq && event->attr.sample_freq)
2526 if (event->attr.exclusive)
2530 perf_pmu_enable(event->pmu);
2536 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2538 struct perf_event *event, *partial_group = NULL;
2539 struct pmu *pmu = group_event->pmu_ctx->pmu;
2541 if (group_event->state == PERF_EVENT_STATE_OFF)
2544 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2546 if (event_sched_in(group_event, ctx))
2550 * Schedule in siblings as one group (if any):
2552 for_each_sibling_event(event, group_event) {
2553 if (event_sched_in(event, ctx)) {
2554 partial_group = event;
2559 if (!pmu->commit_txn(pmu))
2564 * Groups can be scheduled in as one unit only, so undo any
2565 * partial group before returning:
2566 * The events up to the failed event are scheduled out normally.
2568 for_each_sibling_event(event, group_event) {
2569 if (event == partial_group)
2572 event_sched_out(event, ctx);
2574 event_sched_out(group_event, ctx);
2577 pmu->cancel_txn(pmu);
2582 * Work out whether we can put this event group on the CPU now.
2584 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2586 struct perf_event_pmu_context *epc = event->pmu_ctx;
2587 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2590 * Groups consisting entirely of software events can always go on.
2592 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2595 * If an exclusive group is already on, no other hardware
2601 * If this group is exclusive and there are already
2602 * events on the CPU, it can't go on.
2604 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2607 * Otherwise, try to add it if all previous groups were able
2613 static void add_event_to_ctx(struct perf_event *event,
2614 struct perf_event_context *ctx)
2616 list_add_event(event, ctx);
2617 perf_group_attach(event);
2620 static void task_ctx_sched_out(struct perf_event_context *ctx,
2621 enum event_type_t event_type)
2623 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2625 if (!cpuctx->task_ctx)
2628 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2631 ctx_sched_out(ctx, event_type);
2634 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2635 struct perf_event_context *ctx)
2637 ctx_sched_in(&cpuctx->ctx, EVENT_PINNED);
2639 ctx_sched_in(ctx, EVENT_PINNED);
2640 ctx_sched_in(&cpuctx->ctx, EVENT_FLEXIBLE);
2642 ctx_sched_in(ctx, EVENT_FLEXIBLE);
2646 * We want to maintain the following priority of scheduling:
2647 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2648 * - task pinned (EVENT_PINNED)
2649 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2650 * - task flexible (EVENT_FLEXIBLE).
2652 * In order to avoid unscheduling and scheduling back in everything every
2653 * time an event is added, only do it for the groups of equal priority and
2656 * This can be called after a batch operation on task events, in which case
2657 * event_type is a bit mask of the types of events involved. For CPU events,
2658 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2661 * XXX: ctx_resched() reschedule entire perf_event_context while adding new
2662 * event to the context or enabling existing event in the context. We can
2663 * probably optimize it by rescheduling only affected pmu_ctx.
2665 static void ctx_resched(struct perf_cpu_context *cpuctx,
2666 struct perf_event_context *task_ctx,
2667 enum event_type_t event_type)
2669 bool cpu_event = !!(event_type & EVENT_CPU);
2672 * If pinned groups are involved, flexible groups also need to be
2675 if (event_type & EVENT_PINNED)
2676 event_type |= EVENT_FLEXIBLE;
2678 event_type &= EVENT_ALL;
2680 perf_ctx_disable(&cpuctx->ctx);
2682 perf_ctx_disable(task_ctx);
2683 task_ctx_sched_out(task_ctx, event_type);
2687 * Decide which cpu ctx groups to schedule out based on the types
2688 * of events that caused rescheduling:
2689 * - EVENT_CPU: schedule out corresponding groups;
2690 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2691 * - otherwise, do nothing more.
2694 ctx_sched_out(&cpuctx->ctx, event_type);
2695 else if (event_type & EVENT_PINNED)
2696 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
2698 perf_event_sched_in(cpuctx, task_ctx);
2700 perf_ctx_enable(&cpuctx->ctx);
2702 perf_ctx_enable(task_ctx);
2705 void perf_pmu_resched(struct pmu *pmu)
2707 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2708 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2710 perf_ctx_lock(cpuctx, task_ctx);
2711 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2712 perf_ctx_unlock(cpuctx, task_ctx);
2716 * Cross CPU call to install and enable a performance event
2718 * Very similar to remote_function() + event_function() but cannot assume that
2719 * things like ctx->is_active and cpuctx->task_ctx are set.
2721 static int __perf_install_in_context(void *info)
2723 struct perf_event *event = info;
2724 struct perf_event_context *ctx = event->ctx;
2725 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2726 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2727 bool reprogram = true;
2730 raw_spin_lock(&cpuctx->ctx.lock);
2732 raw_spin_lock(&ctx->lock);
2735 reprogram = (ctx->task == current);
2738 * If the task is running, it must be running on this CPU,
2739 * otherwise we cannot reprogram things.
2741 * If its not running, we don't care, ctx->lock will
2742 * serialize against it becoming runnable.
2744 if (task_curr(ctx->task) && !reprogram) {
2749 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2750 } else if (task_ctx) {
2751 raw_spin_lock(&task_ctx->lock);
2754 #ifdef CONFIG_CGROUP_PERF
2755 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2757 * If the current cgroup doesn't match the event's
2758 * cgroup, we should not try to schedule it.
2760 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2761 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2762 event->cgrp->css.cgroup);
2767 ctx_sched_out(ctx, EVENT_TIME);
2768 add_event_to_ctx(event, ctx);
2769 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2771 add_event_to_ctx(event, ctx);
2775 perf_ctx_unlock(cpuctx, task_ctx);
2780 static bool exclusive_event_installable(struct perf_event *event,
2781 struct perf_event_context *ctx);
2784 * Attach a performance event to a context.
2786 * Very similar to event_function_call, see comment there.
2789 perf_install_in_context(struct perf_event_context *ctx,
2790 struct perf_event *event,
2793 struct task_struct *task = READ_ONCE(ctx->task);
2795 lockdep_assert_held(&ctx->mutex);
2797 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2799 if (event->cpu != -1)
2800 WARN_ON_ONCE(event->cpu != cpu);
2803 * Ensures that if we can observe event->ctx, both the event and ctx
2804 * will be 'complete'. See perf_iterate_sb_cpu().
2806 smp_store_release(&event->ctx, ctx);
2809 * perf_event_attr::disabled events will not run and can be initialized
2810 * without IPI. Except when this is the first event for the context, in
2811 * that case we need the magic of the IPI to set ctx->is_active.
2813 * The IOC_ENABLE that is sure to follow the creation of a disabled
2814 * event will issue the IPI and reprogram the hardware.
2816 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2817 ctx->nr_events && !is_cgroup_event(event)) {
2818 raw_spin_lock_irq(&ctx->lock);
2819 if (ctx->task == TASK_TOMBSTONE) {
2820 raw_spin_unlock_irq(&ctx->lock);
2823 add_event_to_ctx(event, ctx);
2824 raw_spin_unlock_irq(&ctx->lock);
2829 cpu_function_call(cpu, __perf_install_in_context, event);
2834 * Should not happen, we validate the ctx is still alive before calling.
2836 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2840 * Installing events is tricky because we cannot rely on ctx->is_active
2841 * to be set in case this is the nr_events 0 -> 1 transition.
2843 * Instead we use task_curr(), which tells us if the task is running.
2844 * However, since we use task_curr() outside of rq::lock, we can race
2845 * against the actual state. This means the result can be wrong.
2847 * If we get a false positive, we retry, this is harmless.
2849 * If we get a false negative, things are complicated. If we are after
2850 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2851 * value must be correct. If we're before, it doesn't matter since
2852 * perf_event_context_sched_in() will program the counter.
2854 * However, this hinges on the remote context switch having observed
2855 * our task->perf_event_ctxp[] store, such that it will in fact take
2856 * ctx::lock in perf_event_context_sched_in().
2858 * We do this by task_function_call(), if the IPI fails to hit the task
2859 * we know any future context switch of task must see the
2860 * perf_event_ctpx[] store.
2864 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2865 * task_cpu() load, such that if the IPI then does not find the task
2866 * running, a future context switch of that task must observe the
2871 if (!task_function_call(task, __perf_install_in_context, event))
2874 raw_spin_lock_irq(&ctx->lock);
2876 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2878 * Cannot happen because we already checked above (which also
2879 * cannot happen), and we hold ctx->mutex, which serializes us
2880 * against perf_event_exit_task_context().
2882 raw_spin_unlock_irq(&ctx->lock);
2886 * If the task is not running, ctx->lock will avoid it becoming so,
2887 * thus we can safely install the event.
2889 if (task_curr(task)) {
2890 raw_spin_unlock_irq(&ctx->lock);
2893 add_event_to_ctx(event, ctx);
2894 raw_spin_unlock_irq(&ctx->lock);
2898 * Cross CPU call to enable a performance event
2900 static void __perf_event_enable(struct perf_event *event,
2901 struct perf_cpu_context *cpuctx,
2902 struct perf_event_context *ctx,
2905 struct perf_event *leader = event->group_leader;
2906 struct perf_event_context *task_ctx;
2908 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2909 event->state <= PERF_EVENT_STATE_ERROR)
2913 ctx_sched_out(ctx, EVENT_TIME);
2915 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2916 perf_cgroup_event_enable(event, ctx);
2918 if (!ctx->is_active)
2921 if (!event_filter_match(event)) {
2922 ctx_sched_in(ctx, EVENT_TIME);
2927 * If the event is in a group and isn't the group leader,
2928 * then don't put it on unless the group is on.
2930 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2931 ctx_sched_in(ctx, EVENT_TIME);
2935 task_ctx = cpuctx->task_ctx;
2937 WARN_ON_ONCE(task_ctx != ctx);
2939 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2945 * If event->ctx is a cloned context, callers must make sure that
2946 * every task struct that event->ctx->task could possibly point to
2947 * remains valid. This condition is satisfied when called through
2948 * perf_event_for_each_child or perf_event_for_each as described
2949 * for perf_event_disable.
2951 static void _perf_event_enable(struct perf_event *event)
2953 struct perf_event_context *ctx = event->ctx;
2955 raw_spin_lock_irq(&ctx->lock);
2956 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2957 event->state < PERF_EVENT_STATE_ERROR) {
2959 raw_spin_unlock_irq(&ctx->lock);
2964 * If the event is in error state, clear that first.
2966 * That way, if we see the event in error state below, we know that it
2967 * has gone back into error state, as distinct from the task having
2968 * been scheduled away before the cross-call arrived.
2970 if (event->state == PERF_EVENT_STATE_ERROR) {
2972 * Detached SIBLING events cannot leave ERROR state.
2974 if (event->event_caps & PERF_EV_CAP_SIBLING &&
2975 event->group_leader == event)
2978 event->state = PERF_EVENT_STATE_OFF;
2980 raw_spin_unlock_irq(&ctx->lock);
2982 event_function_call(event, __perf_event_enable, NULL);
2986 * See perf_event_disable();
2988 void perf_event_enable(struct perf_event *event)
2990 struct perf_event_context *ctx;
2992 ctx = perf_event_ctx_lock(event);
2993 _perf_event_enable(event);
2994 perf_event_ctx_unlock(event, ctx);
2996 EXPORT_SYMBOL_GPL(perf_event_enable);
2998 struct stop_event_data {
2999 struct perf_event *event;
3000 unsigned int restart;
3003 static int __perf_event_stop(void *info)
3005 struct stop_event_data *sd = info;
3006 struct perf_event *event = sd->event;
3008 /* if it's already INACTIVE, do nothing */
3009 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3012 /* matches smp_wmb() in event_sched_in() */
3016 * There is a window with interrupts enabled before we get here,
3017 * so we need to check again lest we try to stop another CPU's event.
3019 if (READ_ONCE(event->oncpu) != smp_processor_id())
3022 event->pmu->stop(event, PERF_EF_UPDATE);
3025 * May race with the actual stop (through perf_pmu_output_stop()),
3026 * but it is only used for events with AUX ring buffer, and such
3027 * events will refuse to restart because of rb::aux_mmap_count==0,
3028 * see comments in perf_aux_output_begin().
3030 * Since this is happening on an event-local CPU, no trace is lost
3034 event->pmu->start(event, 0);
3039 static int perf_event_stop(struct perf_event *event, int restart)
3041 struct stop_event_data sd = {
3048 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3051 /* matches smp_wmb() in event_sched_in() */
3055 * We only want to restart ACTIVE events, so if the event goes
3056 * inactive here (event->oncpu==-1), there's nothing more to do;
3057 * fall through with ret==-ENXIO.
3059 ret = cpu_function_call(READ_ONCE(event->oncpu),
3060 __perf_event_stop, &sd);
3061 } while (ret == -EAGAIN);
3067 * In order to contain the amount of racy and tricky in the address filter
3068 * configuration management, it is a two part process:
3070 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3071 * we update the addresses of corresponding vmas in
3072 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3073 * (p2) when an event is scheduled in (pmu::add), it calls
3074 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3075 * if the generation has changed since the previous call.
3077 * If (p1) happens while the event is active, we restart it to force (p2).
3079 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3080 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3082 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3083 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3085 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3088 void perf_event_addr_filters_sync(struct perf_event *event)
3090 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3092 if (!has_addr_filter(event))
3095 raw_spin_lock(&ifh->lock);
3096 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3097 event->pmu->addr_filters_sync(event);
3098 event->hw.addr_filters_gen = event->addr_filters_gen;
3100 raw_spin_unlock(&ifh->lock);
3102 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3104 static int _perf_event_refresh(struct perf_event *event, int refresh)
3107 * not supported on inherited events
3109 if (event->attr.inherit || !is_sampling_event(event))
3112 atomic_add(refresh, &event->event_limit);
3113 _perf_event_enable(event);
3119 * See perf_event_disable()
3121 int perf_event_refresh(struct perf_event *event, int refresh)
3123 struct perf_event_context *ctx;
3126 ctx = perf_event_ctx_lock(event);
3127 ret = _perf_event_refresh(event, refresh);
3128 perf_event_ctx_unlock(event, ctx);
3132 EXPORT_SYMBOL_GPL(perf_event_refresh);
3134 static int perf_event_modify_breakpoint(struct perf_event *bp,
3135 struct perf_event_attr *attr)
3139 _perf_event_disable(bp);
3141 err = modify_user_hw_breakpoint_check(bp, attr, true);
3143 if (!bp->attr.disabled)
3144 _perf_event_enable(bp);
3150 * Copy event-type-independent attributes that may be modified.
3152 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3153 const struct perf_event_attr *from)
3155 to->sig_data = from->sig_data;
3158 static int perf_event_modify_attr(struct perf_event *event,
3159 struct perf_event_attr *attr)
3161 int (*func)(struct perf_event *, struct perf_event_attr *);
3162 struct perf_event *child;
3165 if (event->attr.type != attr->type)
3168 switch (event->attr.type) {
3169 case PERF_TYPE_BREAKPOINT:
3170 func = perf_event_modify_breakpoint;
3173 /* Place holder for future additions. */
3177 WARN_ON_ONCE(event->ctx->parent_ctx);
3179 mutex_lock(&event->child_mutex);
3181 * Event-type-independent attributes must be copied before event-type
3182 * modification, which will validate that final attributes match the
3183 * source attributes after all relevant attributes have been copied.
3185 perf_event_modify_copy_attr(&event->attr, attr);
3186 err = func(event, attr);
3189 list_for_each_entry(child, &event->child_list, child_list) {
3190 perf_event_modify_copy_attr(&child->attr, attr);
3191 err = func(child, attr);
3196 mutex_unlock(&event->child_mutex);
3200 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3201 enum event_type_t event_type)
3203 struct perf_event_context *ctx = pmu_ctx->ctx;
3204 struct perf_event *event, *tmp;
3205 struct pmu *pmu = pmu_ctx->pmu;
3207 if (ctx->task && !ctx->is_active) {
3208 struct perf_cpu_pmu_context *cpc;
3210 cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3211 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3212 cpc->task_epc = NULL;
3218 perf_pmu_disable(pmu);
3219 if (event_type & EVENT_PINNED) {
3220 list_for_each_entry_safe(event, tmp,
3221 &pmu_ctx->pinned_active,
3223 group_sched_out(event, ctx);
3226 if (event_type & EVENT_FLEXIBLE) {
3227 list_for_each_entry_safe(event, tmp,
3228 &pmu_ctx->flexible_active,
3230 group_sched_out(event, ctx);
3232 * Since we cleared EVENT_FLEXIBLE, also clear
3233 * rotate_necessary, is will be reset by
3234 * ctx_flexible_sched_in() when needed.
3236 pmu_ctx->rotate_necessary = 0;
3238 perf_pmu_enable(pmu);
3242 ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type)
3244 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3245 struct perf_event_pmu_context *pmu_ctx;
3246 int is_active = ctx->is_active;
3248 lockdep_assert_held(&ctx->lock);
3250 if (likely(!ctx->nr_events)) {
3252 * See __perf_remove_from_context().
3254 WARN_ON_ONCE(ctx->is_active);
3256 WARN_ON_ONCE(cpuctx->task_ctx);
3261 * Always update time if it was set; not only when it changes.
3262 * Otherwise we can 'forget' to update time for any but the last
3263 * context we sched out. For example:
3265 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3266 * ctx_sched_out(.event_type = EVENT_PINNED)
3268 * would only update time for the pinned events.
3270 if (is_active & EVENT_TIME) {
3271 /* update (and stop) ctx time */
3272 update_context_time(ctx);
3273 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3275 * CPU-release for the below ->is_active store,
3276 * see __load_acquire() in perf_event_time_now()
3281 ctx->is_active &= ~event_type;
3282 if (!(ctx->is_active & EVENT_ALL))
3286 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3287 if (!ctx->is_active)
3288 cpuctx->task_ctx = NULL;
3291 is_active ^= ctx->is_active; /* changed bits */
3293 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry)
3294 __pmu_ctx_sched_out(pmu_ctx, is_active);
3298 * Test whether two contexts are equivalent, i.e. whether they have both been
3299 * cloned from the same version of the same context.
3301 * Equivalence is measured using a generation number in the context that is
3302 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3303 * and list_del_event().
3305 static int context_equiv(struct perf_event_context *ctx1,
3306 struct perf_event_context *ctx2)
3308 lockdep_assert_held(&ctx1->lock);
3309 lockdep_assert_held(&ctx2->lock);
3311 /* Pinning disables the swap optimization */
3312 if (ctx1->pin_count || ctx2->pin_count)
3315 /* If ctx1 is the parent of ctx2 */
3316 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3319 /* If ctx2 is the parent of ctx1 */
3320 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3324 * If ctx1 and ctx2 have the same parent; we flatten the parent
3325 * hierarchy, see perf_event_init_context().
3327 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3328 ctx1->parent_gen == ctx2->parent_gen)
3335 static void __perf_event_sync_stat(struct perf_event *event,
3336 struct perf_event *next_event)
3340 if (!event->attr.inherit_stat)
3344 * Update the event value, we cannot use perf_event_read()
3345 * because we're in the middle of a context switch and have IRQs
3346 * disabled, which upsets smp_call_function_single(), however
3347 * we know the event must be on the current CPU, therefore we
3348 * don't need to use it.
3350 if (event->state == PERF_EVENT_STATE_ACTIVE)
3351 event->pmu->read(event);
3353 perf_event_update_time(event);
3356 * In order to keep per-task stats reliable we need to flip the event
3357 * values when we flip the contexts.
3359 value = local64_read(&next_event->count);
3360 value = local64_xchg(&event->count, value);
3361 local64_set(&next_event->count, value);
3363 swap(event->total_time_enabled, next_event->total_time_enabled);
3364 swap(event->total_time_running, next_event->total_time_running);
3367 * Since we swizzled the values, update the user visible data too.
3369 perf_event_update_userpage(event);
3370 perf_event_update_userpage(next_event);
3373 static void perf_event_sync_stat(struct perf_event_context *ctx,
3374 struct perf_event_context *next_ctx)
3376 struct perf_event *event, *next_event;
3381 update_context_time(ctx);
3383 event = list_first_entry(&ctx->event_list,
3384 struct perf_event, event_entry);
3386 next_event = list_first_entry(&next_ctx->event_list,
3387 struct perf_event, event_entry);
3389 while (&event->event_entry != &ctx->event_list &&
3390 &next_event->event_entry != &next_ctx->event_list) {
3392 __perf_event_sync_stat(event, next_event);
3394 event = list_next_entry(event, event_entry);
3395 next_event = list_next_entry(next_event, event_entry);
3399 #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \
3400 for (pos1 = list_first_entry(head1, typeof(*pos1), member), \
3401 pos2 = list_first_entry(head2, typeof(*pos2), member); \
3402 !list_entry_is_head(pos1, head1, member) && \
3403 !list_entry_is_head(pos2, head2, member); \
3404 pos1 = list_next_entry(pos1, member), \
3405 pos2 = list_next_entry(pos2, member))
3407 static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx,
3408 struct perf_event_context *next_ctx)
3410 struct perf_event_pmu_context *prev_epc, *next_epc;
3412 if (!prev_ctx->nr_task_data)
3415 double_list_for_each_entry(prev_epc, next_epc,
3416 &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list,
3419 if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu))
3423 * PMU specific parts of task perf context can require
3424 * additional synchronization. As an example of such
3425 * synchronization see implementation details of Intel
3426 * LBR call stack data profiling;
3428 if (prev_epc->pmu->swap_task_ctx)
3429 prev_epc->pmu->swap_task_ctx(prev_epc, next_epc);
3431 swap(prev_epc->task_ctx_data, next_epc->task_ctx_data);
3435 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in)
3437 struct perf_event_pmu_context *pmu_ctx;
3438 struct perf_cpu_pmu_context *cpc;
3440 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3441 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3443 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3444 pmu_ctx->pmu->sched_task(pmu_ctx, sched_in);
3449 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3451 struct perf_event_context *ctx = task->perf_event_ctxp;
3452 struct perf_event_context *next_ctx;
3453 struct perf_event_context *parent, *next_parent;
3460 next_ctx = rcu_dereference(next->perf_event_ctxp);
3464 parent = rcu_dereference(ctx->parent_ctx);
3465 next_parent = rcu_dereference(next_ctx->parent_ctx);
3467 /* If neither context have a parent context; they cannot be clones. */
3468 if (!parent && !next_parent)
3471 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3473 * Looks like the two contexts are clones, so we might be
3474 * able to optimize the context switch. We lock both
3475 * contexts and check that they are clones under the
3476 * lock (including re-checking that neither has been
3477 * uncloned in the meantime). It doesn't matter which
3478 * order we take the locks because no other cpu could
3479 * be trying to lock both of these tasks.
3481 raw_spin_lock(&ctx->lock);
3482 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3483 if (context_equiv(ctx, next_ctx)) {
3485 perf_ctx_disable(ctx);
3487 /* PMIs are disabled; ctx->nr_pending is stable. */
3488 if (local_read(&ctx->nr_pending) ||
3489 local_read(&next_ctx->nr_pending)) {
3491 * Must not swap out ctx when there's pending
3492 * events that rely on the ctx->task relation.
3494 raw_spin_unlock(&next_ctx->lock);
3499 WRITE_ONCE(ctx->task, next);
3500 WRITE_ONCE(next_ctx->task, task);
3502 perf_ctx_sched_task_cb(ctx, false);
3503 perf_event_swap_task_ctx_data(ctx, next_ctx);
3505 perf_ctx_enable(ctx);
3508 * RCU_INIT_POINTER here is safe because we've not
3509 * modified the ctx and the above modification of
3510 * ctx->task and ctx->task_ctx_data are immaterial
3511 * since those values are always verified under
3512 * ctx->lock which we're now holding.
3514 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3515 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3519 perf_event_sync_stat(ctx, next_ctx);
3521 raw_spin_unlock(&next_ctx->lock);
3522 raw_spin_unlock(&ctx->lock);
3528 raw_spin_lock(&ctx->lock);
3529 perf_ctx_disable(ctx);
3532 perf_ctx_sched_task_cb(ctx, false);
3533 task_ctx_sched_out(ctx, EVENT_ALL);
3535 perf_ctx_enable(ctx);
3536 raw_spin_unlock(&ctx->lock);
3540 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3541 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3543 void perf_sched_cb_dec(struct pmu *pmu)
3545 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3547 this_cpu_dec(perf_sched_cb_usages);
3550 if (!--cpc->sched_cb_usage)
3551 list_del(&cpc->sched_cb_entry);
3555 void perf_sched_cb_inc(struct pmu *pmu)
3557 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3559 if (!cpc->sched_cb_usage++)
3560 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3563 this_cpu_inc(perf_sched_cb_usages);
3567 * This function provides the context switch callback to the lower code
3568 * layer. It is invoked ONLY when the context switch callback is enabled.
3570 * This callback is relevant even to per-cpu events; for example multi event
3571 * PEBS requires this to provide PID/TID information. This requires we flush
3572 * all queued PEBS records before we context switch to a new task.
3574 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in)
3576 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3581 /* software PMUs will not have sched_task */
3582 if (WARN_ON_ONCE(!pmu->sched_task))
3585 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3586 perf_pmu_disable(pmu);
3588 pmu->sched_task(cpc->task_epc, sched_in);
3590 perf_pmu_enable(pmu);
3591 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3594 static void perf_pmu_sched_task(struct task_struct *prev,
3595 struct task_struct *next,
3598 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3599 struct perf_cpu_pmu_context *cpc;
3601 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3602 if (prev == next || cpuctx->task_ctx)
3605 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3606 __perf_pmu_sched_task(cpc, sched_in);
3609 static void perf_event_switch(struct task_struct *task,
3610 struct task_struct *next_prev, bool sched_in);
3613 * Called from scheduler to remove the events of the current task,
3614 * with interrupts disabled.
3616 * We stop each event and update the event value in event->count.
3618 * This does not protect us against NMI, but disable()
3619 * sets the disabled bit in the control field of event _before_
3620 * accessing the event control register. If a NMI hits, then it will
3621 * not restart the event.
3623 void __perf_event_task_sched_out(struct task_struct *task,
3624 struct task_struct *next)
3626 if (__this_cpu_read(perf_sched_cb_usages))
3627 perf_pmu_sched_task(task, next, false);
3629 if (atomic_read(&nr_switch_events))
3630 perf_event_switch(task, next, false);
3632 perf_event_context_sched_out(task, next);
3635 * if cgroup events exist on this CPU, then we need
3636 * to check if we have to switch out PMU state.
3637 * cgroup event are system-wide mode only
3639 perf_cgroup_switch(next);
3642 static bool perf_less_group_idx(const void *l, const void *r)
3644 const struct perf_event *le = *(const struct perf_event **)l;
3645 const struct perf_event *re = *(const struct perf_event **)r;
3647 return le->group_index < re->group_index;
3650 static void swap_ptr(void *l, void *r)
3652 void **lp = l, **rp = r;
3657 static const struct min_heap_callbacks perf_min_heap = {
3658 .elem_size = sizeof(struct perf_event *),
3659 .less = perf_less_group_idx,
3663 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3665 struct perf_event **itrs = heap->data;
3668 itrs[heap->nr] = event;
3673 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3675 struct perf_cpu_pmu_context *cpc;
3677 if (!pmu_ctx->ctx->task)
3680 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3681 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3682 cpc->task_epc = pmu_ctx;
3685 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3686 struct perf_event_groups *groups, int cpu,
3688 int (*func)(struct perf_event *, void *),
3691 #ifdef CONFIG_CGROUP_PERF
3692 struct cgroup_subsys_state *css = NULL;
3694 struct perf_cpu_context *cpuctx = NULL;
3695 /* Space for per CPU and/or any CPU event iterators. */
3696 struct perf_event *itrs[2];
3697 struct min_heap event_heap;
3698 struct perf_event **evt;
3701 if (pmu->filter && pmu->filter(pmu, cpu))
3705 cpuctx = this_cpu_ptr(&perf_cpu_context);
3706 event_heap = (struct min_heap){
3707 .data = cpuctx->heap,
3709 .size = cpuctx->heap_size,
3712 lockdep_assert_held(&cpuctx->ctx.lock);
3714 #ifdef CONFIG_CGROUP_PERF
3716 css = &cpuctx->cgrp->css;
3719 event_heap = (struct min_heap){
3722 .size = ARRAY_SIZE(itrs),
3724 /* Events not within a CPU context may be on any CPU. */
3725 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3727 evt = event_heap.data;
3729 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3731 #ifdef CONFIG_CGROUP_PERF
3732 for (; css; css = css->parent)
3733 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3736 if (event_heap.nr) {
3737 __link_epc((*evt)->pmu_ctx);
3738 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3741 min_heapify_all(&event_heap, &perf_min_heap);
3743 while (event_heap.nr) {
3744 ret = func(*evt, data);
3748 *evt = perf_event_groups_next(*evt, pmu);
3750 min_heapify(&event_heap, 0, &perf_min_heap);
3752 min_heap_pop(&event_heap, &perf_min_heap);
3759 * Because the userpage is strictly per-event (there is no concept of context,
3760 * so there cannot be a context indirection), every userpage must be updated
3761 * when context time starts :-(
3763 * IOW, we must not miss EVENT_TIME edges.
3765 static inline bool event_update_userpage(struct perf_event *event)
3767 if (likely(!atomic_read(&event->mmap_count)))
3770 perf_event_update_time(event);
3771 perf_event_update_userpage(event);
3776 static inline void group_update_userpage(struct perf_event *group_event)
3778 struct perf_event *event;
3780 if (!event_update_userpage(group_event))
3783 for_each_sibling_event(event, group_event)
3784 event_update_userpage(event);
3787 static int merge_sched_in(struct perf_event *event, void *data)
3789 struct perf_event_context *ctx = event->ctx;
3790 int *can_add_hw = data;
3792 if (event->state <= PERF_EVENT_STATE_OFF)
3795 if (!event_filter_match(event))
3798 if (group_can_go_on(event, *can_add_hw)) {
3799 if (!group_sched_in(event, ctx))
3800 list_add_tail(&event->active_list, get_event_list(event));
3803 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3805 if (event->attr.pinned) {
3806 perf_cgroup_event_disable(event, ctx);
3807 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3809 struct perf_cpu_pmu_context *cpc;
3811 event->pmu_ctx->rotate_necessary = 1;
3812 cpc = this_cpu_ptr(event->pmu_ctx->pmu->cpu_pmu_context);
3813 perf_mux_hrtimer_restart(cpc);
3814 group_update_userpage(event);
3821 static void ctx_pinned_sched_in(struct perf_event_context *ctx, struct pmu *pmu)
3823 struct perf_event_pmu_context *pmu_ctx;
3827 visit_groups_merge(ctx, &ctx->pinned_groups,
3828 smp_processor_id(), pmu,
3829 merge_sched_in, &can_add_hw);
3831 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3833 visit_groups_merge(ctx, &ctx->pinned_groups,
3834 smp_processor_id(), pmu_ctx->pmu,
3835 merge_sched_in, &can_add_hw);
3840 static void ctx_flexible_sched_in(struct perf_event_context *ctx, struct pmu *pmu)
3842 struct perf_event_pmu_context *pmu_ctx;
3846 visit_groups_merge(ctx, &ctx->flexible_groups,
3847 smp_processor_id(), pmu,
3848 merge_sched_in, &can_add_hw);
3850 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3852 visit_groups_merge(ctx, &ctx->flexible_groups,
3853 smp_processor_id(), pmu_ctx->pmu,
3854 merge_sched_in, &can_add_hw);
3859 static void __pmu_ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu)
3861 ctx_flexible_sched_in(ctx, pmu);
3865 ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type)
3867 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3868 int is_active = ctx->is_active;
3870 lockdep_assert_held(&ctx->lock);
3872 if (likely(!ctx->nr_events))
3875 if (is_active ^ EVENT_TIME) {
3876 /* start ctx time */
3877 __update_context_time(ctx, false);
3878 perf_cgroup_set_timestamp(cpuctx);
3880 * CPU-release for the below ->is_active store,
3881 * see __load_acquire() in perf_event_time_now()
3886 ctx->is_active |= (event_type | EVENT_TIME);
3889 cpuctx->task_ctx = ctx;
3891 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3894 is_active ^= ctx->is_active; /* changed bits */
3897 * First go through the list and put on any pinned groups
3898 * in order to give them the best chance of going on.
3900 if (is_active & EVENT_PINNED)
3901 ctx_pinned_sched_in(ctx, NULL);
3903 /* Then walk through the lower prio flexible groups */
3904 if (is_active & EVENT_FLEXIBLE)
3905 ctx_flexible_sched_in(ctx, NULL);
3908 static void perf_event_context_sched_in(struct task_struct *task)
3910 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3911 struct perf_event_context *ctx;
3914 ctx = rcu_dereference(task->perf_event_ctxp);
3918 if (cpuctx->task_ctx == ctx) {
3919 perf_ctx_lock(cpuctx, ctx);
3920 perf_ctx_disable(ctx);
3922 perf_ctx_sched_task_cb(ctx, true);
3924 perf_ctx_enable(ctx);
3925 perf_ctx_unlock(cpuctx, ctx);
3929 perf_ctx_lock(cpuctx, ctx);
3931 * We must check ctx->nr_events while holding ctx->lock, such
3932 * that we serialize against perf_install_in_context().
3934 if (!ctx->nr_events)
3937 perf_ctx_disable(ctx);
3939 * We want to keep the following priority order:
3940 * cpu pinned (that don't need to move), task pinned,
3941 * cpu flexible, task flexible.
3943 * However, if task's ctx is not carrying any pinned
3944 * events, no need to flip the cpuctx's events around.
3946 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
3947 perf_ctx_disable(&cpuctx->ctx);
3948 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
3951 perf_event_sched_in(cpuctx, ctx);
3953 perf_ctx_sched_task_cb(cpuctx->task_ctx, true);
3955 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3956 perf_ctx_enable(&cpuctx->ctx);
3958 perf_ctx_enable(ctx);
3961 perf_ctx_unlock(cpuctx, ctx);
3967 * Called from scheduler to add the events of the current task
3968 * with interrupts disabled.
3970 * We restore the event value and then enable it.
3972 * This does not protect us against NMI, but enable()
3973 * sets the enabled bit in the control field of event _before_
3974 * accessing the event control register. If a NMI hits, then it will
3975 * keep the event running.
3977 void __perf_event_task_sched_in(struct task_struct *prev,
3978 struct task_struct *task)
3980 perf_event_context_sched_in(task);
3982 if (atomic_read(&nr_switch_events))
3983 perf_event_switch(task, prev, true);
3985 if (__this_cpu_read(perf_sched_cb_usages))
3986 perf_pmu_sched_task(prev, task, true);
3989 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3991 u64 frequency = event->attr.sample_freq;
3992 u64 sec = NSEC_PER_SEC;
3993 u64 divisor, dividend;
3995 int count_fls, nsec_fls, frequency_fls, sec_fls;
3997 count_fls = fls64(count);
3998 nsec_fls = fls64(nsec);
3999 frequency_fls = fls64(frequency);
4003 * We got @count in @nsec, with a target of sample_freq HZ
4004 * the target period becomes:
4007 * period = -------------------
4008 * @nsec * sample_freq
4013 * Reduce accuracy by one bit such that @a and @b converge
4014 * to a similar magnitude.
4016 #define REDUCE_FLS(a, b) \
4018 if (a##_fls > b##_fls) { \
4028 * Reduce accuracy until either term fits in a u64, then proceed with
4029 * the other, so that finally we can do a u64/u64 division.
4031 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4032 REDUCE_FLS(nsec, frequency);
4033 REDUCE_FLS(sec, count);
4036 if (count_fls + sec_fls > 64) {
4037 divisor = nsec * frequency;
4039 while (count_fls + sec_fls > 64) {
4040 REDUCE_FLS(count, sec);
4044 dividend = count * sec;
4046 dividend = count * sec;
4048 while (nsec_fls + frequency_fls > 64) {
4049 REDUCE_FLS(nsec, frequency);
4053 divisor = nsec * frequency;
4059 return div64_u64(dividend, divisor);
4062 static DEFINE_PER_CPU(int, perf_throttled_count);
4063 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4065 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4067 struct hw_perf_event *hwc = &event->hw;
4068 s64 period, sample_period;
4071 period = perf_calculate_period(event, nsec, count);
4073 delta = (s64)(period - hwc->sample_period);
4074 delta = (delta + 7) / 8; /* low pass filter */
4076 sample_period = hwc->sample_period + delta;
4081 hwc->sample_period = sample_period;
4083 if (local64_read(&hwc->period_left) > 8*sample_period) {
4085 event->pmu->stop(event, PERF_EF_UPDATE);
4087 local64_set(&hwc->period_left, 0);
4090 event->pmu->start(event, PERF_EF_RELOAD);
4095 * combine freq adjustment with unthrottling to avoid two passes over the
4096 * events. At the same time, make sure, having freq events does not change
4097 * the rate of unthrottling as that would introduce bias.
4100 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4102 struct perf_event *event;
4103 struct hw_perf_event *hwc;
4104 u64 now, period = TICK_NSEC;
4108 * only need to iterate over all events iff:
4109 * - context have events in frequency mode (needs freq adjust)
4110 * - there are events to unthrottle on this cpu
4112 if (!(ctx->nr_freq || unthrottle))
4115 raw_spin_lock(&ctx->lock);
4117 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4118 if (event->state != PERF_EVENT_STATE_ACTIVE)
4121 // XXX use visit thingy to avoid the -1,cpu match
4122 if (!event_filter_match(event))
4125 perf_pmu_disable(event->pmu);
4129 if (hwc->interrupts == MAX_INTERRUPTS) {
4130 hwc->interrupts = 0;
4131 perf_log_throttle(event, 1);
4132 event->pmu->start(event, 0);
4135 if (!event->attr.freq || !event->attr.sample_freq)
4139 * stop the event and update event->count
4141 event->pmu->stop(event, PERF_EF_UPDATE);
4143 now = local64_read(&event->count);
4144 delta = now - hwc->freq_count_stamp;
4145 hwc->freq_count_stamp = now;
4149 * reload only if value has changed
4150 * we have stopped the event so tell that
4151 * to perf_adjust_period() to avoid stopping it
4155 perf_adjust_period(event, period, delta, false);
4157 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4159 perf_pmu_enable(event->pmu);
4162 raw_spin_unlock(&ctx->lock);
4166 * Move @event to the tail of the @ctx's elegible events.
4168 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4171 * Rotate the first entry last of non-pinned groups. Rotation might be
4172 * disabled by the inheritance code.
4174 if (ctx->rotate_disable)
4177 perf_event_groups_delete(&ctx->flexible_groups, event);
4178 perf_event_groups_insert(&ctx->flexible_groups, event);
4181 /* pick an event from the flexible_groups to rotate */
4182 static inline struct perf_event *
4183 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4185 struct perf_event *event;
4186 struct rb_node *node;
4187 struct rb_root *tree;
4188 struct __group_key key = {
4189 .pmu = pmu_ctx->pmu,
4192 /* pick the first active flexible event */
4193 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4194 struct perf_event, active_list);
4198 /* if no active flexible event, pick the first event */
4199 tree = &pmu_ctx->ctx->flexible_groups.tree;
4201 if (!pmu_ctx->ctx->task) {
4202 key.cpu = smp_processor_id();
4204 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4206 event = __node_2_pe(node);
4211 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4213 event = __node_2_pe(node);
4217 key.cpu = smp_processor_id();
4218 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4220 event = __node_2_pe(node);
4224 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4225 * finds there are unschedulable events, it will set it again.
4227 pmu_ctx->rotate_necessary = 0;
4232 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4234 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4235 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4236 struct perf_event *cpu_event = NULL, *task_event = NULL;
4237 int cpu_rotate, task_rotate;
4241 * Since we run this from IRQ context, nobody can install new
4242 * events, thus the event count values are stable.
4245 cpu_epc = &cpc->epc;
4247 task_epc = cpc->task_epc;
4249 cpu_rotate = cpu_epc->rotate_necessary;
4250 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4252 if (!(cpu_rotate || task_rotate))
4255 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4256 perf_pmu_disable(pmu);
4259 task_event = ctx_event_to_rotate(task_epc);
4261 cpu_event = ctx_event_to_rotate(cpu_epc);
4264 * As per the order given at ctx_resched() first 'pop' task flexible
4265 * and then, if needed CPU flexible.
4267 if (task_event || (task_epc && cpu_event)) {
4268 update_context_time(task_epc->ctx);
4269 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4273 update_context_time(&cpuctx->ctx);
4274 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4275 rotate_ctx(&cpuctx->ctx, cpu_event);
4276 __pmu_ctx_sched_in(&cpuctx->ctx, pmu);
4280 rotate_ctx(task_epc->ctx, task_event);
4282 if (task_event || (task_epc && cpu_event))
4283 __pmu_ctx_sched_in(task_epc->ctx, pmu);
4285 perf_pmu_enable(pmu);
4286 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4291 void perf_event_task_tick(void)
4293 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4294 struct perf_event_context *ctx;
4297 lockdep_assert_irqs_disabled();
4299 __this_cpu_inc(perf_throttled_seq);
4300 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4301 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4303 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4306 ctx = rcu_dereference(current->perf_event_ctxp);
4308 perf_adjust_freq_unthr_context(ctx, !!throttled);
4312 static int event_enable_on_exec(struct perf_event *event,
4313 struct perf_event_context *ctx)
4315 if (!event->attr.enable_on_exec)
4318 event->attr.enable_on_exec = 0;
4319 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4322 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4328 * Enable all of a task's events that have been marked enable-on-exec.
4329 * This expects task == current.
4331 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4333 struct perf_event_context *clone_ctx = NULL;
4334 enum event_type_t event_type = 0;
4335 struct perf_cpu_context *cpuctx;
4336 struct perf_event *event;
4337 unsigned long flags;
4340 local_irq_save(flags);
4341 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4344 if (!ctx->nr_events)
4347 cpuctx = this_cpu_ptr(&perf_cpu_context);
4348 perf_ctx_lock(cpuctx, ctx);
4349 ctx_sched_out(ctx, EVENT_TIME);
4351 list_for_each_entry(event, &ctx->event_list, event_entry) {
4352 enabled |= event_enable_on_exec(event, ctx);
4353 event_type |= get_event_type(event);
4357 * Unclone and reschedule this context if we enabled any event.
4360 clone_ctx = unclone_ctx(ctx);
4361 ctx_resched(cpuctx, ctx, event_type);
4363 ctx_sched_in(ctx, EVENT_TIME);
4365 perf_ctx_unlock(cpuctx, ctx);
4368 local_irq_restore(flags);
4374 static void perf_remove_from_owner(struct perf_event *event);
4375 static void perf_event_exit_event(struct perf_event *event,
4376 struct perf_event_context *ctx);
4379 * Removes all events from the current task that have been marked
4380 * remove-on-exec, and feeds their values back to parent events.
4382 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4384 struct perf_event_context *clone_ctx = NULL;
4385 struct perf_event *event, *next;
4386 unsigned long flags;
4387 bool modified = false;
4389 mutex_lock(&ctx->mutex);
4391 if (WARN_ON_ONCE(ctx->task != current))
4394 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4395 if (!event->attr.remove_on_exec)
4398 if (!is_kernel_event(event))
4399 perf_remove_from_owner(event);
4403 perf_event_exit_event(event, ctx);
4406 raw_spin_lock_irqsave(&ctx->lock, flags);
4408 clone_ctx = unclone_ctx(ctx);
4409 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4412 mutex_unlock(&ctx->mutex);
4418 struct perf_read_data {
4419 struct perf_event *event;
4424 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4426 u16 local_pkg, event_pkg;
4428 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4429 int local_cpu = smp_processor_id();
4431 event_pkg = topology_physical_package_id(event_cpu);
4432 local_pkg = topology_physical_package_id(local_cpu);
4434 if (event_pkg == local_pkg)
4442 * Cross CPU call to read the hardware event
4444 static void __perf_event_read(void *info)
4446 struct perf_read_data *data = info;
4447 struct perf_event *sub, *event = data->event;
4448 struct perf_event_context *ctx = event->ctx;
4449 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4450 struct pmu *pmu = event->pmu;
4453 * If this is a task context, we need to check whether it is
4454 * the current task context of this cpu. If not it has been
4455 * scheduled out before the smp call arrived. In that case
4456 * event->count would have been updated to a recent sample
4457 * when the event was scheduled out.
4459 if (ctx->task && cpuctx->task_ctx != ctx)
4462 raw_spin_lock(&ctx->lock);
4463 if (ctx->is_active & EVENT_TIME) {
4464 update_context_time(ctx);
4465 update_cgrp_time_from_event(event);
4468 perf_event_update_time(event);
4470 perf_event_update_sibling_time(event);
4472 if (event->state != PERF_EVENT_STATE_ACTIVE)
4481 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4485 for_each_sibling_event(sub, event) {
4486 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4488 * Use sibling's PMU rather than @event's since
4489 * sibling could be on different (eg: software) PMU.
4491 sub->pmu->read(sub);
4495 data->ret = pmu->commit_txn(pmu);
4498 raw_spin_unlock(&ctx->lock);
4501 static inline u64 perf_event_count(struct perf_event *event)
4503 return local64_read(&event->count) + atomic64_read(&event->child_count);
4506 static void calc_timer_values(struct perf_event *event,
4513 *now = perf_clock();
4514 ctx_time = perf_event_time_now(event, *now);
4515 __perf_update_times(event, ctx_time, enabled, running);
4519 * NMI-safe method to read a local event, that is an event that
4521 * - either for the current task, or for this CPU
4522 * - does not have inherit set, for inherited task events
4523 * will not be local and we cannot read them atomically
4524 * - must not have a pmu::count method
4526 int perf_event_read_local(struct perf_event *event, u64 *value,
4527 u64 *enabled, u64 *running)
4529 unsigned long flags;
4533 * Disabling interrupts avoids all counter scheduling (context
4534 * switches, timer based rotation and IPIs).
4536 local_irq_save(flags);
4539 * It must not be an event with inherit set, we cannot read
4540 * all child counters from atomic context.
4542 if (event->attr.inherit) {
4547 /* If this is a per-task event, it must be for current */
4548 if ((event->attach_state & PERF_ATTACH_TASK) &&
4549 event->hw.target != current) {
4554 /* If this is a per-CPU event, it must be for this CPU */
4555 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4556 event->cpu != smp_processor_id()) {
4561 /* If this is a pinned event it must be running on this CPU */
4562 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4568 * If the event is currently on this CPU, its either a per-task event,
4569 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4572 if (event->oncpu == smp_processor_id())
4573 event->pmu->read(event);
4575 *value = local64_read(&event->count);
4576 if (enabled || running) {
4577 u64 __enabled, __running, __now;
4579 calc_timer_values(event, &__now, &__enabled, &__running);
4581 *enabled = __enabled;
4583 *running = __running;
4586 local_irq_restore(flags);
4591 static int perf_event_read(struct perf_event *event, bool group)
4593 enum perf_event_state state = READ_ONCE(event->state);
4594 int event_cpu, ret = 0;
4597 * If event is enabled and currently active on a CPU, update the
4598 * value in the event structure:
4601 if (state == PERF_EVENT_STATE_ACTIVE) {
4602 struct perf_read_data data;
4605 * Orders the ->state and ->oncpu loads such that if we see
4606 * ACTIVE we must also see the right ->oncpu.
4608 * Matches the smp_wmb() from event_sched_in().
4612 event_cpu = READ_ONCE(event->oncpu);
4613 if ((unsigned)event_cpu >= nr_cpu_ids)
4616 data = (struct perf_read_data){
4623 event_cpu = __perf_event_read_cpu(event, event_cpu);
4626 * Purposely ignore the smp_call_function_single() return
4629 * If event_cpu isn't a valid CPU it means the event got
4630 * scheduled out and that will have updated the event count.
4632 * Therefore, either way, we'll have an up-to-date event count
4635 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4639 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4640 struct perf_event_context *ctx = event->ctx;
4641 unsigned long flags;
4643 raw_spin_lock_irqsave(&ctx->lock, flags);
4644 state = event->state;
4645 if (state != PERF_EVENT_STATE_INACTIVE) {
4646 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4651 * May read while context is not active (e.g., thread is
4652 * blocked), in that case we cannot update context time
4654 if (ctx->is_active & EVENT_TIME) {
4655 update_context_time(ctx);
4656 update_cgrp_time_from_event(event);
4659 perf_event_update_time(event);
4661 perf_event_update_sibling_time(event);
4662 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4669 * Initialize the perf_event context in a task_struct:
4671 static void __perf_event_init_context(struct perf_event_context *ctx)
4673 raw_spin_lock_init(&ctx->lock);
4674 mutex_init(&ctx->mutex);
4675 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4676 perf_event_groups_init(&ctx->pinned_groups);
4677 perf_event_groups_init(&ctx->flexible_groups);
4678 INIT_LIST_HEAD(&ctx->event_list);
4679 refcount_set(&ctx->refcount, 1);
4683 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4686 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4687 INIT_LIST_HEAD(&epc->pinned_active);
4688 INIT_LIST_HEAD(&epc->flexible_active);
4689 atomic_set(&epc->refcount, 1);
4692 static struct perf_event_context *
4693 alloc_perf_context(struct task_struct *task)
4695 struct perf_event_context *ctx;
4697 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4701 __perf_event_init_context(ctx);
4703 ctx->task = get_task_struct(task);
4708 static struct task_struct *
4709 find_lively_task_by_vpid(pid_t vpid)
4711 struct task_struct *task;
4717 task = find_task_by_vpid(vpid);
4719 get_task_struct(task);
4723 return ERR_PTR(-ESRCH);
4729 * Returns a matching context with refcount and pincount.
4731 static struct perf_event_context *
4732 find_get_context(struct task_struct *task, struct perf_event *event)
4734 struct perf_event_context *ctx, *clone_ctx = NULL;
4735 struct perf_cpu_context *cpuctx;
4736 unsigned long flags;
4740 /* Must be root to operate on a CPU event: */
4741 err = perf_allow_cpu(&event->attr);
4743 return ERR_PTR(err);
4745 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4748 raw_spin_lock_irqsave(&ctx->lock, flags);
4750 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4757 ctx = perf_lock_task_context(task, &flags);
4759 clone_ctx = unclone_ctx(ctx);
4762 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4767 ctx = alloc_perf_context(task);
4773 mutex_lock(&task->perf_event_mutex);
4775 * If it has already passed perf_event_exit_task().
4776 * we must see PF_EXITING, it takes this mutex too.
4778 if (task->flags & PF_EXITING)
4780 else if (task->perf_event_ctxp)
4785 rcu_assign_pointer(task->perf_event_ctxp, ctx);
4787 mutex_unlock(&task->perf_event_mutex);
4789 if (unlikely(err)) {
4801 return ERR_PTR(err);
4804 static struct perf_event_pmu_context *
4805 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
4806 struct perf_event *event)
4808 struct perf_event_pmu_context *new = NULL, *epc;
4809 void *task_ctx_data = NULL;
4812 struct perf_cpu_pmu_context *cpc;
4814 cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
4818 atomic_set(&epc->refcount, 1);
4820 raw_spin_lock_irq(&ctx->lock);
4821 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4823 raw_spin_unlock_irq(&ctx->lock);
4825 WARN_ON_ONCE(epc->ctx != ctx);
4826 atomic_inc(&epc->refcount);
4832 new = kzalloc(sizeof(*epc), GFP_KERNEL);
4834 return ERR_PTR(-ENOMEM);
4836 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4837 task_ctx_data = alloc_task_ctx_data(pmu);
4838 if (!task_ctx_data) {
4840 return ERR_PTR(-ENOMEM);
4844 __perf_init_event_pmu_context(new, pmu);
4849 * lockdep_assert_held(&ctx->mutex);
4851 * can't because perf_event_init_task() doesn't actually hold the
4855 raw_spin_lock_irq(&ctx->lock);
4856 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4857 if (epc->pmu == pmu) {
4858 WARN_ON_ONCE(epc->ctx != ctx);
4859 atomic_inc(&epc->refcount);
4867 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4871 if (task_ctx_data && !epc->task_ctx_data) {
4872 epc->task_ctx_data = task_ctx_data;
4873 task_ctx_data = NULL;
4874 ctx->nr_task_data++;
4876 raw_spin_unlock_irq(&ctx->lock);
4878 free_task_ctx_data(pmu, task_ctx_data);
4884 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
4886 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
4889 static void free_epc_rcu(struct rcu_head *head)
4891 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
4893 kfree(epc->task_ctx_data);
4897 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
4899 unsigned long flags;
4901 if (!atomic_dec_and_test(&epc->refcount))
4905 struct perf_event_context *ctx = epc->ctx;
4910 * lockdep_assert_held(&ctx->mutex);
4912 * can't because of the call-site in _free_event()/put_event()
4913 * which isn't always called under ctx->mutex.
4916 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
4917 raw_spin_lock_irqsave(&ctx->lock, flags);
4918 list_del_init(&epc->pmu_ctx_entry);
4920 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4923 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
4924 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
4929 call_rcu(&epc->rcu_head, free_epc_rcu);
4932 static void perf_event_free_filter(struct perf_event *event);
4934 static void free_event_rcu(struct rcu_head *head)
4936 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
4939 put_pid_ns(event->ns);
4940 perf_event_free_filter(event);
4941 kmem_cache_free(perf_event_cache, event);
4944 static void ring_buffer_attach(struct perf_event *event,
4945 struct perf_buffer *rb);
4947 static void detach_sb_event(struct perf_event *event)
4949 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4951 raw_spin_lock(&pel->lock);
4952 list_del_rcu(&event->sb_list);
4953 raw_spin_unlock(&pel->lock);
4956 static bool is_sb_event(struct perf_event *event)
4958 struct perf_event_attr *attr = &event->attr;
4963 if (event->attach_state & PERF_ATTACH_TASK)
4966 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4967 attr->comm || attr->comm_exec ||
4968 attr->task || attr->ksymbol ||
4969 attr->context_switch || attr->text_poke ||
4975 static void unaccount_pmu_sb_event(struct perf_event *event)
4977 if (is_sb_event(event))
4978 detach_sb_event(event);
4981 #ifdef CONFIG_NO_HZ_FULL
4982 static DEFINE_SPINLOCK(nr_freq_lock);
4985 static void unaccount_freq_event_nohz(void)
4987 #ifdef CONFIG_NO_HZ_FULL
4988 spin_lock(&nr_freq_lock);
4989 if (atomic_dec_and_test(&nr_freq_events))
4990 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4991 spin_unlock(&nr_freq_lock);
4995 static void unaccount_freq_event(void)
4997 if (tick_nohz_full_enabled())
4998 unaccount_freq_event_nohz();
5000 atomic_dec(&nr_freq_events);
5003 static void unaccount_event(struct perf_event *event)
5010 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5012 if (event->attr.mmap || event->attr.mmap_data)
5013 atomic_dec(&nr_mmap_events);
5014 if (event->attr.build_id)
5015 atomic_dec(&nr_build_id_events);
5016 if (event->attr.comm)
5017 atomic_dec(&nr_comm_events);
5018 if (event->attr.namespaces)
5019 atomic_dec(&nr_namespaces_events);
5020 if (event->attr.cgroup)
5021 atomic_dec(&nr_cgroup_events);
5022 if (event->attr.task)
5023 atomic_dec(&nr_task_events);
5024 if (event->attr.freq)
5025 unaccount_freq_event();
5026 if (event->attr.context_switch) {
5028 atomic_dec(&nr_switch_events);
5030 if (is_cgroup_event(event))
5032 if (has_branch_stack(event))
5034 if (event->attr.ksymbol)
5035 atomic_dec(&nr_ksymbol_events);
5036 if (event->attr.bpf_event)
5037 atomic_dec(&nr_bpf_events);
5038 if (event->attr.text_poke)
5039 atomic_dec(&nr_text_poke_events);
5042 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5043 schedule_delayed_work(&perf_sched_work, HZ);
5046 unaccount_pmu_sb_event(event);
5049 static void perf_sched_delayed(struct work_struct *work)
5051 mutex_lock(&perf_sched_mutex);
5052 if (atomic_dec_and_test(&perf_sched_count))
5053 static_branch_disable(&perf_sched_events);
5054 mutex_unlock(&perf_sched_mutex);
5058 * The following implement mutual exclusion of events on "exclusive" pmus
5059 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5060 * at a time, so we disallow creating events that might conflict, namely:
5062 * 1) cpu-wide events in the presence of per-task events,
5063 * 2) per-task events in the presence of cpu-wide events,
5064 * 3) two matching events on the same perf_event_context.
5066 * The former two cases are handled in the allocation path (perf_event_alloc(),
5067 * _free_event()), the latter -- before the first perf_install_in_context().
5069 static int exclusive_event_init(struct perf_event *event)
5071 struct pmu *pmu = event->pmu;
5073 if (!is_exclusive_pmu(pmu))
5077 * Prevent co-existence of per-task and cpu-wide events on the
5078 * same exclusive pmu.
5080 * Negative pmu::exclusive_cnt means there are cpu-wide
5081 * events on this "exclusive" pmu, positive means there are
5084 * Since this is called in perf_event_alloc() path, event::ctx
5085 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5086 * to mean "per-task event", because unlike other attach states it
5087 * never gets cleared.
5089 if (event->attach_state & PERF_ATTACH_TASK) {
5090 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5093 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5100 static void exclusive_event_destroy(struct perf_event *event)
5102 struct pmu *pmu = event->pmu;
5104 if (!is_exclusive_pmu(pmu))
5107 /* see comment in exclusive_event_init() */
5108 if (event->attach_state & PERF_ATTACH_TASK)
5109 atomic_dec(&pmu->exclusive_cnt);
5111 atomic_inc(&pmu->exclusive_cnt);
5114 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5116 if ((e1->pmu == e2->pmu) &&
5117 (e1->cpu == e2->cpu ||
5124 static bool exclusive_event_installable(struct perf_event *event,
5125 struct perf_event_context *ctx)
5127 struct perf_event *iter_event;
5128 struct pmu *pmu = event->pmu;
5130 lockdep_assert_held(&ctx->mutex);
5132 if (!is_exclusive_pmu(pmu))
5135 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5136 if (exclusive_event_match(iter_event, event))
5143 static void perf_addr_filters_splice(struct perf_event *event,
5144 struct list_head *head);
5146 static void _free_event(struct perf_event *event)
5148 irq_work_sync(&event->pending_irq);
5150 unaccount_event(event);
5152 security_perf_event_free(event);
5156 * Can happen when we close an event with re-directed output.
5158 * Since we have a 0 refcount, perf_mmap_close() will skip
5159 * over us; possibly making our ring_buffer_put() the last.
5161 mutex_lock(&event->mmap_mutex);
5162 ring_buffer_attach(event, NULL);
5163 mutex_unlock(&event->mmap_mutex);
5166 if (is_cgroup_event(event))
5167 perf_detach_cgroup(event);
5169 if (!event->parent) {
5170 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
5171 put_callchain_buffers();
5174 perf_event_free_bpf_prog(event);
5175 perf_addr_filters_splice(event, NULL);
5176 kfree(event->addr_filter_ranges);
5179 event->destroy(event);
5182 * Must be after ->destroy(), due to uprobe_perf_close() using
5185 if (event->hw.target)
5186 put_task_struct(event->hw.target);
5189 put_pmu_ctx(event->pmu_ctx);
5192 * perf_event_free_task() relies on put_ctx() being 'last', in particular
5193 * all task references must be cleaned up.
5196 put_ctx(event->ctx);
5198 exclusive_event_destroy(event);
5199 module_put(event->pmu->module);
5201 call_rcu(&event->rcu_head, free_event_rcu);
5205 * Used to free events which have a known refcount of 1, such as in error paths
5206 * where the event isn't exposed yet and inherited events.
5208 static void free_event(struct perf_event *event)
5210 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5211 "unexpected event refcount: %ld; ptr=%p\n",
5212 atomic_long_read(&event->refcount), event)) {
5213 /* leak to avoid use-after-free */
5221 * Remove user event from the owner task.
5223 static void perf_remove_from_owner(struct perf_event *event)
5225 struct task_struct *owner;
5229 * Matches the smp_store_release() in perf_event_exit_task(). If we
5230 * observe !owner it means the list deletion is complete and we can
5231 * indeed free this event, otherwise we need to serialize on
5232 * owner->perf_event_mutex.
5234 owner = READ_ONCE(event->owner);
5237 * Since delayed_put_task_struct() also drops the last
5238 * task reference we can safely take a new reference
5239 * while holding the rcu_read_lock().
5241 get_task_struct(owner);
5247 * If we're here through perf_event_exit_task() we're already
5248 * holding ctx->mutex which would be an inversion wrt. the
5249 * normal lock order.
5251 * However we can safely take this lock because its the child
5254 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5257 * We have to re-check the event->owner field, if it is cleared
5258 * we raced with perf_event_exit_task(), acquiring the mutex
5259 * ensured they're done, and we can proceed with freeing the
5263 list_del_init(&event->owner_entry);
5264 smp_store_release(&event->owner, NULL);
5266 mutex_unlock(&owner->perf_event_mutex);
5267 put_task_struct(owner);
5271 static void put_event(struct perf_event *event)
5273 if (!atomic_long_dec_and_test(&event->refcount))
5280 * Kill an event dead; while event:refcount will preserve the event
5281 * object, it will not preserve its functionality. Once the last 'user'
5282 * gives up the object, we'll destroy the thing.
5284 int perf_event_release_kernel(struct perf_event *event)
5286 struct perf_event_context *ctx = event->ctx;
5287 struct perf_event *child, *tmp;
5288 LIST_HEAD(free_list);
5291 * If we got here through err_alloc: free_event(event); we will not
5292 * have attached to a context yet.
5295 WARN_ON_ONCE(event->attach_state &
5296 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5300 if (!is_kernel_event(event))
5301 perf_remove_from_owner(event);
5303 ctx = perf_event_ctx_lock(event);
5304 WARN_ON_ONCE(ctx->parent_ctx);
5307 * Mark this event as STATE_DEAD, there is no external reference to it
5310 * Anybody acquiring event->child_mutex after the below loop _must_
5311 * also see this, most importantly inherit_event() which will avoid
5312 * placing more children on the list.
5314 * Thus this guarantees that we will in fact observe and kill _ALL_
5317 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5319 perf_event_ctx_unlock(event, ctx);
5322 mutex_lock(&event->child_mutex);
5323 list_for_each_entry(child, &event->child_list, child_list) {
5326 * Cannot change, child events are not migrated, see the
5327 * comment with perf_event_ctx_lock_nested().
5329 ctx = READ_ONCE(child->ctx);
5331 * Since child_mutex nests inside ctx::mutex, we must jump
5332 * through hoops. We start by grabbing a reference on the ctx.
5334 * Since the event cannot get freed while we hold the
5335 * child_mutex, the context must also exist and have a !0
5341 * Now that we have a ctx ref, we can drop child_mutex, and
5342 * acquire ctx::mutex without fear of it going away. Then we
5343 * can re-acquire child_mutex.
5345 mutex_unlock(&event->child_mutex);
5346 mutex_lock(&ctx->mutex);
5347 mutex_lock(&event->child_mutex);
5350 * Now that we hold ctx::mutex and child_mutex, revalidate our
5351 * state, if child is still the first entry, it didn't get freed
5352 * and we can continue doing so.
5354 tmp = list_first_entry_or_null(&event->child_list,
5355 struct perf_event, child_list);
5357 perf_remove_from_context(child, DETACH_GROUP);
5358 list_move(&child->child_list, &free_list);
5360 * This matches the refcount bump in inherit_event();
5361 * this can't be the last reference.
5366 mutex_unlock(&event->child_mutex);
5367 mutex_unlock(&ctx->mutex);
5371 mutex_unlock(&event->child_mutex);
5373 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5374 void *var = &child->ctx->refcount;
5376 list_del(&child->child_list);
5380 * Wake any perf_event_free_task() waiting for this event to be
5383 smp_mb(); /* pairs with wait_var_event() */
5388 put_event(event); /* Must be the 'last' reference */
5391 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5394 * Called when the last reference to the file is gone.
5396 static int perf_release(struct inode *inode, struct file *file)
5398 perf_event_release_kernel(file->private_data);
5402 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5404 struct perf_event *child;
5410 mutex_lock(&event->child_mutex);
5412 (void)perf_event_read(event, false);
5413 total += perf_event_count(event);
5415 *enabled += event->total_time_enabled +
5416 atomic64_read(&event->child_total_time_enabled);
5417 *running += event->total_time_running +
5418 atomic64_read(&event->child_total_time_running);
5420 list_for_each_entry(child, &event->child_list, child_list) {
5421 (void)perf_event_read(child, false);
5422 total += perf_event_count(child);
5423 *enabled += child->total_time_enabled;
5424 *running += child->total_time_running;
5426 mutex_unlock(&event->child_mutex);
5431 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5433 struct perf_event_context *ctx;
5436 ctx = perf_event_ctx_lock(event);
5437 count = __perf_event_read_value(event, enabled, running);
5438 perf_event_ctx_unlock(event, ctx);
5442 EXPORT_SYMBOL_GPL(perf_event_read_value);
5444 static int __perf_read_group_add(struct perf_event *leader,
5445 u64 read_format, u64 *values)
5447 struct perf_event_context *ctx = leader->ctx;
5448 struct perf_event *sub;
5449 unsigned long flags;
5450 int n = 1; /* skip @nr */
5453 ret = perf_event_read(leader, true);
5457 raw_spin_lock_irqsave(&ctx->lock, flags);
5460 * Since we co-schedule groups, {enabled,running} times of siblings
5461 * will be identical to those of the leader, so we only publish one
5464 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5465 values[n++] += leader->total_time_enabled +
5466 atomic64_read(&leader->child_total_time_enabled);
5469 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5470 values[n++] += leader->total_time_running +
5471 atomic64_read(&leader->child_total_time_running);
5475 * Write {count,id} tuples for every sibling.
5477 values[n++] += perf_event_count(leader);
5478 if (read_format & PERF_FORMAT_ID)
5479 values[n++] = primary_event_id(leader);
5480 if (read_format & PERF_FORMAT_LOST)
5481 values[n++] = atomic64_read(&leader->lost_samples);
5483 for_each_sibling_event(sub, leader) {
5484 values[n++] += perf_event_count(sub);
5485 if (read_format & PERF_FORMAT_ID)
5486 values[n++] = primary_event_id(sub);
5487 if (read_format & PERF_FORMAT_LOST)
5488 values[n++] = atomic64_read(&sub->lost_samples);
5491 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5495 static int perf_read_group(struct perf_event *event,
5496 u64 read_format, char __user *buf)
5498 struct perf_event *leader = event->group_leader, *child;
5499 struct perf_event_context *ctx = leader->ctx;
5503 lockdep_assert_held(&ctx->mutex);
5505 values = kzalloc(event->read_size, GFP_KERNEL);
5509 values[0] = 1 + leader->nr_siblings;
5512 * By locking the child_mutex of the leader we effectively
5513 * lock the child list of all siblings.. XXX explain how.
5515 mutex_lock(&leader->child_mutex);
5517 ret = __perf_read_group_add(leader, read_format, values);
5521 list_for_each_entry(child, &leader->child_list, child_list) {
5522 ret = __perf_read_group_add(child, read_format, values);
5527 mutex_unlock(&leader->child_mutex);
5529 ret = event->read_size;
5530 if (copy_to_user(buf, values, event->read_size))
5535 mutex_unlock(&leader->child_mutex);
5541 static int perf_read_one(struct perf_event *event,
5542 u64 read_format, char __user *buf)
5544 u64 enabled, running;
5548 values[n++] = __perf_event_read_value(event, &enabled, &running);
5549 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5550 values[n++] = enabled;
5551 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5552 values[n++] = running;
5553 if (read_format & PERF_FORMAT_ID)
5554 values[n++] = primary_event_id(event);
5555 if (read_format & PERF_FORMAT_LOST)
5556 values[n++] = atomic64_read(&event->lost_samples);
5558 if (copy_to_user(buf, values, n * sizeof(u64)))
5561 return n * sizeof(u64);
5564 static bool is_event_hup(struct perf_event *event)
5568 if (event->state > PERF_EVENT_STATE_EXIT)
5571 mutex_lock(&event->child_mutex);
5572 no_children = list_empty(&event->child_list);
5573 mutex_unlock(&event->child_mutex);
5578 * Read the performance event - simple non blocking version for now
5581 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5583 u64 read_format = event->attr.read_format;
5587 * Return end-of-file for a read on an event that is in
5588 * error state (i.e. because it was pinned but it couldn't be
5589 * scheduled on to the CPU at some point).
5591 if (event->state == PERF_EVENT_STATE_ERROR)
5594 if (count < event->read_size)
5597 WARN_ON_ONCE(event->ctx->parent_ctx);
5598 if (read_format & PERF_FORMAT_GROUP)
5599 ret = perf_read_group(event, read_format, buf);
5601 ret = perf_read_one(event, read_format, buf);
5607 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5609 struct perf_event *event = file->private_data;
5610 struct perf_event_context *ctx;
5613 ret = security_perf_event_read(event);
5617 ctx = perf_event_ctx_lock(event);
5618 ret = __perf_read(event, buf, count);
5619 perf_event_ctx_unlock(event, ctx);
5624 static __poll_t perf_poll(struct file *file, poll_table *wait)
5626 struct perf_event *event = file->private_data;
5627 struct perf_buffer *rb;
5628 __poll_t events = EPOLLHUP;
5630 poll_wait(file, &event->waitq, wait);
5632 if (is_event_hup(event))
5636 * Pin the event->rb by taking event->mmap_mutex; otherwise
5637 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5639 mutex_lock(&event->mmap_mutex);
5642 events = atomic_xchg(&rb->poll, 0);
5643 mutex_unlock(&event->mmap_mutex);
5647 static void _perf_event_reset(struct perf_event *event)
5649 (void)perf_event_read(event, false);
5650 local64_set(&event->count, 0);
5651 perf_event_update_userpage(event);
5654 /* Assume it's not an event with inherit set. */
5655 u64 perf_event_pause(struct perf_event *event, bool reset)
5657 struct perf_event_context *ctx;
5660 ctx = perf_event_ctx_lock(event);
5661 WARN_ON_ONCE(event->attr.inherit);
5662 _perf_event_disable(event);
5663 count = local64_read(&event->count);
5665 local64_set(&event->count, 0);
5666 perf_event_ctx_unlock(event, ctx);
5670 EXPORT_SYMBOL_GPL(perf_event_pause);
5673 * Holding the top-level event's child_mutex means that any
5674 * descendant process that has inherited this event will block
5675 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5676 * task existence requirements of perf_event_enable/disable.
5678 static void perf_event_for_each_child(struct perf_event *event,
5679 void (*func)(struct perf_event *))
5681 struct perf_event *child;
5683 WARN_ON_ONCE(event->ctx->parent_ctx);
5685 mutex_lock(&event->child_mutex);
5687 list_for_each_entry(child, &event->child_list, child_list)
5689 mutex_unlock(&event->child_mutex);
5692 static void perf_event_for_each(struct perf_event *event,
5693 void (*func)(struct perf_event *))
5695 struct perf_event_context *ctx = event->ctx;
5696 struct perf_event *sibling;
5698 lockdep_assert_held(&ctx->mutex);
5700 event = event->group_leader;
5702 perf_event_for_each_child(event, func);
5703 for_each_sibling_event(sibling, event)
5704 perf_event_for_each_child(sibling, func);
5707 static void __perf_event_period(struct perf_event *event,
5708 struct perf_cpu_context *cpuctx,
5709 struct perf_event_context *ctx,
5712 u64 value = *((u64 *)info);
5715 if (event->attr.freq) {
5716 event->attr.sample_freq = value;
5718 event->attr.sample_period = value;
5719 event->hw.sample_period = value;
5722 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5724 perf_pmu_disable(event->pmu);
5726 * We could be throttled; unthrottle now to avoid the tick
5727 * trying to unthrottle while we already re-started the event.
5729 if (event->hw.interrupts == MAX_INTERRUPTS) {
5730 event->hw.interrupts = 0;
5731 perf_log_throttle(event, 1);
5733 event->pmu->stop(event, PERF_EF_UPDATE);
5736 local64_set(&event->hw.period_left, 0);
5739 event->pmu->start(event, PERF_EF_RELOAD);
5740 perf_pmu_enable(event->pmu);
5744 static int perf_event_check_period(struct perf_event *event, u64 value)
5746 return event->pmu->check_period(event, value);
5749 static int _perf_event_period(struct perf_event *event, u64 value)
5751 if (!is_sampling_event(event))
5757 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5760 if (perf_event_check_period(event, value))
5763 if (!event->attr.freq && (value & (1ULL << 63)))
5766 event_function_call(event, __perf_event_period, &value);
5771 int perf_event_period(struct perf_event *event, u64 value)
5773 struct perf_event_context *ctx;
5776 ctx = perf_event_ctx_lock(event);
5777 ret = _perf_event_period(event, value);
5778 perf_event_ctx_unlock(event, ctx);
5782 EXPORT_SYMBOL_GPL(perf_event_period);
5784 static const struct file_operations perf_fops;
5786 static inline int perf_fget_light(int fd, struct fd *p)
5788 struct fd f = fdget(fd);
5792 if (f.file->f_op != &perf_fops) {
5800 static int perf_event_set_output(struct perf_event *event,
5801 struct perf_event *output_event);
5802 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5803 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5804 struct perf_event_attr *attr);
5806 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5808 void (*func)(struct perf_event *);
5812 case PERF_EVENT_IOC_ENABLE:
5813 func = _perf_event_enable;
5815 case PERF_EVENT_IOC_DISABLE:
5816 func = _perf_event_disable;
5818 case PERF_EVENT_IOC_RESET:
5819 func = _perf_event_reset;
5822 case PERF_EVENT_IOC_REFRESH:
5823 return _perf_event_refresh(event, arg);
5825 case PERF_EVENT_IOC_PERIOD:
5829 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5832 return _perf_event_period(event, value);
5834 case PERF_EVENT_IOC_ID:
5836 u64 id = primary_event_id(event);
5838 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5843 case PERF_EVENT_IOC_SET_OUTPUT:
5847 struct perf_event *output_event;
5849 ret = perf_fget_light(arg, &output);
5852 output_event = output.file->private_data;
5853 ret = perf_event_set_output(event, output_event);
5856 ret = perf_event_set_output(event, NULL);
5861 case PERF_EVENT_IOC_SET_FILTER:
5862 return perf_event_set_filter(event, (void __user *)arg);
5864 case PERF_EVENT_IOC_SET_BPF:
5866 struct bpf_prog *prog;
5869 prog = bpf_prog_get(arg);
5871 return PTR_ERR(prog);
5873 err = perf_event_set_bpf_prog(event, prog, 0);
5882 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5883 struct perf_buffer *rb;
5886 rb = rcu_dereference(event->rb);
5887 if (!rb || !rb->nr_pages) {
5891 rb_toggle_paused(rb, !!arg);
5896 case PERF_EVENT_IOC_QUERY_BPF:
5897 return perf_event_query_prog_array(event, (void __user *)arg);
5899 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5900 struct perf_event_attr new_attr;
5901 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5907 return perf_event_modify_attr(event, &new_attr);
5913 if (flags & PERF_IOC_FLAG_GROUP)
5914 perf_event_for_each(event, func);
5916 perf_event_for_each_child(event, func);
5921 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5923 struct perf_event *event = file->private_data;
5924 struct perf_event_context *ctx;
5927 /* Treat ioctl like writes as it is likely a mutating operation. */
5928 ret = security_perf_event_write(event);
5932 ctx = perf_event_ctx_lock(event);
5933 ret = _perf_ioctl(event, cmd, arg);
5934 perf_event_ctx_unlock(event, ctx);
5939 #ifdef CONFIG_COMPAT
5940 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5943 switch (_IOC_NR(cmd)) {
5944 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5945 case _IOC_NR(PERF_EVENT_IOC_ID):
5946 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5947 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5948 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5949 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5950 cmd &= ~IOCSIZE_MASK;
5951 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5955 return perf_ioctl(file, cmd, arg);
5958 # define perf_compat_ioctl NULL
5961 int perf_event_task_enable(void)
5963 struct perf_event_context *ctx;
5964 struct perf_event *event;
5966 mutex_lock(¤t->perf_event_mutex);
5967 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5968 ctx = perf_event_ctx_lock(event);
5969 perf_event_for_each_child(event, _perf_event_enable);
5970 perf_event_ctx_unlock(event, ctx);
5972 mutex_unlock(¤t->perf_event_mutex);
5977 int perf_event_task_disable(void)
5979 struct perf_event_context *ctx;
5980 struct perf_event *event;
5982 mutex_lock(¤t->perf_event_mutex);
5983 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5984 ctx = perf_event_ctx_lock(event);
5985 perf_event_for_each_child(event, _perf_event_disable);
5986 perf_event_ctx_unlock(event, ctx);
5988 mutex_unlock(¤t->perf_event_mutex);
5993 static int perf_event_index(struct perf_event *event)
5995 if (event->hw.state & PERF_HES_STOPPED)
5998 if (event->state != PERF_EVENT_STATE_ACTIVE)
6001 return event->pmu->event_idx(event);
6004 static void perf_event_init_userpage(struct perf_event *event)
6006 struct perf_event_mmap_page *userpg;
6007 struct perf_buffer *rb;
6010 rb = rcu_dereference(event->rb);
6014 userpg = rb->user_page;
6016 /* Allow new userspace to detect that bit 0 is deprecated */
6017 userpg->cap_bit0_is_deprecated = 1;
6018 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6019 userpg->data_offset = PAGE_SIZE;
6020 userpg->data_size = perf_data_size(rb);
6026 void __weak arch_perf_update_userpage(
6027 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6032 * Callers need to ensure there can be no nesting of this function, otherwise
6033 * the seqlock logic goes bad. We can not serialize this because the arch
6034 * code calls this from NMI context.
6036 void perf_event_update_userpage(struct perf_event *event)
6038 struct perf_event_mmap_page *userpg;
6039 struct perf_buffer *rb;
6040 u64 enabled, running, now;
6043 rb = rcu_dereference(event->rb);
6048 * compute total_time_enabled, total_time_running
6049 * based on snapshot values taken when the event
6050 * was last scheduled in.
6052 * we cannot simply called update_context_time()
6053 * because of locking issue as we can be called in
6056 calc_timer_values(event, &now, &enabled, &running);
6058 userpg = rb->user_page;
6060 * Disable preemption to guarantee consistent time stamps are stored to
6066 userpg->index = perf_event_index(event);
6067 userpg->offset = perf_event_count(event);
6069 userpg->offset -= local64_read(&event->hw.prev_count);
6071 userpg->time_enabled = enabled +
6072 atomic64_read(&event->child_total_time_enabled);
6074 userpg->time_running = running +
6075 atomic64_read(&event->child_total_time_running);
6077 arch_perf_update_userpage(event, userpg, now);
6085 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6087 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
6089 struct perf_event *event = vmf->vma->vm_file->private_data;
6090 struct perf_buffer *rb;
6091 vm_fault_t ret = VM_FAULT_SIGBUS;
6093 if (vmf->flags & FAULT_FLAG_MKWRITE) {
6094 if (vmf->pgoff == 0)
6100 rb = rcu_dereference(event->rb);
6104 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
6107 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
6111 get_page(vmf->page);
6112 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
6113 vmf->page->index = vmf->pgoff;
6122 static void ring_buffer_attach(struct perf_event *event,
6123 struct perf_buffer *rb)
6125 struct perf_buffer *old_rb = NULL;
6126 unsigned long flags;
6128 WARN_ON_ONCE(event->parent);
6132 * Should be impossible, we set this when removing
6133 * event->rb_entry and wait/clear when adding event->rb_entry.
6135 WARN_ON_ONCE(event->rcu_pending);
6138 spin_lock_irqsave(&old_rb->event_lock, flags);
6139 list_del_rcu(&event->rb_entry);
6140 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6142 event->rcu_batches = get_state_synchronize_rcu();
6143 event->rcu_pending = 1;
6147 if (event->rcu_pending) {
6148 cond_synchronize_rcu(event->rcu_batches);
6149 event->rcu_pending = 0;
6152 spin_lock_irqsave(&rb->event_lock, flags);
6153 list_add_rcu(&event->rb_entry, &rb->event_list);
6154 spin_unlock_irqrestore(&rb->event_lock, flags);
6158 * Avoid racing with perf_mmap_close(AUX): stop the event
6159 * before swizzling the event::rb pointer; if it's getting
6160 * unmapped, its aux_mmap_count will be 0 and it won't
6161 * restart. See the comment in __perf_pmu_output_stop().
6163 * Data will inevitably be lost when set_output is done in
6164 * mid-air, but then again, whoever does it like this is
6165 * not in for the data anyway.
6168 perf_event_stop(event, 0);
6170 rcu_assign_pointer(event->rb, rb);
6173 ring_buffer_put(old_rb);
6175 * Since we detached before setting the new rb, so that we
6176 * could attach the new rb, we could have missed a wakeup.
6179 wake_up_all(&event->waitq);
6183 static void ring_buffer_wakeup(struct perf_event *event)
6185 struct perf_buffer *rb;
6188 event = event->parent;
6191 rb = rcu_dereference(event->rb);
6193 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6194 wake_up_all(&event->waitq);
6199 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6201 struct perf_buffer *rb;
6204 event = event->parent;
6207 rb = rcu_dereference(event->rb);
6209 if (!refcount_inc_not_zero(&rb->refcount))
6217 void ring_buffer_put(struct perf_buffer *rb)
6219 if (!refcount_dec_and_test(&rb->refcount))
6222 WARN_ON_ONCE(!list_empty(&rb->event_list));
6224 call_rcu(&rb->rcu_head, rb_free_rcu);
6227 static void perf_mmap_open(struct vm_area_struct *vma)
6229 struct perf_event *event = vma->vm_file->private_data;
6231 atomic_inc(&event->mmap_count);
6232 atomic_inc(&event->rb->mmap_count);
6235 atomic_inc(&event->rb->aux_mmap_count);
6237 if (event->pmu->event_mapped)
6238 event->pmu->event_mapped(event, vma->vm_mm);
6241 static void perf_pmu_output_stop(struct perf_event *event);
6244 * A buffer can be mmap()ed multiple times; either directly through the same
6245 * event, or through other events by use of perf_event_set_output().
6247 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6248 * the buffer here, where we still have a VM context. This means we need
6249 * to detach all events redirecting to us.
6251 static void perf_mmap_close(struct vm_area_struct *vma)
6253 struct perf_event *event = vma->vm_file->private_data;
6254 struct perf_buffer *rb = ring_buffer_get(event);
6255 struct user_struct *mmap_user = rb->mmap_user;
6256 int mmap_locked = rb->mmap_locked;
6257 unsigned long size = perf_data_size(rb);
6258 bool detach_rest = false;
6260 if (event->pmu->event_unmapped)
6261 event->pmu->event_unmapped(event, vma->vm_mm);
6264 * rb->aux_mmap_count will always drop before rb->mmap_count and
6265 * event->mmap_count, so it is ok to use event->mmap_mutex to
6266 * serialize with perf_mmap here.
6268 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6269 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6271 * Stop all AUX events that are writing to this buffer,
6272 * so that we can free its AUX pages and corresponding PMU
6273 * data. Note that after rb::aux_mmap_count dropped to zero,
6274 * they won't start any more (see perf_aux_output_begin()).
6276 perf_pmu_output_stop(event);
6278 /* now it's safe to free the pages */
6279 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6280 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6282 /* this has to be the last one */
6284 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6286 mutex_unlock(&event->mmap_mutex);
6289 if (atomic_dec_and_test(&rb->mmap_count))
6292 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6295 ring_buffer_attach(event, NULL);
6296 mutex_unlock(&event->mmap_mutex);
6298 /* If there's still other mmap()s of this buffer, we're done. */
6303 * No other mmap()s, detach from all other events that might redirect
6304 * into the now unreachable buffer. Somewhat complicated by the
6305 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6309 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6310 if (!atomic_long_inc_not_zero(&event->refcount)) {
6312 * This event is en-route to free_event() which will
6313 * detach it and remove it from the list.
6319 mutex_lock(&event->mmap_mutex);
6321 * Check we didn't race with perf_event_set_output() which can
6322 * swizzle the rb from under us while we were waiting to
6323 * acquire mmap_mutex.
6325 * If we find a different rb; ignore this event, a next
6326 * iteration will no longer find it on the list. We have to
6327 * still restart the iteration to make sure we're not now
6328 * iterating the wrong list.
6330 if (event->rb == rb)
6331 ring_buffer_attach(event, NULL);
6333 mutex_unlock(&event->mmap_mutex);
6337 * Restart the iteration; either we're on the wrong list or
6338 * destroyed its integrity by doing a deletion.
6345 * It could be there's still a few 0-ref events on the list; they'll
6346 * get cleaned up by free_event() -- they'll also still have their
6347 * ref on the rb and will free it whenever they are done with it.
6349 * Aside from that, this buffer is 'fully' detached and unmapped,
6350 * undo the VM accounting.
6353 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6354 &mmap_user->locked_vm);
6355 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6356 free_uid(mmap_user);
6359 ring_buffer_put(rb); /* could be last */
6362 static const struct vm_operations_struct perf_mmap_vmops = {
6363 .open = perf_mmap_open,
6364 .close = perf_mmap_close, /* non mergeable */
6365 .fault = perf_mmap_fault,
6366 .page_mkwrite = perf_mmap_fault,
6369 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6371 struct perf_event *event = file->private_data;
6372 unsigned long user_locked, user_lock_limit;
6373 struct user_struct *user = current_user();
6374 struct perf_buffer *rb = NULL;
6375 unsigned long locked, lock_limit;
6376 unsigned long vma_size;
6377 unsigned long nr_pages;
6378 long user_extra = 0, extra = 0;
6379 int ret = 0, flags = 0;
6382 * Don't allow mmap() of inherited per-task counters. This would
6383 * create a performance issue due to all children writing to the
6386 if (event->cpu == -1 && event->attr.inherit)
6389 if (!(vma->vm_flags & VM_SHARED))
6392 ret = security_perf_event_read(event);
6396 vma_size = vma->vm_end - vma->vm_start;
6398 if (vma->vm_pgoff == 0) {
6399 nr_pages = (vma_size / PAGE_SIZE) - 1;
6402 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6403 * mapped, all subsequent mappings should have the same size
6404 * and offset. Must be above the normal perf buffer.
6406 u64 aux_offset, aux_size;
6411 nr_pages = vma_size / PAGE_SIZE;
6413 mutex_lock(&event->mmap_mutex);
6420 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6421 aux_size = READ_ONCE(rb->user_page->aux_size);
6423 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6426 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6429 /* already mapped with a different offset */
6430 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6433 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6436 /* already mapped with a different size */
6437 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6440 if (!is_power_of_2(nr_pages))
6443 if (!atomic_inc_not_zero(&rb->mmap_count))
6446 if (rb_has_aux(rb)) {
6447 atomic_inc(&rb->aux_mmap_count);
6452 atomic_set(&rb->aux_mmap_count, 1);
6453 user_extra = nr_pages;
6459 * If we have rb pages ensure they're a power-of-two number, so we
6460 * can do bitmasks instead of modulo.
6462 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6465 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6468 WARN_ON_ONCE(event->ctx->parent_ctx);
6470 mutex_lock(&event->mmap_mutex);
6472 if (data_page_nr(event->rb) != nr_pages) {
6477 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6479 * Raced against perf_mmap_close(); remove the
6480 * event and try again.
6482 ring_buffer_attach(event, NULL);
6483 mutex_unlock(&event->mmap_mutex);
6490 user_extra = nr_pages + 1;
6493 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6496 * Increase the limit linearly with more CPUs:
6498 user_lock_limit *= num_online_cpus();
6500 user_locked = atomic_long_read(&user->locked_vm);
6503 * sysctl_perf_event_mlock may have changed, so that
6504 * user->locked_vm > user_lock_limit
6506 if (user_locked > user_lock_limit)
6507 user_locked = user_lock_limit;
6508 user_locked += user_extra;
6510 if (user_locked > user_lock_limit) {
6512 * charge locked_vm until it hits user_lock_limit;
6513 * charge the rest from pinned_vm
6515 extra = user_locked - user_lock_limit;
6516 user_extra -= extra;
6519 lock_limit = rlimit(RLIMIT_MEMLOCK);
6520 lock_limit >>= PAGE_SHIFT;
6521 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6523 if ((locked > lock_limit) && perf_is_paranoid() &&
6524 !capable(CAP_IPC_LOCK)) {
6529 WARN_ON(!rb && event->rb);
6531 if (vma->vm_flags & VM_WRITE)
6532 flags |= RING_BUFFER_WRITABLE;
6535 rb = rb_alloc(nr_pages,
6536 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6544 atomic_set(&rb->mmap_count, 1);
6545 rb->mmap_user = get_current_user();
6546 rb->mmap_locked = extra;
6548 ring_buffer_attach(event, rb);
6550 perf_event_update_time(event);
6551 perf_event_init_userpage(event);
6552 perf_event_update_userpage(event);
6554 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6555 event->attr.aux_watermark, flags);
6557 rb->aux_mmap_locked = extra;
6562 atomic_long_add(user_extra, &user->locked_vm);
6563 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6565 atomic_inc(&event->mmap_count);
6567 atomic_dec(&rb->mmap_count);
6570 mutex_unlock(&event->mmap_mutex);
6573 * Since pinned accounting is per vm we cannot allow fork() to copy our
6576 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6577 vma->vm_ops = &perf_mmap_vmops;
6579 if (event->pmu->event_mapped)
6580 event->pmu->event_mapped(event, vma->vm_mm);
6585 static int perf_fasync(int fd, struct file *filp, int on)
6587 struct inode *inode = file_inode(filp);
6588 struct perf_event *event = filp->private_data;
6592 retval = fasync_helper(fd, filp, on, &event->fasync);
6593 inode_unlock(inode);
6601 static const struct file_operations perf_fops = {
6602 .llseek = no_llseek,
6603 .release = perf_release,
6606 .unlocked_ioctl = perf_ioctl,
6607 .compat_ioctl = perf_compat_ioctl,
6609 .fasync = perf_fasync,
6615 * If there's data, ensure we set the poll() state and publish everything
6616 * to user-space before waking everybody up.
6619 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6621 /* only the parent has fasync state */
6623 event = event->parent;
6624 return &event->fasync;
6627 void perf_event_wakeup(struct perf_event *event)
6629 ring_buffer_wakeup(event);
6631 if (event->pending_kill) {
6632 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6633 event->pending_kill = 0;
6637 static void perf_sigtrap(struct perf_event *event)
6640 * We'd expect this to only occur if the irq_work is delayed and either
6641 * ctx->task or current has changed in the meantime. This can be the
6642 * case on architectures that do not implement arch_irq_work_raise().
6644 if (WARN_ON_ONCE(event->ctx->task != current))
6648 * Both perf_pending_task() and perf_pending_irq() can race with the
6651 if (current->flags & PF_EXITING)
6654 send_sig_perf((void __user *)event->pending_addr,
6655 event->attr.type, event->attr.sig_data);
6659 * Deliver the pending work in-event-context or follow the context.
6661 static void __perf_pending_irq(struct perf_event *event)
6663 int cpu = READ_ONCE(event->oncpu);
6666 * If the event isn't running; we done. event_sched_out() will have
6667 * taken care of things.
6673 * Yay, we hit home and are in the context of the event.
6675 if (cpu == smp_processor_id()) {
6676 if (event->pending_sigtrap) {
6677 event->pending_sigtrap = 0;
6678 perf_sigtrap(event);
6679 local_dec(&event->ctx->nr_pending);
6681 if (event->pending_disable) {
6682 event->pending_disable = 0;
6683 perf_event_disable_local(event);
6691 * perf_event_disable_inatomic()
6692 * @pending_disable = CPU-A;
6696 * @pending_disable = -1;
6699 * perf_event_disable_inatomic()
6700 * @pending_disable = CPU-B;
6701 * irq_work_queue(); // FAILS
6704 * perf_pending_irq()
6706 * But the event runs on CPU-B and wants disabling there.
6708 irq_work_queue_on(&event->pending_irq, cpu);
6711 static void perf_pending_irq(struct irq_work *entry)
6713 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6717 * If we 'fail' here, that's OK, it means recursion is already disabled
6718 * and we won't recurse 'further'.
6720 rctx = perf_swevent_get_recursion_context();
6723 * The wakeup isn't bound to the context of the event -- it can happen
6724 * irrespective of where the event is.
6726 if (event->pending_wakeup) {
6727 event->pending_wakeup = 0;
6728 perf_event_wakeup(event);
6731 __perf_pending_irq(event);
6734 perf_swevent_put_recursion_context(rctx);
6737 static void perf_pending_task(struct callback_head *head)
6739 struct perf_event *event = container_of(head, struct perf_event, pending_task);
6743 * If we 'fail' here, that's OK, it means recursion is already disabled
6744 * and we won't recurse 'further'.
6746 preempt_disable_notrace();
6747 rctx = perf_swevent_get_recursion_context();
6749 if (event->pending_work) {
6750 event->pending_work = 0;
6751 perf_sigtrap(event);
6752 local_dec(&event->ctx->nr_pending);
6756 perf_swevent_put_recursion_context(rctx);
6757 preempt_enable_notrace();
6762 #ifdef CONFIG_GUEST_PERF_EVENTS
6763 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6765 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
6766 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
6767 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
6769 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6771 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6774 rcu_assign_pointer(perf_guest_cbs, cbs);
6775 static_call_update(__perf_guest_state, cbs->state);
6776 static_call_update(__perf_guest_get_ip, cbs->get_ip);
6778 /* Implementing ->handle_intel_pt_intr is optional. */
6779 if (cbs->handle_intel_pt_intr)
6780 static_call_update(__perf_guest_handle_intel_pt_intr,
6781 cbs->handle_intel_pt_intr);
6783 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6785 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6787 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6790 rcu_assign_pointer(perf_guest_cbs, NULL);
6791 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
6792 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
6793 static_call_update(__perf_guest_handle_intel_pt_intr,
6794 (void *)&__static_call_return0);
6797 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6801 perf_output_sample_regs(struct perf_output_handle *handle,
6802 struct pt_regs *regs, u64 mask)
6805 DECLARE_BITMAP(_mask, 64);
6807 bitmap_from_u64(_mask, mask);
6808 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6811 val = perf_reg_value(regs, bit);
6812 perf_output_put(handle, val);
6816 static void perf_sample_regs_user(struct perf_regs *regs_user,
6817 struct pt_regs *regs)
6819 if (user_mode(regs)) {
6820 regs_user->abi = perf_reg_abi(current);
6821 regs_user->regs = regs;
6822 } else if (!(current->flags & PF_KTHREAD)) {
6823 perf_get_regs_user(regs_user, regs);
6825 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6826 regs_user->regs = NULL;
6830 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6831 struct pt_regs *regs)
6833 regs_intr->regs = regs;
6834 regs_intr->abi = perf_reg_abi(current);
6839 * Get remaining task size from user stack pointer.
6841 * It'd be better to take stack vma map and limit this more
6842 * precisely, but there's no way to get it safely under interrupt,
6843 * so using TASK_SIZE as limit.
6845 static u64 perf_ustack_task_size(struct pt_regs *regs)
6847 unsigned long addr = perf_user_stack_pointer(regs);
6849 if (!addr || addr >= TASK_SIZE)
6852 return TASK_SIZE - addr;
6856 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6857 struct pt_regs *regs)
6861 /* No regs, no stack pointer, no dump. */
6866 * Check if we fit in with the requested stack size into the:
6868 * If we don't, we limit the size to the TASK_SIZE.
6870 * - remaining sample size
6871 * If we don't, we customize the stack size to
6872 * fit in to the remaining sample size.
6875 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6876 stack_size = min(stack_size, (u16) task_size);
6878 /* Current header size plus static size and dynamic size. */
6879 header_size += 2 * sizeof(u64);
6881 /* Do we fit in with the current stack dump size? */
6882 if ((u16) (header_size + stack_size) < header_size) {
6884 * If we overflow the maximum size for the sample,
6885 * we customize the stack dump size to fit in.
6887 stack_size = USHRT_MAX - header_size - sizeof(u64);
6888 stack_size = round_up(stack_size, sizeof(u64));
6895 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6896 struct pt_regs *regs)
6898 /* Case of a kernel thread, nothing to dump */
6901 perf_output_put(handle, size);
6910 * - the size requested by user or the best one we can fit
6911 * in to the sample max size
6913 * - user stack dump data
6915 * - the actual dumped size
6919 perf_output_put(handle, dump_size);
6922 sp = perf_user_stack_pointer(regs);
6923 rem = __output_copy_user(handle, (void *) sp, dump_size);
6924 dyn_size = dump_size - rem;
6926 perf_output_skip(handle, rem);
6929 perf_output_put(handle, dyn_size);
6933 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6934 struct perf_sample_data *data,
6937 struct perf_event *sampler = event->aux_event;
6938 struct perf_buffer *rb;
6945 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6948 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6951 rb = ring_buffer_get(sampler);
6956 * If this is an NMI hit inside sampling code, don't take
6957 * the sample. See also perf_aux_sample_output().
6959 if (READ_ONCE(rb->aux_in_sampling)) {
6962 size = min_t(size_t, size, perf_aux_size(rb));
6963 data->aux_size = ALIGN(size, sizeof(u64));
6965 ring_buffer_put(rb);
6968 return data->aux_size;
6971 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6972 struct perf_event *event,
6973 struct perf_output_handle *handle,
6976 unsigned long flags;
6980 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6981 * paths. If we start calling them in NMI context, they may race with
6982 * the IRQ ones, that is, for example, re-starting an event that's just
6983 * been stopped, which is why we're using a separate callback that
6984 * doesn't change the event state.
6986 * IRQs need to be disabled to prevent IPIs from racing with us.
6988 local_irq_save(flags);
6990 * Guard against NMI hits inside the critical section;
6991 * see also perf_prepare_sample_aux().
6993 WRITE_ONCE(rb->aux_in_sampling, 1);
6996 ret = event->pmu->snapshot_aux(event, handle, size);
6999 WRITE_ONCE(rb->aux_in_sampling, 0);
7000 local_irq_restore(flags);
7005 static void perf_aux_sample_output(struct perf_event *event,
7006 struct perf_output_handle *handle,
7007 struct perf_sample_data *data)
7009 struct perf_event *sampler = event->aux_event;
7010 struct perf_buffer *rb;
7014 if (WARN_ON_ONCE(!sampler || !data->aux_size))
7017 rb = ring_buffer_get(sampler);
7021 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7024 * An error here means that perf_output_copy() failed (returned a
7025 * non-zero surplus that it didn't copy), which in its current
7026 * enlightened implementation is not possible. If that changes, we'd
7029 if (WARN_ON_ONCE(size < 0))
7033 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7034 * perf_prepare_sample_aux(), so should not be more than that.
7036 pad = data->aux_size - size;
7037 if (WARN_ON_ONCE(pad >= sizeof(u64)))
7042 perf_output_copy(handle, &zero, pad);
7046 ring_buffer_put(rb);
7049 static void __perf_event_header__init_id(struct perf_event_header *header,
7050 struct perf_sample_data *data,
7051 struct perf_event *event,
7054 data->type = event->attr.sample_type;
7055 header->size += event->id_header_size;
7057 if (sample_type & PERF_SAMPLE_TID) {
7058 /* namespace issues */
7059 data->tid_entry.pid = perf_event_pid(event, current);
7060 data->tid_entry.tid = perf_event_tid(event, current);
7063 if (sample_type & PERF_SAMPLE_TIME)
7064 data->time = perf_event_clock(event);
7066 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7067 data->id = primary_event_id(event);
7069 if (sample_type & PERF_SAMPLE_STREAM_ID)
7070 data->stream_id = event->id;
7072 if (sample_type & PERF_SAMPLE_CPU) {
7073 data->cpu_entry.cpu = raw_smp_processor_id();
7074 data->cpu_entry.reserved = 0;
7078 void perf_event_header__init_id(struct perf_event_header *header,
7079 struct perf_sample_data *data,
7080 struct perf_event *event)
7082 if (event->attr.sample_id_all)
7083 __perf_event_header__init_id(header, data, event, event->attr.sample_type);
7086 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7087 struct perf_sample_data *data)
7089 u64 sample_type = data->type;
7091 if (sample_type & PERF_SAMPLE_TID)
7092 perf_output_put(handle, data->tid_entry);
7094 if (sample_type & PERF_SAMPLE_TIME)
7095 perf_output_put(handle, data->time);
7097 if (sample_type & PERF_SAMPLE_ID)
7098 perf_output_put(handle, data->id);
7100 if (sample_type & PERF_SAMPLE_STREAM_ID)
7101 perf_output_put(handle, data->stream_id);
7103 if (sample_type & PERF_SAMPLE_CPU)
7104 perf_output_put(handle, data->cpu_entry);
7106 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7107 perf_output_put(handle, data->id);
7110 void perf_event__output_id_sample(struct perf_event *event,
7111 struct perf_output_handle *handle,
7112 struct perf_sample_data *sample)
7114 if (event->attr.sample_id_all)
7115 __perf_event__output_id_sample(handle, sample);
7118 static void perf_output_read_one(struct perf_output_handle *handle,
7119 struct perf_event *event,
7120 u64 enabled, u64 running)
7122 u64 read_format = event->attr.read_format;
7126 values[n++] = perf_event_count(event);
7127 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7128 values[n++] = enabled +
7129 atomic64_read(&event->child_total_time_enabled);
7131 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7132 values[n++] = running +
7133 atomic64_read(&event->child_total_time_running);
7135 if (read_format & PERF_FORMAT_ID)
7136 values[n++] = primary_event_id(event);
7137 if (read_format & PERF_FORMAT_LOST)
7138 values[n++] = atomic64_read(&event->lost_samples);
7140 __output_copy(handle, values, n * sizeof(u64));
7143 static void perf_output_read_group(struct perf_output_handle *handle,
7144 struct perf_event *event,
7145 u64 enabled, u64 running)
7147 struct perf_event *leader = event->group_leader, *sub;
7148 u64 read_format = event->attr.read_format;
7149 unsigned long flags;
7154 * Disabling interrupts avoids all counter scheduling
7155 * (context switches, timer based rotation and IPIs).
7157 local_irq_save(flags);
7159 values[n++] = 1 + leader->nr_siblings;
7161 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7162 values[n++] = enabled;
7164 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7165 values[n++] = running;
7167 if ((leader != event) &&
7168 (leader->state == PERF_EVENT_STATE_ACTIVE))
7169 leader->pmu->read(leader);
7171 values[n++] = perf_event_count(leader);
7172 if (read_format & PERF_FORMAT_ID)
7173 values[n++] = primary_event_id(leader);
7174 if (read_format & PERF_FORMAT_LOST)
7175 values[n++] = atomic64_read(&leader->lost_samples);
7177 __output_copy(handle, values, n * sizeof(u64));
7179 for_each_sibling_event(sub, leader) {
7182 if ((sub != event) &&
7183 (sub->state == PERF_EVENT_STATE_ACTIVE))
7184 sub->pmu->read(sub);
7186 values[n++] = perf_event_count(sub);
7187 if (read_format & PERF_FORMAT_ID)
7188 values[n++] = primary_event_id(sub);
7189 if (read_format & PERF_FORMAT_LOST)
7190 values[n++] = atomic64_read(&sub->lost_samples);
7192 __output_copy(handle, values, n * sizeof(u64));
7195 local_irq_restore(flags);
7198 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7199 PERF_FORMAT_TOTAL_TIME_RUNNING)
7202 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7204 * The problem is that its both hard and excessively expensive to iterate the
7205 * child list, not to mention that its impossible to IPI the children running
7206 * on another CPU, from interrupt/NMI context.
7208 static void perf_output_read(struct perf_output_handle *handle,
7209 struct perf_event *event)
7211 u64 enabled = 0, running = 0, now;
7212 u64 read_format = event->attr.read_format;
7215 * compute total_time_enabled, total_time_running
7216 * based on snapshot values taken when the event
7217 * was last scheduled in.
7219 * we cannot simply called update_context_time()
7220 * because of locking issue as we are called in
7223 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7224 calc_timer_values(event, &now, &enabled, &running);
7226 if (event->attr.read_format & PERF_FORMAT_GROUP)
7227 perf_output_read_group(handle, event, enabled, running);
7229 perf_output_read_one(handle, event, enabled, running);
7232 void perf_output_sample(struct perf_output_handle *handle,
7233 struct perf_event_header *header,
7234 struct perf_sample_data *data,
7235 struct perf_event *event)
7237 u64 sample_type = data->type;
7239 perf_output_put(handle, *header);
7241 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7242 perf_output_put(handle, data->id);
7244 if (sample_type & PERF_SAMPLE_IP)
7245 perf_output_put(handle, data->ip);
7247 if (sample_type & PERF_SAMPLE_TID)
7248 perf_output_put(handle, data->tid_entry);
7250 if (sample_type & PERF_SAMPLE_TIME)
7251 perf_output_put(handle, data->time);
7253 if (sample_type & PERF_SAMPLE_ADDR)
7254 perf_output_put(handle, data->addr);
7256 if (sample_type & PERF_SAMPLE_ID)
7257 perf_output_put(handle, data->id);
7259 if (sample_type & PERF_SAMPLE_STREAM_ID)
7260 perf_output_put(handle, data->stream_id);
7262 if (sample_type & PERF_SAMPLE_CPU)
7263 perf_output_put(handle, data->cpu_entry);
7265 if (sample_type & PERF_SAMPLE_PERIOD)
7266 perf_output_put(handle, data->period);
7268 if (sample_type & PERF_SAMPLE_READ)
7269 perf_output_read(handle, event);
7271 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7274 size += data->callchain->nr;
7275 size *= sizeof(u64);
7276 __output_copy(handle, data->callchain, size);
7279 if (sample_type & PERF_SAMPLE_RAW) {
7280 struct perf_raw_record *raw = data->raw;
7283 struct perf_raw_frag *frag = &raw->frag;
7285 perf_output_put(handle, raw->size);
7288 __output_custom(handle, frag->copy,
7289 frag->data, frag->size);
7291 __output_copy(handle, frag->data,
7294 if (perf_raw_frag_last(frag))
7299 __output_skip(handle, NULL, frag->pad);
7305 .size = sizeof(u32),
7308 perf_output_put(handle, raw);
7312 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7313 if (data->br_stack) {
7316 size = data->br_stack->nr
7317 * sizeof(struct perf_branch_entry);
7319 perf_output_put(handle, data->br_stack->nr);
7320 if (branch_sample_hw_index(event))
7321 perf_output_put(handle, data->br_stack->hw_idx);
7322 perf_output_copy(handle, data->br_stack->entries, size);
7325 * we always store at least the value of nr
7328 perf_output_put(handle, nr);
7332 if (sample_type & PERF_SAMPLE_REGS_USER) {
7333 u64 abi = data->regs_user.abi;
7336 * If there are no regs to dump, notice it through
7337 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7339 perf_output_put(handle, abi);
7342 u64 mask = event->attr.sample_regs_user;
7343 perf_output_sample_regs(handle,
7344 data->regs_user.regs,
7349 if (sample_type & PERF_SAMPLE_STACK_USER) {
7350 perf_output_sample_ustack(handle,
7351 data->stack_user_size,
7352 data->regs_user.regs);
7355 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7356 perf_output_put(handle, data->weight.full);
7358 if (sample_type & PERF_SAMPLE_DATA_SRC)
7359 perf_output_put(handle, data->data_src.val);
7361 if (sample_type & PERF_SAMPLE_TRANSACTION)
7362 perf_output_put(handle, data->txn);
7364 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7365 u64 abi = data->regs_intr.abi;
7367 * If there are no regs to dump, notice it through
7368 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7370 perf_output_put(handle, abi);
7373 u64 mask = event->attr.sample_regs_intr;
7375 perf_output_sample_regs(handle,
7376 data->regs_intr.regs,
7381 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7382 perf_output_put(handle, data->phys_addr);
7384 if (sample_type & PERF_SAMPLE_CGROUP)
7385 perf_output_put(handle, data->cgroup);
7387 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7388 perf_output_put(handle, data->data_page_size);
7390 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7391 perf_output_put(handle, data->code_page_size);
7393 if (sample_type & PERF_SAMPLE_AUX) {
7394 perf_output_put(handle, data->aux_size);
7397 perf_aux_sample_output(event, handle, data);
7400 if (!event->attr.watermark) {
7401 int wakeup_events = event->attr.wakeup_events;
7403 if (wakeup_events) {
7404 struct perf_buffer *rb = handle->rb;
7405 int events = local_inc_return(&rb->events);
7407 if (events >= wakeup_events) {
7408 local_sub(wakeup_events, &rb->events);
7409 local_inc(&rb->wakeup);
7415 static u64 perf_virt_to_phys(u64 virt)
7422 if (virt >= TASK_SIZE) {
7423 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7424 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7425 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7426 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7429 * Walking the pages tables for user address.
7430 * Interrupts are disabled, so it prevents any tear down
7431 * of the page tables.
7432 * Try IRQ-safe get_user_page_fast_only first.
7433 * If failed, leave phys_addr as 0.
7435 if (current->mm != NULL) {
7438 pagefault_disable();
7439 if (get_user_page_fast_only(virt, 0, &p)) {
7440 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7451 * Return the pagetable size of a given virtual address.
7453 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7457 #ifdef CONFIG_HAVE_FAST_GUP
7464 pgdp = pgd_offset(mm, addr);
7465 pgd = READ_ONCE(*pgdp);
7470 return pgd_leaf_size(pgd);
7472 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7473 p4d = READ_ONCE(*p4dp);
7474 if (!p4d_present(p4d))
7478 return p4d_leaf_size(p4d);
7480 pudp = pud_offset_lockless(p4dp, p4d, addr);
7481 pud = READ_ONCE(*pudp);
7482 if (!pud_present(pud))
7486 return pud_leaf_size(pud);
7488 pmdp = pmd_offset_lockless(pudp, pud, addr);
7489 pmd = pmdp_get_lockless(pmdp);
7490 if (!pmd_present(pmd))
7494 return pmd_leaf_size(pmd);
7496 ptep = pte_offset_map(&pmd, addr);
7497 pte = ptep_get_lockless(ptep);
7498 if (pte_present(pte))
7499 size = pte_leaf_size(pte);
7501 #endif /* CONFIG_HAVE_FAST_GUP */
7506 static u64 perf_get_page_size(unsigned long addr)
7508 struct mm_struct *mm;
7509 unsigned long flags;
7516 * Software page-table walkers must disable IRQs,
7517 * which prevents any tear down of the page tables.
7519 local_irq_save(flags);
7524 * For kernel threads and the like, use init_mm so that
7525 * we can find kernel memory.
7530 size = perf_get_pgtable_size(mm, addr);
7532 local_irq_restore(flags);
7537 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7539 struct perf_callchain_entry *
7540 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7542 bool kernel = !event->attr.exclude_callchain_kernel;
7543 bool user = !event->attr.exclude_callchain_user;
7544 /* Disallow cross-task user callchains. */
7545 bool crosstask = event->ctx->task && event->ctx->task != current;
7546 const u32 max_stack = event->attr.sample_max_stack;
7547 struct perf_callchain_entry *callchain;
7549 if (!kernel && !user)
7550 return &__empty_callchain;
7552 callchain = get_perf_callchain(regs, 0, kernel, user,
7553 max_stack, crosstask, true);
7554 return callchain ?: &__empty_callchain;
7557 void perf_prepare_sample(struct perf_event_header *header,
7558 struct perf_sample_data *data,
7559 struct perf_event *event,
7560 struct pt_regs *regs)
7562 u64 sample_type = event->attr.sample_type;
7563 u64 filtered_sample_type;
7565 header->type = PERF_RECORD_SAMPLE;
7566 header->size = sizeof(*header) + event->header_size;
7569 header->misc |= perf_misc_flags(regs);
7572 * Clear the sample flags that have already been done by the
7575 filtered_sample_type = sample_type & ~data->sample_flags;
7576 __perf_event_header__init_id(header, data, event, filtered_sample_type);
7578 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7579 data->ip = perf_instruction_pointer(regs);
7581 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7582 perf_sample_save_callchain(data, event, regs);
7584 if (filtered_sample_type & PERF_SAMPLE_RAW) {
7586 data->dyn_size += sizeof(u64);
7587 data->sample_flags |= PERF_SAMPLE_RAW;
7590 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
7591 data->br_stack = NULL;
7592 data->dyn_size += sizeof(u64);
7593 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
7596 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7597 perf_sample_regs_user(&data->regs_user, regs);
7599 if (sample_type & PERF_SAMPLE_REGS_USER) {
7600 /* regs dump ABI info */
7601 int size = sizeof(u64);
7603 if (data->regs_user.regs) {
7604 u64 mask = event->attr.sample_regs_user;
7605 size += hweight64(mask) * sizeof(u64);
7608 data->dyn_size += size;
7611 if (sample_type & PERF_SAMPLE_STACK_USER) {
7613 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7614 * processed as the last one or have additional check added
7615 * in case new sample type is added, because we could eat
7616 * up the rest of the sample size.
7618 u16 stack_size = event->attr.sample_stack_user;
7619 u16 size = sizeof(u64);
7621 stack_size = perf_sample_ustack_size(stack_size, header->size,
7622 data->regs_user.regs);
7625 * If there is something to dump, add space for the dump
7626 * itself and for the field that tells the dynamic size,
7627 * which is how many have been actually dumped.
7630 size += sizeof(u64) + stack_size;
7632 data->stack_user_size = stack_size;
7633 data->dyn_size += size;
7636 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7637 data->weight.full = 0;
7639 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC)
7640 data->data_src.val = PERF_MEM_NA;
7642 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION)
7645 if (sample_type & (PERF_SAMPLE_ADDR | PERF_SAMPLE_PHYS_ADDR | PERF_SAMPLE_DATA_PAGE_SIZE)) {
7646 if (filtered_sample_type & PERF_SAMPLE_ADDR)
7650 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7651 /* regs dump ABI info */
7652 int size = sizeof(u64);
7654 perf_sample_regs_intr(&data->regs_intr, regs);
7656 if (data->regs_intr.regs) {
7657 u64 mask = event->attr.sample_regs_intr;
7659 size += hweight64(mask) * sizeof(u64);
7662 data->dyn_size += size;
7665 if (sample_type & PERF_SAMPLE_PHYS_ADDR &&
7666 filtered_sample_type & PERF_SAMPLE_PHYS_ADDR)
7667 data->phys_addr = perf_virt_to_phys(data->addr);
7669 #ifdef CONFIG_CGROUP_PERF
7670 if (sample_type & PERF_SAMPLE_CGROUP) {
7671 struct cgroup *cgrp;
7673 /* protected by RCU */
7674 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7675 data->cgroup = cgroup_id(cgrp);
7680 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7681 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7682 * but the value will not dump to the userspace.
7684 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7685 data->data_page_size = perf_get_page_size(data->addr);
7687 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7688 data->code_page_size = perf_get_page_size(data->ip);
7690 if (sample_type & PERF_SAMPLE_AUX) {
7693 header->size += sizeof(u64); /* size */
7696 * Given the 16bit nature of header::size, an AUX sample can
7697 * easily overflow it, what with all the preceding sample bits.
7698 * Make sure this doesn't happen by using up to U16_MAX bytes
7699 * per sample in total (rounded down to 8 byte boundary).
7701 size = min_t(size_t, U16_MAX - header->size,
7702 event->attr.aux_sample_size);
7703 size = rounddown(size, 8);
7704 size = perf_prepare_sample_aux(event, data, size);
7706 WARN_ON_ONCE(size + header->size > U16_MAX);
7707 data->dyn_size += size + sizeof(u64); /* size above */
7710 header->size += data->dyn_size;
7713 * If you're adding more sample types here, you likely need to do
7714 * something about the overflowing header::size, like repurpose the
7715 * lowest 3 bits of size, which should be always zero at the moment.
7716 * This raises a more important question, do we really need 512k sized
7717 * samples and why, so good argumentation is in order for whatever you
7720 WARN_ON_ONCE(header->size & 7);
7723 static __always_inline int
7724 __perf_event_output(struct perf_event *event,
7725 struct perf_sample_data *data,
7726 struct pt_regs *regs,
7727 int (*output_begin)(struct perf_output_handle *,
7728 struct perf_sample_data *,
7729 struct perf_event *,
7732 struct perf_output_handle handle;
7733 struct perf_event_header header;
7736 /* protect the callchain buffers */
7739 perf_prepare_sample(&header, data, event, regs);
7741 err = output_begin(&handle, data, event, header.size);
7745 perf_output_sample(&handle, &header, data, event);
7747 perf_output_end(&handle);
7755 perf_event_output_forward(struct perf_event *event,
7756 struct perf_sample_data *data,
7757 struct pt_regs *regs)
7759 __perf_event_output(event, data, regs, perf_output_begin_forward);
7763 perf_event_output_backward(struct perf_event *event,
7764 struct perf_sample_data *data,
7765 struct pt_regs *regs)
7767 __perf_event_output(event, data, regs, perf_output_begin_backward);
7771 perf_event_output(struct perf_event *event,
7772 struct perf_sample_data *data,
7773 struct pt_regs *regs)
7775 return __perf_event_output(event, data, regs, perf_output_begin);
7782 struct perf_read_event {
7783 struct perf_event_header header;
7790 perf_event_read_event(struct perf_event *event,
7791 struct task_struct *task)
7793 struct perf_output_handle handle;
7794 struct perf_sample_data sample;
7795 struct perf_read_event read_event = {
7797 .type = PERF_RECORD_READ,
7799 .size = sizeof(read_event) + event->read_size,
7801 .pid = perf_event_pid(event, task),
7802 .tid = perf_event_tid(event, task),
7806 perf_event_header__init_id(&read_event.header, &sample, event);
7807 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7811 perf_output_put(&handle, read_event);
7812 perf_output_read(&handle, event);
7813 perf_event__output_id_sample(event, &handle, &sample);
7815 perf_output_end(&handle);
7818 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7821 perf_iterate_ctx(struct perf_event_context *ctx,
7822 perf_iterate_f output,
7823 void *data, bool all)
7825 struct perf_event *event;
7827 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7829 if (event->state < PERF_EVENT_STATE_INACTIVE)
7831 if (!event_filter_match(event))
7835 output(event, data);
7839 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7841 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7842 struct perf_event *event;
7844 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7846 * Skip events that are not fully formed yet; ensure that
7847 * if we observe event->ctx, both event and ctx will be
7848 * complete enough. See perf_install_in_context().
7850 if (!smp_load_acquire(&event->ctx))
7853 if (event->state < PERF_EVENT_STATE_INACTIVE)
7855 if (!event_filter_match(event))
7857 output(event, data);
7862 * Iterate all events that need to receive side-band events.
7864 * For new callers; ensure that account_pmu_sb_event() includes
7865 * your event, otherwise it might not get delivered.
7868 perf_iterate_sb(perf_iterate_f output, void *data,
7869 struct perf_event_context *task_ctx)
7871 struct perf_event_context *ctx;
7877 * If we have task_ctx != NULL we only notify the task context itself.
7878 * The task_ctx is set only for EXIT events before releasing task
7882 perf_iterate_ctx(task_ctx, output, data, false);
7886 perf_iterate_sb_cpu(output, data);
7888 ctx = rcu_dereference(current->perf_event_ctxp);
7890 perf_iterate_ctx(ctx, output, data, false);
7897 * Clear all file-based filters at exec, they'll have to be
7898 * re-instated when/if these objects are mmapped again.
7900 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7902 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7903 struct perf_addr_filter *filter;
7904 unsigned int restart = 0, count = 0;
7905 unsigned long flags;
7907 if (!has_addr_filter(event))
7910 raw_spin_lock_irqsave(&ifh->lock, flags);
7911 list_for_each_entry(filter, &ifh->list, entry) {
7912 if (filter->path.dentry) {
7913 event->addr_filter_ranges[count].start = 0;
7914 event->addr_filter_ranges[count].size = 0;
7922 event->addr_filters_gen++;
7923 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7926 perf_event_stop(event, 1);
7929 void perf_event_exec(void)
7931 struct perf_event_context *ctx;
7933 ctx = perf_pin_task_context(current);
7937 perf_event_enable_on_exec(ctx);
7938 perf_event_remove_on_exec(ctx);
7939 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
7941 perf_unpin_context(ctx);
7945 struct remote_output {
7946 struct perf_buffer *rb;
7950 static void __perf_event_output_stop(struct perf_event *event, void *data)
7952 struct perf_event *parent = event->parent;
7953 struct remote_output *ro = data;
7954 struct perf_buffer *rb = ro->rb;
7955 struct stop_event_data sd = {
7959 if (!has_aux(event))
7966 * In case of inheritance, it will be the parent that links to the
7967 * ring-buffer, but it will be the child that's actually using it.
7969 * We are using event::rb to determine if the event should be stopped,
7970 * however this may race with ring_buffer_attach() (through set_output),
7971 * which will make us skip the event that actually needs to be stopped.
7972 * So ring_buffer_attach() has to stop an aux event before re-assigning
7975 if (rcu_dereference(parent->rb) == rb)
7976 ro->err = __perf_event_stop(&sd);
7979 static int __perf_pmu_output_stop(void *info)
7981 struct perf_event *event = info;
7982 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
7983 struct remote_output ro = {
7988 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7989 if (cpuctx->task_ctx)
7990 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7997 static void perf_pmu_output_stop(struct perf_event *event)
7999 struct perf_event *iter;
8004 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8006 * For per-CPU events, we need to make sure that neither they
8007 * nor their children are running; for cpu==-1 events it's
8008 * sufficient to stop the event itself if it's active, since
8009 * it can't have children.
8013 cpu = READ_ONCE(iter->oncpu);
8018 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8019 if (err == -EAGAIN) {
8028 * task tracking -- fork/exit
8030 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8033 struct perf_task_event {
8034 struct task_struct *task;
8035 struct perf_event_context *task_ctx;
8038 struct perf_event_header header;
8048 static int perf_event_task_match(struct perf_event *event)
8050 return event->attr.comm || event->attr.mmap ||
8051 event->attr.mmap2 || event->attr.mmap_data ||
8055 static void perf_event_task_output(struct perf_event *event,
8058 struct perf_task_event *task_event = data;
8059 struct perf_output_handle handle;
8060 struct perf_sample_data sample;
8061 struct task_struct *task = task_event->task;
8062 int ret, size = task_event->event_id.header.size;
8064 if (!perf_event_task_match(event))
8067 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8069 ret = perf_output_begin(&handle, &sample, event,
8070 task_event->event_id.header.size);
8074 task_event->event_id.pid = perf_event_pid(event, task);
8075 task_event->event_id.tid = perf_event_tid(event, task);
8077 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8078 task_event->event_id.ppid = perf_event_pid(event,
8080 task_event->event_id.ptid = perf_event_pid(event,
8082 } else { /* PERF_RECORD_FORK */
8083 task_event->event_id.ppid = perf_event_pid(event, current);
8084 task_event->event_id.ptid = perf_event_tid(event, current);
8087 task_event->event_id.time = perf_event_clock(event);
8089 perf_output_put(&handle, task_event->event_id);
8091 perf_event__output_id_sample(event, &handle, &sample);
8093 perf_output_end(&handle);
8095 task_event->event_id.header.size = size;
8098 static void perf_event_task(struct task_struct *task,
8099 struct perf_event_context *task_ctx,
8102 struct perf_task_event task_event;
8104 if (!atomic_read(&nr_comm_events) &&
8105 !atomic_read(&nr_mmap_events) &&
8106 !atomic_read(&nr_task_events))
8109 task_event = (struct perf_task_event){
8111 .task_ctx = task_ctx,
8114 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8116 .size = sizeof(task_event.event_id),
8126 perf_iterate_sb(perf_event_task_output,
8131 void perf_event_fork(struct task_struct *task)
8133 perf_event_task(task, NULL, 1);
8134 perf_event_namespaces(task);
8141 struct perf_comm_event {
8142 struct task_struct *task;
8147 struct perf_event_header header;
8154 static int perf_event_comm_match(struct perf_event *event)
8156 return event->attr.comm;
8159 static void perf_event_comm_output(struct perf_event *event,
8162 struct perf_comm_event *comm_event = data;
8163 struct perf_output_handle handle;
8164 struct perf_sample_data sample;
8165 int size = comm_event->event_id.header.size;
8168 if (!perf_event_comm_match(event))
8171 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8172 ret = perf_output_begin(&handle, &sample, event,
8173 comm_event->event_id.header.size);
8178 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8179 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8181 perf_output_put(&handle, comm_event->event_id);
8182 __output_copy(&handle, comm_event->comm,
8183 comm_event->comm_size);
8185 perf_event__output_id_sample(event, &handle, &sample);
8187 perf_output_end(&handle);
8189 comm_event->event_id.header.size = size;
8192 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8194 char comm[TASK_COMM_LEN];
8197 memset(comm, 0, sizeof(comm));
8198 strlcpy(comm, comm_event->task->comm, sizeof(comm));
8199 size = ALIGN(strlen(comm)+1, sizeof(u64));
8201 comm_event->comm = comm;
8202 comm_event->comm_size = size;
8204 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8206 perf_iterate_sb(perf_event_comm_output,
8211 void perf_event_comm(struct task_struct *task, bool exec)
8213 struct perf_comm_event comm_event;
8215 if (!atomic_read(&nr_comm_events))
8218 comm_event = (struct perf_comm_event){
8224 .type = PERF_RECORD_COMM,
8225 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8233 perf_event_comm_event(&comm_event);
8237 * namespaces tracking
8240 struct perf_namespaces_event {
8241 struct task_struct *task;
8244 struct perf_event_header header;
8249 struct perf_ns_link_info link_info[NR_NAMESPACES];
8253 static int perf_event_namespaces_match(struct perf_event *event)
8255 return event->attr.namespaces;
8258 static void perf_event_namespaces_output(struct perf_event *event,
8261 struct perf_namespaces_event *namespaces_event = data;
8262 struct perf_output_handle handle;
8263 struct perf_sample_data sample;
8264 u16 header_size = namespaces_event->event_id.header.size;
8267 if (!perf_event_namespaces_match(event))
8270 perf_event_header__init_id(&namespaces_event->event_id.header,
8272 ret = perf_output_begin(&handle, &sample, event,
8273 namespaces_event->event_id.header.size);
8277 namespaces_event->event_id.pid = perf_event_pid(event,
8278 namespaces_event->task);
8279 namespaces_event->event_id.tid = perf_event_tid(event,
8280 namespaces_event->task);
8282 perf_output_put(&handle, namespaces_event->event_id);
8284 perf_event__output_id_sample(event, &handle, &sample);
8286 perf_output_end(&handle);
8288 namespaces_event->event_id.header.size = header_size;
8291 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8292 struct task_struct *task,
8293 const struct proc_ns_operations *ns_ops)
8295 struct path ns_path;
8296 struct inode *ns_inode;
8299 error = ns_get_path(&ns_path, task, ns_ops);
8301 ns_inode = ns_path.dentry->d_inode;
8302 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8303 ns_link_info->ino = ns_inode->i_ino;
8308 void perf_event_namespaces(struct task_struct *task)
8310 struct perf_namespaces_event namespaces_event;
8311 struct perf_ns_link_info *ns_link_info;
8313 if (!atomic_read(&nr_namespaces_events))
8316 namespaces_event = (struct perf_namespaces_event){
8320 .type = PERF_RECORD_NAMESPACES,
8322 .size = sizeof(namespaces_event.event_id),
8326 .nr_namespaces = NR_NAMESPACES,
8327 /* .link_info[NR_NAMESPACES] */
8331 ns_link_info = namespaces_event.event_id.link_info;
8333 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8334 task, &mntns_operations);
8336 #ifdef CONFIG_USER_NS
8337 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8338 task, &userns_operations);
8340 #ifdef CONFIG_NET_NS
8341 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8342 task, &netns_operations);
8344 #ifdef CONFIG_UTS_NS
8345 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8346 task, &utsns_operations);
8348 #ifdef CONFIG_IPC_NS
8349 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8350 task, &ipcns_operations);
8352 #ifdef CONFIG_PID_NS
8353 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8354 task, &pidns_operations);
8356 #ifdef CONFIG_CGROUPS
8357 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8358 task, &cgroupns_operations);
8361 perf_iterate_sb(perf_event_namespaces_output,
8369 #ifdef CONFIG_CGROUP_PERF
8371 struct perf_cgroup_event {
8375 struct perf_event_header header;
8381 static int perf_event_cgroup_match(struct perf_event *event)
8383 return event->attr.cgroup;
8386 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8388 struct perf_cgroup_event *cgroup_event = data;
8389 struct perf_output_handle handle;
8390 struct perf_sample_data sample;
8391 u16 header_size = cgroup_event->event_id.header.size;
8394 if (!perf_event_cgroup_match(event))
8397 perf_event_header__init_id(&cgroup_event->event_id.header,
8399 ret = perf_output_begin(&handle, &sample, event,
8400 cgroup_event->event_id.header.size);
8404 perf_output_put(&handle, cgroup_event->event_id);
8405 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8407 perf_event__output_id_sample(event, &handle, &sample);
8409 perf_output_end(&handle);
8411 cgroup_event->event_id.header.size = header_size;
8414 static void perf_event_cgroup(struct cgroup *cgrp)
8416 struct perf_cgroup_event cgroup_event;
8417 char path_enomem[16] = "//enomem";
8421 if (!atomic_read(&nr_cgroup_events))
8424 cgroup_event = (struct perf_cgroup_event){
8427 .type = PERF_RECORD_CGROUP,
8429 .size = sizeof(cgroup_event.event_id),
8431 .id = cgroup_id(cgrp),
8435 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8436 if (pathname == NULL) {
8437 cgroup_event.path = path_enomem;
8439 /* just to be sure to have enough space for alignment */
8440 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8441 cgroup_event.path = pathname;
8445 * Since our buffer works in 8 byte units we need to align our string
8446 * size to a multiple of 8. However, we must guarantee the tail end is
8447 * zero'd out to avoid leaking random bits to userspace.
8449 size = strlen(cgroup_event.path) + 1;
8450 while (!IS_ALIGNED(size, sizeof(u64)))
8451 cgroup_event.path[size++] = '\0';
8453 cgroup_event.event_id.header.size += size;
8454 cgroup_event.path_size = size;
8456 perf_iterate_sb(perf_event_cgroup_output,
8469 struct perf_mmap_event {
8470 struct vm_area_struct *vma;
8472 const char *file_name;
8478 u8 build_id[BUILD_ID_SIZE_MAX];
8482 struct perf_event_header header;
8492 static int perf_event_mmap_match(struct perf_event *event,
8495 struct perf_mmap_event *mmap_event = data;
8496 struct vm_area_struct *vma = mmap_event->vma;
8497 int executable = vma->vm_flags & VM_EXEC;
8499 return (!executable && event->attr.mmap_data) ||
8500 (executable && (event->attr.mmap || event->attr.mmap2));
8503 static void perf_event_mmap_output(struct perf_event *event,
8506 struct perf_mmap_event *mmap_event = data;
8507 struct perf_output_handle handle;
8508 struct perf_sample_data sample;
8509 int size = mmap_event->event_id.header.size;
8510 u32 type = mmap_event->event_id.header.type;
8514 if (!perf_event_mmap_match(event, data))
8517 if (event->attr.mmap2) {
8518 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8519 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8520 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8521 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8522 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8523 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8524 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8527 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8528 ret = perf_output_begin(&handle, &sample, event,
8529 mmap_event->event_id.header.size);
8533 mmap_event->event_id.pid = perf_event_pid(event, current);
8534 mmap_event->event_id.tid = perf_event_tid(event, current);
8536 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8538 if (event->attr.mmap2 && use_build_id)
8539 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8541 perf_output_put(&handle, mmap_event->event_id);
8543 if (event->attr.mmap2) {
8545 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8547 __output_copy(&handle, size, 4);
8548 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8550 perf_output_put(&handle, mmap_event->maj);
8551 perf_output_put(&handle, mmap_event->min);
8552 perf_output_put(&handle, mmap_event->ino);
8553 perf_output_put(&handle, mmap_event->ino_generation);
8555 perf_output_put(&handle, mmap_event->prot);
8556 perf_output_put(&handle, mmap_event->flags);
8559 __output_copy(&handle, mmap_event->file_name,
8560 mmap_event->file_size);
8562 perf_event__output_id_sample(event, &handle, &sample);
8564 perf_output_end(&handle);
8566 mmap_event->event_id.header.size = size;
8567 mmap_event->event_id.header.type = type;
8570 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8572 struct vm_area_struct *vma = mmap_event->vma;
8573 struct file *file = vma->vm_file;
8574 int maj = 0, min = 0;
8575 u64 ino = 0, gen = 0;
8576 u32 prot = 0, flags = 0;
8582 if (vma->vm_flags & VM_READ)
8584 if (vma->vm_flags & VM_WRITE)
8586 if (vma->vm_flags & VM_EXEC)
8589 if (vma->vm_flags & VM_MAYSHARE)
8592 flags = MAP_PRIVATE;
8594 if (vma->vm_flags & VM_LOCKED)
8595 flags |= MAP_LOCKED;
8596 if (is_vm_hugetlb_page(vma))
8597 flags |= MAP_HUGETLB;
8600 struct inode *inode;
8603 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8609 * d_path() works from the end of the rb backwards, so we
8610 * need to add enough zero bytes after the string to handle
8611 * the 64bit alignment we do later.
8613 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8618 inode = file_inode(vma->vm_file);
8619 dev = inode->i_sb->s_dev;
8621 gen = inode->i_generation;
8627 if (vma->vm_ops && vma->vm_ops->name) {
8628 name = (char *) vma->vm_ops->name(vma);
8633 name = (char *)arch_vma_name(vma);
8637 if (vma->vm_start <= vma->vm_mm->start_brk &&
8638 vma->vm_end >= vma->vm_mm->brk) {
8642 if (vma->vm_start <= vma->vm_mm->start_stack &&
8643 vma->vm_end >= vma->vm_mm->start_stack) {
8653 strlcpy(tmp, name, sizeof(tmp));
8657 * Since our buffer works in 8 byte units we need to align our string
8658 * size to a multiple of 8. However, we must guarantee the tail end is
8659 * zero'd out to avoid leaking random bits to userspace.
8661 size = strlen(name)+1;
8662 while (!IS_ALIGNED(size, sizeof(u64)))
8663 name[size++] = '\0';
8665 mmap_event->file_name = name;
8666 mmap_event->file_size = size;
8667 mmap_event->maj = maj;
8668 mmap_event->min = min;
8669 mmap_event->ino = ino;
8670 mmap_event->ino_generation = gen;
8671 mmap_event->prot = prot;
8672 mmap_event->flags = flags;
8674 if (!(vma->vm_flags & VM_EXEC))
8675 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8677 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8679 if (atomic_read(&nr_build_id_events))
8680 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8682 perf_iterate_sb(perf_event_mmap_output,
8690 * Check whether inode and address range match filter criteria.
8692 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8693 struct file *file, unsigned long offset,
8696 /* d_inode(NULL) won't be equal to any mapped user-space file */
8697 if (!filter->path.dentry)
8700 if (d_inode(filter->path.dentry) != file_inode(file))
8703 if (filter->offset > offset + size)
8706 if (filter->offset + filter->size < offset)
8712 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8713 struct vm_area_struct *vma,
8714 struct perf_addr_filter_range *fr)
8716 unsigned long vma_size = vma->vm_end - vma->vm_start;
8717 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8718 struct file *file = vma->vm_file;
8720 if (!perf_addr_filter_match(filter, file, off, vma_size))
8723 if (filter->offset < off) {
8724 fr->start = vma->vm_start;
8725 fr->size = min(vma_size, filter->size - (off - filter->offset));
8727 fr->start = vma->vm_start + filter->offset - off;
8728 fr->size = min(vma->vm_end - fr->start, filter->size);
8734 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8736 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8737 struct vm_area_struct *vma = data;
8738 struct perf_addr_filter *filter;
8739 unsigned int restart = 0, count = 0;
8740 unsigned long flags;
8742 if (!has_addr_filter(event))
8748 raw_spin_lock_irqsave(&ifh->lock, flags);
8749 list_for_each_entry(filter, &ifh->list, entry) {
8750 if (perf_addr_filter_vma_adjust(filter, vma,
8751 &event->addr_filter_ranges[count]))
8758 event->addr_filters_gen++;
8759 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8762 perf_event_stop(event, 1);
8766 * Adjust all task's events' filters to the new vma
8768 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8770 struct perf_event_context *ctx;
8773 * Data tracing isn't supported yet and as such there is no need
8774 * to keep track of anything that isn't related to executable code:
8776 if (!(vma->vm_flags & VM_EXEC))
8780 ctx = rcu_dereference(current->perf_event_ctxp);
8782 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8786 void perf_event_mmap(struct vm_area_struct *vma)
8788 struct perf_mmap_event mmap_event;
8790 if (!atomic_read(&nr_mmap_events))
8793 mmap_event = (struct perf_mmap_event){
8799 .type = PERF_RECORD_MMAP,
8800 .misc = PERF_RECORD_MISC_USER,
8805 .start = vma->vm_start,
8806 .len = vma->vm_end - vma->vm_start,
8807 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8809 /* .maj (attr_mmap2 only) */
8810 /* .min (attr_mmap2 only) */
8811 /* .ino (attr_mmap2 only) */
8812 /* .ino_generation (attr_mmap2 only) */
8813 /* .prot (attr_mmap2 only) */
8814 /* .flags (attr_mmap2 only) */
8817 perf_addr_filters_adjust(vma);
8818 perf_event_mmap_event(&mmap_event);
8821 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8822 unsigned long size, u64 flags)
8824 struct perf_output_handle handle;
8825 struct perf_sample_data sample;
8826 struct perf_aux_event {
8827 struct perf_event_header header;
8833 .type = PERF_RECORD_AUX,
8835 .size = sizeof(rec),
8843 perf_event_header__init_id(&rec.header, &sample, event);
8844 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8849 perf_output_put(&handle, rec);
8850 perf_event__output_id_sample(event, &handle, &sample);
8852 perf_output_end(&handle);
8856 * Lost/dropped samples logging
8858 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8860 struct perf_output_handle handle;
8861 struct perf_sample_data sample;
8865 struct perf_event_header header;
8867 } lost_samples_event = {
8869 .type = PERF_RECORD_LOST_SAMPLES,
8871 .size = sizeof(lost_samples_event),
8876 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8878 ret = perf_output_begin(&handle, &sample, event,
8879 lost_samples_event.header.size);
8883 perf_output_put(&handle, lost_samples_event);
8884 perf_event__output_id_sample(event, &handle, &sample);
8885 perf_output_end(&handle);
8889 * context_switch tracking
8892 struct perf_switch_event {
8893 struct task_struct *task;
8894 struct task_struct *next_prev;
8897 struct perf_event_header header;
8903 static int perf_event_switch_match(struct perf_event *event)
8905 return event->attr.context_switch;
8908 static void perf_event_switch_output(struct perf_event *event, void *data)
8910 struct perf_switch_event *se = data;
8911 struct perf_output_handle handle;
8912 struct perf_sample_data sample;
8915 if (!perf_event_switch_match(event))
8918 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8919 if (event->ctx->task) {
8920 se->event_id.header.type = PERF_RECORD_SWITCH;
8921 se->event_id.header.size = sizeof(se->event_id.header);
8923 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8924 se->event_id.header.size = sizeof(se->event_id);
8925 se->event_id.next_prev_pid =
8926 perf_event_pid(event, se->next_prev);
8927 se->event_id.next_prev_tid =
8928 perf_event_tid(event, se->next_prev);
8931 perf_event_header__init_id(&se->event_id.header, &sample, event);
8933 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8937 if (event->ctx->task)
8938 perf_output_put(&handle, se->event_id.header);
8940 perf_output_put(&handle, se->event_id);
8942 perf_event__output_id_sample(event, &handle, &sample);
8944 perf_output_end(&handle);
8947 static void perf_event_switch(struct task_struct *task,
8948 struct task_struct *next_prev, bool sched_in)
8950 struct perf_switch_event switch_event;
8952 /* N.B. caller checks nr_switch_events != 0 */
8954 switch_event = (struct perf_switch_event){
8956 .next_prev = next_prev,
8960 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8963 /* .next_prev_pid */
8964 /* .next_prev_tid */
8968 if (!sched_in && task->on_rq) {
8969 switch_event.event_id.header.misc |=
8970 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8973 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
8977 * IRQ throttle logging
8980 static void perf_log_throttle(struct perf_event *event, int enable)
8982 struct perf_output_handle handle;
8983 struct perf_sample_data sample;
8987 struct perf_event_header header;
8991 } throttle_event = {
8993 .type = PERF_RECORD_THROTTLE,
8995 .size = sizeof(throttle_event),
8997 .time = perf_event_clock(event),
8998 .id = primary_event_id(event),
8999 .stream_id = event->id,
9003 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9005 perf_event_header__init_id(&throttle_event.header, &sample, event);
9007 ret = perf_output_begin(&handle, &sample, event,
9008 throttle_event.header.size);
9012 perf_output_put(&handle, throttle_event);
9013 perf_event__output_id_sample(event, &handle, &sample);
9014 perf_output_end(&handle);
9018 * ksymbol register/unregister tracking
9021 struct perf_ksymbol_event {
9025 struct perf_event_header header;
9033 static int perf_event_ksymbol_match(struct perf_event *event)
9035 return event->attr.ksymbol;
9038 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9040 struct perf_ksymbol_event *ksymbol_event = data;
9041 struct perf_output_handle handle;
9042 struct perf_sample_data sample;
9045 if (!perf_event_ksymbol_match(event))
9048 perf_event_header__init_id(&ksymbol_event->event_id.header,
9050 ret = perf_output_begin(&handle, &sample, event,
9051 ksymbol_event->event_id.header.size);
9055 perf_output_put(&handle, ksymbol_event->event_id);
9056 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9057 perf_event__output_id_sample(event, &handle, &sample);
9059 perf_output_end(&handle);
9062 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9065 struct perf_ksymbol_event ksymbol_event;
9066 char name[KSYM_NAME_LEN];
9070 if (!atomic_read(&nr_ksymbol_events))
9073 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9074 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9077 strlcpy(name, sym, KSYM_NAME_LEN);
9078 name_len = strlen(name) + 1;
9079 while (!IS_ALIGNED(name_len, sizeof(u64)))
9080 name[name_len++] = '\0';
9081 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9084 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9086 ksymbol_event = (struct perf_ksymbol_event){
9088 .name_len = name_len,
9091 .type = PERF_RECORD_KSYMBOL,
9092 .size = sizeof(ksymbol_event.event_id) +
9097 .ksym_type = ksym_type,
9102 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9105 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9109 * bpf program load/unload tracking
9112 struct perf_bpf_event {
9113 struct bpf_prog *prog;
9115 struct perf_event_header header;
9119 u8 tag[BPF_TAG_SIZE];
9123 static int perf_event_bpf_match(struct perf_event *event)
9125 return event->attr.bpf_event;
9128 static void perf_event_bpf_output(struct perf_event *event, void *data)
9130 struct perf_bpf_event *bpf_event = data;
9131 struct perf_output_handle handle;
9132 struct perf_sample_data sample;
9135 if (!perf_event_bpf_match(event))
9138 perf_event_header__init_id(&bpf_event->event_id.header,
9140 ret = perf_output_begin(&handle, data, event,
9141 bpf_event->event_id.header.size);
9145 perf_output_put(&handle, bpf_event->event_id);
9146 perf_event__output_id_sample(event, &handle, &sample);
9148 perf_output_end(&handle);
9151 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9152 enum perf_bpf_event_type type)
9154 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9157 if (prog->aux->func_cnt == 0) {
9158 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9159 (u64)(unsigned long)prog->bpf_func,
9160 prog->jited_len, unregister,
9161 prog->aux->ksym.name);
9163 for (i = 0; i < prog->aux->func_cnt; i++) {
9164 struct bpf_prog *subprog = prog->aux->func[i];
9167 PERF_RECORD_KSYMBOL_TYPE_BPF,
9168 (u64)(unsigned long)subprog->bpf_func,
9169 subprog->jited_len, unregister,
9170 subprog->aux->ksym.name);
9175 void perf_event_bpf_event(struct bpf_prog *prog,
9176 enum perf_bpf_event_type type,
9179 struct perf_bpf_event bpf_event;
9181 if (type <= PERF_BPF_EVENT_UNKNOWN ||
9182 type >= PERF_BPF_EVENT_MAX)
9186 case PERF_BPF_EVENT_PROG_LOAD:
9187 case PERF_BPF_EVENT_PROG_UNLOAD:
9188 if (atomic_read(&nr_ksymbol_events))
9189 perf_event_bpf_emit_ksymbols(prog, type);
9195 if (!atomic_read(&nr_bpf_events))
9198 bpf_event = (struct perf_bpf_event){
9202 .type = PERF_RECORD_BPF_EVENT,
9203 .size = sizeof(bpf_event.event_id),
9207 .id = prog->aux->id,
9211 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9213 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9214 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9217 struct perf_text_poke_event {
9218 const void *old_bytes;
9219 const void *new_bytes;
9225 struct perf_event_header header;
9231 static int perf_event_text_poke_match(struct perf_event *event)
9233 return event->attr.text_poke;
9236 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9238 struct perf_text_poke_event *text_poke_event = data;
9239 struct perf_output_handle handle;
9240 struct perf_sample_data sample;
9244 if (!perf_event_text_poke_match(event))
9247 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9249 ret = perf_output_begin(&handle, &sample, event,
9250 text_poke_event->event_id.header.size);
9254 perf_output_put(&handle, text_poke_event->event_id);
9255 perf_output_put(&handle, text_poke_event->old_len);
9256 perf_output_put(&handle, text_poke_event->new_len);
9258 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9259 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9261 if (text_poke_event->pad)
9262 __output_copy(&handle, &padding, text_poke_event->pad);
9264 perf_event__output_id_sample(event, &handle, &sample);
9266 perf_output_end(&handle);
9269 void perf_event_text_poke(const void *addr, const void *old_bytes,
9270 size_t old_len, const void *new_bytes, size_t new_len)
9272 struct perf_text_poke_event text_poke_event;
9275 if (!atomic_read(&nr_text_poke_events))
9278 tot = sizeof(text_poke_event.old_len) + old_len;
9279 tot += sizeof(text_poke_event.new_len) + new_len;
9280 pad = ALIGN(tot, sizeof(u64)) - tot;
9282 text_poke_event = (struct perf_text_poke_event){
9283 .old_bytes = old_bytes,
9284 .new_bytes = new_bytes,
9290 .type = PERF_RECORD_TEXT_POKE,
9291 .misc = PERF_RECORD_MISC_KERNEL,
9292 .size = sizeof(text_poke_event.event_id) + tot + pad,
9294 .addr = (unsigned long)addr,
9298 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9301 void perf_event_itrace_started(struct perf_event *event)
9303 event->attach_state |= PERF_ATTACH_ITRACE;
9306 static void perf_log_itrace_start(struct perf_event *event)
9308 struct perf_output_handle handle;
9309 struct perf_sample_data sample;
9310 struct perf_aux_event {
9311 struct perf_event_header header;
9318 event = event->parent;
9320 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9321 event->attach_state & PERF_ATTACH_ITRACE)
9324 rec.header.type = PERF_RECORD_ITRACE_START;
9325 rec.header.misc = 0;
9326 rec.header.size = sizeof(rec);
9327 rec.pid = perf_event_pid(event, current);
9328 rec.tid = perf_event_tid(event, current);
9330 perf_event_header__init_id(&rec.header, &sample, event);
9331 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9336 perf_output_put(&handle, rec);
9337 perf_event__output_id_sample(event, &handle, &sample);
9339 perf_output_end(&handle);
9342 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9344 struct perf_output_handle handle;
9345 struct perf_sample_data sample;
9346 struct perf_aux_event {
9347 struct perf_event_header header;
9353 event = event->parent;
9355 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9356 rec.header.misc = 0;
9357 rec.header.size = sizeof(rec);
9360 perf_event_header__init_id(&rec.header, &sample, event);
9361 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9366 perf_output_put(&handle, rec);
9367 perf_event__output_id_sample(event, &handle, &sample);
9369 perf_output_end(&handle);
9373 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9375 struct hw_perf_event *hwc = &event->hw;
9379 seq = __this_cpu_read(perf_throttled_seq);
9380 if (seq != hwc->interrupts_seq) {
9381 hwc->interrupts_seq = seq;
9382 hwc->interrupts = 1;
9385 if (unlikely(throttle
9386 && hwc->interrupts >= max_samples_per_tick)) {
9387 __this_cpu_inc(perf_throttled_count);
9388 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9389 hwc->interrupts = MAX_INTERRUPTS;
9390 perf_log_throttle(event, 0);
9395 if (event->attr.freq) {
9396 u64 now = perf_clock();
9397 s64 delta = now - hwc->freq_time_stamp;
9399 hwc->freq_time_stamp = now;
9401 if (delta > 0 && delta < 2*TICK_NSEC)
9402 perf_adjust_period(event, delta, hwc->last_period, true);
9408 int perf_event_account_interrupt(struct perf_event *event)
9410 return __perf_event_account_interrupt(event, 1);
9413 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
9416 * Due to interrupt latency (AKA "skid"), we may enter the
9417 * kernel before taking an overflow, even if the PMU is only
9418 * counting user events.
9420 if (event->attr.exclude_kernel && !user_mode(regs))
9427 * Generic event overflow handling, sampling.
9430 static int __perf_event_overflow(struct perf_event *event,
9431 int throttle, struct perf_sample_data *data,
9432 struct pt_regs *regs)
9434 int events = atomic_read(&event->event_limit);
9438 * Non-sampling counters might still use the PMI to fold short
9439 * hardware counters, ignore those.
9441 if (unlikely(!is_sampling_event(event)))
9444 ret = __perf_event_account_interrupt(event, throttle);
9447 * XXX event_limit might not quite work as expected on inherited
9451 event->pending_kill = POLL_IN;
9452 if (events && atomic_dec_and_test(&event->event_limit)) {
9454 event->pending_kill = POLL_HUP;
9455 perf_event_disable_inatomic(event);
9458 if (event->attr.sigtrap) {
9460 * The desired behaviour of sigtrap vs invalid samples is a bit
9461 * tricky; on the one hand, one should not loose the SIGTRAP if
9462 * it is the first event, on the other hand, we should also not
9463 * trigger the WARN or override the data address.
9465 bool valid_sample = sample_is_allowed(event, regs);
9466 unsigned int pending_id = 1;
9469 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
9470 if (!event->pending_sigtrap) {
9471 event->pending_sigtrap = pending_id;
9472 local_inc(&event->ctx->nr_pending);
9473 } else if (event->attr.exclude_kernel && valid_sample) {
9475 * Should not be able to return to user space without
9476 * consuming pending_sigtrap; with exceptions:
9478 * 1. Where !exclude_kernel, events can overflow again
9479 * in the kernel without returning to user space.
9481 * 2. Events that can overflow again before the IRQ-
9482 * work without user space progress (e.g. hrtimer).
9483 * To approximate progress (with false negatives),
9484 * check 32-bit hash of the current IP.
9486 WARN_ON_ONCE(event->pending_sigtrap != pending_id);
9489 event->pending_addr = 0;
9490 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
9491 event->pending_addr = data->addr;
9492 irq_work_queue(&event->pending_irq);
9495 READ_ONCE(event->overflow_handler)(event, data, regs);
9497 if (*perf_event_fasync(event) && event->pending_kill) {
9498 event->pending_wakeup = 1;
9499 irq_work_queue(&event->pending_irq);
9505 int perf_event_overflow(struct perf_event *event,
9506 struct perf_sample_data *data,
9507 struct pt_regs *regs)
9509 return __perf_event_overflow(event, 1, data, regs);
9513 * Generic software event infrastructure
9516 struct swevent_htable {
9517 struct swevent_hlist *swevent_hlist;
9518 struct mutex hlist_mutex;
9521 /* Recursion avoidance in each contexts */
9522 int recursion[PERF_NR_CONTEXTS];
9525 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9528 * We directly increment event->count and keep a second value in
9529 * event->hw.period_left to count intervals. This period event
9530 * is kept in the range [-sample_period, 0] so that we can use the
9534 u64 perf_swevent_set_period(struct perf_event *event)
9536 struct hw_perf_event *hwc = &event->hw;
9537 u64 period = hwc->last_period;
9541 hwc->last_period = hwc->sample_period;
9544 old = val = local64_read(&hwc->period_left);
9548 nr = div64_u64(period + val, period);
9549 offset = nr * period;
9551 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9557 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9558 struct perf_sample_data *data,
9559 struct pt_regs *regs)
9561 struct hw_perf_event *hwc = &event->hw;
9565 overflow = perf_swevent_set_period(event);
9567 if (hwc->interrupts == MAX_INTERRUPTS)
9570 for (; overflow; overflow--) {
9571 if (__perf_event_overflow(event, throttle,
9574 * We inhibit the overflow from happening when
9575 * hwc->interrupts == MAX_INTERRUPTS.
9583 static void perf_swevent_event(struct perf_event *event, u64 nr,
9584 struct perf_sample_data *data,
9585 struct pt_regs *regs)
9587 struct hw_perf_event *hwc = &event->hw;
9589 local64_add(nr, &event->count);
9594 if (!is_sampling_event(event))
9597 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9599 return perf_swevent_overflow(event, 1, data, regs);
9601 data->period = event->hw.last_period;
9603 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9604 return perf_swevent_overflow(event, 1, data, regs);
9606 if (local64_add_negative(nr, &hwc->period_left))
9609 perf_swevent_overflow(event, 0, data, regs);
9612 static int perf_exclude_event(struct perf_event *event,
9613 struct pt_regs *regs)
9615 if (event->hw.state & PERF_HES_STOPPED)
9619 if (event->attr.exclude_user && user_mode(regs))
9622 if (event->attr.exclude_kernel && !user_mode(regs))
9629 static int perf_swevent_match(struct perf_event *event,
9630 enum perf_type_id type,
9632 struct perf_sample_data *data,
9633 struct pt_regs *regs)
9635 if (event->attr.type != type)
9638 if (event->attr.config != event_id)
9641 if (perf_exclude_event(event, regs))
9647 static inline u64 swevent_hash(u64 type, u32 event_id)
9649 u64 val = event_id | (type << 32);
9651 return hash_64(val, SWEVENT_HLIST_BITS);
9654 static inline struct hlist_head *
9655 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9657 u64 hash = swevent_hash(type, event_id);
9659 return &hlist->heads[hash];
9662 /* For the read side: events when they trigger */
9663 static inline struct hlist_head *
9664 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9666 struct swevent_hlist *hlist;
9668 hlist = rcu_dereference(swhash->swevent_hlist);
9672 return __find_swevent_head(hlist, type, event_id);
9675 /* For the event head insertion and removal in the hlist */
9676 static inline struct hlist_head *
9677 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9679 struct swevent_hlist *hlist;
9680 u32 event_id = event->attr.config;
9681 u64 type = event->attr.type;
9684 * Event scheduling is always serialized against hlist allocation
9685 * and release. Which makes the protected version suitable here.
9686 * The context lock guarantees that.
9688 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9689 lockdep_is_held(&event->ctx->lock));
9693 return __find_swevent_head(hlist, type, event_id);
9696 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9698 struct perf_sample_data *data,
9699 struct pt_regs *regs)
9701 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9702 struct perf_event *event;
9703 struct hlist_head *head;
9706 head = find_swevent_head_rcu(swhash, type, event_id);
9710 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9711 if (perf_swevent_match(event, type, event_id, data, regs))
9712 perf_swevent_event(event, nr, data, regs);
9718 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9720 int perf_swevent_get_recursion_context(void)
9722 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9724 return get_recursion_context(swhash->recursion);
9726 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9728 void perf_swevent_put_recursion_context(int rctx)
9730 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9732 put_recursion_context(swhash->recursion, rctx);
9735 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9737 struct perf_sample_data data;
9739 if (WARN_ON_ONCE(!regs))
9742 perf_sample_data_init(&data, addr, 0);
9743 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9746 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9750 preempt_disable_notrace();
9751 rctx = perf_swevent_get_recursion_context();
9752 if (unlikely(rctx < 0))
9755 ___perf_sw_event(event_id, nr, regs, addr);
9757 perf_swevent_put_recursion_context(rctx);
9759 preempt_enable_notrace();
9762 static void perf_swevent_read(struct perf_event *event)
9766 static int perf_swevent_add(struct perf_event *event, int flags)
9768 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9769 struct hw_perf_event *hwc = &event->hw;
9770 struct hlist_head *head;
9772 if (is_sampling_event(event)) {
9773 hwc->last_period = hwc->sample_period;
9774 perf_swevent_set_period(event);
9777 hwc->state = !(flags & PERF_EF_START);
9779 head = find_swevent_head(swhash, event);
9780 if (WARN_ON_ONCE(!head))
9783 hlist_add_head_rcu(&event->hlist_entry, head);
9784 perf_event_update_userpage(event);
9789 static void perf_swevent_del(struct perf_event *event, int flags)
9791 hlist_del_rcu(&event->hlist_entry);
9794 static void perf_swevent_start(struct perf_event *event, int flags)
9796 event->hw.state = 0;
9799 static void perf_swevent_stop(struct perf_event *event, int flags)
9801 event->hw.state = PERF_HES_STOPPED;
9804 /* Deref the hlist from the update side */
9805 static inline struct swevent_hlist *
9806 swevent_hlist_deref(struct swevent_htable *swhash)
9808 return rcu_dereference_protected(swhash->swevent_hlist,
9809 lockdep_is_held(&swhash->hlist_mutex));
9812 static void swevent_hlist_release(struct swevent_htable *swhash)
9814 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9819 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9820 kfree_rcu(hlist, rcu_head);
9823 static void swevent_hlist_put_cpu(int cpu)
9825 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9827 mutex_lock(&swhash->hlist_mutex);
9829 if (!--swhash->hlist_refcount)
9830 swevent_hlist_release(swhash);
9832 mutex_unlock(&swhash->hlist_mutex);
9835 static void swevent_hlist_put(void)
9839 for_each_possible_cpu(cpu)
9840 swevent_hlist_put_cpu(cpu);
9843 static int swevent_hlist_get_cpu(int cpu)
9845 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9848 mutex_lock(&swhash->hlist_mutex);
9849 if (!swevent_hlist_deref(swhash) &&
9850 cpumask_test_cpu(cpu, perf_online_mask)) {
9851 struct swevent_hlist *hlist;
9853 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9858 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9860 swhash->hlist_refcount++;
9862 mutex_unlock(&swhash->hlist_mutex);
9867 static int swevent_hlist_get(void)
9869 int err, cpu, failed_cpu;
9871 mutex_lock(&pmus_lock);
9872 for_each_possible_cpu(cpu) {
9873 err = swevent_hlist_get_cpu(cpu);
9879 mutex_unlock(&pmus_lock);
9882 for_each_possible_cpu(cpu) {
9883 if (cpu == failed_cpu)
9885 swevent_hlist_put_cpu(cpu);
9887 mutex_unlock(&pmus_lock);
9891 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9893 static void sw_perf_event_destroy(struct perf_event *event)
9895 u64 event_id = event->attr.config;
9897 WARN_ON(event->parent);
9899 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9900 swevent_hlist_put();
9903 static int perf_swevent_init(struct perf_event *event)
9905 u64 event_id = event->attr.config;
9907 if (event->attr.type != PERF_TYPE_SOFTWARE)
9911 * no branch sampling for software events
9913 if (has_branch_stack(event))
9917 case PERF_COUNT_SW_CPU_CLOCK:
9918 case PERF_COUNT_SW_TASK_CLOCK:
9925 if (event_id >= PERF_COUNT_SW_MAX)
9928 if (!event->parent) {
9931 err = swevent_hlist_get();
9935 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9936 event->destroy = sw_perf_event_destroy;
9942 static struct pmu perf_swevent = {
9943 .task_ctx_nr = perf_sw_context,
9945 .capabilities = PERF_PMU_CAP_NO_NMI,
9947 .event_init = perf_swevent_init,
9948 .add = perf_swevent_add,
9949 .del = perf_swevent_del,
9950 .start = perf_swevent_start,
9951 .stop = perf_swevent_stop,
9952 .read = perf_swevent_read,
9955 #ifdef CONFIG_EVENT_TRACING
9957 static void tp_perf_event_destroy(struct perf_event *event)
9959 perf_trace_destroy(event);
9962 static int perf_tp_event_init(struct perf_event *event)
9966 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9970 * no branch sampling for tracepoint events
9972 if (has_branch_stack(event))
9975 err = perf_trace_init(event);
9979 event->destroy = tp_perf_event_destroy;
9984 static struct pmu perf_tracepoint = {
9985 .task_ctx_nr = perf_sw_context,
9987 .event_init = perf_tp_event_init,
9988 .add = perf_trace_add,
9989 .del = perf_trace_del,
9990 .start = perf_swevent_start,
9991 .stop = perf_swevent_stop,
9992 .read = perf_swevent_read,
9995 static int perf_tp_filter_match(struct perf_event *event,
9996 struct perf_sample_data *data)
9998 void *record = data->raw->frag.data;
10000 /* only top level events have filters set */
10002 event = event->parent;
10004 if (likely(!event->filter) || filter_match_preds(event->filter, record))
10009 static int perf_tp_event_match(struct perf_event *event,
10010 struct perf_sample_data *data,
10011 struct pt_regs *regs)
10013 if (event->hw.state & PERF_HES_STOPPED)
10016 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10018 if (event->attr.exclude_kernel && !user_mode(regs))
10021 if (!perf_tp_filter_match(event, data))
10027 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10028 struct trace_event_call *call, u64 count,
10029 struct pt_regs *regs, struct hlist_head *head,
10030 struct task_struct *task)
10032 if (bpf_prog_array_valid(call)) {
10033 *(struct pt_regs **)raw_data = regs;
10034 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10035 perf_swevent_put_recursion_context(rctx);
10039 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10042 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10044 static void __perf_tp_event_target_task(u64 count, void *record,
10045 struct pt_regs *regs,
10046 struct perf_sample_data *data,
10047 struct perf_event *event)
10049 struct trace_entry *entry = record;
10051 if (event->attr.config != entry->type)
10053 /* Cannot deliver synchronous signal to other task. */
10054 if (event->attr.sigtrap)
10056 if (perf_tp_event_match(event, data, regs))
10057 perf_swevent_event(event, count, data, regs);
10060 static void perf_tp_event_target_task(u64 count, void *record,
10061 struct pt_regs *regs,
10062 struct perf_sample_data *data,
10063 struct perf_event_context *ctx)
10065 unsigned int cpu = smp_processor_id();
10066 struct pmu *pmu = &perf_tracepoint;
10067 struct perf_event *event, *sibling;
10069 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10070 __perf_tp_event_target_task(count, record, regs, data, event);
10071 for_each_sibling_event(sibling, event)
10072 __perf_tp_event_target_task(count, record, regs, data, sibling);
10075 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10076 __perf_tp_event_target_task(count, record, regs, data, event);
10077 for_each_sibling_event(sibling, event)
10078 __perf_tp_event_target_task(count, record, regs, data, sibling);
10082 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10083 struct pt_regs *regs, struct hlist_head *head, int rctx,
10084 struct task_struct *task)
10086 struct perf_sample_data data;
10087 struct perf_event *event;
10089 struct perf_raw_record raw = {
10091 .size = entry_size,
10096 perf_sample_data_init(&data, 0, 0);
10097 perf_sample_save_raw_data(&data, &raw);
10099 perf_trace_buf_update(record, event_type);
10101 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10102 if (perf_tp_event_match(event, &data, regs))
10103 perf_swevent_event(event, count, &data, regs);
10107 * If we got specified a target task, also iterate its context and
10108 * deliver this event there too.
10110 if (task && task != current) {
10111 struct perf_event_context *ctx;
10114 ctx = rcu_dereference(task->perf_event_ctxp);
10118 raw_spin_lock(&ctx->lock);
10119 perf_tp_event_target_task(count, record, regs, &data, ctx);
10120 raw_spin_unlock(&ctx->lock);
10125 perf_swevent_put_recursion_context(rctx);
10127 EXPORT_SYMBOL_GPL(perf_tp_event);
10129 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10131 * Flags in config, used by dynamic PMU kprobe and uprobe
10132 * The flags should match following PMU_FORMAT_ATTR().
10134 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10135 * if not set, create kprobe/uprobe
10137 * The following values specify a reference counter (or semaphore in the
10138 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10139 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10141 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
10142 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
10144 enum perf_probe_config {
10145 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
10146 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
10147 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
10150 PMU_FORMAT_ATTR(retprobe, "config:0");
10153 #ifdef CONFIG_KPROBE_EVENTS
10154 static struct attribute *kprobe_attrs[] = {
10155 &format_attr_retprobe.attr,
10159 static struct attribute_group kprobe_format_group = {
10161 .attrs = kprobe_attrs,
10164 static const struct attribute_group *kprobe_attr_groups[] = {
10165 &kprobe_format_group,
10169 static int perf_kprobe_event_init(struct perf_event *event);
10170 static struct pmu perf_kprobe = {
10171 .task_ctx_nr = perf_sw_context,
10172 .event_init = perf_kprobe_event_init,
10173 .add = perf_trace_add,
10174 .del = perf_trace_del,
10175 .start = perf_swevent_start,
10176 .stop = perf_swevent_stop,
10177 .read = perf_swevent_read,
10178 .attr_groups = kprobe_attr_groups,
10181 static int perf_kprobe_event_init(struct perf_event *event)
10186 if (event->attr.type != perf_kprobe.type)
10189 if (!perfmon_capable())
10193 * no branch sampling for probe events
10195 if (has_branch_stack(event))
10196 return -EOPNOTSUPP;
10198 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10199 err = perf_kprobe_init(event, is_retprobe);
10203 event->destroy = perf_kprobe_destroy;
10207 #endif /* CONFIG_KPROBE_EVENTS */
10209 #ifdef CONFIG_UPROBE_EVENTS
10210 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10212 static struct attribute *uprobe_attrs[] = {
10213 &format_attr_retprobe.attr,
10214 &format_attr_ref_ctr_offset.attr,
10218 static struct attribute_group uprobe_format_group = {
10220 .attrs = uprobe_attrs,
10223 static const struct attribute_group *uprobe_attr_groups[] = {
10224 &uprobe_format_group,
10228 static int perf_uprobe_event_init(struct perf_event *event);
10229 static struct pmu perf_uprobe = {
10230 .task_ctx_nr = perf_sw_context,
10231 .event_init = perf_uprobe_event_init,
10232 .add = perf_trace_add,
10233 .del = perf_trace_del,
10234 .start = perf_swevent_start,
10235 .stop = perf_swevent_stop,
10236 .read = perf_swevent_read,
10237 .attr_groups = uprobe_attr_groups,
10240 static int perf_uprobe_event_init(struct perf_event *event)
10243 unsigned long ref_ctr_offset;
10246 if (event->attr.type != perf_uprobe.type)
10249 if (!perfmon_capable())
10253 * no branch sampling for probe events
10255 if (has_branch_stack(event))
10256 return -EOPNOTSUPP;
10258 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10259 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10260 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10264 event->destroy = perf_uprobe_destroy;
10268 #endif /* CONFIG_UPROBE_EVENTS */
10270 static inline void perf_tp_register(void)
10272 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10273 #ifdef CONFIG_KPROBE_EVENTS
10274 perf_pmu_register(&perf_kprobe, "kprobe", -1);
10276 #ifdef CONFIG_UPROBE_EVENTS
10277 perf_pmu_register(&perf_uprobe, "uprobe", -1);
10281 static void perf_event_free_filter(struct perf_event *event)
10283 ftrace_profile_free_filter(event);
10286 #ifdef CONFIG_BPF_SYSCALL
10287 static void bpf_overflow_handler(struct perf_event *event,
10288 struct perf_sample_data *data,
10289 struct pt_regs *regs)
10291 struct bpf_perf_event_data_kern ctx = {
10295 struct bpf_prog *prog;
10298 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10299 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10302 prog = READ_ONCE(event->prog);
10304 if (prog->call_get_stack &&
10305 (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) &&
10306 !(data->sample_flags & PERF_SAMPLE_CALLCHAIN)) {
10307 data->callchain = perf_callchain(event, regs);
10308 data->sample_flags |= PERF_SAMPLE_CALLCHAIN;
10311 ret = bpf_prog_run(prog, &ctx);
10315 __this_cpu_dec(bpf_prog_active);
10319 event->orig_overflow_handler(event, data, regs);
10322 static int perf_event_set_bpf_handler(struct perf_event *event,
10323 struct bpf_prog *prog,
10326 if (event->overflow_handler_context)
10327 /* hw breakpoint or kernel counter */
10333 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10336 if (event->attr.precise_ip &&
10337 prog->call_get_stack &&
10338 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10339 event->attr.exclude_callchain_kernel ||
10340 event->attr.exclude_callchain_user)) {
10342 * On perf_event with precise_ip, calling bpf_get_stack()
10343 * may trigger unwinder warnings and occasional crashes.
10344 * bpf_get_[stack|stackid] works around this issue by using
10345 * callchain attached to perf_sample_data. If the
10346 * perf_event does not full (kernel and user) callchain
10347 * attached to perf_sample_data, do not allow attaching BPF
10348 * program that calls bpf_get_[stack|stackid].
10353 event->prog = prog;
10354 event->bpf_cookie = bpf_cookie;
10355 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
10356 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
10360 static void perf_event_free_bpf_handler(struct perf_event *event)
10362 struct bpf_prog *prog = event->prog;
10367 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
10368 event->prog = NULL;
10369 bpf_prog_put(prog);
10372 static int perf_event_set_bpf_handler(struct perf_event *event,
10373 struct bpf_prog *prog,
10376 return -EOPNOTSUPP;
10378 static void perf_event_free_bpf_handler(struct perf_event *event)
10384 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10385 * with perf_event_open()
10387 static inline bool perf_event_is_tracing(struct perf_event *event)
10389 if (event->pmu == &perf_tracepoint)
10391 #ifdef CONFIG_KPROBE_EVENTS
10392 if (event->pmu == &perf_kprobe)
10395 #ifdef CONFIG_UPROBE_EVENTS
10396 if (event->pmu == &perf_uprobe)
10402 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10405 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10407 if (!perf_event_is_tracing(event))
10408 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10410 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10411 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10412 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10413 is_syscall_tp = is_syscall_trace_event(event->tp_event);
10414 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10415 /* bpf programs can only be attached to u/kprobe or tracepoint */
10418 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10419 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10420 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10423 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->aux->sleepable && !is_uprobe)
10424 /* only uprobe programs are allowed to be sleepable */
10427 /* Kprobe override only works for kprobes, not uprobes. */
10428 if (prog->kprobe_override && !is_kprobe)
10431 if (is_tracepoint || is_syscall_tp) {
10432 int off = trace_event_get_offsets(event->tp_event);
10434 if (prog->aux->max_ctx_offset > off)
10438 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10441 void perf_event_free_bpf_prog(struct perf_event *event)
10443 if (!perf_event_is_tracing(event)) {
10444 perf_event_free_bpf_handler(event);
10447 perf_event_detach_bpf_prog(event);
10452 static inline void perf_tp_register(void)
10456 static void perf_event_free_filter(struct perf_event *event)
10460 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10466 void perf_event_free_bpf_prog(struct perf_event *event)
10469 #endif /* CONFIG_EVENT_TRACING */
10471 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10472 void perf_bp_event(struct perf_event *bp, void *data)
10474 struct perf_sample_data sample;
10475 struct pt_regs *regs = data;
10477 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10479 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10480 perf_swevent_event(bp, 1, &sample, regs);
10485 * Allocate a new address filter
10487 static struct perf_addr_filter *
10488 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10490 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10491 struct perf_addr_filter *filter;
10493 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10497 INIT_LIST_HEAD(&filter->entry);
10498 list_add_tail(&filter->entry, filters);
10503 static void free_filters_list(struct list_head *filters)
10505 struct perf_addr_filter *filter, *iter;
10507 list_for_each_entry_safe(filter, iter, filters, entry) {
10508 path_put(&filter->path);
10509 list_del(&filter->entry);
10515 * Free existing address filters and optionally install new ones
10517 static void perf_addr_filters_splice(struct perf_event *event,
10518 struct list_head *head)
10520 unsigned long flags;
10523 if (!has_addr_filter(event))
10526 /* don't bother with children, they don't have their own filters */
10530 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10532 list_splice_init(&event->addr_filters.list, &list);
10534 list_splice(head, &event->addr_filters.list);
10536 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10538 free_filters_list(&list);
10542 * Scan through mm's vmas and see if one of them matches the
10543 * @filter; if so, adjust filter's address range.
10544 * Called with mm::mmap_lock down for reading.
10546 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10547 struct mm_struct *mm,
10548 struct perf_addr_filter_range *fr)
10550 struct vm_area_struct *vma;
10551 VMA_ITERATOR(vmi, mm, 0);
10553 for_each_vma(vmi, vma) {
10557 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10563 * Update event's address range filters based on the
10564 * task's existing mappings, if any.
10566 static void perf_event_addr_filters_apply(struct perf_event *event)
10568 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10569 struct task_struct *task = READ_ONCE(event->ctx->task);
10570 struct perf_addr_filter *filter;
10571 struct mm_struct *mm = NULL;
10572 unsigned int count = 0;
10573 unsigned long flags;
10576 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10577 * will stop on the parent's child_mutex that our caller is also holding
10579 if (task == TASK_TOMBSTONE)
10582 if (ifh->nr_file_filters) {
10583 mm = get_task_mm(task);
10587 mmap_read_lock(mm);
10590 raw_spin_lock_irqsave(&ifh->lock, flags);
10591 list_for_each_entry(filter, &ifh->list, entry) {
10592 if (filter->path.dentry) {
10594 * Adjust base offset if the filter is associated to a
10595 * binary that needs to be mapped:
10597 event->addr_filter_ranges[count].start = 0;
10598 event->addr_filter_ranges[count].size = 0;
10600 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10602 event->addr_filter_ranges[count].start = filter->offset;
10603 event->addr_filter_ranges[count].size = filter->size;
10609 event->addr_filters_gen++;
10610 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10612 if (ifh->nr_file_filters) {
10613 mmap_read_unlock(mm);
10619 perf_event_stop(event, 1);
10623 * Address range filtering: limiting the data to certain
10624 * instruction address ranges. Filters are ioctl()ed to us from
10625 * userspace as ascii strings.
10627 * Filter string format:
10629 * ACTION RANGE_SPEC
10630 * where ACTION is one of the
10631 * * "filter": limit the trace to this region
10632 * * "start": start tracing from this address
10633 * * "stop": stop tracing at this address/region;
10635 * * for kernel addresses: <start address>[/<size>]
10636 * * for object files: <start address>[/<size>]@</path/to/object/file>
10638 * if <size> is not specified or is zero, the range is treated as a single
10639 * address; not valid for ACTION=="filter".
10653 IF_STATE_ACTION = 0,
10658 static const match_table_t if_tokens = {
10659 { IF_ACT_FILTER, "filter" },
10660 { IF_ACT_START, "start" },
10661 { IF_ACT_STOP, "stop" },
10662 { IF_SRC_FILE, "%u/%u@%s" },
10663 { IF_SRC_KERNEL, "%u/%u" },
10664 { IF_SRC_FILEADDR, "%u@%s" },
10665 { IF_SRC_KERNELADDR, "%u" },
10666 { IF_ACT_NONE, NULL },
10670 * Address filter string parser
10673 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10674 struct list_head *filters)
10676 struct perf_addr_filter *filter = NULL;
10677 char *start, *orig, *filename = NULL;
10678 substring_t args[MAX_OPT_ARGS];
10679 int state = IF_STATE_ACTION, token;
10680 unsigned int kernel = 0;
10683 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10687 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10688 static const enum perf_addr_filter_action_t actions[] = {
10689 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10690 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10691 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10698 /* filter definition begins */
10699 if (state == IF_STATE_ACTION) {
10700 filter = perf_addr_filter_new(event, filters);
10705 token = match_token(start, if_tokens, args);
10707 case IF_ACT_FILTER:
10710 if (state != IF_STATE_ACTION)
10713 filter->action = actions[token];
10714 state = IF_STATE_SOURCE;
10717 case IF_SRC_KERNELADDR:
10718 case IF_SRC_KERNEL:
10722 case IF_SRC_FILEADDR:
10724 if (state != IF_STATE_SOURCE)
10728 ret = kstrtoul(args[0].from, 0, &filter->offset);
10732 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10734 ret = kstrtoul(args[1].from, 0, &filter->size);
10739 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10740 int fpos = token == IF_SRC_FILE ? 2 : 1;
10743 filename = match_strdup(&args[fpos]);
10750 state = IF_STATE_END;
10758 * Filter definition is fully parsed, validate and install it.
10759 * Make sure that it doesn't contradict itself or the event's
10762 if (state == IF_STATE_END) {
10766 * ACTION "filter" must have a non-zero length region
10769 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10778 * For now, we only support file-based filters
10779 * in per-task events; doing so for CPU-wide
10780 * events requires additional context switching
10781 * trickery, since same object code will be
10782 * mapped at different virtual addresses in
10783 * different processes.
10786 if (!event->ctx->task)
10789 /* look up the path and grab its inode */
10790 ret = kern_path(filename, LOOKUP_FOLLOW,
10796 if (!filter->path.dentry ||
10797 !S_ISREG(d_inode(filter->path.dentry)
10801 event->addr_filters.nr_file_filters++;
10804 /* ready to consume more filters */
10807 state = IF_STATE_ACTION;
10813 if (state != IF_STATE_ACTION)
10823 free_filters_list(filters);
10830 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10832 LIST_HEAD(filters);
10836 * Since this is called in perf_ioctl() path, we're already holding
10839 lockdep_assert_held(&event->ctx->mutex);
10841 if (WARN_ON_ONCE(event->parent))
10844 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10846 goto fail_clear_files;
10848 ret = event->pmu->addr_filters_validate(&filters);
10850 goto fail_free_filters;
10852 /* remove existing filters, if any */
10853 perf_addr_filters_splice(event, &filters);
10855 /* install new filters */
10856 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10861 free_filters_list(&filters);
10864 event->addr_filters.nr_file_filters = 0;
10869 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10874 filter_str = strndup_user(arg, PAGE_SIZE);
10875 if (IS_ERR(filter_str))
10876 return PTR_ERR(filter_str);
10878 #ifdef CONFIG_EVENT_TRACING
10879 if (perf_event_is_tracing(event)) {
10880 struct perf_event_context *ctx = event->ctx;
10883 * Beware, here be dragons!!
10885 * the tracepoint muck will deadlock against ctx->mutex, but
10886 * the tracepoint stuff does not actually need it. So
10887 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10888 * already have a reference on ctx.
10890 * This can result in event getting moved to a different ctx,
10891 * but that does not affect the tracepoint state.
10893 mutex_unlock(&ctx->mutex);
10894 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10895 mutex_lock(&ctx->mutex);
10898 if (has_addr_filter(event))
10899 ret = perf_event_set_addr_filter(event, filter_str);
10906 * hrtimer based swevent callback
10909 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10911 enum hrtimer_restart ret = HRTIMER_RESTART;
10912 struct perf_sample_data data;
10913 struct pt_regs *regs;
10914 struct perf_event *event;
10917 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10919 if (event->state != PERF_EVENT_STATE_ACTIVE)
10920 return HRTIMER_NORESTART;
10922 event->pmu->read(event);
10924 perf_sample_data_init(&data, 0, event->hw.last_period);
10925 regs = get_irq_regs();
10927 if (regs && !perf_exclude_event(event, regs)) {
10928 if (!(event->attr.exclude_idle && is_idle_task(current)))
10929 if (__perf_event_overflow(event, 1, &data, regs))
10930 ret = HRTIMER_NORESTART;
10933 period = max_t(u64, 10000, event->hw.sample_period);
10934 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10939 static void perf_swevent_start_hrtimer(struct perf_event *event)
10941 struct hw_perf_event *hwc = &event->hw;
10944 if (!is_sampling_event(event))
10947 period = local64_read(&hwc->period_left);
10952 local64_set(&hwc->period_left, 0);
10954 period = max_t(u64, 10000, hwc->sample_period);
10956 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10957 HRTIMER_MODE_REL_PINNED_HARD);
10960 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10962 struct hw_perf_event *hwc = &event->hw;
10964 if (is_sampling_event(event)) {
10965 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10966 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10968 hrtimer_cancel(&hwc->hrtimer);
10972 static void perf_swevent_init_hrtimer(struct perf_event *event)
10974 struct hw_perf_event *hwc = &event->hw;
10976 if (!is_sampling_event(event))
10979 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10980 hwc->hrtimer.function = perf_swevent_hrtimer;
10983 * Since hrtimers have a fixed rate, we can do a static freq->period
10984 * mapping and avoid the whole period adjust feedback stuff.
10986 if (event->attr.freq) {
10987 long freq = event->attr.sample_freq;
10989 event->attr.sample_period = NSEC_PER_SEC / freq;
10990 hwc->sample_period = event->attr.sample_period;
10991 local64_set(&hwc->period_left, hwc->sample_period);
10992 hwc->last_period = hwc->sample_period;
10993 event->attr.freq = 0;
10998 * Software event: cpu wall time clock
11001 static void cpu_clock_event_update(struct perf_event *event)
11006 now = local_clock();
11007 prev = local64_xchg(&event->hw.prev_count, now);
11008 local64_add(now - prev, &event->count);
11011 static void cpu_clock_event_start(struct perf_event *event, int flags)
11013 local64_set(&event->hw.prev_count, local_clock());
11014 perf_swevent_start_hrtimer(event);
11017 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11019 perf_swevent_cancel_hrtimer(event);
11020 cpu_clock_event_update(event);
11023 static int cpu_clock_event_add(struct perf_event *event, int flags)
11025 if (flags & PERF_EF_START)
11026 cpu_clock_event_start(event, flags);
11027 perf_event_update_userpage(event);
11032 static void cpu_clock_event_del(struct perf_event *event, int flags)
11034 cpu_clock_event_stop(event, flags);
11037 static void cpu_clock_event_read(struct perf_event *event)
11039 cpu_clock_event_update(event);
11042 static int cpu_clock_event_init(struct perf_event *event)
11044 if (event->attr.type != PERF_TYPE_SOFTWARE)
11047 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11051 * no branch sampling for software events
11053 if (has_branch_stack(event))
11054 return -EOPNOTSUPP;
11056 perf_swevent_init_hrtimer(event);
11061 static struct pmu perf_cpu_clock = {
11062 .task_ctx_nr = perf_sw_context,
11064 .capabilities = PERF_PMU_CAP_NO_NMI,
11066 .event_init = cpu_clock_event_init,
11067 .add = cpu_clock_event_add,
11068 .del = cpu_clock_event_del,
11069 .start = cpu_clock_event_start,
11070 .stop = cpu_clock_event_stop,
11071 .read = cpu_clock_event_read,
11075 * Software event: task time clock
11078 static void task_clock_event_update(struct perf_event *event, u64 now)
11083 prev = local64_xchg(&event->hw.prev_count, now);
11084 delta = now - prev;
11085 local64_add(delta, &event->count);
11088 static void task_clock_event_start(struct perf_event *event, int flags)
11090 local64_set(&event->hw.prev_count, event->ctx->time);
11091 perf_swevent_start_hrtimer(event);
11094 static void task_clock_event_stop(struct perf_event *event, int flags)
11096 perf_swevent_cancel_hrtimer(event);
11097 task_clock_event_update(event, event->ctx->time);
11100 static int task_clock_event_add(struct perf_event *event, int flags)
11102 if (flags & PERF_EF_START)
11103 task_clock_event_start(event, flags);
11104 perf_event_update_userpage(event);
11109 static void task_clock_event_del(struct perf_event *event, int flags)
11111 task_clock_event_stop(event, PERF_EF_UPDATE);
11114 static void task_clock_event_read(struct perf_event *event)
11116 u64 now = perf_clock();
11117 u64 delta = now - event->ctx->timestamp;
11118 u64 time = event->ctx->time + delta;
11120 task_clock_event_update(event, time);
11123 static int task_clock_event_init(struct perf_event *event)
11125 if (event->attr.type != PERF_TYPE_SOFTWARE)
11128 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11132 * no branch sampling for software events
11134 if (has_branch_stack(event))
11135 return -EOPNOTSUPP;
11137 perf_swevent_init_hrtimer(event);
11142 static struct pmu perf_task_clock = {
11143 .task_ctx_nr = perf_sw_context,
11145 .capabilities = PERF_PMU_CAP_NO_NMI,
11147 .event_init = task_clock_event_init,
11148 .add = task_clock_event_add,
11149 .del = task_clock_event_del,
11150 .start = task_clock_event_start,
11151 .stop = task_clock_event_stop,
11152 .read = task_clock_event_read,
11155 static void perf_pmu_nop_void(struct pmu *pmu)
11159 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11163 static int perf_pmu_nop_int(struct pmu *pmu)
11168 static int perf_event_nop_int(struct perf_event *event, u64 value)
11173 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11175 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11177 __this_cpu_write(nop_txn_flags, flags);
11179 if (flags & ~PERF_PMU_TXN_ADD)
11182 perf_pmu_disable(pmu);
11185 static int perf_pmu_commit_txn(struct pmu *pmu)
11187 unsigned int flags = __this_cpu_read(nop_txn_flags);
11189 __this_cpu_write(nop_txn_flags, 0);
11191 if (flags & ~PERF_PMU_TXN_ADD)
11194 perf_pmu_enable(pmu);
11198 static void perf_pmu_cancel_txn(struct pmu *pmu)
11200 unsigned int flags = __this_cpu_read(nop_txn_flags);
11202 __this_cpu_write(nop_txn_flags, 0);
11204 if (flags & ~PERF_PMU_TXN_ADD)
11207 perf_pmu_enable(pmu);
11210 static int perf_event_idx_default(struct perf_event *event)
11215 static void free_pmu_context(struct pmu *pmu)
11217 free_percpu(pmu->cpu_pmu_context);
11221 * Let userspace know that this PMU supports address range filtering:
11223 static ssize_t nr_addr_filters_show(struct device *dev,
11224 struct device_attribute *attr,
11227 struct pmu *pmu = dev_get_drvdata(dev);
11229 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11231 DEVICE_ATTR_RO(nr_addr_filters);
11233 static struct idr pmu_idr;
11236 type_show(struct device *dev, struct device_attribute *attr, char *page)
11238 struct pmu *pmu = dev_get_drvdata(dev);
11240 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11242 static DEVICE_ATTR_RO(type);
11245 perf_event_mux_interval_ms_show(struct device *dev,
11246 struct device_attribute *attr,
11249 struct pmu *pmu = dev_get_drvdata(dev);
11251 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11254 static DEFINE_MUTEX(mux_interval_mutex);
11257 perf_event_mux_interval_ms_store(struct device *dev,
11258 struct device_attribute *attr,
11259 const char *buf, size_t count)
11261 struct pmu *pmu = dev_get_drvdata(dev);
11262 int timer, cpu, ret;
11264 ret = kstrtoint(buf, 0, &timer);
11271 /* same value, noting to do */
11272 if (timer == pmu->hrtimer_interval_ms)
11275 mutex_lock(&mux_interval_mutex);
11276 pmu->hrtimer_interval_ms = timer;
11278 /* update all cpuctx for this PMU */
11280 for_each_online_cpu(cpu) {
11281 struct perf_cpu_pmu_context *cpc;
11282 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11283 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11285 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
11287 cpus_read_unlock();
11288 mutex_unlock(&mux_interval_mutex);
11292 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11294 static struct attribute *pmu_dev_attrs[] = {
11295 &dev_attr_type.attr,
11296 &dev_attr_perf_event_mux_interval_ms.attr,
11299 ATTRIBUTE_GROUPS(pmu_dev);
11301 static int pmu_bus_running;
11302 static struct bus_type pmu_bus = {
11303 .name = "event_source",
11304 .dev_groups = pmu_dev_groups,
11307 static void pmu_dev_release(struct device *dev)
11312 static int pmu_dev_alloc(struct pmu *pmu)
11316 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11320 pmu->dev->groups = pmu->attr_groups;
11321 device_initialize(pmu->dev);
11323 dev_set_drvdata(pmu->dev, pmu);
11324 pmu->dev->bus = &pmu_bus;
11325 pmu->dev->release = pmu_dev_release;
11327 ret = dev_set_name(pmu->dev, "%s", pmu->name);
11331 ret = device_add(pmu->dev);
11335 /* For PMUs with address filters, throw in an extra attribute: */
11336 if (pmu->nr_addr_filters)
11337 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
11342 if (pmu->attr_update)
11343 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11352 device_del(pmu->dev);
11355 put_device(pmu->dev);
11359 static struct lock_class_key cpuctx_mutex;
11360 static struct lock_class_key cpuctx_lock;
11362 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11364 int cpu, ret, max = PERF_TYPE_MAX;
11366 mutex_lock(&pmus_lock);
11368 pmu->pmu_disable_count = alloc_percpu(int);
11369 if (!pmu->pmu_disable_count)
11377 if (type != PERF_TYPE_SOFTWARE) {
11381 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
11385 WARN_ON(type >= 0 && ret != type);
11391 if (pmu_bus_running) {
11392 ret = pmu_dev_alloc(pmu);
11399 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context);
11400 if (!pmu->cpu_pmu_context)
11403 for_each_possible_cpu(cpu) {
11404 struct perf_cpu_pmu_context *cpc;
11406 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11407 __perf_init_event_pmu_context(&cpc->epc, pmu);
11408 __perf_mux_hrtimer_init(cpc, cpu);
11411 if (!pmu->start_txn) {
11412 if (pmu->pmu_enable) {
11414 * If we have pmu_enable/pmu_disable calls, install
11415 * transaction stubs that use that to try and batch
11416 * hardware accesses.
11418 pmu->start_txn = perf_pmu_start_txn;
11419 pmu->commit_txn = perf_pmu_commit_txn;
11420 pmu->cancel_txn = perf_pmu_cancel_txn;
11422 pmu->start_txn = perf_pmu_nop_txn;
11423 pmu->commit_txn = perf_pmu_nop_int;
11424 pmu->cancel_txn = perf_pmu_nop_void;
11428 if (!pmu->pmu_enable) {
11429 pmu->pmu_enable = perf_pmu_nop_void;
11430 pmu->pmu_disable = perf_pmu_nop_void;
11433 if (!pmu->check_period)
11434 pmu->check_period = perf_event_nop_int;
11436 if (!pmu->event_idx)
11437 pmu->event_idx = perf_event_idx_default;
11440 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
11441 * since these cannot be in the IDR. This way the linear search
11442 * is fast, provided a valid software event is provided.
11444 if (type == PERF_TYPE_SOFTWARE || !name)
11445 list_add_rcu(&pmu->entry, &pmus);
11447 list_add_tail_rcu(&pmu->entry, &pmus);
11449 atomic_set(&pmu->exclusive_cnt, 0);
11452 mutex_unlock(&pmus_lock);
11457 device_del(pmu->dev);
11458 put_device(pmu->dev);
11461 if (pmu->type != PERF_TYPE_SOFTWARE)
11462 idr_remove(&pmu_idr, pmu->type);
11465 free_percpu(pmu->pmu_disable_count);
11468 EXPORT_SYMBOL_GPL(perf_pmu_register);
11470 void perf_pmu_unregister(struct pmu *pmu)
11472 mutex_lock(&pmus_lock);
11473 list_del_rcu(&pmu->entry);
11476 * We dereference the pmu list under both SRCU and regular RCU, so
11477 * synchronize against both of those.
11479 synchronize_srcu(&pmus_srcu);
11482 free_percpu(pmu->pmu_disable_count);
11483 if (pmu->type != PERF_TYPE_SOFTWARE)
11484 idr_remove(&pmu_idr, pmu->type);
11485 if (pmu_bus_running) {
11486 if (pmu->nr_addr_filters)
11487 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11488 device_del(pmu->dev);
11489 put_device(pmu->dev);
11491 free_pmu_context(pmu);
11492 mutex_unlock(&pmus_lock);
11494 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11496 static inline bool has_extended_regs(struct perf_event *event)
11498 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11499 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11502 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11504 struct perf_event_context *ctx = NULL;
11507 if (!try_module_get(pmu->module))
11511 * A number of pmu->event_init() methods iterate the sibling_list to,
11512 * for example, validate if the group fits on the PMU. Therefore,
11513 * if this is a sibling event, acquire the ctx->mutex to protect
11514 * the sibling_list.
11516 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11518 * This ctx->mutex can nest when we're called through
11519 * inheritance. See the perf_event_ctx_lock_nested() comment.
11521 ctx = perf_event_ctx_lock_nested(event->group_leader,
11522 SINGLE_DEPTH_NESTING);
11527 ret = pmu->event_init(event);
11530 perf_event_ctx_unlock(event->group_leader, ctx);
11533 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11534 has_extended_regs(event))
11537 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11538 event_has_any_exclude_flag(event))
11541 if (ret && event->destroy)
11542 event->destroy(event);
11546 module_put(pmu->module);
11551 static struct pmu *perf_init_event(struct perf_event *event)
11553 bool extended_type = false;
11554 int idx, type, ret;
11557 idx = srcu_read_lock(&pmus_srcu);
11559 /* Try parent's PMU first: */
11560 if (event->parent && event->parent->pmu) {
11561 pmu = event->parent->pmu;
11562 ret = perf_try_init_event(pmu, event);
11568 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11569 * are often aliases for PERF_TYPE_RAW.
11571 type = event->attr.type;
11572 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
11573 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
11575 type = PERF_TYPE_RAW;
11577 extended_type = true;
11578 event->attr.config &= PERF_HW_EVENT_MASK;
11584 pmu = idr_find(&pmu_idr, type);
11587 if (event->attr.type != type && type != PERF_TYPE_RAW &&
11588 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
11591 ret = perf_try_init_event(pmu, event);
11592 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
11593 type = event->attr.type;
11598 pmu = ERR_PTR(ret);
11603 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11604 ret = perf_try_init_event(pmu, event);
11608 if (ret != -ENOENT) {
11609 pmu = ERR_PTR(ret);
11614 pmu = ERR_PTR(-ENOENT);
11616 srcu_read_unlock(&pmus_srcu, idx);
11621 static void attach_sb_event(struct perf_event *event)
11623 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11625 raw_spin_lock(&pel->lock);
11626 list_add_rcu(&event->sb_list, &pel->list);
11627 raw_spin_unlock(&pel->lock);
11631 * We keep a list of all !task (and therefore per-cpu) events
11632 * that need to receive side-band records.
11634 * This avoids having to scan all the various PMU per-cpu contexts
11635 * looking for them.
11637 static void account_pmu_sb_event(struct perf_event *event)
11639 if (is_sb_event(event))
11640 attach_sb_event(event);
11643 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11644 static void account_freq_event_nohz(void)
11646 #ifdef CONFIG_NO_HZ_FULL
11647 /* Lock so we don't race with concurrent unaccount */
11648 spin_lock(&nr_freq_lock);
11649 if (atomic_inc_return(&nr_freq_events) == 1)
11650 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11651 spin_unlock(&nr_freq_lock);
11655 static void account_freq_event(void)
11657 if (tick_nohz_full_enabled())
11658 account_freq_event_nohz();
11660 atomic_inc(&nr_freq_events);
11664 static void account_event(struct perf_event *event)
11671 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11673 if (event->attr.mmap || event->attr.mmap_data)
11674 atomic_inc(&nr_mmap_events);
11675 if (event->attr.build_id)
11676 atomic_inc(&nr_build_id_events);
11677 if (event->attr.comm)
11678 atomic_inc(&nr_comm_events);
11679 if (event->attr.namespaces)
11680 atomic_inc(&nr_namespaces_events);
11681 if (event->attr.cgroup)
11682 atomic_inc(&nr_cgroup_events);
11683 if (event->attr.task)
11684 atomic_inc(&nr_task_events);
11685 if (event->attr.freq)
11686 account_freq_event();
11687 if (event->attr.context_switch) {
11688 atomic_inc(&nr_switch_events);
11691 if (has_branch_stack(event))
11693 if (is_cgroup_event(event))
11695 if (event->attr.ksymbol)
11696 atomic_inc(&nr_ksymbol_events);
11697 if (event->attr.bpf_event)
11698 atomic_inc(&nr_bpf_events);
11699 if (event->attr.text_poke)
11700 atomic_inc(&nr_text_poke_events);
11704 * We need the mutex here because static_branch_enable()
11705 * must complete *before* the perf_sched_count increment
11708 if (atomic_inc_not_zero(&perf_sched_count))
11711 mutex_lock(&perf_sched_mutex);
11712 if (!atomic_read(&perf_sched_count)) {
11713 static_branch_enable(&perf_sched_events);
11715 * Guarantee that all CPUs observe they key change and
11716 * call the perf scheduling hooks before proceeding to
11717 * install events that need them.
11722 * Now that we have waited for the sync_sched(), allow further
11723 * increments to by-pass the mutex.
11725 atomic_inc(&perf_sched_count);
11726 mutex_unlock(&perf_sched_mutex);
11730 account_pmu_sb_event(event);
11734 * Allocate and initialize an event structure
11736 static struct perf_event *
11737 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11738 struct task_struct *task,
11739 struct perf_event *group_leader,
11740 struct perf_event *parent_event,
11741 perf_overflow_handler_t overflow_handler,
11742 void *context, int cgroup_fd)
11745 struct perf_event *event;
11746 struct hw_perf_event *hwc;
11747 long err = -EINVAL;
11750 if ((unsigned)cpu >= nr_cpu_ids) {
11751 if (!task || cpu != -1)
11752 return ERR_PTR(-EINVAL);
11754 if (attr->sigtrap && !task) {
11755 /* Requires a task: avoid signalling random tasks. */
11756 return ERR_PTR(-EINVAL);
11759 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11760 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11763 return ERR_PTR(-ENOMEM);
11766 * Single events are their own group leaders, with an
11767 * empty sibling list:
11770 group_leader = event;
11772 mutex_init(&event->child_mutex);
11773 INIT_LIST_HEAD(&event->child_list);
11775 INIT_LIST_HEAD(&event->event_entry);
11776 INIT_LIST_HEAD(&event->sibling_list);
11777 INIT_LIST_HEAD(&event->active_list);
11778 init_event_group(event);
11779 INIT_LIST_HEAD(&event->rb_entry);
11780 INIT_LIST_HEAD(&event->active_entry);
11781 INIT_LIST_HEAD(&event->addr_filters.list);
11782 INIT_HLIST_NODE(&event->hlist_entry);
11785 init_waitqueue_head(&event->waitq);
11786 init_irq_work(&event->pending_irq, perf_pending_irq);
11787 init_task_work(&event->pending_task, perf_pending_task);
11789 mutex_init(&event->mmap_mutex);
11790 raw_spin_lock_init(&event->addr_filters.lock);
11792 atomic_long_set(&event->refcount, 1);
11794 event->attr = *attr;
11795 event->group_leader = group_leader;
11799 event->parent = parent_event;
11801 event->ns = get_pid_ns(task_active_pid_ns(current));
11802 event->id = atomic64_inc_return(&perf_event_id);
11804 event->state = PERF_EVENT_STATE_INACTIVE;
11807 event->event_caps = parent_event->event_caps;
11810 event->attach_state = PERF_ATTACH_TASK;
11812 * XXX pmu::event_init needs to know what task to account to
11813 * and we cannot use the ctx information because we need the
11814 * pmu before we get a ctx.
11816 event->hw.target = get_task_struct(task);
11819 event->clock = &local_clock;
11821 event->clock = parent_event->clock;
11823 if (!overflow_handler && parent_event) {
11824 overflow_handler = parent_event->overflow_handler;
11825 context = parent_event->overflow_handler_context;
11826 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11827 if (overflow_handler == bpf_overflow_handler) {
11828 struct bpf_prog *prog = parent_event->prog;
11830 bpf_prog_inc(prog);
11831 event->prog = prog;
11832 event->orig_overflow_handler =
11833 parent_event->orig_overflow_handler;
11838 if (overflow_handler) {
11839 event->overflow_handler = overflow_handler;
11840 event->overflow_handler_context = context;
11841 } else if (is_write_backward(event)){
11842 event->overflow_handler = perf_event_output_backward;
11843 event->overflow_handler_context = NULL;
11845 event->overflow_handler = perf_event_output_forward;
11846 event->overflow_handler_context = NULL;
11849 perf_event__state_init(event);
11854 hwc->sample_period = attr->sample_period;
11855 if (attr->freq && attr->sample_freq)
11856 hwc->sample_period = 1;
11857 hwc->last_period = hwc->sample_period;
11859 local64_set(&hwc->period_left, hwc->sample_period);
11862 * We currently do not support PERF_SAMPLE_READ on inherited events.
11863 * See perf_output_read().
11865 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11868 if (!has_branch_stack(event))
11869 event->attr.branch_sample_type = 0;
11871 pmu = perf_init_event(event);
11873 err = PTR_ERR(pmu);
11878 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
11879 * events (they don't make sense as the cgroup will be different
11880 * on other CPUs in the uncore mask).
11882 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) {
11887 if (event->attr.aux_output &&
11888 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11893 if (cgroup_fd != -1) {
11894 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11899 err = exclusive_event_init(event);
11903 if (has_addr_filter(event)) {
11904 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11905 sizeof(struct perf_addr_filter_range),
11907 if (!event->addr_filter_ranges) {
11913 * Clone the parent's vma offsets: they are valid until exec()
11914 * even if the mm is not shared with the parent.
11916 if (event->parent) {
11917 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11919 raw_spin_lock_irq(&ifh->lock);
11920 memcpy(event->addr_filter_ranges,
11921 event->parent->addr_filter_ranges,
11922 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11923 raw_spin_unlock_irq(&ifh->lock);
11926 /* force hw sync on the address filters */
11927 event->addr_filters_gen = 1;
11930 if (!event->parent) {
11931 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11932 err = get_callchain_buffers(attr->sample_max_stack);
11934 goto err_addr_filters;
11938 err = security_perf_event_alloc(event);
11940 goto err_callchain_buffer;
11942 /* symmetric to unaccount_event() in _free_event() */
11943 account_event(event);
11947 err_callchain_buffer:
11948 if (!event->parent) {
11949 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11950 put_callchain_buffers();
11953 kfree(event->addr_filter_ranges);
11956 exclusive_event_destroy(event);
11959 if (is_cgroup_event(event))
11960 perf_detach_cgroup(event);
11961 if (event->destroy)
11962 event->destroy(event);
11963 module_put(pmu->module);
11965 if (event->hw.target)
11966 put_task_struct(event->hw.target);
11967 call_rcu(&event->rcu_head, free_event_rcu);
11969 return ERR_PTR(err);
11972 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11973 struct perf_event_attr *attr)
11978 /* Zero the full structure, so that a short copy will be nice. */
11979 memset(attr, 0, sizeof(*attr));
11981 ret = get_user(size, &uattr->size);
11985 /* ABI compatibility quirk: */
11987 size = PERF_ATTR_SIZE_VER0;
11988 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11991 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
12000 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
12003 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
12006 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
12009 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
12010 u64 mask = attr->branch_sample_type;
12012 /* only using defined bits */
12013 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
12016 /* at least one branch bit must be set */
12017 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
12020 /* propagate priv level, when not set for branch */
12021 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
12023 /* exclude_kernel checked on syscall entry */
12024 if (!attr->exclude_kernel)
12025 mask |= PERF_SAMPLE_BRANCH_KERNEL;
12027 if (!attr->exclude_user)
12028 mask |= PERF_SAMPLE_BRANCH_USER;
12030 if (!attr->exclude_hv)
12031 mask |= PERF_SAMPLE_BRANCH_HV;
12033 * adjust user setting (for HW filter setup)
12035 attr->branch_sample_type = mask;
12037 /* privileged levels capture (kernel, hv): check permissions */
12038 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
12039 ret = perf_allow_kernel(attr);
12045 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
12046 ret = perf_reg_validate(attr->sample_regs_user);
12051 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
12052 if (!arch_perf_have_user_stack_dump())
12056 * We have __u32 type for the size, but so far
12057 * we can only use __u16 as maximum due to the
12058 * __u16 sample size limit.
12060 if (attr->sample_stack_user >= USHRT_MAX)
12062 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
12066 if (!attr->sample_max_stack)
12067 attr->sample_max_stack = sysctl_perf_event_max_stack;
12069 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
12070 ret = perf_reg_validate(attr->sample_regs_intr);
12072 #ifndef CONFIG_CGROUP_PERF
12073 if (attr->sample_type & PERF_SAMPLE_CGROUP)
12076 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
12077 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
12080 if (!attr->inherit && attr->inherit_thread)
12083 if (attr->remove_on_exec && attr->enable_on_exec)
12086 if (attr->sigtrap && !attr->remove_on_exec)
12093 put_user(sizeof(*attr), &uattr->size);
12098 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12104 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12108 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12110 struct perf_buffer *rb = NULL;
12113 if (!output_event) {
12114 mutex_lock(&event->mmap_mutex);
12118 /* don't allow circular references */
12119 if (event == output_event)
12123 * Don't allow cross-cpu buffers
12125 if (output_event->cpu != event->cpu)
12129 * If its not a per-cpu rb, it must be the same task.
12131 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
12135 * Mixing clocks in the same buffer is trouble you don't need.
12137 if (output_event->clock != event->clock)
12141 * Either writing ring buffer from beginning or from end.
12142 * Mixing is not allowed.
12144 if (is_write_backward(output_event) != is_write_backward(event))
12148 * If both events generate aux data, they must be on the same PMU
12150 if (has_aux(event) && has_aux(output_event) &&
12151 event->pmu != output_event->pmu)
12155 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12156 * output_event is already on rb->event_list, and the list iteration
12157 * restarts after every removal, it is guaranteed this new event is
12158 * observed *OR* if output_event is already removed, it's guaranteed we
12159 * observe !rb->mmap_count.
12161 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12163 /* Can't redirect output if we've got an active mmap() */
12164 if (atomic_read(&event->mmap_count))
12167 if (output_event) {
12168 /* get the rb we want to redirect to */
12169 rb = ring_buffer_get(output_event);
12173 /* did we race against perf_mmap_close() */
12174 if (!atomic_read(&rb->mmap_count)) {
12175 ring_buffer_put(rb);
12180 ring_buffer_attach(event, rb);
12184 mutex_unlock(&event->mmap_mutex);
12186 mutex_unlock(&output_event->mmap_mutex);
12192 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12194 bool nmi_safe = false;
12197 case CLOCK_MONOTONIC:
12198 event->clock = &ktime_get_mono_fast_ns;
12202 case CLOCK_MONOTONIC_RAW:
12203 event->clock = &ktime_get_raw_fast_ns;
12207 case CLOCK_REALTIME:
12208 event->clock = &ktime_get_real_ns;
12211 case CLOCK_BOOTTIME:
12212 event->clock = &ktime_get_boottime_ns;
12216 event->clock = &ktime_get_clocktai_ns;
12223 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12230 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12232 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12233 bool is_capable = perfmon_capable();
12235 if (attr->sigtrap) {
12237 * perf_event_attr::sigtrap sends signals to the other task.
12238 * Require the current task to also have CAP_KILL.
12241 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12245 * If the required capabilities aren't available, checks for
12246 * ptrace permissions: upgrade to ATTACH, since sending signals
12247 * can effectively change the target task.
12249 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12253 * Preserve ptrace permission check for backwards compatibility. The
12254 * ptrace check also includes checks that the current task and other
12255 * task have matching uids, and is therefore not done here explicitly.
12257 return is_capable || ptrace_may_access(task, ptrace_mode);
12261 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12263 * @attr_uptr: event_id type attributes for monitoring/sampling
12266 * @group_fd: group leader event fd
12267 * @flags: perf event open flags
12269 SYSCALL_DEFINE5(perf_event_open,
12270 struct perf_event_attr __user *, attr_uptr,
12271 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12273 struct perf_event *group_leader = NULL, *output_event = NULL;
12274 struct perf_event_pmu_context *pmu_ctx;
12275 struct perf_event *event, *sibling;
12276 struct perf_event_attr attr;
12277 struct perf_event_context *ctx;
12278 struct file *event_file = NULL;
12279 struct fd group = {NULL, 0};
12280 struct task_struct *task = NULL;
12283 int move_group = 0;
12285 int f_flags = O_RDWR;
12286 int cgroup_fd = -1;
12288 /* for future expandability... */
12289 if (flags & ~PERF_FLAG_ALL)
12292 err = perf_copy_attr(attr_uptr, &attr);
12296 /* Do we allow access to perf_event_open(2) ? */
12297 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12301 if (!attr.exclude_kernel) {
12302 err = perf_allow_kernel(&attr);
12307 if (attr.namespaces) {
12308 if (!perfmon_capable())
12313 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12316 if (attr.sample_period & (1ULL << 63))
12320 /* Only privileged users can get physical addresses */
12321 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12322 err = perf_allow_kernel(&attr);
12327 /* REGS_INTR can leak data, lockdown must prevent this */
12328 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12329 err = security_locked_down(LOCKDOWN_PERF);
12335 * In cgroup mode, the pid argument is used to pass the fd
12336 * opened to the cgroup directory in cgroupfs. The cpu argument
12337 * designates the cpu on which to monitor threads from that
12340 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12343 if (flags & PERF_FLAG_FD_CLOEXEC)
12344 f_flags |= O_CLOEXEC;
12346 event_fd = get_unused_fd_flags(f_flags);
12350 if (group_fd != -1) {
12351 err = perf_fget_light(group_fd, &group);
12354 group_leader = group.file->private_data;
12355 if (flags & PERF_FLAG_FD_OUTPUT)
12356 output_event = group_leader;
12357 if (flags & PERF_FLAG_FD_NO_GROUP)
12358 group_leader = NULL;
12361 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12362 task = find_lively_task_by_vpid(pid);
12363 if (IS_ERR(task)) {
12364 err = PTR_ERR(task);
12369 if (task && group_leader &&
12370 group_leader->attr.inherit != attr.inherit) {
12375 if (flags & PERF_FLAG_PID_CGROUP)
12378 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12379 NULL, NULL, cgroup_fd);
12380 if (IS_ERR(event)) {
12381 err = PTR_ERR(event);
12385 if (is_sampling_event(event)) {
12386 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12393 * Special case software events and allow them to be part of
12394 * any hardware group.
12398 if (attr.use_clockid) {
12399 err = perf_event_set_clock(event, attr.clockid);
12404 if (pmu->task_ctx_nr == perf_sw_context)
12405 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12408 err = down_read_interruptible(&task->signal->exec_update_lock);
12413 * We must hold exec_update_lock across this and any potential
12414 * perf_install_in_context() call for this new event to
12415 * serialize against exec() altering our credentials (and the
12416 * perf_event_exit_task() that could imply).
12419 if (!perf_check_permission(&attr, task))
12424 * Get the target context (task or percpu):
12426 ctx = find_get_context(task, event);
12428 err = PTR_ERR(ctx);
12432 mutex_lock(&ctx->mutex);
12434 if (ctx->task == TASK_TOMBSTONE) {
12441 * Check if the @cpu we're creating an event for is online.
12443 * We use the perf_cpu_context::ctx::mutex to serialize against
12444 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12446 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
12448 if (!cpuctx->online) {
12454 if (group_leader) {
12458 * Do not allow a recursive hierarchy (this new sibling
12459 * becoming part of another group-sibling):
12461 if (group_leader->group_leader != group_leader)
12464 /* All events in a group should have the same clock */
12465 if (group_leader->clock != event->clock)
12469 * Make sure we're both events for the same CPU;
12470 * grouping events for different CPUs is broken; since
12471 * you can never concurrently schedule them anyhow.
12473 if (group_leader->cpu != event->cpu)
12477 * Make sure we're both on the same context; either task or cpu.
12479 if (group_leader->ctx != ctx)
12483 * Only a group leader can be exclusive or pinned
12485 if (attr.exclusive || attr.pinned)
12488 if (is_software_event(event) &&
12489 !in_software_context(group_leader)) {
12491 * If the event is a sw event, but the group_leader
12492 * is on hw context.
12494 * Allow the addition of software events to hw
12495 * groups, this is safe because software events
12496 * never fail to schedule.
12498 * Note the comment that goes with struct
12499 * perf_event_pmu_context.
12501 pmu = group_leader->pmu_ctx->pmu;
12502 } else if (!is_software_event(event)) {
12503 if (is_software_event(group_leader) &&
12504 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12506 * In case the group is a pure software group, and we
12507 * try to add a hardware event, move the whole group to
12508 * the hardware context.
12513 /* Don't allow group of multiple hw events from different pmus */
12514 if (!in_software_context(group_leader) &&
12515 group_leader->pmu_ctx->pmu != pmu)
12521 * Now that we're certain of the pmu; find the pmu_ctx.
12523 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12524 if (IS_ERR(pmu_ctx)) {
12525 err = PTR_ERR(pmu_ctx);
12528 event->pmu_ctx = pmu_ctx;
12530 if (output_event) {
12531 err = perf_event_set_output(event, output_event);
12536 if (!perf_event_validate_size(event)) {
12541 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12547 * Must be under the same ctx::mutex as perf_install_in_context(),
12548 * because we need to serialize with concurrent event creation.
12550 if (!exclusive_event_installable(event, ctx)) {
12555 WARN_ON_ONCE(ctx->parent_ctx);
12557 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
12558 if (IS_ERR(event_file)) {
12559 err = PTR_ERR(event_file);
12565 * This is the point on no return; we cannot fail hereafter. This is
12566 * where we start modifying current state.
12570 perf_remove_from_context(group_leader, 0);
12571 put_pmu_ctx(group_leader->pmu_ctx);
12573 for_each_sibling_event(sibling, group_leader) {
12574 perf_remove_from_context(sibling, 0);
12575 put_pmu_ctx(sibling->pmu_ctx);
12579 * Install the group siblings before the group leader.
12581 * Because a group leader will try and install the entire group
12582 * (through the sibling list, which is still in-tact), we can
12583 * end up with siblings installed in the wrong context.
12585 * By installing siblings first we NO-OP because they're not
12586 * reachable through the group lists.
12588 for_each_sibling_event(sibling, group_leader) {
12589 sibling->pmu_ctx = pmu_ctx;
12590 get_pmu_ctx(pmu_ctx);
12591 perf_event__state_init(sibling);
12592 perf_install_in_context(ctx, sibling, sibling->cpu);
12596 * Removing from the context ends up with disabled
12597 * event. What we want here is event in the initial
12598 * startup state, ready to be add into new context.
12600 group_leader->pmu_ctx = pmu_ctx;
12601 get_pmu_ctx(pmu_ctx);
12602 perf_event__state_init(group_leader);
12603 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12607 * Precalculate sample_data sizes; do while holding ctx::mutex such
12608 * that we're serialized against further additions and before
12609 * perf_install_in_context() which is the point the event is active and
12610 * can use these values.
12612 perf_event__header_size(event);
12613 perf_event__id_header_size(event);
12615 event->owner = current;
12617 perf_install_in_context(ctx, event, event->cpu);
12618 perf_unpin_context(ctx);
12620 mutex_unlock(&ctx->mutex);
12623 up_read(&task->signal->exec_update_lock);
12624 put_task_struct(task);
12627 mutex_lock(¤t->perf_event_mutex);
12628 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12629 mutex_unlock(¤t->perf_event_mutex);
12632 * Drop the reference on the group_event after placing the
12633 * new event on the sibling_list. This ensures destruction
12634 * of the group leader will find the pointer to itself in
12635 * perf_group_detach().
12638 fd_install(event_fd, event_file);
12642 put_pmu_ctx(event->pmu_ctx);
12643 event->pmu_ctx = NULL; /* _free_event() */
12645 mutex_unlock(&ctx->mutex);
12646 perf_unpin_context(ctx);
12650 up_read(&task->signal->exec_update_lock);
12655 put_task_struct(task);
12659 put_unused_fd(event_fd);
12664 * perf_event_create_kernel_counter
12666 * @attr: attributes of the counter to create
12667 * @cpu: cpu in which the counter is bound
12668 * @task: task to profile (NULL for percpu)
12669 * @overflow_handler: callback to trigger when we hit the event
12670 * @context: context data could be used in overflow_handler callback
12672 struct perf_event *
12673 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12674 struct task_struct *task,
12675 perf_overflow_handler_t overflow_handler,
12678 struct perf_event_pmu_context *pmu_ctx;
12679 struct perf_event_context *ctx;
12680 struct perf_event *event;
12685 * Grouping is not supported for kernel events, neither is 'AUX',
12686 * make sure the caller's intentions are adjusted.
12688 if (attr->aux_output)
12689 return ERR_PTR(-EINVAL);
12691 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12692 overflow_handler, context, -1);
12693 if (IS_ERR(event)) {
12694 err = PTR_ERR(event);
12698 /* Mark owner so we could distinguish it from user events. */
12699 event->owner = TASK_TOMBSTONE;
12702 if (pmu->task_ctx_nr == perf_sw_context)
12703 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12706 * Get the target context (task or percpu):
12708 ctx = find_get_context(task, event);
12710 err = PTR_ERR(ctx);
12714 WARN_ON_ONCE(ctx->parent_ctx);
12715 mutex_lock(&ctx->mutex);
12716 if (ctx->task == TASK_TOMBSTONE) {
12721 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12722 if (IS_ERR(pmu_ctx)) {
12723 err = PTR_ERR(pmu_ctx);
12726 event->pmu_ctx = pmu_ctx;
12730 * Check if the @cpu we're creating an event for is online.
12732 * We use the perf_cpu_context::ctx::mutex to serialize against
12733 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12735 struct perf_cpu_context *cpuctx =
12736 container_of(ctx, struct perf_cpu_context, ctx);
12737 if (!cpuctx->online) {
12743 if (!exclusive_event_installable(event, ctx)) {
12748 perf_install_in_context(ctx, event, event->cpu);
12749 perf_unpin_context(ctx);
12750 mutex_unlock(&ctx->mutex);
12755 put_pmu_ctx(pmu_ctx);
12756 event->pmu_ctx = NULL; /* _free_event() */
12758 mutex_unlock(&ctx->mutex);
12759 perf_unpin_context(ctx);
12764 return ERR_PTR(err);
12766 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12768 static void __perf_pmu_remove(struct perf_event_context *ctx,
12769 int cpu, struct pmu *pmu,
12770 struct perf_event_groups *groups,
12771 struct list_head *events)
12773 struct perf_event *event, *sibling;
12775 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
12776 perf_remove_from_context(event, 0);
12777 put_pmu_ctx(event->pmu_ctx);
12778 list_add(&event->migrate_entry, events);
12780 for_each_sibling_event(sibling, event) {
12781 perf_remove_from_context(sibling, 0);
12782 put_pmu_ctx(sibling->pmu_ctx);
12783 list_add(&sibling->migrate_entry, events);
12788 static void __perf_pmu_install_event(struct pmu *pmu,
12789 struct perf_event_context *ctx,
12790 int cpu, struct perf_event *event)
12792 struct perf_event_pmu_context *epc;
12795 epc = find_get_pmu_context(pmu, ctx, event);
12796 event->pmu_ctx = epc;
12798 if (event->state >= PERF_EVENT_STATE_OFF)
12799 event->state = PERF_EVENT_STATE_INACTIVE;
12800 perf_install_in_context(ctx, event, cpu);
12803 static void __perf_pmu_install(struct perf_event_context *ctx,
12804 int cpu, struct pmu *pmu, struct list_head *events)
12806 struct perf_event *event, *tmp;
12809 * Re-instate events in 2 passes.
12811 * Skip over group leaders and only install siblings on this first
12812 * pass, siblings will not get enabled without a leader, however a
12813 * leader will enable its siblings, even if those are still on the old
12816 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12817 if (event->group_leader == event)
12820 list_del(&event->migrate_entry);
12821 __perf_pmu_install_event(pmu, ctx, cpu, event);
12825 * Once all the siblings are setup properly, install the group leaders
12828 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12829 list_del(&event->migrate_entry);
12830 __perf_pmu_install_event(pmu, ctx, cpu, event);
12834 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12836 struct perf_event_context *src_ctx, *dst_ctx;
12839 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
12840 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
12843 * See perf_event_ctx_lock() for comments on the details
12844 * of swizzling perf_event::ctx.
12846 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12848 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
12849 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
12852 * Wait for the events to quiesce before re-instating them.
12856 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
12858 mutex_unlock(&dst_ctx->mutex);
12859 mutex_unlock(&src_ctx->mutex);
12861 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12863 static void sync_child_event(struct perf_event *child_event)
12865 struct perf_event *parent_event = child_event->parent;
12868 if (child_event->attr.inherit_stat) {
12869 struct task_struct *task = child_event->ctx->task;
12871 if (task && task != TASK_TOMBSTONE)
12872 perf_event_read_event(child_event, task);
12875 child_val = perf_event_count(child_event);
12878 * Add back the child's count to the parent's count:
12880 atomic64_add(child_val, &parent_event->child_count);
12881 atomic64_add(child_event->total_time_enabled,
12882 &parent_event->child_total_time_enabled);
12883 atomic64_add(child_event->total_time_running,
12884 &parent_event->child_total_time_running);
12888 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
12890 struct perf_event *parent_event = event->parent;
12891 unsigned long detach_flags = 0;
12893 if (parent_event) {
12895 * Do not destroy the 'original' grouping; because of the
12896 * context switch optimization the original events could've
12897 * ended up in a random child task.
12899 * If we were to destroy the original group, all group related
12900 * operations would cease to function properly after this
12901 * random child dies.
12903 * Do destroy all inherited groups, we don't care about those
12904 * and being thorough is better.
12906 detach_flags = DETACH_GROUP | DETACH_CHILD;
12907 mutex_lock(&parent_event->child_mutex);
12910 perf_remove_from_context(event, detach_flags);
12912 raw_spin_lock_irq(&ctx->lock);
12913 if (event->state > PERF_EVENT_STATE_EXIT)
12914 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
12915 raw_spin_unlock_irq(&ctx->lock);
12918 * Child events can be freed.
12920 if (parent_event) {
12921 mutex_unlock(&parent_event->child_mutex);
12923 * Kick perf_poll() for is_event_hup();
12925 perf_event_wakeup(parent_event);
12927 put_event(parent_event);
12932 * Parent events are governed by their filedesc, retain them.
12934 perf_event_wakeup(event);
12937 static void perf_event_exit_task_context(struct task_struct *child)
12939 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12940 struct perf_event *child_event, *next;
12942 WARN_ON_ONCE(child != current);
12944 child_ctx = perf_pin_task_context(child);
12949 * In order to reduce the amount of tricky in ctx tear-down, we hold
12950 * ctx::mutex over the entire thing. This serializes against almost
12951 * everything that wants to access the ctx.
12953 * The exception is sys_perf_event_open() /
12954 * perf_event_create_kernel_count() which does find_get_context()
12955 * without ctx::mutex (it cannot because of the move_group double mutex
12956 * lock thing). See the comments in perf_install_in_context().
12958 mutex_lock(&child_ctx->mutex);
12961 * In a single ctx::lock section, de-schedule the events and detach the
12962 * context from the task such that we cannot ever get it scheduled back
12965 raw_spin_lock_irq(&child_ctx->lock);
12966 task_ctx_sched_out(child_ctx, EVENT_ALL);
12969 * Now that the context is inactive, destroy the task <-> ctx relation
12970 * and mark the context dead.
12972 RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
12973 put_ctx(child_ctx); /* cannot be last */
12974 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12975 put_task_struct(current); /* cannot be last */
12977 clone_ctx = unclone_ctx(child_ctx);
12978 raw_spin_unlock_irq(&child_ctx->lock);
12981 put_ctx(clone_ctx);
12984 * Report the task dead after unscheduling the events so that we
12985 * won't get any samples after PERF_RECORD_EXIT. We can however still
12986 * get a few PERF_RECORD_READ events.
12988 perf_event_task(child, child_ctx, 0);
12990 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12991 perf_event_exit_event(child_event, child_ctx);
12993 mutex_unlock(&child_ctx->mutex);
12995 put_ctx(child_ctx);
12999 * When a child task exits, feed back event values to parent events.
13001 * Can be called with exec_update_lock held when called from
13002 * setup_new_exec().
13004 void perf_event_exit_task(struct task_struct *child)
13006 struct perf_event *event, *tmp;
13008 mutex_lock(&child->perf_event_mutex);
13009 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
13011 list_del_init(&event->owner_entry);
13014 * Ensure the list deletion is visible before we clear
13015 * the owner, closes a race against perf_release() where
13016 * we need to serialize on the owner->perf_event_mutex.
13018 smp_store_release(&event->owner, NULL);
13020 mutex_unlock(&child->perf_event_mutex);
13022 perf_event_exit_task_context(child);
13025 * The perf_event_exit_task_context calls perf_event_task
13026 * with child's task_ctx, which generates EXIT events for
13027 * child contexts and sets child->perf_event_ctxp[] to NULL.
13028 * At this point we need to send EXIT events to cpu contexts.
13030 perf_event_task(child, NULL, 0);
13033 static void perf_free_event(struct perf_event *event,
13034 struct perf_event_context *ctx)
13036 struct perf_event *parent = event->parent;
13038 if (WARN_ON_ONCE(!parent))
13041 mutex_lock(&parent->child_mutex);
13042 list_del_init(&event->child_list);
13043 mutex_unlock(&parent->child_mutex);
13047 raw_spin_lock_irq(&ctx->lock);
13048 perf_group_detach(event);
13049 list_del_event(event, ctx);
13050 raw_spin_unlock_irq(&ctx->lock);
13055 * Free a context as created by inheritance by perf_event_init_task() below,
13056 * used by fork() in case of fail.
13058 * Even though the task has never lived, the context and events have been
13059 * exposed through the child_list, so we must take care tearing it all down.
13061 void perf_event_free_task(struct task_struct *task)
13063 struct perf_event_context *ctx;
13064 struct perf_event *event, *tmp;
13066 ctx = rcu_access_pointer(task->perf_event_ctxp);
13070 mutex_lock(&ctx->mutex);
13071 raw_spin_lock_irq(&ctx->lock);
13073 * Destroy the task <-> ctx relation and mark the context dead.
13075 * This is important because even though the task hasn't been
13076 * exposed yet the context has been (through child_list).
13078 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
13079 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13080 put_task_struct(task); /* cannot be last */
13081 raw_spin_unlock_irq(&ctx->lock);
13084 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13085 perf_free_event(event, ctx);
13087 mutex_unlock(&ctx->mutex);
13090 * perf_event_release_kernel() could've stolen some of our
13091 * child events and still have them on its free_list. In that
13092 * case we must wait for these events to have been freed (in
13093 * particular all their references to this task must've been
13096 * Without this copy_process() will unconditionally free this
13097 * task (irrespective of its reference count) and
13098 * _free_event()'s put_task_struct(event->hw.target) will be a
13101 * Wait for all events to drop their context reference.
13103 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13104 put_ctx(ctx); /* must be last */
13107 void perf_event_delayed_put(struct task_struct *task)
13109 WARN_ON_ONCE(task->perf_event_ctxp);
13112 struct file *perf_event_get(unsigned int fd)
13114 struct file *file = fget(fd);
13116 return ERR_PTR(-EBADF);
13118 if (file->f_op != &perf_fops) {
13120 return ERR_PTR(-EBADF);
13126 const struct perf_event *perf_get_event(struct file *file)
13128 if (file->f_op != &perf_fops)
13129 return ERR_PTR(-EINVAL);
13131 return file->private_data;
13134 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13137 return ERR_PTR(-EINVAL);
13139 return &event->attr;
13143 * Inherit an event from parent task to child task.
13146 * - valid pointer on success
13147 * - NULL for orphaned events
13148 * - IS_ERR() on error
13150 static struct perf_event *
13151 inherit_event(struct perf_event *parent_event,
13152 struct task_struct *parent,
13153 struct perf_event_context *parent_ctx,
13154 struct task_struct *child,
13155 struct perf_event *group_leader,
13156 struct perf_event_context *child_ctx)
13158 enum perf_event_state parent_state = parent_event->state;
13159 struct perf_event_pmu_context *pmu_ctx;
13160 struct perf_event *child_event;
13161 unsigned long flags;
13164 * Instead of creating recursive hierarchies of events,
13165 * we link inherited events back to the original parent,
13166 * which has a filp for sure, which we use as the reference
13169 if (parent_event->parent)
13170 parent_event = parent_event->parent;
13172 child_event = perf_event_alloc(&parent_event->attr,
13175 group_leader, parent_event,
13177 if (IS_ERR(child_event))
13178 return child_event;
13180 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
13181 if (IS_ERR(pmu_ctx)) {
13182 free_event(child_event);
13183 return ERR_CAST(pmu_ctx);
13185 child_event->pmu_ctx = pmu_ctx;
13188 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13189 * must be under the same lock in order to serialize against
13190 * perf_event_release_kernel(), such that either we must observe
13191 * is_orphaned_event() or they will observe us on the child_list.
13193 mutex_lock(&parent_event->child_mutex);
13194 if (is_orphaned_event(parent_event) ||
13195 !atomic_long_inc_not_zero(&parent_event->refcount)) {
13196 mutex_unlock(&parent_event->child_mutex);
13197 /* task_ctx_data is freed with child_ctx */
13198 free_event(child_event);
13202 get_ctx(child_ctx);
13205 * Make the child state follow the state of the parent event,
13206 * not its attr.disabled bit. We hold the parent's mutex,
13207 * so we won't race with perf_event_{en, dis}able_family.
13209 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13210 child_event->state = PERF_EVENT_STATE_INACTIVE;
13212 child_event->state = PERF_EVENT_STATE_OFF;
13214 if (parent_event->attr.freq) {
13215 u64 sample_period = parent_event->hw.sample_period;
13216 struct hw_perf_event *hwc = &child_event->hw;
13218 hwc->sample_period = sample_period;
13219 hwc->last_period = sample_period;
13221 local64_set(&hwc->period_left, sample_period);
13224 child_event->ctx = child_ctx;
13225 child_event->overflow_handler = parent_event->overflow_handler;
13226 child_event->overflow_handler_context
13227 = parent_event->overflow_handler_context;
13230 * Precalculate sample_data sizes
13232 perf_event__header_size(child_event);
13233 perf_event__id_header_size(child_event);
13236 * Link it up in the child's context:
13238 raw_spin_lock_irqsave(&child_ctx->lock, flags);
13239 add_event_to_ctx(child_event, child_ctx);
13240 child_event->attach_state |= PERF_ATTACH_CHILD;
13241 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13244 * Link this into the parent event's child list
13246 list_add_tail(&child_event->child_list, &parent_event->child_list);
13247 mutex_unlock(&parent_event->child_mutex);
13249 return child_event;
13253 * Inherits an event group.
13255 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13256 * This matches with perf_event_release_kernel() removing all child events.
13262 static int inherit_group(struct perf_event *parent_event,
13263 struct task_struct *parent,
13264 struct perf_event_context *parent_ctx,
13265 struct task_struct *child,
13266 struct perf_event_context *child_ctx)
13268 struct perf_event *leader;
13269 struct perf_event *sub;
13270 struct perf_event *child_ctr;
13272 leader = inherit_event(parent_event, parent, parent_ctx,
13273 child, NULL, child_ctx);
13274 if (IS_ERR(leader))
13275 return PTR_ERR(leader);
13277 * @leader can be NULL here because of is_orphaned_event(). In this
13278 * case inherit_event() will create individual events, similar to what
13279 * perf_group_detach() would do anyway.
13281 for_each_sibling_event(sub, parent_event) {
13282 child_ctr = inherit_event(sub, parent, parent_ctx,
13283 child, leader, child_ctx);
13284 if (IS_ERR(child_ctr))
13285 return PTR_ERR(child_ctr);
13287 if (sub->aux_event == parent_event && child_ctr &&
13288 !perf_get_aux_event(child_ctr, leader))
13295 * Creates the child task context and tries to inherit the event-group.
13297 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13298 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13299 * consistent with perf_event_release_kernel() removing all child events.
13306 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13307 struct perf_event_context *parent_ctx,
13308 struct task_struct *child,
13309 u64 clone_flags, int *inherited_all)
13311 struct perf_event_context *child_ctx;
13314 if (!event->attr.inherit ||
13315 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13316 /* Do not inherit if sigtrap and signal handlers were cleared. */
13317 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13318 *inherited_all = 0;
13322 child_ctx = child->perf_event_ctxp;
13325 * This is executed from the parent task context, so
13326 * inherit events that have been marked for cloning.
13327 * First allocate and initialize a context for the
13330 child_ctx = alloc_perf_context(child);
13334 child->perf_event_ctxp = child_ctx;
13337 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
13339 *inherited_all = 0;
13345 * Initialize the perf_event context in task_struct
13347 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
13349 struct perf_event_context *child_ctx, *parent_ctx;
13350 struct perf_event_context *cloned_ctx;
13351 struct perf_event *event;
13352 struct task_struct *parent = current;
13353 int inherited_all = 1;
13354 unsigned long flags;
13357 if (likely(!parent->perf_event_ctxp))
13361 * If the parent's context is a clone, pin it so it won't get
13362 * swapped under us.
13364 parent_ctx = perf_pin_task_context(parent);
13369 * No need to check if parent_ctx != NULL here; since we saw
13370 * it non-NULL earlier, the only reason for it to become NULL
13371 * is if we exit, and since we're currently in the middle of
13372 * a fork we can't be exiting at the same time.
13376 * Lock the parent list. No need to lock the child - not PID
13377 * hashed yet and not running, so nobody can access it.
13379 mutex_lock(&parent_ctx->mutex);
13382 * We dont have to disable NMIs - we are only looking at
13383 * the list, not manipulating it:
13385 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13386 ret = inherit_task_group(event, parent, parent_ctx,
13387 child, clone_flags, &inherited_all);
13393 * We can't hold ctx->lock when iterating the ->flexible_group list due
13394 * to allocations, but we need to prevent rotation because
13395 * rotate_ctx() will change the list from interrupt context.
13397 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13398 parent_ctx->rotate_disable = 1;
13399 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13401 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13402 ret = inherit_task_group(event, parent, parent_ctx,
13403 child, clone_flags, &inherited_all);
13408 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13409 parent_ctx->rotate_disable = 0;
13411 child_ctx = child->perf_event_ctxp;
13413 if (child_ctx && inherited_all) {
13415 * Mark the child context as a clone of the parent
13416 * context, or of whatever the parent is a clone of.
13418 * Note that if the parent is a clone, the holding of
13419 * parent_ctx->lock avoids it from being uncloned.
13421 cloned_ctx = parent_ctx->parent_ctx;
13423 child_ctx->parent_ctx = cloned_ctx;
13424 child_ctx->parent_gen = parent_ctx->parent_gen;
13426 child_ctx->parent_ctx = parent_ctx;
13427 child_ctx->parent_gen = parent_ctx->generation;
13429 get_ctx(child_ctx->parent_ctx);
13432 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13434 mutex_unlock(&parent_ctx->mutex);
13436 perf_unpin_context(parent_ctx);
13437 put_ctx(parent_ctx);
13443 * Initialize the perf_event context in task_struct
13445 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
13449 child->perf_event_ctxp = NULL;
13450 mutex_init(&child->perf_event_mutex);
13451 INIT_LIST_HEAD(&child->perf_event_list);
13453 ret = perf_event_init_context(child, clone_flags);
13455 perf_event_free_task(child);
13462 static void __init perf_event_init_all_cpus(void)
13464 struct swevent_htable *swhash;
13465 struct perf_cpu_context *cpuctx;
13468 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13470 for_each_possible_cpu(cpu) {
13471 swhash = &per_cpu(swevent_htable, cpu);
13472 mutex_init(&swhash->hlist_mutex);
13474 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13475 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13477 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13479 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13480 __perf_event_init_context(&cpuctx->ctx);
13481 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
13482 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
13483 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
13484 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
13485 cpuctx->heap = cpuctx->heap_default;
13489 static void perf_swevent_init_cpu(unsigned int cpu)
13491 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13493 mutex_lock(&swhash->hlist_mutex);
13494 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13495 struct swevent_hlist *hlist;
13497 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13499 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13501 mutex_unlock(&swhash->hlist_mutex);
13504 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13505 static void __perf_event_exit_context(void *__info)
13507 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
13508 struct perf_event_context *ctx = __info;
13509 struct perf_event *event;
13511 raw_spin_lock(&ctx->lock);
13512 ctx_sched_out(ctx, EVENT_TIME);
13513 list_for_each_entry(event, &ctx->event_list, event_entry)
13514 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13515 raw_spin_unlock(&ctx->lock);
13518 static void perf_event_exit_cpu_context(int cpu)
13520 struct perf_cpu_context *cpuctx;
13521 struct perf_event_context *ctx;
13523 // XXX simplify cpuctx->online
13524 mutex_lock(&pmus_lock);
13525 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13526 ctx = &cpuctx->ctx;
13528 mutex_lock(&ctx->mutex);
13529 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13530 cpuctx->online = 0;
13531 mutex_unlock(&ctx->mutex);
13532 cpumask_clear_cpu(cpu, perf_online_mask);
13533 mutex_unlock(&pmus_lock);
13537 static void perf_event_exit_cpu_context(int cpu) { }
13541 int perf_event_init_cpu(unsigned int cpu)
13543 struct perf_cpu_context *cpuctx;
13544 struct perf_event_context *ctx;
13546 perf_swevent_init_cpu(cpu);
13548 mutex_lock(&pmus_lock);
13549 cpumask_set_cpu(cpu, perf_online_mask);
13550 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13551 ctx = &cpuctx->ctx;
13553 mutex_lock(&ctx->mutex);
13554 cpuctx->online = 1;
13555 mutex_unlock(&ctx->mutex);
13556 mutex_unlock(&pmus_lock);
13561 int perf_event_exit_cpu(unsigned int cpu)
13563 perf_event_exit_cpu_context(cpu);
13568 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13572 for_each_online_cpu(cpu)
13573 perf_event_exit_cpu(cpu);
13579 * Run the perf reboot notifier at the very last possible moment so that
13580 * the generic watchdog code runs as long as possible.
13582 static struct notifier_block perf_reboot_notifier = {
13583 .notifier_call = perf_reboot,
13584 .priority = INT_MIN,
13587 void __init perf_event_init(void)
13591 idr_init(&pmu_idr);
13593 perf_event_init_all_cpus();
13594 init_srcu_struct(&pmus_srcu);
13595 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13596 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13597 perf_pmu_register(&perf_task_clock, NULL, -1);
13598 perf_tp_register();
13599 perf_event_init_cpu(smp_processor_id());
13600 register_reboot_notifier(&perf_reboot_notifier);
13602 ret = init_hw_breakpoint();
13603 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13605 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13608 * Build time assertion that we keep the data_head at the intended
13609 * location. IOW, validation we got the __reserved[] size right.
13611 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13615 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13618 struct perf_pmu_events_attr *pmu_attr =
13619 container_of(attr, struct perf_pmu_events_attr, attr);
13621 if (pmu_attr->event_str)
13622 return sprintf(page, "%s\n", pmu_attr->event_str);
13626 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13628 static int __init perf_event_sysfs_init(void)
13633 mutex_lock(&pmus_lock);
13635 ret = bus_register(&pmu_bus);
13639 list_for_each_entry(pmu, &pmus, entry) {
13640 if (!pmu->name || pmu->type < 0)
13643 ret = pmu_dev_alloc(pmu);
13644 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13646 pmu_bus_running = 1;
13650 mutex_unlock(&pmus_lock);
13654 device_initcall(perf_event_sysfs_init);
13656 #ifdef CONFIG_CGROUP_PERF
13657 static struct cgroup_subsys_state *
13658 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13660 struct perf_cgroup *jc;
13662 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13664 return ERR_PTR(-ENOMEM);
13666 jc->info = alloc_percpu(struct perf_cgroup_info);
13669 return ERR_PTR(-ENOMEM);
13675 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13677 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13679 free_percpu(jc->info);
13683 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13685 perf_event_cgroup(css->cgroup);
13689 static int __perf_cgroup_move(void *info)
13691 struct task_struct *task = info;
13694 perf_cgroup_switch(task);
13700 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13702 struct task_struct *task;
13703 struct cgroup_subsys_state *css;
13705 cgroup_taskset_for_each(task, css, tset)
13706 task_function_call(task, __perf_cgroup_move, task);
13709 struct cgroup_subsys perf_event_cgrp_subsys = {
13710 .css_alloc = perf_cgroup_css_alloc,
13711 .css_free = perf_cgroup_css_free,
13712 .css_online = perf_cgroup_css_online,
13713 .attach = perf_cgroup_attach,
13715 * Implicitly enable on dfl hierarchy so that perf events can
13716 * always be filtered by cgroup2 path as long as perf_event
13717 * controller is not mounted on a legacy hierarchy.
13719 .implicit_on_dfl = true,
13722 #endif /* CONFIG_CGROUP_PERF */
13724 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);