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 inline struct perf_cpu_context *
159 __get_cpu_context(struct perf_event_context *ctx)
161 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
164 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
165 struct perf_event_context *ctx)
167 raw_spin_lock(&cpuctx->ctx.lock);
169 raw_spin_lock(&ctx->lock);
172 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
173 struct perf_event_context *ctx)
176 raw_spin_unlock(&ctx->lock);
177 raw_spin_unlock(&cpuctx->ctx.lock);
180 #define TASK_TOMBSTONE ((void *)-1L)
182 static bool is_kernel_event(struct perf_event *event)
184 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
188 * On task ctx scheduling...
190 * When !ctx->nr_events a task context will not be scheduled. This means
191 * we can disable the scheduler hooks (for performance) without leaving
192 * pending task ctx state.
194 * This however results in two special cases:
196 * - removing the last event from a task ctx; this is relatively straight
197 * forward and is done in __perf_remove_from_context.
199 * - adding the first event to a task ctx; this is tricky because we cannot
200 * rely on ctx->is_active and therefore cannot use event_function_call().
201 * See perf_install_in_context().
203 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
206 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
207 struct perf_event_context *, void *);
209 struct event_function_struct {
210 struct perf_event *event;
215 static int event_function(void *info)
217 struct event_function_struct *efs = info;
218 struct perf_event *event = efs->event;
219 struct perf_event_context *ctx = event->ctx;
220 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
221 struct perf_event_context *task_ctx = cpuctx->task_ctx;
224 lockdep_assert_irqs_disabled();
226 perf_ctx_lock(cpuctx, task_ctx);
228 * Since we do the IPI call without holding ctx->lock things can have
229 * changed, double check we hit the task we set out to hit.
232 if (ctx->task != current) {
238 * We only use event_function_call() on established contexts,
239 * and event_function() is only ever called when active (or
240 * rather, we'll have bailed in task_function_call() or the
241 * above ctx->task != current test), therefore we must have
242 * ctx->is_active here.
244 WARN_ON_ONCE(!ctx->is_active);
246 * And since we have ctx->is_active, cpuctx->task_ctx must
249 WARN_ON_ONCE(task_ctx != ctx);
251 WARN_ON_ONCE(&cpuctx->ctx != ctx);
254 efs->func(event, cpuctx, ctx, efs->data);
256 perf_ctx_unlock(cpuctx, task_ctx);
261 static void event_function_call(struct perf_event *event, event_f func, void *data)
263 struct perf_event_context *ctx = event->ctx;
264 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
265 struct event_function_struct efs = {
271 if (!event->parent) {
273 * If this is a !child event, we must hold ctx::mutex to
274 * stabilize the event->ctx relation. See
275 * perf_event_ctx_lock().
277 lockdep_assert_held(&ctx->mutex);
281 cpu_function_call(event->cpu, event_function, &efs);
285 if (task == TASK_TOMBSTONE)
289 if (!task_function_call(task, event_function, &efs))
292 raw_spin_lock_irq(&ctx->lock);
294 * Reload the task pointer, it might have been changed by
295 * a concurrent perf_event_context_sched_out().
298 if (task == TASK_TOMBSTONE) {
299 raw_spin_unlock_irq(&ctx->lock);
302 if (ctx->is_active) {
303 raw_spin_unlock_irq(&ctx->lock);
306 func(event, NULL, ctx, data);
307 raw_spin_unlock_irq(&ctx->lock);
311 * Similar to event_function_call() + event_function(), but hard assumes IRQs
312 * are already disabled and we're on the right CPU.
314 static void event_function_local(struct perf_event *event, event_f func, void *data)
316 struct perf_event_context *ctx = event->ctx;
317 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
318 struct task_struct *task = READ_ONCE(ctx->task);
319 struct perf_event_context *task_ctx = NULL;
321 lockdep_assert_irqs_disabled();
324 if (task == TASK_TOMBSTONE)
330 perf_ctx_lock(cpuctx, task_ctx);
333 if (task == TASK_TOMBSTONE)
338 * We must be either inactive or active and the right task,
339 * otherwise we're screwed, since we cannot IPI to somewhere
342 if (ctx->is_active) {
343 if (WARN_ON_ONCE(task != current))
346 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
350 WARN_ON_ONCE(&cpuctx->ctx != ctx);
353 func(event, cpuctx, ctx, data);
355 perf_ctx_unlock(cpuctx, task_ctx);
358 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
359 PERF_FLAG_FD_OUTPUT |\
360 PERF_FLAG_PID_CGROUP |\
361 PERF_FLAG_FD_CLOEXEC)
364 * branch priv levels that need permission checks
366 #define PERF_SAMPLE_BRANCH_PERM_PLM \
367 (PERF_SAMPLE_BRANCH_KERNEL |\
368 PERF_SAMPLE_BRANCH_HV)
371 EVENT_FLEXIBLE = 0x1,
374 /* see ctx_resched() for details */
376 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
380 * perf_sched_events : >0 events exist
381 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
384 static void perf_sched_delayed(struct work_struct *work);
385 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
386 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
387 static DEFINE_MUTEX(perf_sched_mutex);
388 static atomic_t perf_sched_count;
390 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
391 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
392 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
394 static atomic_t nr_mmap_events __read_mostly;
395 static atomic_t nr_comm_events __read_mostly;
396 static atomic_t nr_namespaces_events __read_mostly;
397 static atomic_t nr_task_events __read_mostly;
398 static atomic_t nr_freq_events __read_mostly;
399 static atomic_t nr_switch_events __read_mostly;
400 static atomic_t nr_ksymbol_events __read_mostly;
401 static atomic_t nr_bpf_events __read_mostly;
402 static atomic_t nr_cgroup_events __read_mostly;
403 static atomic_t nr_text_poke_events __read_mostly;
404 static atomic_t nr_build_id_events __read_mostly;
406 static LIST_HEAD(pmus);
407 static DEFINE_MUTEX(pmus_lock);
408 static struct srcu_struct pmus_srcu;
409 static cpumask_var_t perf_online_mask;
410 static struct kmem_cache *perf_event_cache;
413 * perf event paranoia level:
414 * -1 - not paranoid at all
415 * 0 - disallow raw tracepoint access for unpriv
416 * 1 - disallow cpu events for unpriv
417 * 2 - disallow kernel profiling for unpriv
419 int sysctl_perf_event_paranoid __read_mostly = 2;
421 /* Minimum for 512 kiB + 1 user control page */
422 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
425 * max perf event sample rate
427 #define DEFAULT_MAX_SAMPLE_RATE 100000
428 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
429 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
431 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
433 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
434 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
436 static int perf_sample_allowed_ns __read_mostly =
437 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
439 static void update_perf_cpu_limits(void)
441 u64 tmp = perf_sample_period_ns;
443 tmp *= sysctl_perf_cpu_time_max_percent;
444 tmp = div_u64(tmp, 100);
448 WRITE_ONCE(perf_sample_allowed_ns, tmp);
451 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
453 int perf_proc_update_handler(struct ctl_table *table, int write,
454 void *buffer, size_t *lenp, loff_t *ppos)
457 int perf_cpu = sysctl_perf_cpu_time_max_percent;
459 * If throttling is disabled don't allow the write:
461 if (write && (perf_cpu == 100 || perf_cpu == 0))
464 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
468 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
469 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
470 update_perf_cpu_limits();
475 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
477 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
478 void *buffer, size_t *lenp, loff_t *ppos)
480 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
485 if (sysctl_perf_cpu_time_max_percent == 100 ||
486 sysctl_perf_cpu_time_max_percent == 0) {
488 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
489 WRITE_ONCE(perf_sample_allowed_ns, 0);
491 update_perf_cpu_limits();
498 * perf samples are done in some very critical code paths (NMIs).
499 * If they take too much CPU time, the system can lock up and not
500 * get any real work done. This will drop the sample rate when
501 * we detect that events are taking too long.
503 #define NR_ACCUMULATED_SAMPLES 128
504 static DEFINE_PER_CPU(u64, running_sample_length);
506 static u64 __report_avg;
507 static u64 __report_allowed;
509 static void perf_duration_warn(struct irq_work *w)
511 printk_ratelimited(KERN_INFO
512 "perf: interrupt took too long (%lld > %lld), lowering "
513 "kernel.perf_event_max_sample_rate to %d\n",
514 __report_avg, __report_allowed,
515 sysctl_perf_event_sample_rate);
518 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
520 void perf_sample_event_took(u64 sample_len_ns)
522 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
530 /* Decay the counter by 1 average sample. */
531 running_len = __this_cpu_read(running_sample_length);
532 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
533 running_len += sample_len_ns;
534 __this_cpu_write(running_sample_length, running_len);
537 * Note: this will be biased artifically low until we have
538 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
539 * from having to maintain a count.
541 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
542 if (avg_len <= max_len)
545 __report_avg = avg_len;
546 __report_allowed = max_len;
549 * Compute a throttle threshold 25% below the current duration.
551 avg_len += avg_len / 4;
552 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
558 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
559 WRITE_ONCE(max_samples_per_tick, max);
561 sysctl_perf_event_sample_rate = max * HZ;
562 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
564 if (!irq_work_queue(&perf_duration_work)) {
565 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
566 "kernel.perf_event_max_sample_rate to %d\n",
567 __report_avg, __report_allowed,
568 sysctl_perf_event_sample_rate);
572 static atomic64_t perf_event_id;
574 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
575 enum event_type_t event_type);
577 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
578 enum event_type_t event_type);
580 static void update_context_time(struct perf_event_context *ctx);
581 static u64 perf_event_time(struct perf_event *event);
583 void __weak perf_event_print_debug(void) { }
585 static inline u64 perf_clock(void)
587 return local_clock();
590 static inline u64 perf_event_clock(struct perf_event *event)
592 return event->clock();
596 * State based event timekeeping...
598 * The basic idea is to use event->state to determine which (if any) time
599 * fields to increment with the current delta. This means we only need to
600 * update timestamps when we change state or when they are explicitly requested
603 * Event groups make things a little more complicated, but not terribly so. The
604 * rules for a group are that if the group leader is OFF the entire group is
605 * OFF, irrespecive of what the group member states are. This results in
606 * __perf_effective_state().
608 * A futher ramification is that when a group leader flips between OFF and
609 * !OFF, we need to update all group member times.
612 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
613 * need to make sure the relevant context time is updated before we try and
614 * update our timestamps.
617 static __always_inline enum perf_event_state
618 __perf_effective_state(struct perf_event *event)
620 struct perf_event *leader = event->group_leader;
622 if (leader->state <= PERF_EVENT_STATE_OFF)
623 return leader->state;
628 static __always_inline void
629 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
631 enum perf_event_state state = __perf_effective_state(event);
632 u64 delta = now - event->tstamp;
634 *enabled = event->total_time_enabled;
635 if (state >= PERF_EVENT_STATE_INACTIVE)
638 *running = event->total_time_running;
639 if (state >= PERF_EVENT_STATE_ACTIVE)
643 static void perf_event_update_time(struct perf_event *event)
645 u64 now = perf_event_time(event);
647 __perf_update_times(event, now, &event->total_time_enabled,
648 &event->total_time_running);
652 static void perf_event_update_sibling_time(struct perf_event *leader)
654 struct perf_event *sibling;
656 for_each_sibling_event(sibling, leader)
657 perf_event_update_time(sibling);
661 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
663 if (event->state == state)
666 perf_event_update_time(event);
668 * If a group leader gets enabled/disabled all its siblings
671 if ((event->state < 0) ^ (state < 0))
672 perf_event_update_sibling_time(event);
674 WRITE_ONCE(event->state, state);
678 * UP store-release, load-acquire
681 #define __store_release(ptr, val) \
684 WRITE_ONCE(*(ptr), (val)); \
687 #define __load_acquire(ptr) \
689 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
694 #ifdef CONFIG_CGROUP_PERF
697 perf_cgroup_match(struct perf_event *event)
699 struct perf_event_context *ctx = event->ctx;
700 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
702 /* @event doesn't care about cgroup */
706 /* wants specific cgroup scope but @cpuctx isn't associated with any */
711 * Cgroup scoping is recursive. An event enabled for a cgroup is
712 * also enabled for all its descendant cgroups. If @cpuctx's
713 * cgroup is a descendant of @event's (the test covers identity
714 * case), it's a match.
716 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
717 event->cgrp->css.cgroup);
720 static inline void perf_detach_cgroup(struct perf_event *event)
722 css_put(&event->cgrp->css);
726 static inline int is_cgroup_event(struct perf_event *event)
728 return event->cgrp != NULL;
731 static inline u64 perf_cgroup_event_time(struct perf_event *event)
733 struct perf_cgroup_info *t;
735 t = per_cpu_ptr(event->cgrp->info, event->cpu);
739 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
741 struct perf_cgroup_info *t;
743 t = per_cpu_ptr(event->cgrp->info, event->cpu);
744 if (!__load_acquire(&t->active))
746 now += READ_ONCE(t->timeoffset);
750 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
753 info->time += now - info->timestamp;
754 info->timestamp = now;
756 * see update_context_time()
758 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
761 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
763 struct perf_cgroup *cgrp = cpuctx->cgrp;
764 struct cgroup_subsys_state *css;
765 struct perf_cgroup_info *info;
768 u64 now = perf_clock();
770 for (css = &cgrp->css; css; css = css->parent) {
771 cgrp = container_of(css, struct perf_cgroup, css);
772 info = this_cpu_ptr(cgrp->info);
774 __update_cgrp_time(info, now, true);
776 __store_release(&info->active, 0);
781 static inline void update_cgrp_time_from_event(struct perf_event *event)
783 struct perf_cgroup_info *info;
786 * ensure we access cgroup data only when needed and
787 * when we know the cgroup is pinned (css_get)
789 if (!is_cgroup_event(event))
792 info = this_cpu_ptr(event->cgrp->info);
794 * Do not update time when cgroup is not active
797 __update_cgrp_time(info, perf_clock(), true);
801 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
803 struct perf_event_context *ctx = &cpuctx->ctx;
804 struct perf_cgroup *cgrp = cpuctx->cgrp;
805 struct perf_cgroup_info *info;
806 struct cgroup_subsys_state *css;
809 * ctx->lock held by caller
810 * ensure we do not access cgroup data
811 * unless we have the cgroup pinned (css_get)
816 WARN_ON_ONCE(!ctx->nr_cgroups);
818 for (css = &cgrp->css; css; css = css->parent) {
819 cgrp = container_of(css, struct perf_cgroup, css);
820 info = this_cpu_ptr(cgrp->info);
821 __update_cgrp_time(info, ctx->timestamp, false);
822 __store_release(&info->active, 1);
826 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
829 * reschedule events based on the cgroup constraint of task.
831 static void perf_cgroup_switch(struct task_struct *task)
833 struct perf_cgroup *cgrp;
834 struct perf_cpu_context *cpuctx, *tmp;
835 struct list_head *list;
839 * Disable interrupts and preemption to avoid this CPU's
840 * cgrp_cpuctx_entry to change under us.
842 local_irq_save(flags);
844 cgrp = perf_cgroup_from_task(task, NULL);
846 list = this_cpu_ptr(&cgrp_cpuctx_list);
847 list_for_each_entry_safe(cpuctx, tmp, list, cgrp_cpuctx_entry) {
848 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
849 if (READ_ONCE(cpuctx->cgrp) == cgrp)
852 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
853 perf_pmu_disable(cpuctx->ctx.pmu);
855 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
857 * must not be done before ctxswout due
858 * to update_cgrp_time_from_cpuctx() in
863 * set cgrp before ctxsw in to allow
864 * perf_cgroup_set_timestamp() in ctx_sched_in()
865 * to not have to pass task around
867 cpu_ctx_sched_in(cpuctx, EVENT_ALL);
869 perf_pmu_enable(cpuctx->ctx.pmu);
870 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
873 local_irq_restore(flags);
876 static int perf_cgroup_ensure_storage(struct perf_event *event,
877 struct cgroup_subsys_state *css)
879 struct perf_cpu_context *cpuctx;
880 struct perf_event **storage;
881 int cpu, heap_size, ret = 0;
884 * Allow storage to have sufficent space for an iterator for each
885 * possibly nested cgroup plus an iterator for events with no cgroup.
887 for (heap_size = 1; css; css = css->parent)
890 for_each_possible_cpu(cpu) {
891 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
892 if (heap_size <= cpuctx->heap_size)
895 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
896 GFP_KERNEL, cpu_to_node(cpu));
902 raw_spin_lock_irq(&cpuctx->ctx.lock);
903 if (cpuctx->heap_size < heap_size) {
904 swap(cpuctx->heap, storage);
905 if (storage == cpuctx->heap_default)
907 cpuctx->heap_size = heap_size;
909 raw_spin_unlock_irq(&cpuctx->ctx.lock);
917 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
918 struct perf_event_attr *attr,
919 struct perf_event *group_leader)
921 struct perf_cgroup *cgrp;
922 struct cgroup_subsys_state *css;
923 struct fd f = fdget(fd);
929 css = css_tryget_online_from_dir(f.file->f_path.dentry,
930 &perf_event_cgrp_subsys);
936 ret = perf_cgroup_ensure_storage(event, css);
940 cgrp = container_of(css, struct perf_cgroup, css);
944 * all events in a group must monitor
945 * the same cgroup because a task belongs
946 * to only one perf cgroup at a time
948 if (group_leader && group_leader->cgrp != cgrp) {
949 perf_detach_cgroup(event);
958 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
960 struct perf_cpu_context *cpuctx;
962 if (!is_cgroup_event(event))
966 * Because cgroup events are always per-cpu events,
967 * @ctx == &cpuctx->ctx.
969 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
971 if (ctx->nr_cgroups++)
974 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
975 list_add(&cpuctx->cgrp_cpuctx_entry,
976 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
980 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
982 struct perf_cpu_context *cpuctx;
984 if (!is_cgroup_event(event))
988 * Because cgroup events are always per-cpu events,
989 * @ctx == &cpuctx->ctx.
991 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
993 if (--ctx->nr_cgroups)
997 list_del(&cpuctx->cgrp_cpuctx_entry);
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_context *cpuctx;
1075 lockdep_assert_irqs_disabled();
1077 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1078 rotations = perf_rotate_context(cpuctx);
1080 raw_spin_lock(&cpuctx->hrtimer_lock);
1082 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1084 cpuctx->hrtimer_active = 0;
1085 raw_spin_unlock(&cpuctx->hrtimer_lock);
1087 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1090 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1092 struct hrtimer *timer = &cpuctx->hrtimer;
1093 struct pmu *pmu = cpuctx->ctx.pmu;
1096 /* no multiplexing needed for SW PMU */
1097 if (pmu->task_ctx_nr == perf_sw_context)
1101 * check default is sane, if not set then force to
1102 * default interval (1/tick)
1104 interval = pmu->hrtimer_interval_ms;
1106 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1108 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1110 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1111 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1112 timer->function = perf_mux_hrtimer_handler;
1115 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1117 struct hrtimer *timer = &cpuctx->hrtimer;
1118 struct pmu *pmu = cpuctx->ctx.pmu;
1119 unsigned long flags;
1121 /* not for SW PMU */
1122 if (pmu->task_ctx_nr == perf_sw_context)
1125 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1126 if (!cpuctx->hrtimer_active) {
1127 cpuctx->hrtimer_active = 1;
1128 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1129 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1131 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1136 void perf_pmu_disable(struct pmu *pmu)
1138 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1140 pmu->pmu_disable(pmu);
1143 void perf_pmu_enable(struct pmu *pmu)
1145 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1147 pmu->pmu_enable(pmu);
1150 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1153 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1154 * perf_event_task_tick() are fully serialized because they're strictly cpu
1155 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1156 * disabled, while perf_event_task_tick is called from IRQ context.
1158 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1160 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1162 lockdep_assert_irqs_disabled();
1164 WARN_ON(!list_empty(&ctx->active_ctx_list));
1166 list_add(&ctx->active_ctx_list, head);
1169 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1171 lockdep_assert_irqs_disabled();
1173 WARN_ON(list_empty(&ctx->active_ctx_list));
1175 list_del_init(&ctx->active_ctx_list);
1178 static void get_ctx(struct perf_event_context *ctx)
1180 refcount_inc(&ctx->refcount);
1183 static void *alloc_task_ctx_data(struct pmu *pmu)
1185 if (pmu->task_ctx_cache)
1186 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1191 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1193 if (pmu->task_ctx_cache && task_ctx_data)
1194 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1197 static void free_ctx(struct rcu_head *head)
1199 struct perf_event_context *ctx;
1201 ctx = container_of(head, struct perf_event_context, rcu_head);
1202 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1206 static void put_ctx(struct perf_event_context *ctx)
1208 if (refcount_dec_and_test(&ctx->refcount)) {
1209 if (ctx->parent_ctx)
1210 put_ctx(ctx->parent_ctx);
1211 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1212 put_task_struct(ctx->task);
1213 call_rcu(&ctx->rcu_head, free_ctx);
1218 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1219 * perf_pmu_migrate_context() we need some magic.
1221 * Those places that change perf_event::ctx will hold both
1222 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1224 * Lock ordering is by mutex address. There are two other sites where
1225 * perf_event_context::mutex nests and those are:
1227 * - perf_event_exit_task_context() [ child , 0 ]
1228 * perf_event_exit_event()
1229 * put_event() [ parent, 1 ]
1231 * - perf_event_init_context() [ parent, 0 ]
1232 * inherit_task_group()
1235 * perf_event_alloc()
1237 * perf_try_init_event() [ child , 1 ]
1239 * While it appears there is an obvious deadlock here -- the parent and child
1240 * nesting levels are inverted between the two. This is in fact safe because
1241 * life-time rules separate them. That is an exiting task cannot fork, and a
1242 * spawning task cannot (yet) exit.
1244 * But remember that these are parent<->child context relations, and
1245 * migration does not affect children, therefore these two orderings should not
1248 * The change in perf_event::ctx does not affect children (as claimed above)
1249 * because the sys_perf_event_open() case will install a new event and break
1250 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1251 * concerned with cpuctx and that doesn't have children.
1253 * The places that change perf_event::ctx will issue:
1255 * perf_remove_from_context();
1256 * synchronize_rcu();
1257 * perf_install_in_context();
1259 * to affect the change. The remove_from_context() + synchronize_rcu() should
1260 * quiesce the event, after which we can install it in the new location. This
1261 * means that only external vectors (perf_fops, prctl) can perturb the event
1262 * while in transit. Therefore all such accessors should also acquire
1263 * perf_event_context::mutex to serialize against this.
1265 * However; because event->ctx can change while we're waiting to acquire
1266 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1271 * task_struct::perf_event_mutex
1272 * perf_event_context::mutex
1273 * perf_event::child_mutex;
1274 * perf_event_context::lock
1275 * perf_event::mmap_mutex
1277 * perf_addr_filters_head::lock
1281 * cpuctx->mutex / perf_event_context::mutex
1283 static struct perf_event_context *
1284 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1286 struct perf_event_context *ctx;
1290 ctx = READ_ONCE(event->ctx);
1291 if (!refcount_inc_not_zero(&ctx->refcount)) {
1297 mutex_lock_nested(&ctx->mutex, nesting);
1298 if (event->ctx != ctx) {
1299 mutex_unlock(&ctx->mutex);
1307 static inline struct perf_event_context *
1308 perf_event_ctx_lock(struct perf_event *event)
1310 return perf_event_ctx_lock_nested(event, 0);
1313 static void perf_event_ctx_unlock(struct perf_event *event,
1314 struct perf_event_context *ctx)
1316 mutex_unlock(&ctx->mutex);
1321 * This must be done under the ctx->lock, such as to serialize against
1322 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1323 * calling scheduler related locks and ctx->lock nests inside those.
1325 static __must_check struct perf_event_context *
1326 unclone_ctx(struct perf_event_context *ctx)
1328 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1330 lockdep_assert_held(&ctx->lock);
1333 ctx->parent_ctx = NULL;
1339 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1344 * only top level events have the pid namespace they were created in
1347 event = event->parent;
1349 nr = __task_pid_nr_ns(p, type, event->ns);
1350 /* avoid -1 if it is idle thread or runs in another ns */
1351 if (!nr && !pid_alive(p))
1356 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1358 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1361 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1363 return perf_event_pid_type(event, p, PIDTYPE_PID);
1367 * If we inherit events we want to return the parent event id
1370 static u64 primary_event_id(struct perf_event *event)
1375 id = event->parent->id;
1381 * Get the perf_event_context for a task and lock it.
1383 * This has to cope with the fact that until it is locked,
1384 * the context could get moved to another task.
1386 static struct perf_event_context *
1387 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1389 struct perf_event_context *ctx;
1393 * One of the few rules of preemptible RCU is that one cannot do
1394 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1395 * part of the read side critical section was irqs-enabled -- see
1396 * rcu_read_unlock_special().
1398 * Since ctx->lock nests under rq->lock we must ensure the entire read
1399 * side critical section has interrupts disabled.
1401 local_irq_save(*flags);
1403 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1406 * If this context is a clone of another, it might
1407 * get swapped for another underneath us by
1408 * perf_event_task_sched_out, though the
1409 * rcu_read_lock() protects us from any context
1410 * getting freed. Lock the context and check if it
1411 * got swapped before we could get the lock, and retry
1412 * if so. If we locked the right context, then it
1413 * can't get swapped on us any more.
1415 raw_spin_lock(&ctx->lock);
1416 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1417 raw_spin_unlock(&ctx->lock);
1419 local_irq_restore(*flags);
1423 if (ctx->task == TASK_TOMBSTONE ||
1424 !refcount_inc_not_zero(&ctx->refcount)) {
1425 raw_spin_unlock(&ctx->lock);
1428 WARN_ON_ONCE(ctx->task != task);
1433 local_irq_restore(*flags);
1438 * Get the context for a task and increment its pin_count so it
1439 * can't get swapped to another task. This also increments its
1440 * reference count so that the context can't get freed.
1442 static struct perf_event_context *
1443 perf_pin_task_context(struct task_struct *task, int ctxn)
1445 struct perf_event_context *ctx;
1446 unsigned long flags;
1448 ctx = perf_lock_task_context(task, ctxn, &flags);
1451 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1456 static void perf_unpin_context(struct perf_event_context *ctx)
1458 unsigned long flags;
1460 raw_spin_lock_irqsave(&ctx->lock, flags);
1462 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1466 * Update the record of the current time in a context.
1468 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1470 u64 now = perf_clock();
1472 lockdep_assert_held(&ctx->lock);
1475 ctx->time += now - ctx->timestamp;
1476 ctx->timestamp = now;
1479 * The above: time' = time + (now - timestamp), can be re-arranged
1480 * into: time` = now + (time - timestamp), which gives a single value
1481 * offset to compute future time without locks on.
1483 * See perf_event_time_now(), which can be used from NMI context where
1484 * it's (obviously) not possible to acquire ctx->lock in order to read
1485 * both the above values in a consistent manner.
1487 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1490 static void update_context_time(struct perf_event_context *ctx)
1492 __update_context_time(ctx, true);
1495 static u64 perf_event_time(struct perf_event *event)
1497 struct perf_event_context *ctx = event->ctx;
1502 if (is_cgroup_event(event))
1503 return perf_cgroup_event_time(event);
1508 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1510 struct perf_event_context *ctx = event->ctx;
1515 if (is_cgroup_event(event))
1516 return perf_cgroup_event_time_now(event, now);
1518 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1521 now += READ_ONCE(ctx->timeoffset);
1525 static enum event_type_t get_event_type(struct perf_event *event)
1527 struct perf_event_context *ctx = event->ctx;
1528 enum event_type_t event_type;
1530 lockdep_assert_held(&ctx->lock);
1533 * It's 'group type', really, because if our group leader is
1534 * pinned, so are we.
1536 if (event->group_leader != event)
1537 event = event->group_leader;
1539 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1541 event_type |= EVENT_CPU;
1547 * Helper function to initialize event group nodes.
1549 static void init_event_group(struct perf_event *event)
1551 RB_CLEAR_NODE(&event->group_node);
1552 event->group_index = 0;
1556 * Extract pinned or flexible groups from the context
1557 * based on event attrs bits.
1559 static struct perf_event_groups *
1560 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1562 if (event->attr.pinned)
1563 return &ctx->pinned_groups;
1565 return &ctx->flexible_groups;
1569 * Helper function to initializes perf_event_group trees.
1571 static void perf_event_groups_init(struct perf_event_groups *groups)
1573 groups->tree = RB_ROOT;
1577 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1579 struct cgroup *cgroup = NULL;
1581 #ifdef CONFIG_CGROUP_PERF
1583 cgroup = event->cgrp->css.cgroup;
1590 * Compare function for event groups;
1592 * Implements complex key that first sorts by CPU and then by virtual index
1593 * which provides ordering when rotating groups for the same CPU.
1595 static __always_inline int
1596 perf_event_groups_cmp(const int left_cpu, const struct cgroup *left_cgroup,
1597 const u64 left_group_index, const struct perf_event *right)
1599 if (left_cpu < right->cpu)
1601 if (left_cpu > right->cpu)
1604 #ifdef CONFIG_CGROUP_PERF
1606 const struct cgroup *right_cgroup = event_cgroup(right);
1608 if (left_cgroup != right_cgroup) {
1611 * Left has no cgroup but right does, no
1612 * cgroups come first.
1616 if (!right_cgroup) {
1618 * Right has no cgroup but left does, no
1619 * cgroups come first.
1623 /* Two dissimilar cgroups, order by id. */
1624 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1632 if (left_group_index < right->group_index)
1634 if (left_group_index > right->group_index)
1640 #define __node_2_pe(node) \
1641 rb_entry((node), struct perf_event, group_node)
1643 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1645 struct perf_event *e = __node_2_pe(a);
1646 return perf_event_groups_cmp(e->cpu, event_cgroup(e), e->group_index,
1647 __node_2_pe(b)) < 0;
1650 struct __group_key {
1652 struct cgroup *cgroup;
1655 static inline int __group_cmp(const void *key, const struct rb_node *node)
1657 const struct __group_key *a = key;
1658 const struct perf_event *b = __node_2_pe(node);
1660 /* partial/subtree match: @cpu, @cgroup; ignore: @group_index */
1661 return perf_event_groups_cmp(a->cpu, a->cgroup, b->group_index, b);
1665 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1666 * key (see perf_event_groups_less). This places it last inside the CPU
1670 perf_event_groups_insert(struct perf_event_groups *groups,
1671 struct perf_event *event)
1673 event->group_index = ++groups->index;
1675 rb_add(&event->group_node, &groups->tree, __group_less);
1679 * Helper function to insert event into the pinned or flexible groups.
1682 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1684 struct perf_event_groups *groups;
1686 groups = get_event_groups(event, ctx);
1687 perf_event_groups_insert(groups, event);
1691 * Delete a group from a tree.
1694 perf_event_groups_delete(struct perf_event_groups *groups,
1695 struct perf_event *event)
1697 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1698 RB_EMPTY_ROOT(&groups->tree));
1700 rb_erase(&event->group_node, &groups->tree);
1701 init_event_group(event);
1705 * Helper function to delete event from its groups.
1708 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1710 struct perf_event_groups *groups;
1712 groups = get_event_groups(event, ctx);
1713 perf_event_groups_delete(groups, event);
1717 * Get the leftmost event in the cpu/cgroup subtree.
1719 static struct perf_event *
1720 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1721 struct cgroup *cgrp)
1723 struct __group_key key = {
1727 struct rb_node *node;
1729 node = rb_find_first(&key, &groups->tree, __group_cmp);
1731 return __node_2_pe(node);
1737 * Like rb_entry_next_safe() for the @cpu subtree.
1739 static struct perf_event *
1740 perf_event_groups_next(struct perf_event *event)
1742 struct __group_key key = {
1744 .cgroup = event_cgroup(event),
1746 struct rb_node *next;
1748 next = rb_next_match(&key, &event->group_node, __group_cmp);
1750 return __node_2_pe(next);
1756 * Iterate through the whole groups tree.
1758 #define perf_event_groups_for_each(event, groups) \
1759 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1760 typeof(*event), group_node); event; \
1761 event = rb_entry_safe(rb_next(&event->group_node), \
1762 typeof(*event), group_node))
1765 * Add an event from the lists for its context.
1766 * Must be called with ctx->mutex and ctx->lock held.
1769 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1771 lockdep_assert_held(&ctx->lock);
1773 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1774 event->attach_state |= PERF_ATTACH_CONTEXT;
1776 event->tstamp = perf_event_time(event);
1779 * If we're a stand alone event or group leader, we go to the context
1780 * list, group events are kept attached to the group so that
1781 * perf_group_detach can, at all times, locate all siblings.
1783 if (event->group_leader == event) {
1784 event->group_caps = event->event_caps;
1785 add_event_to_groups(event, ctx);
1788 list_add_rcu(&event->event_entry, &ctx->event_list);
1790 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1792 if (event->attr.inherit_stat)
1795 if (event->state > PERF_EVENT_STATE_OFF)
1796 perf_cgroup_event_enable(event, ctx);
1802 * Initialize event state based on the perf_event_attr::disabled.
1804 static inline void perf_event__state_init(struct perf_event *event)
1806 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1807 PERF_EVENT_STATE_INACTIVE;
1810 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1812 int entry = sizeof(u64); /* value */
1816 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1817 size += sizeof(u64);
1819 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1820 size += sizeof(u64);
1822 if (event->attr.read_format & PERF_FORMAT_ID)
1823 entry += sizeof(u64);
1825 if (event->attr.read_format & PERF_FORMAT_LOST)
1826 entry += sizeof(u64);
1828 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1830 size += sizeof(u64);
1834 event->read_size = size;
1837 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1839 struct perf_sample_data *data;
1842 if (sample_type & PERF_SAMPLE_IP)
1843 size += sizeof(data->ip);
1845 if (sample_type & PERF_SAMPLE_ADDR)
1846 size += sizeof(data->addr);
1848 if (sample_type & PERF_SAMPLE_PERIOD)
1849 size += sizeof(data->period);
1851 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1852 size += sizeof(data->weight.full);
1854 if (sample_type & PERF_SAMPLE_READ)
1855 size += event->read_size;
1857 if (sample_type & PERF_SAMPLE_DATA_SRC)
1858 size += sizeof(data->data_src.val);
1860 if (sample_type & PERF_SAMPLE_TRANSACTION)
1861 size += sizeof(data->txn);
1863 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1864 size += sizeof(data->phys_addr);
1866 if (sample_type & PERF_SAMPLE_CGROUP)
1867 size += sizeof(data->cgroup);
1869 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1870 size += sizeof(data->data_page_size);
1872 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1873 size += sizeof(data->code_page_size);
1875 event->header_size = size;
1879 * Called at perf_event creation and when events are attached/detached from a
1882 static void perf_event__header_size(struct perf_event *event)
1884 __perf_event_read_size(event,
1885 event->group_leader->nr_siblings);
1886 __perf_event_header_size(event, event->attr.sample_type);
1889 static void perf_event__id_header_size(struct perf_event *event)
1891 struct perf_sample_data *data;
1892 u64 sample_type = event->attr.sample_type;
1895 if (sample_type & PERF_SAMPLE_TID)
1896 size += sizeof(data->tid_entry);
1898 if (sample_type & PERF_SAMPLE_TIME)
1899 size += sizeof(data->time);
1901 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1902 size += sizeof(data->id);
1904 if (sample_type & PERF_SAMPLE_ID)
1905 size += sizeof(data->id);
1907 if (sample_type & PERF_SAMPLE_STREAM_ID)
1908 size += sizeof(data->stream_id);
1910 if (sample_type & PERF_SAMPLE_CPU)
1911 size += sizeof(data->cpu_entry);
1913 event->id_header_size = size;
1916 static bool perf_event_validate_size(struct perf_event *event)
1919 * The values computed here will be over-written when we actually
1922 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1923 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1924 perf_event__id_header_size(event);
1927 * Sum the lot; should not exceed the 64k limit we have on records.
1928 * Conservative limit to allow for callchains and other variable fields.
1930 if (event->read_size + event->header_size +
1931 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1937 static void perf_group_attach(struct perf_event *event)
1939 struct perf_event *group_leader = event->group_leader, *pos;
1941 lockdep_assert_held(&event->ctx->lock);
1944 * We can have double attach due to group movement in perf_event_open.
1946 if (event->attach_state & PERF_ATTACH_GROUP)
1949 event->attach_state |= PERF_ATTACH_GROUP;
1951 if (group_leader == event)
1954 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1956 group_leader->group_caps &= event->event_caps;
1958 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1959 group_leader->nr_siblings++;
1961 perf_event__header_size(group_leader);
1963 for_each_sibling_event(pos, group_leader)
1964 perf_event__header_size(pos);
1968 * Remove an event from the lists for its context.
1969 * Must be called with ctx->mutex and ctx->lock held.
1972 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1974 WARN_ON_ONCE(event->ctx != ctx);
1975 lockdep_assert_held(&ctx->lock);
1978 * We can have double detach due to exit/hot-unplug + close.
1980 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1983 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1986 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1988 if (event->attr.inherit_stat)
1991 list_del_rcu(&event->event_entry);
1993 if (event->group_leader == event)
1994 del_event_from_groups(event, ctx);
1997 * If event was in error state, then keep it
1998 * that way, otherwise bogus counts will be
1999 * returned on read(). The only way to get out
2000 * of error state is by explicit re-enabling
2003 if (event->state > PERF_EVENT_STATE_OFF) {
2004 perf_cgroup_event_disable(event, ctx);
2005 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2012 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2014 if (!has_aux(aux_event))
2017 if (!event->pmu->aux_output_match)
2020 return event->pmu->aux_output_match(aux_event);
2023 static void put_event(struct perf_event *event);
2024 static void event_sched_out(struct perf_event *event,
2025 struct perf_cpu_context *cpuctx,
2026 struct perf_event_context *ctx);
2028 static void perf_put_aux_event(struct perf_event *event)
2030 struct perf_event_context *ctx = event->ctx;
2031 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2032 struct perf_event *iter;
2035 * If event uses aux_event tear down the link
2037 if (event->aux_event) {
2038 iter = event->aux_event;
2039 event->aux_event = NULL;
2045 * If the event is an aux_event, tear down all links to
2046 * it from other events.
2048 for_each_sibling_event(iter, event->group_leader) {
2049 if (iter->aux_event != event)
2052 iter->aux_event = NULL;
2056 * If it's ACTIVE, schedule it out and put it into ERROR
2057 * state so that we don't try to schedule it again. Note
2058 * that perf_event_enable() will clear the ERROR status.
2060 event_sched_out(iter, cpuctx, ctx);
2061 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2065 static bool perf_need_aux_event(struct perf_event *event)
2067 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2070 static int perf_get_aux_event(struct perf_event *event,
2071 struct perf_event *group_leader)
2074 * Our group leader must be an aux event if we want to be
2075 * an aux_output. This way, the aux event will precede its
2076 * aux_output events in the group, and therefore will always
2083 * aux_output and aux_sample_size are mutually exclusive.
2085 if (event->attr.aux_output && event->attr.aux_sample_size)
2088 if (event->attr.aux_output &&
2089 !perf_aux_output_match(event, group_leader))
2092 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2095 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2099 * Link aux_outputs to their aux event; this is undone in
2100 * perf_group_detach() by perf_put_aux_event(). When the
2101 * group in torn down, the aux_output events loose their
2102 * link to the aux_event and can't schedule any more.
2104 event->aux_event = group_leader;
2109 static inline struct list_head *get_event_list(struct perf_event *event)
2111 struct perf_event_context *ctx = event->ctx;
2112 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2116 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2117 * cannot exist on their own, schedule them out and move them into the ERROR
2118 * state. Also see _perf_event_enable(), it will not be able to recover
2121 static inline void perf_remove_sibling_event(struct perf_event *event)
2123 struct perf_event_context *ctx = event->ctx;
2124 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2126 event_sched_out(event, cpuctx, ctx);
2127 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2130 static void perf_group_detach(struct perf_event *event)
2132 struct perf_event *leader = event->group_leader;
2133 struct perf_event *sibling, *tmp;
2134 struct perf_event_context *ctx = event->ctx;
2136 lockdep_assert_held(&ctx->lock);
2139 * We can have double detach due to exit/hot-unplug + close.
2141 if (!(event->attach_state & PERF_ATTACH_GROUP))
2144 event->attach_state &= ~PERF_ATTACH_GROUP;
2146 perf_put_aux_event(event);
2149 * If this is a sibling, remove it from its group.
2151 if (leader != event) {
2152 list_del_init(&event->sibling_list);
2153 event->group_leader->nr_siblings--;
2158 * If this was a group event with sibling events then
2159 * upgrade the siblings to singleton events by adding them
2160 * to whatever list we are on.
2162 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2164 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2165 perf_remove_sibling_event(sibling);
2167 sibling->group_leader = sibling;
2168 list_del_init(&sibling->sibling_list);
2170 /* Inherit group flags from the previous leader */
2171 sibling->group_caps = event->group_caps;
2173 if (!RB_EMPTY_NODE(&event->group_node)) {
2174 add_event_to_groups(sibling, event->ctx);
2176 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2177 list_add_tail(&sibling->active_list, get_event_list(sibling));
2180 WARN_ON_ONCE(sibling->ctx != event->ctx);
2184 for_each_sibling_event(tmp, leader)
2185 perf_event__header_size(tmp);
2187 perf_event__header_size(leader);
2190 static void sync_child_event(struct perf_event *child_event);
2192 static void perf_child_detach(struct perf_event *event)
2194 struct perf_event *parent_event = event->parent;
2196 if (!(event->attach_state & PERF_ATTACH_CHILD))
2199 event->attach_state &= ~PERF_ATTACH_CHILD;
2201 if (WARN_ON_ONCE(!parent_event))
2204 lockdep_assert_held(&parent_event->child_mutex);
2206 sync_child_event(event);
2207 list_del_init(&event->child_list);
2210 static bool is_orphaned_event(struct perf_event *event)
2212 return event->state == PERF_EVENT_STATE_DEAD;
2215 static inline int __pmu_filter_match(struct perf_event *event)
2217 struct pmu *pmu = event->pmu;
2218 return pmu->filter_match ? pmu->filter_match(event) : 1;
2222 * Check whether we should attempt to schedule an event group based on
2223 * PMU-specific filtering. An event group can consist of HW and SW events,
2224 * potentially with a SW leader, so we must check all the filters, to
2225 * determine whether a group is schedulable:
2227 static inline int pmu_filter_match(struct perf_event *event)
2229 struct perf_event *sibling;
2230 unsigned long flags;
2233 if (!__pmu_filter_match(event))
2236 local_irq_save(flags);
2237 for_each_sibling_event(sibling, event) {
2238 if (!__pmu_filter_match(sibling)) {
2243 local_irq_restore(flags);
2249 event_filter_match(struct perf_event *event)
2251 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2252 perf_cgroup_match(event) && pmu_filter_match(event);
2256 event_sched_out(struct perf_event *event,
2257 struct perf_cpu_context *cpuctx,
2258 struct perf_event_context *ctx)
2260 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2262 WARN_ON_ONCE(event->ctx != ctx);
2263 lockdep_assert_held(&ctx->lock);
2265 if (event->state != PERF_EVENT_STATE_ACTIVE)
2269 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2270 * we can schedule events _OUT_ individually through things like
2271 * __perf_remove_from_context().
2273 list_del_init(&event->active_list);
2275 perf_pmu_disable(event->pmu);
2277 event->pmu->del(event, 0);
2280 if (event->pending_disable) {
2281 event->pending_disable = 0;
2282 perf_cgroup_event_disable(event, ctx);
2283 state = PERF_EVENT_STATE_OFF;
2286 if (event->pending_sigtrap) {
2289 event->pending_sigtrap = 0;
2290 if (state != PERF_EVENT_STATE_OFF &&
2291 !event->pending_work) {
2292 event->pending_work = 1;
2294 task_work_add(current, &event->pending_task, TWA_RESUME);
2297 local_dec(&event->ctx->nr_pending);
2300 perf_event_set_state(event, state);
2302 if (!is_software_event(event))
2303 cpuctx->active_oncpu--;
2304 if (!--ctx->nr_active)
2305 perf_event_ctx_deactivate(ctx);
2306 if (event->attr.freq && event->attr.sample_freq)
2308 if (event->attr.exclusive || !cpuctx->active_oncpu)
2309 cpuctx->exclusive = 0;
2311 perf_pmu_enable(event->pmu);
2315 group_sched_out(struct perf_event *group_event,
2316 struct perf_cpu_context *cpuctx,
2317 struct perf_event_context *ctx)
2319 struct perf_event *event;
2321 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2324 perf_pmu_disable(ctx->pmu);
2326 event_sched_out(group_event, cpuctx, ctx);
2329 * Schedule out siblings (if any):
2331 for_each_sibling_event(event, group_event)
2332 event_sched_out(event, cpuctx, ctx);
2334 perf_pmu_enable(ctx->pmu);
2337 #define DETACH_GROUP 0x01UL
2338 #define DETACH_CHILD 0x02UL
2341 * Cross CPU call to remove a performance event
2343 * We disable the event on the hardware level first. After that we
2344 * remove it from the context list.
2347 __perf_remove_from_context(struct perf_event *event,
2348 struct perf_cpu_context *cpuctx,
2349 struct perf_event_context *ctx,
2352 unsigned long flags = (unsigned long)info;
2354 if (ctx->is_active & EVENT_TIME) {
2355 update_context_time(ctx);
2356 update_cgrp_time_from_cpuctx(cpuctx, false);
2359 event_sched_out(event, cpuctx, ctx);
2360 if (flags & DETACH_GROUP)
2361 perf_group_detach(event);
2362 if (flags & DETACH_CHILD)
2363 perf_child_detach(event);
2364 list_del_event(event, ctx);
2366 if (!ctx->nr_events && ctx->is_active) {
2367 if (ctx == &cpuctx->ctx)
2368 update_cgrp_time_from_cpuctx(cpuctx, true);
2371 ctx->rotate_necessary = 0;
2373 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2374 cpuctx->task_ctx = NULL;
2380 * Remove the event from a task's (or a CPU's) list of events.
2382 * If event->ctx is a cloned context, callers must make sure that
2383 * every task struct that event->ctx->task could possibly point to
2384 * remains valid. This is OK when called from perf_release since
2385 * that only calls us on the top-level context, which can't be a clone.
2386 * When called from perf_event_exit_task, it's OK because the
2387 * context has been detached from its task.
2389 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2391 struct perf_event_context *ctx = event->ctx;
2393 lockdep_assert_held(&ctx->mutex);
2396 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2397 * to work in the face of TASK_TOMBSTONE, unlike every other
2398 * event_function_call() user.
2400 raw_spin_lock_irq(&ctx->lock);
2402 * Cgroup events are per-cpu events, and must IPI because of
2405 if (!ctx->is_active && !is_cgroup_event(event)) {
2406 __perf_remove_from_context(event, __get_cpu_context(ctx),
2407 ctx, (void *)flags);
2408 raw_spin_unlock_irq(&ctx->lock);
2411 raw_spin_unlock_irq(&ctx->lock);
2413 event_function_call(event, __perf_remove_from_context, (void *)flags);
2417 * Cross CPU call to disable a performance event
2419 static void __perf_event_disable(struct perf_event *event,
2420 struct perf_cpu_context *cpuctx,
2421 struct perf_event_context *ctx,
2424 if (event->state < PERF_EVENT_STATE_INACTIVE)
2427 if (ctx->is_active & EVENT_TIME) {
2428 update_context_time(ctx);
2429 update_cgrp_time_from_event(event);
2432 if (event == event->group_leader)
2433 group_sched_out(event, cpuctx, ctx);
2435 event_sched_out(event, cpuctx, ctx);
2437 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2438 perf_cgroup_event_disable(event, ctx);
2444 * If event->ctx is a cloned context, callers must make sure that
2445 * every task struct that event->ctx->task could possibly point to
2446 * remains valid. This condition is satisfied when called through
2447 * perf_event_for_each_child or perf_event_for_each because they
2448 * hold the top-level event's child_mutex, so any descendant that
2449 * goes to exit will block in perf_event_exit_event().
2451 * When called from perf_pending_irq it's OK because event->ctx
2452 * is the current context on this CPU and preemption is disabled,
2453 * hence we can't get into perf_event_task_sched_out for this context.
2455 static void _perf_event_disable(struct perf_event *event)
2457 struct perf_event_context *ctx = event->ctx;
2459 raw_spin_lock_irq(&ctx->lock);
2460 if (event->state <= PERF_EVENT_STATE_OFF) {
2461 raw_spin_unlock_irq(&ctx->lock);
2464 raw_spin_unlock_irq(&ctx->lock);
2466 event_function_call(event, __perf_event_disable, NULL);
2469 void perf_event_disable_local(struct perf_event *event)
2471 event_function_local(event, __perf_event_disable, NULL);
2475 * Strictly speaking kernel users cannot create groups and therefore this
2476 * interface does not need the perf_event_ctx_lock() magic.
2478 void perf_event_disable(struct perf_event *event)
2480 struct perf_event_context *ctx;
2482 ctx = perf_event_ctx_lock(event);
2483 _perf_event_disable(event);
2484 perf_event_ctx_unlock(event, ctx);
2486 EXPORT_SYMBOL_GPL(perf_event_disable);
2488 void perf_event_disable_inatomic(struct perf_event *event)
2490 event->pending_disable = 1;
2491 irq_work_queue(&event->pending_irq);
2494 #define MAX_INTERRUPTS (~0ULL)
2496 static void perf_log_throttle(struct perf_event *event, int enable);
2497 static void perf_log_itrace_start(struct perf_event *event);
2500 event_sched_in(struct perf_event *event,
2501 struct perf_cpu_context *cpuctx,
2502 struct perf_event_context *ctx)
2506 WARN_ON_ONCE(event->ctx != ctx);
2508 lockdep_assert_held(&ctx->lock);
2510 if (event->state <= PERF_EVENT_STATE_OFF)
2513 WRITE_ONCE(event->oncpu, smp_processor_id());
2515 * Order event::oncpu write to happen before the ACTIVE state is
2516 * visible. This allows perf_event_{stop,read}() to observe the correct
2517 * ->oncpu if it sees ACTIVE.
2520 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2523 * Unthrottle events, since we scheduled we might have missed several
2524 * ticks already, also for a heavily scheduling task there is little
2525 * guarantee it'll get a tick in a timely manner.
2527 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2528 perf_log_throttle(event, 1);
2529 event->hw.interrupts = 0;
2532 perf_pmu_disable(event->pmu);
2534 perf_log_itrace_start(event);
2536 if (event->pmu->add(event, PERF_EF_START)) {
2537 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2543 if (!is_software_event(event))
2544 cpuctx->active_oncpu++;
2545 if (!ctx->nr_active++)
2546 perf_event_ctx_activate(ctx);
2547 if (event->attr.freq && event->attr.sample_freq)
2550 if (event->attr.exclusive)
2551 cpuctx->exclusive = 1;
2554 perf_pmu_enable(event->pmu);
2560 group_sched_in(struct perf_event *group_event,
2561 struct perf_cpu_context *cpuctx,
2562 struct perf_event_context *ctx)
2564 struct perf_event *event, *partial_group = NULL;
2565 struct pmu *pmu = ctx->pmu;
2567 if (group_event->state == PERF_EVENT_STATE_OFF)
2570 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2572 if (event_sched_in(group_event, cpuctx, ctx))
2576 * Schedule in siblings as one group (if any):
2578 for_each_sibling_event(event, group_event) {
2579 if (event_sched_in(event, cpuctx, ctx)) {
2580 partial_group = event;
2585 if (!pmu->commit_txn(pmu))
2590 * Groups can be scheduled in as one unit only, so undo any
2591 * partial group before returning:
2592 * The events up to the failed event are scheduled out normally.
2594 for_each_sibling_event(event, group_event) {
2595 if (event == partial_group)
2598 event_sched_out(event, cpuctx, ctx);
2600 event_sched_out(group_event, cpuctx, ctx);
2603 pmu->cancel_txn(pmu);
2608 * Work out whether we can put this event group on the CPU now.
2610 static int group_can_go_on(struct perf_event *event,
2611 struct perf_cpu_context *cpuctx,
2615 * Groups consisting entirely of software events can always go on.
2617 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2620 * If an exclusive group is already on, no other hardware
2623 if (cpuctx->exclusive)
2626 * If this group is exclusive and there are already
2627 * events on the CPU, it can't go on.
2629 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2632 * Otherwise, try to add it if all previous groups were able
2638 static void add_event_to_ctx(struct perf_event *event,
2639 struct perf_event_context *ctx)
2641 list_add_event(event, ctx);
2642 perf_group_attach(event);
2645 static void ctx_sched_out(struct perf_event_context *ctx,
2646 struct perf_cpu_context *cpuctx,
2647 enum event_type_t event_type);
2649 ctx_sched_in(struct perf_event_context *ctx,
2650 struct perf_cpu_context *cpuctx,
2651 enum event_type_t event_type);
2653 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2654 struct perf_event_context *ctx,
2655 enum event_type_t event_type)
2657 if (!cpuctx->task_ctx)
2660 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2663 ctx_sched_out(ctx, cpuctx, event_type);
2666 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2667 struct perf_event_context *ctx)
2669 cpu_ctx_sched_in(cpuctx, EVENT_PINNED);
2671 ctx_sched_in(ctx, cpuctx, EVENT_PINNED);
2672 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
2674 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE);
2678 * We want to maintain the following priority of scheduling:
2679 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2680 * - task pinned (EVENT_PINNED)
2681 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2682 * - task flexible (EVENT_FLEXIBLE).
2684 * In order to avoid unscheduling and scheduling back in everything every
2685 * time an event is added, only do it for the groups of equal priority and
2688 * This can be called after a batch operation on task events, in which case
2689 * event_type is a bit mask of the types of events involved. For CPU events,
2690 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2692 static void ctx_resched(struct perf_cpu_context *cpuctx,
2693 struct perf_event_context *task_ctx,
2694 enum event_type_t event_type)
2696 enum event_type_t ctx_event_type;
2697 bool cpu_event = !!(event_type & EVENT_CPU);
2700 * If pinned groups are involved, flexible groups also need to be
2703 if (event_type & EVENT_PINNED)
2704 event_type |= EVENT_FLEXIBLE;
2706 ctx_event_type = event_type & EVENT_ALL;
2708 perf_pmu_disable(cpuctx->ctx.pmu);
2710 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2713 * Decide which cpu ctx groups to schedule out based on the types
2714 * of events that caused rescheduling:
2715 * - EVENT_CPU: schedule out corresponding groups;
2716 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2717 * - otherwise, do nothing more.
2720 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2721 else if (ctx_event_type & EVENT_PINNED)
2722 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2724 perf_event_sched_in(cpuctx, task_ctx);
2725 perf_pmu_enable(cpuctx->ctx.pmu);
2728 void perf_pmu_resched(struct pmu *pmu)
2730 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2731 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2733 perf_ctx_lock(cpuctx, task_ctx);
2734 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2735 perf_ctx_unlock(cpuctx, task_ctx);
2739 * Cross CPU call to install and enable a performance event
2741 * Very similar to remote_function() + event_function() but cannot assume that
2742 * things like ctx->is_active and cpuctx->task_ctx are set.
2744 static int __perf_install_in_context(void *info)
2746 struct perf_event *event = info;
2747 struct perf_event_context *ctx = event->ctx;
2748 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2749 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2750 bool reprogram = true;
2753 raw_spin_lock(&cpuctx->ctx.lock);
2755 raw_spin_lock(&ctx->lock);
2758 reprogram = (ctx->task == current);
2761 * If the task is running, it must be running on this CPU,
2762 * otherwise we cannot reprogram things.
2764 * If its not running, we don't care, ctx->lock will
2765 * serialize against it becoming runnable.
2767 if (task_curr(ctx->task) && !reprogram) {
2772 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2773 } else if (task_ctx) {
2774 raw_spin_lock(&task_ctx->lock);
2777 #ifdef CONFIG_CGROUP_PERF
2778 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2780 * If the current cgroup doesn't match the event's
2781 * cgroup, we should not try to schedule it.
2783 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2784 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2785 event->cgrp->css.cgroup);
2790 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2791 add_event_to_ctx(event, ctx);
2792 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2794 add_event_to_ctx(event, ctx);
2798 perf_ctx_unlock(cpuctx, task_ctx);
2803 static bool exclusive_event_installable(struct perf_event *event,
2804 struct perf_event_context *ctx);
2807 * Attach a performance event to a context.
2809 * Very similar to event_function_call, see comment there.
2812 perf_install_in_context(struct perf_event_context *ctx,
2813 struct perf_event *event,
2816 struct task_struct *task = READ_ONCE(ctx->task);
2818 lockdep_assert_held(&ctx->mutex);
2820 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2822 if (event->cpu != -1)
2826 * Ensures that if we can observe event->ctx, both the event and ctx
2827 * will be 'complete'. See perf_iterate_sb_cpu().
2829 smp_store_release(&event->ctx, ctx);
2832 * perf_event_attr::disabled events will not run and can be initialized
2833 * without IPI. Except when this is the first event for the context, in
2834 * that case we need the magic of the IPI to set ctx->is_active.
2835 * Similarly, cgroup events for the context also needs the IPI to
2836 * manipulate the cgrp_cpuctx_list.
2838 * The IOC_ENABLE that is sure to follow the creation of a disabled
2839 * event will issue the IPI and reprogram the hardware.
2841 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2842 ctx->nr_events && !is_cgroup_event(event)) {
2843 raw_spin_lock_irq(&ctx->lock);
2844 if (ctx->task == TASK_TOMBSTONE) {
2845 raw_spin_unlock_irq(&ctx->lock);
2848 add_event_to_ctx(event, ctx);
2849 raw_spin_unlock_irq(&ctx->lock);
2854 cpu_function_call(cpu, __perf_install_in_context, event);
2859 * Should not happen, we validate the ctx is still alive before calling.
2861 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2865 * Installing events is tricky because we cannot rely on ctx->is_active
2866 * to be set in case this is the nr_events 0 -> 1 transition.
2868 * Instead we use task_curr(), which tells us if the task is running.
2869 * However, since we use task_curr() outside of rq::lock, we can race
2870 * against the actual state. This means the result can be wrong.
2872 * If we get a false positive, we retry, this is harmless.
2874 * If we get a false negative, things are complicated. If we are after
2875 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2876 * value must be correct. If we're before, it doesn't matter since
2877 * perf_event_context_sched_in() will program the counter.
2879 * However, this hinges on the remote context switch having observed
2880 * our task->perf_event_ctxp[] store, such that it will in fact take
2881 * ctx::lock in perf_event_context_sched_in().
2883 * We do this by task_function_call(), if the IPI fails to hit the task
2884 * we know any future context switch of task must see the
2885 * perf_event_ctpx[] store.
2889 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2890 * task_cpu() load, such that if the IPI then does not find the task
2891 * running, a future context switch of that task must observe the
2896 if (!task_function_call(task, __perf_install_in_context, event))
2899 raw_spin_lock_irq(&ctx->lock);
2901 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2903 * Cannot happen because we already checked above (which also
2904 * cannot happen), and we hold ctx->mutex, which serializes us
2905 * against perf_event_exit_task_context().
2907 raw_spin_unlock_irq(&ctx->lock);
2911 * If the task is not running, ctx->lock will avoid it becoming so,
2912 * thus we can safely install the event.
2914 if (task_curr(task)) {
2915 raw_spin_unlock_irq(&ctx->lock);
2918 add_event_to_ctx(event, ctx);
2919 raw_spin_unlock_irq(&ctx->lock);
2923 * Cross CPU call to enable a performance event
2925 static void __perf_event_enable(struct perf_event *event,
2926 struct perf_cpu_context *cpuctx,
2927 struct perf_event_context *ctx,
2930 struct perf_event *leader = event->group_leader;
2931 struct perf_event_context *task_ctx;
2933 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2934 event->state <= PERF_EVENT_STATE_ERROR)
2938 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2940 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2941 perf_cgroup_event_enable(event, ctx);
2943 if (!ctx->is_active)
2946 if (!event_filter_match(event)) {
2947 ctx_sched_in(ctx, cpuctx, EVENT_TIME);
2952 * If the event is in a group and isn't the group leader,
2953 * then don't put it on unless the group is on.
2955 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2956 ctx_sched_in(ctx, cpuctx, EVENT_TIME);
2960 task_ctx = cpuctx->task_ctx;
2962 WARN_ON_ONCE(task_ctx != ctx);
2964 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2970 * If event->ctx is a cloned context, callers must make sure that
2971 * every task struct that event->ctx->task could possibly point to
2972 * remains valid. This condition is satisfied when called through
2973 * perf_event_for_each_child or perf_event_for_each as described
2974 * for perf_event_disable.
2976 static void _perf_event_enable(struct perf_event *event)
2978 struct perf_event_context *ctx = event->ctx;
2980 raw_spin_lock_irq(&ctx->lock);
2981 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2982 event->state < PERF_EVENT_STATE_ERROR) {
2984 raw_spin_unlock_irq(&ctx->lock);
2989 * If the event is in error state, clear that first.
2991 * That way, if we see the event in error state below, we know that it
2992 * has gone back into error state, as distinct from the task having
2993 * been scheduled away before the cross-call arrived.
2995 if (event->state == PERF_EVENT_STATE_ERROR) {
2997 * Detached SIBLING events cannot leave ERROR state.
2999 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3000 event->group_leader == event)
3003 event->state = PERF_EVENT_STATE_OFF;
3005 raw_spin_unlock_irq(&ctx->lock);
3007 event_function_call(event, __perf_event_enable, NULL);
3011 * See perf_event_disable();
3013 void perf_event_enable(struct perf_event *event)
3015 struct perf_event_context *ctx;
3017 ctx = perf_event_ctx_lock(event);
3018 _perf_event_enable(event);
3019 perf_event_ctx_unlock(event, ctx);
3021 EXPORT_SYMBOL_GPL(perf_event_enable);
3023 struct stop_event_data {
3024 struct perf_event *event;
3025 unsigned int restart;
3028 static int __perf_event_stop(void *info)
3030 struct stop_event_data *sd = info;
3031 struct perf_event *event = sd->event;
3033 /* if it's already INACTIVE, do nothing */
3034 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3037 /* matches smp_wmb() in event_sched_in() */
3041 * There is a window with interrupts enabled before we get here,
3042 * so we need to check again lest we try to stop another CPU's event.
3044 if (READ_ONCE(event->oncpu) != smp_processor_id())
3047 event->pmu->stop(event, PERF_EF_UPDATE);
3050 * May race with the actual stop (through perf_pmu_output_stop()),
3051 * but it is only used for events with AUX ring buffer, and such
3052 * events will refuse to restart because of rb::aux_mmap_count==0,
3053 * see comments in perf_aux_output_begin().
3055 * Since this is happening on an event-local CPU, no trace is lost
3059 event->pmu->start(event, 0);
3064 static int perf_event_stop(struct perf_event *event, int restart)
3066 struct stop_event_data sd = {
3073 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3076 /* matches smp_wmb() in event_sched_in() */
3080 * We only want to restart ACTIVE events, so if the event goes
3081 * inactive here (event->oncpu==-1), there's nothing more to do;
3082 * fall through with ret==-ENXIO.
3084 ret = cpu_function_call(READ_ONCE(event->oncpu),
3085 __perf_event_stop, &sd);
3086 } while (ret == -EAGAIN);
3092 * In order to contain the amount of racy and tricky in the address filter
3093 * configuration management, it is a two part process:
3095 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3096 * we update the addresses of corresponding vmas in
3097 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3098 * (p2) when an event is scheduled in (pmu::add), it calls
3099 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3100 * if the generation has changed since the previous call.
3102 * If (p1) happens while the event is active, we restart it to force (p2).
3104 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3105 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3107 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3108 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3110 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3113 void perf_event_addr_filters_sync(struct perf_event *event)
3115 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3117 if (!has_addr_filter(event))
3120 raw_spin_lock(&ifh->lock);
3121 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3122 event->pmu->addr_filters_sync(event);
3123 event->hw.addr_filters_gen = event->addr_filters_gen;
3125 raw_spin_unlock(&ifh->lock);
3127 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3129 static int _perf_event_refresh(struct perf_event *event, int refresh)
3132 * not supported on inherited events
3134 if (event->attr.inherit || !is_sampling_event(event))
3137 atomic_add(refresh, &event->event_limit);
3138 _perf_event_enable(event);
3144 * See perf_event_disable()
3146 int perf_event_refresh(struct perf_event *event, int refresh)
3148 struct perf_event_context *ctx;
3151 ctx = perf_event_ctx_lock(event);
3152 ret = _perf_event_refresh(event, refresh);
3153 perf_event_ctx_unlock(event, ctx);
3157 EXPORT_SYMBOL_GPL(perf_event_refresh);
3159 static int perf_event_modify_breakpoint(struct perf_event *bp,
3160 struct perf_event_attr *attr)
3164 _perf_event_disable(bp);
3166 err = modify_user_hw_breakpoint_check(bp, attr, true);
3168 if (!bp->attr.disabled)
3169 _perf_event_enable(bp);
3175 * Copy event-type-independent attributes that may be modified.
3177 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3178 const struct perf_event_attr *from)
3180 to->sig_data = from->sig_data;
3183 static int perf_event_modify_attr(struct perf_event *event,
3184 struct perf_event_attr *attr)
3186 int (*func)(struct perf_event *, struct perf_event_attr *);
3187 struct perf_event *child;
3190 if (event->attr.type != attr->type)
3193 switch (event->attr.type) {
3194 case PERF_TYPE_BREAKPOINT:
3195 func = perf_event_modify_breakpoint;
3198 /* Place holder for future additions. */
3202 WARN_ON_ONCE(event->ctx->parent_ctx);
3204 mutex_lock(&event->child_mutex);
3206 * Event-type-independent attributes must be copied before event-type
3207 * modification, which will validate that final attributes match the
3208 * source attributes after all relevant attributes have been copied.
3210 perf_event_modify_copy_attr(&event->attr, attr);
3211 err = func(event, attr);
3214 list_for_each_entry(child, &event->child_list, child_list) {
3215 perf_event_modify_copy_attr(&child->attr, attr);
3216 err = func(child, attr);
3221 mutex_unlock(&event->child_mutex);
3225 static void ctx_sched_out(struct perf_event_context *ctx,
3226 struct perf_cpu_context *cpuctx,
3227 enum event_type_t event_type)
3229 struct perf_event *event, *tmp;
3230 int is_active = ctx->is_active;
3232 lockdep_assert_held(&ctx->lock);
3234 if (likely(!ctx->nr_events)) {
3236 * See __perf_remove_from_context().
3238 WARN_ON_ONCE(ctx->is_active);
3240 WARN_ON_ONCE(cpuctx->task_ctx);
3245 * Always update time if it was set; not only when it changes.
3246 * Otherwise we can 'forget' to update time for any but the last
3247 * context we sched out. For example:
3249 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3250 * ctx_sched_out(.event_type = EVENT_PINNED)
3252 * would only update time for the pinned events.
3254 if (is_active & EVENT_TIME) {
3255 /* update (and stop) ctx time */
3256 update_context_time(ctx);
3257 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3259 * CPU-release for the below ->is_active store,
3260 * see __load_acquire() in perf_event_time_now()
3265 ctx->is_active &= ~event_type;
3266 if (!(ctx->is_active & EVENT_ALL))
3270 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3271 if (!ctx->is_active)
3272 cpuctx->task_ctx = NULL;
3275 is_active ^= ctx->is_active; /* changed bits */
3277 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3280 perf_pmu_disable(ctx->pmu);
3281 if (is_active & EVENT_PINNED) {
3282 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3283 group_sched_out(event, cpuctx, ctx);
3286 if (is_active & EVENT_FLEXIBLE) {
3287 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3288 group_sched_out(event, cpuctx, ctx);
3291 * Since we cleared EVENT_FLEXIBLE, also clear
3292 * rotate_necessary, is will be reset by
3293 * ctx_flexible_sched_in() when needed.
3295 ctx->rotate_necessary = 0;
3297 perf_pmu_enable(ctx->pmu);
3301 * Test whether two contexts are equivalent, i.e. whether they have both been
3302 * cloned from the same version of the same context.
3304 * Equivalence is measured using a generation number in the context that is
3305 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3306 * and list_del_event().
3308 static int context_equiv(struct perf_event_context *ctx1,
3309 struct perf_event_context *ctx2)
3311 lockdep_assert_held(&ctx1->lock);
3312 lockdep_assert_held(&ctx2->lock);
3314 /* Pinning disables the swap optimization */
3315 if (ctx1->pin_count || ctx2->pin_count)
3318 /* If ctx1 is the parent of ctx2 */
3319 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3322 /* If ctx2 is the parent of ctx1 */
3323 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3327 * If ctx1 and ctx2 have the same parent; we flatten the parent
3328 * hierarchy, see perf_event_init_context().
3330 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3331 ctx1->parent_gen == ctx2->parent_gen)
3338 static void __perf_event_sync_stat(struct perf_event *event,
3339 struct perf_event *next_event)
3343 if (!event->attr.inherit_stat)
3347 * Update the event value, we cannot use perf_event_read()
3348 * because we're in the middle of a context switch and have IRQs
3349 * disabled, which upsets smp_call_function_single(), however
3350 * we know the event must be on the current CPU, therefore we
3351 * don't need to use it.
3353 if (event->state == PERF_EVENT_STATE_ACTIVE)
3354 event->pmu->read(event);
3356 perf_event_update_time(event);
3359 * In order to keep per-task stats reliable we need to flip the event
3360 * values when we flip the contexts.
3362 value = local64_read(&next_event->count);
3363 value = local64_xchg(&event->count, value);
3364 local64_set(&next_event->count, value);
3366 swap(event->total_time_enabled, next_event->total_time_enabled);
3367 swap(event->total_time_running, next_event->total_time_running);
3370 * Since we swizzled the values, update the user visible data too.
3372 perf_event_update_userpage(event);
3373 perf_event_update_userpage(next_event);
3376 static void perf_event_sync_stat(struct perf_event_context *ctx,
3377 struct perf_event_context *next_ctx)
3379 struct perf_event *event, *next_event;
3384 update_context_time(ctx);
3386 event = list_first_entry(&ctx->event_list,
3387 struct perf_event, event_entry);
3389 next_event = list_first_entry(&next_ctx->event_list,
3390 struct perf_event, event_entry);
3392 while (&event->event_entry != &ctx->event_list &&
3393 &next_event->event_entry != &next_ctx->event_list) {
3395 __perf_event_sync_stat(event, next_event);
3397 event = list_next_entry(event, event_entry);
3398 next_event = list_next_entry(next_event, event_entry);
3402 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3403 struct task_struct *next)
3405 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3406 struct perf_event_context *next_ctx;
3407 struct perf_event_context *parent, *next_parent;
3408 struct perf_cpu_context *cpuctx;
3416 cpuctx = __get_cpu_context(ctx);
3417 if (!cpuctx->task_ctx)
3421 next_ctx = next->perf_event_ctxp[ctxn];
3425 parent = rcu_dereference(ctx->parent_ctx);
3426 next_parent = rcu_dereference(next_ctx->parent_ctx);
3428 /* If neither context have a parent context; they cannot be clones. */
3429 if (!parent && !next_parent)
3432 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3434 * Looks like the two contexts are clones, so we might be
3435 * able to optimize the context switch. We lock both
3436 * contexts and check that they are clones under the
3437 * lock (including re-checking that neither has been
3438 * uncloned in the meantime). It doesn't matter which
3439 * order we take the locks because no other cpu could
3440 * be trying to lock both of these tasks.
3442 raw_spin_lock(&ctx->lock);
3443 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3444 if (context_equiv(ctx, next_ctx)) {
3446 perf_pmu_disable(pmu);
3448 /* PMIs are disabled; ctx->nr_pending is stable. */
3449 if (local_read(&ctx->nr_pending) ||
3450 local_read(&next_ctx->nr_pending)) {
3452 * Must not swap out ctx when there's pending
3453 * events that rely on the ctx->task relation.
3455 raw_spin_unlock(&next_ctx->lock);
3460 WRITE_ONCE(ctx->task, next);
3461 WRITE_ONCE(next_ctx->task, task);
3463 if (cpuctx->sched_cb_usage && pmu->sched_task)
3464 pmu->sched_task(ctx, false);
3467 * PMU specific parts of task perf context can require
3468 * additional synchronization. As an example of such
3469 * synchronization see implementation details of Intel
3470 * LBR call stack data profiling;
3472 if (pmu->swap_task_ctx)
3473 pmu->swap_task_ctx(ctx, next_ctx);
3475 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3477 perf_pmu_enable(pmu);
3480 * RCU_INIT_POINTER here is safe because we've not
3481 * modified the ctx and the above modification of
3482 * ctx->task and ctx->task_ctx_data are immaterial
3483 * since those values are always verified under
3484 * ctx->lock which we're now holding.
3486 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3487 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3491 perf_event_sync_stat(ctx, next_ctx);
3493 raw_spin_unlock(&next_ctx->lock);
3494 raw_spin_unlock(&ctx->lock);
3500 raw_spin_lock(&ctx->lock);
3501 perf_pmu_disable(pmu);
3504 if (cpuctx->sched_cb_usage && pmu->sched_task)
3505 pmu->sched_task(ctx, false);
3506 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3508 perf_pmu_enable(pmu);
3509 raw_spin_unlock(&ctx->lock);
3513 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3515 void perf_sched_cb_dec(struct pmu *pmu)
3517 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3519 this_cpu_dec(perf_sched_cb_usages);
3521 if (!--cpuctx->sched_cb_usage)
3522 list_del(&cpuctx->sched_cb_entry);
3526 void perf_sched_cb_inc(struct pmu *pmu)
3528 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3530 if (!cpuctx->sched_cb_usage++)
3531 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3533 this_cpu_inc(perf_sched_cb_usages);
3537 * This function provides the context switch callback to the lower code
3538 * layer. It is invoked ONLY when the context switch callback is enabled.
3540 * This callback is relevant even to per-cpu events; for example multi event
3541 * PEBS requires this to provide PID/TID information. This requires we flush
3542 * all queued PEBS records before we context switch to a new task.
3544 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3548 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3550 if (WARN_ON_ONCE(!pmu->sched_task))
3553 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3554 perf_pmu_disable(pmu);
3556 pmu->sched_task(cpuctx->task_ctx, sched_in);
3558 perf_pmu_enable(pmu);
3559 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3562 static void perf_pmu_sched_task(struct task_struct *prev,
3563 struct task_struct *next,
3566 struct perf_cpu_context *cpuctx;
3571 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3572 /* will be handled in perf_event_context_sched_in/out */
3573 if (cpuctx->task_ctx)
3576 __perf_pmu_sched_task(cpuctx, sched_in);
3580 static void perf_event_switch(struct task_struct *task,
3581 struct task_struct *next_prev, bool sched_in);
3583 #define for_each_task_context_nr(ctxn) \
3584 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3587 * Called from scheduler to remove the events of the current task,
3588 * with interrupts disabled.
3590 * We stop each event and update the event value in event->count.
3592 * This does not protect us against NMI, but disable()
3593 * sets the disabled bit in the control field of event _before_
3594 * accessing the event control register. If a NMI hits, then it will
3595 * not restart the event.
3597 void __perf_event_task_sched_out(struct task_struct *task,
3598 struct task_struct *next)
3602 if (__this_cpu_read(perf_sched_cb_usages))
3603 perf_pmu_sched_task(task, next, false);
3605 if (atomic_read(&nr_switch_events))
3606 perf_event_switch(task, next, false);
3608 for_each_task_context_nr(ctxn)
3609 perf_event_context_sched_out(task, ctxn, next);
3612 * if cgroup events exist on this CPU, then we need
3613 * to check if we have to switch out PMU state.
3614 * cgroup event are system-wide mode only
3616 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3617 perf_cgroup_switch(next);
3621 * Called with IRQs disabled
3623 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3624 enum event_type_t event_type)
3626 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3629 static bool perf_less_group_idx(const void *l, const void *r)
3631 const struct perf_event *le = *(const struct perf_event **)l;
3632 const struct perf_event *re = *(const struct perf_event **)r;
3634 return le->group_index < re->group_index;
3637 static void swap_ptr(void *l, void *r)
3639 void **lp = l, **rp = r;
3644 static const struct min_heap_callbacks perf_min_heap = {
3645 .elem_size = sizeof(struct perf_event *),
3646 .less = perf_less_group_idx,
3650 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3652 struct perf_event **itrs = heap->data;
3655 itrs[heap->nr] = event;
3660 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3661 struct perf_event_groups *groups, int cpu,
3662 int (*func)(struct perf_event *, void *),
3665 #ifdef CONFIG_CGROUP_PERF
3666 struct cgroup_subsys_state *css = NULL;
3668 /* Space for per CPU and/or any CPU event iterators. */
3669 struct perf_event *itrs[2];
3670 struct min_heap event_heap;
3671 struct perf_event **evt;
3675 event_heap = (struct min_heap){
3676 .data = cpuctx->heap,
3678 .size = cpuctx->heap_size,
3681 lockdep_assert_held(&cpuctx->ctx.lock);
3683 #ifdef CONFIG_CGROUP_PERF
3685 css = &cpuctx->cgrp->css;
3688 event_heap = (struct min_heap){
3691 .size = ARRAY_SIZE(itrs),
3693 /* Events not within a CPU context may be on any CPU. */
3694 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3696 evt = event_heap.data;
3698 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3700 #ifdef CONFIG_CGROUP_PERF
3701 for (; css; css = css->parent)
3702 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3705 min_heapify_all(&event_heap, &perf_min_heap);
3707 while (event_heap.nr) {
3708 ret = func(*evt, data);
3712 *evt = perf_event_groups_next(*evt);
3714 min_heapify(&event_heap, 0, &perf_min_heap);
3716 min_heap_pop(&event_heap, &perf_min_heap);
3723 * Because the userpage is strictly per-event (there is no concept of context,
3724 * so there cannot be a context indirection), every userpage must be updated
3725 * when context time starts :-(
3727 * IOW, we must not miss EVENT_TIME edges.
3729 static inline bool event_update_userpage(struct perf_event *event)
3731 if (likely(!atomic_read(&event->mmap_count)))
3734 perf_event_update_time(event);
3735 perf_event_update_userpage(event);
3740 static inline void group_update_userpage(struct perf_event *group_event)
3742 struct perf_event *event;
3744 if (!event_update_userpage(group_event))
3747 for_each_sibling_event(event, group_event)
3748 event_update_userpage(event);
3751 static int merge_sched_in(struct perf_event *event, void *data)
3753 struct perf_event_context *ctx = event->ctx;
3754 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3755 int *can_add_hw = data;
3757 if (event->state <= PERF_EVENT_STATE_OFF)
3760 if (!event_filter_match(event))
3763 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3764 if (!group_sched_in(event, cpuctx, ctx))
3765 list_add_tail(&event->active_list, get_event_list(event));
3768 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3770 if (event->attr.pinned) {
3771 perf_cgroup_event_disable(event, ctx);
3772 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3774 ctx->rotate_necessary = 1;
3775 perf_mux_hrtimer_restart(cpuctx);
3776 group_update_userpage(event);
3784 ctx_pinned_sched_in(struct perf_event_context *ctx,
3785 struct perf_cpu_context *cpuctx)
3789 if (ctx != &cpuctx->ctx)
3792 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3794 merge_sched_in, &can_add_hw);
3798 ctx_flexible_sched_in(struct perf_event_context *ctx,
3799 struct perf_cpu_context *cpuctx)
3803 if (ctx != &cpuctx->ctx)
3806 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3808 merge_sched_in, &can_add_hw);
3812 ctx_sched_in(struct perf_event_context *ctx,
3813 struct perf_cpu_context *cpuctx,
3814 enum event_type_t event_type)
3816 int is_active = ctx->is_active;
3818 lockdep_assert_held(&ctx->lock);
3820 if (likely(!ctx->nr_events))
3823 if (is_active ^ EVENT_TIME) {
3824 /* start ctx time */
3825 __update_context_time(ctx, false);
3826 perf_cgroup_set_timestamp(cpuctx);
3828 * CPU-release for the below ->is_active store,
3829 * see __load_acquire() in perf_event_time_now()
3834 ctx->is_active |= (event_type | EVENT_TIME);
3837 cpuctx->task_ctx = ctx;
3839 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3842 is_active ^= ctx->is_active; /* changed bits */
3845 * First go through the list and put on any pinned groups
3846 * in order to give them the best chance of going on.
3848 if (is_active & EVENT_PINNED)
3849 ctx_pinned_sched_in(ctx, cpuctx);
3851 /* Then walk through the lower prio flexible groups */
3852 if (is_active & EVENT_FLEXIBLE)
3853 ctx_flexible_sched_in(ctx, cpuctx);
3856 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3857 enum event_type_t event_type)
3859 struct perf_event_context *ctx = &cpuctx->ctx;
3861 ctx_sched_in(ctx, cpuctx, event_type);
3864 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3865 struct task_struct *task)
3867 struct perf_cpu_context *cpuctx;
3870 cpuctx = __get_cpu_context(ctx);
3873 * HACK: for HETEROGENEOUS the task context might have switched to a
3874 * different PMU, force (re)set the context,
3876 pmu = ctx->pmu = cpuctx->ctx.pmu;
3878 if (cpuctx->task_ctx == ctx) {
3879 if (cpuctx->sched_cb_usage)
3880 __perf_pmu_sched_task(cpuctx, true);
3884 perf_ctx_lock(cpuctx, ctx);
3886 * We must check ctx->nr_events while holding ctx->lock, such
3887 * that we serialize against perf_install_in_context().
3889 if (!ctx->nr_events)
3892 perf_pmu_disable(pmu);
3894 * We want to keep the following priority order:
3895 * cpu pinned (that don't need to move), task pinned,
3896 * cpu flexible, task flexible.
3898 * However, if task's ctx is not carrying any pinned
3899 * events, no need to flip the cpuctx's events around.
3901 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3902 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3903 perf_event_sched_in(cpuctx, ctx);
3905 if (cpuctx->sched_cb_usage && pmu->sched_task)
3906 pmu->sched_task(cpuctx->task_ctx, true);
3908 perf_pmu_enable(pmu);
3911 perf_ctx_unlock(cpuctx, ctx);
3915 * Called from scheduler to add the events of the current task
3916 * with interrupts disabled.
3918 * We restore the event value and then enable it.
3920 * This does not protect us against NMI, but enable()
3921 * sets the enabled bit in the control field of event _before_
3922 * accessing the event control register. If a NMI hits, then it will
3923 * keep the event running.
3925 void __perf_event_task_sched_in(struct task_struct *prev,
3926 struct task_struct *task)
3928 struct perf_event_context *ctx;
3931 for_each_task_context_nr(ctxn) {
3932 ctx = task->perf_event_ctxp[ctxn];
3936 perf_event_context_sched_in(ctx, task);
3939 if (atomic_read(&nr_switch_events))
3940 perf_event_switch(task, prev, true);
3942 if (__this_cpu_read(perf_sched_cb_usages))
3943 perf_pmu_sched_task(prev, task, true);
3946 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3948 u64 frequency = event->attr.sample_freq;
3949 u64 sec = NSEC_PER_SEC;
3950 u64 divisor, dividend;
3952 int count_fls, nsec_fls, frequency_fls, sec_fls;
3954 count_fls = fls64(count);
3955 nsec_fls = fls64(nsec);
3956 frequency_fls = fls64(frequency);
3960 * We got @count in @nsec, with a target of sample_freq HZ
3961 * the target period becomes:
3964 * period = -------------------
3965 * @nsec * sample_freq
3970 * Reduce accuracy by one bit such that @a and @b converge
3971 * to a similar magnitude.
3973 #define REDUCE_FLS(a, b) \
3975 if (a##_fls > b##_fls) { \
3985 * Reduce accuracy until either term fits in a u64, then proceed with
3986 * the other, so that finally we can do a u64/u64 division.
3988 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3989 REDUCE_FLS(nsec, frequency);
3990 REDUCE_FLS(sec, count);
3993 if (count_fls + sec_fls > 64) {
3994 divisor = nsec * frequency;
3996 while (count_fls + sec_fls > 64) {
3997 REDUCE_FLS(count, sec);
4001 dividend = count * sec;
4003 dividend = count * sec;
4005 while (nsec_fls + frequency_fls > 64) {
4006 REDUCE_FLS(nsec, frequency);
4010 divisor = nsec * frequency;
4016 return div64_u64(dividend, divisor);
4019 static DEFINE_PER_CPU(int, perf_throttled_count);
4020 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4022 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4024 struct hw_perf_event *hwc = &event->hw;
4025 s64 period, sample_period;
4028 period = perf_calculate_period(event, nsec, count);
4030 delta = (s64)(period - hwc->sample_period);
4031 delta = (delta + 7) / 8; /* low pass filter */
4033 sample_period = hwc->sample_period + delta;
4038 hwc->sample_period = sample_period;
4040 if (local64_read(&hwc->period_left) > 8*sample_period) {
4042 event->pmu->stop(event, PERF_EF_UPDATE);
4044 local64_set(&hwc->period_left, 0);
4047 event->pmu->start(event, PERF_EF_RELOAD);
4052 * combine freq adjustment with unthrottling to avoid two passes over the
4053 * events. At the same time, make sure, having freq events does not change
4054 * the rate of unthrottling as that would introduce bias.
4056 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
4059 struct perf_event *event;
4060 struct hw_perf_event *hwc;
4061 u64 now, period = TICK_NSEC;
4065 * only need to iterate over all events iff:
4066 * - context have events in frequency mode (needs freq adjust)
4067 * - there are events to unthrottle on this cpu
4069 if (!(ctx->nr_freq || needs_unthr))
4072 raw_spin_lock(&ctx->lock);
4073 perf_pmu_disable(ctx->pmu);
4075 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4076 if (event->state != PERF_EVENT_STATE_ACTIVE)
4079 if (!event_filter_match(event))
4082 perf_pmu_disable(event->pmu);
4086 if (hwc->interrupts == MAX_INTERRUPTS) {
4087 hwc->interrupts = 0;
4088 perf_log_throttle(event, 1);
4089 event->pmu->start(event, 0);
4092 if (!event->attr.freq || !event->attr.sample_freq)
4096 * stop the event and update event->count
4098 event->pmu->stop(event, PERF_EF_UPDATE);
4100 now = local64_read(&event->count);
4101 delta = now - hwc->freq_count_stamp;
4102 hwc->freq_count_stamp = now;
4106 * reload only if value has changed
4107 * we have stopped the event so tell that
4108 * to perf_adjust_period() to avoid stopping it
4112 perf_adjust_period(event, period, delta, false);
4114 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4116 perf_pmu_enable(event->pmu);
4119 perf_pmu_enable(ctx->pmu);
4120 raw_spin_unlock(&ctx->lock);
4124 * Move @event to the tail of the @ctx's elegible events.
4126 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4129 * Rotate the first entry last of non-pinned groups. Rotation might be
4130 * disabled by the inheritance code.
4132 if (ctx->rotate_disable)
4135 perf_event_groups_delete(&ctx->flexible_groups, event);
4136 perf_event_groups_insert(&ctx->flexible_groups, event);
4139 /* pick an event from the flexible_groups to rotate */
4140 static inline struct perf_event *
4141 ctx_event_to_rotate(struct perf_event_context *ctx)
4143 struct perf_event *event;
4145 /* pick the first active flexible event */
4146 event = list_first_entry_or_null(&ctx->flexible_active,
4147 struct perf_event, active_list);
4149 /* if no active flexible event, pick the first event */
4151 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4152 typeof(*event), group_node);
4156 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4157 * finds there are unschedulable events, it will set it again.
4159 ctx->rotate_necessary = 0;
4164 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4166 struct perf_event *cpu_event = NULL, *task_event = NULL;
4167 struct perf_event_context *task_ctx = NULL;
4168 int cpu_rotate, task_rotate;
4171 * Since we run this from IRQ context, nobody can install new
4172 * events, thus the event count values are stable.
4175 cpu_rotate = cpuctx->ctx.rotate_necessary;
4176 task_ctx = cpuctx->task_ctx;
4177 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4179 if (!(cpu_rotate || task_rotate))
4182 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4183 perf_pmu_disable(cpuctx->ctx.pmu);
4186 task_event = ctx_event_to_rotate(task_ctx);
4188 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4191 * As per the order given at ctx_resched() first 'pop' task flexible
4192 * and then, if needed CPU flexible.
4194 if (task_event || (task_ctx && cpu_event))
4195 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4197 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4200 rotate_ctx(task_ctx, task_event);
4202 rotate_ctx(&cpuctx->ctx, cpu_event);
4204 perf_event_sched_in(cpuctx, task_ctx);
4206 perf_pmu_enable(cpuctx->ctx.pmu);
4207 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4212 void perf_event_task_tick(void)
4214 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4215 struct perf_event_context *ctx, *tmp;
4218 lockdep_assert_irqs_disabled();
4220 __this_cpu_inc(perf_throttled_seq);
4221 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4222 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4224 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4225 perf_adjust_freq_unthr_context(ctx, throttled);
4228 static int event_enable_on_exec(struct perf_event *event,
4229 struct perf_event_context *ctx)
4231 if (!event->attr.enable_on_exec)
4234 event->attr.enable_on_exec = 0;
4235 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4238 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4244 * Enable all of a task's events that have been marked enable-on-exec.
4245 * This expects task == current.
4247 static void perf_event_enable_on_exec(int ctxn)
4249 struct perf_event_context *ctx, *clone_ctx = NULL;
4250 enum event_type_t event_type = 0;
4251 struct perf_cpu_context *cpuctx;
4252 struct perf_event *event;
4253 unsigned long flags;
4256 local_irq_save(flags);
4257 ctx = current->perf_event_ctxp[ctxn];
4258 if (!ctx || !ctx->nr_events)
4261 cpuctx = __get_cpu_context(ctx);
4262 perf_ctx_lock(cpuctx, ctx);
4263 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4264 list_for_each_entry(event, &ctx->event_list, event_entry) {
4265 enabled |= event_enable_on_exec(event, ctx);
4266 event_type |= get_event_type(event);
4270 * Unclone and reschedule this context if we enabled any event.
4273 clone_ctx = unclone_ctx(ctx);
4274 ctx_resched(cpuctx, ctx, event_type);
4276 ctx_sched_in(ctx, cpuctx, EVENT_TIME);
4278 perf_ctx_unlock(cpuctx, ctx);
4281 local_irq_restore(flags);
4287 static void perf_remove_from_owner(struct perf_event *event);
4288 static void perf_event_exit_event(struct perf_event *event,
4289 struct perf_event_context *ctx);
4292 * Removes all events from the current task that have been marked
4293 * remove-on-exec, and feeds their values back to parent events.
4295 static void perf_event_remove_on_exec(int ctxn)
4297 struct perf_event_context *ctx, *clone_ctx = NULL;
4298 struct perf_event *event, *next;
4299 unsigned long flags;
4300 bool modified = false;
4302 ctx = perf_pin_task_context(current, ctxn);
4306 mutex_lock(&ctx->mutex);
4308 if (WARN_ON_ONCE(ctx->task != current))
4311 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4312 if (!event->attr.remove_on_exec)
4315 if (!is_kernel_event(event))
4316 perf_remove_from_owner(event);
4320 perf_event_exit_event(event, ctx);
4323 raw_spin_lock_irqsave(&ctx->lock, flags);
4325 clone_ctx = unclone_ctx(ctx);
4327 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4330 mutex_unlock(&ctx->mutex);
4337 struct perf_read_data {
4338 struct perf_event *event;
4343 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4345 u16 local_pkg, event_pkg;
4347 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4348 int local_cpu = smp_processor_id();
4350 event_pkg = topology_physical_package_id(event_cpu);
4351 local_pkg = topology_physical_package_id(local_cpu);
4353 if (event_pkg == local_pkg)
4361 * Cross CPU call to read the hardware event
4363 static void __perf_event_read(void *info)
4365 struct perf_read_data *data = info;
4366 struct perf_event *sub, *event = data->event;
4367 struct perf_event_context *ctx = event->ctx;
4368 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4369 struct pmu *pmu = event->pmu;
4372 * If this is a task context, we need to check whether it is
4373 * the current task context of this cpu. If not it has been
4374 * scheduled out before the smp call arrived. In that case
4375 * event->count would have been updated to a recent sample
4376 * when the event was scheduled out.
4378 if (ctx->task && cpuctx->task_ctx != ctx)
4381 raw_spin_lock(&ctx->lock);
4382 if (ctx->is_active & EVENT_TIME) {
4383 update_context_time(ctx);
4384 update_cgrp_time_from_event(event);
4387 perf_event_update_time(event);
4389 perf_event_update_sibling_time(event);
4391 if (event->state != PERF_EVENT_STATE_ACTIVE)
4400 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4404 for_each_sibling_event(sub, event) {
4405 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4407 * Use sibling's PMU rather than @event's since
4408 * sibling could be on different (eg: software) PMU.
4410 sub->pmu->read(sub);
4414 data->ret = pmu->commit_txn(pmu);
4417 raw_spin_unlock(&ctx->lock);
4420 static inline u64 perf_event_count(struct perf_event *event)
4422 return local64_read(&event->count) + atomic64_read(&event->child_count);
4425 static void calc_timer_values(struct perf_event *event,
4432 *now = perf_clock();
4433 ctx_time = perf_event_time_now(event, *now);
4434 __perf_update_times(event, ctx_time, enabled, running);
4438 * NMI-safe method to read a local event, that is an event that
4440 * - either for the current task, or for this CPU
4441 * - does not have inherit set, for inherited task events
4442 * will not be local and we cannot read them atomically
4443 * - must not have a pmu::count method
4445 int perf_event_read_local(struct perf_event *event, u64 *value,
4446 u64 *enabled, u64 *running)
4448 unsigned long flags;
4452 * Disabling interrupts avoids all counter scheduling (context
4453 * switches, timer based rotation and IPIs).
4455 local_irq_save(flags);
4458 * It must not be an event with inherit set, we cannot read
4459 * all child counters from atomic context.
4461 if (event->attr.inherit) {
4466 /* If this is a per-task event, it must be for current */
4467 if ((event->attach_state & PERF_ATTACH_TASK) &&
4468 event->hw.target != current) {
4473 /* If this is a per-CPU event, it must be for this CPU */
4474 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4475 event->cpu != smp_processor_id()) {
4480 /* If this is a pinned event it must be running on this CPU */
4481 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4487 * If the event is currently on this CPU, its either a per-task event,
4488 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4491 if (event->oncpu == smp_processor_id())
4492 event->pmu->read(event);
4494 *value = local64_read(&event->count);
4495 if (enabled || running) {
4496 u64 __enabled, __running, __now;
4498 calc_timer_values(event, &__now, &__enabled, &__running);
4500 *enabled = __enabled;
4502 *running = __running;
4505 local_irq_restore(flags);
4510 static int perf_event_read(struct perf_event *event, bool group)
4512 enum perf_event_state state = READ_ONCE(event->state);
4513 int event_cpu, ret = 0;
4516 * If event is enabled and currently active on a CPU, update the
4517 * value in the event structure:
4520 if (state == PERF_EVENT_STATE_ACTIVE) {
4521 struct perf_read_data data;
4524 * Orders the ->state and ->oncpu loads such that if we see
4525 * ACTIVE we must also see the right ->oncpu.
4527 * Matches the smp_wmb() from event_sched_in().
4531 event_cpu = READ_ONCE(event->oncpu);
4532 if ((unsigned)event_cpu >= nr_cpu_ids)
4535 data = (struct perf_read_data){
4542 event_cpu = __perf_event_read_cpu(event, event_cpu);
4545 * Purposely ignore the smp_call_function_single() return
4548 * If event_cpu isn't a valid CPU it means the event got
4549 * scheduled out and that will have updated the event count.
4551 * Therefore, either way, we'll have an up-to-date event count
4554 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4558 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4559 struct perf_event_context *ctx = event->ctx;
4560 unsigned long flags;
4562 raw_spin_lock_irqsave(&ctx->lock, flags);
4563 state = event->state;
4564 if (state != PERF_EVENT_STATE_INACTIVE) {
4565 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4570 * May read while context is not active (e.g., thread is
4571 * blocked), in that case we cannot update context time
4573 if (ctx->is_active & EVENT_TIME) {
4574 update_context_time(ctx);
4575 update_cgrp_time_from_event(event);
4578 perf_event_update_time(event);
4580 perf_event_update_sibling_time(event);
4581 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4588 * Initialize the perf_event context in a task_struct:
4590 static void __perf_event_init_context(struct perf_event_context *ctx)
4592 raw_spin_lock_init(&ctx->lock);
4593 mutex_init(&ctx->mutex);
4594 INIT_LIST_HEAD(&ctx->active_ctx_list);
4595 perf_event_groups_init(&ctx->pinned_groups);
4596 perf_event_groups_init(&ctx->flexible_groups);
4597 INIT_LIST_HEAD(&ctx->event_list);
4598 INIT_LIST_HEAD(&ctx->pinned_active);
4599 INIT_LIST_HEAD(&ctx->flexible_active);
4600 refcount_set(&ctx->refcount, 1);
4603 static struct perf_event_context *
4604 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4606 struct perf_event_context *ctx;
4608 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4612 __perf_event_init_context(ctx);
4614 ctx->task = get_task_struct(task);
4620 static struct task_struct *
4621 find_lively_task_by_vpid(pid_t vpid)
4623 struct task_struct *task;
4629 task = find_task_by_vpid(vpid);
4631 get_task_struct(task);
4635 return ERR_PTR(-ESRCH);
4641 * Returns a matching context with refcount and pincount.
4643 static struct perf_event_context *
4644 find_get_context(struct pmu *pmu, struct task_struct *task,
4645 struct perf_event *event)
4647 struct perf_event_context *ctx, *clone_ctx = NULL;
4648 struct perf_cpu_context *cpuctx;
4649 void *task_ctx_data = NULL;
4650 unsigned long flags;
4652 int cpu = event->cpu;
4655 /* Must be root to operate on a CPU event: */
4656 err = perf_allow_cpu(&event->attr);
4658 return ERR_PTR(err);
4660 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4663 raw_spin_lock_irqsave(&ctx->lock, flags);
4665 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4671 ctxn = pmu->task_ctx_nr;
4675 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4676 task_ctx_data = alloc_task_ctx_data(pmu);
4677 if (!task_ctx_data) {
4684 ctx = perf_lock_task_context(task, ctxn, &flags);
4686 clone_ctx = unclone_ctx(ctx);
4689 if (task_ctx_data && !ctx->task_ctx_data) {
4690 ctx->task_ctx_data = task_ctx_data;
4691 task_ctx_data = NULL;
4693 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4698 ctx = alloc_perf_context(pmu, task);
4703 if (task_ctx_data) {
4704 ctx->task_ctx_data = task_ctx_data;
4705 task_ctx_data = NULL;
4709 mutex_lock(&task->perf_event_mutex);
4711 * If it has already passed perf_event_exit_task().
4712 * we must see PF_EXITING, it takes this mutex too.
4714 if (task->flags & PF_EXITING)
4716 else if (task->perf_event_ctxp[ctxn])
4721 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4723 mutex_unlock(&task->perf_event_mutex);
4725 if (unlikely(err)) {
4734 free_task_ctx_data(pmu, task_ctx_data);
4738 free_task_ctx_data(pmu, task_ctx_data);
4739 return ERR_PTR(err);
4742 static void perf_event_free_filter(struct perf_event *event);
4744 static void free_event_rcu(struct rcu_head *head)
4746 struct perf_event *event;
4748 event = container_of(head, struct perf_event, rcu_head);
4750 put_pid_ns(event->ns);
4751 perf_event_free_filter(event);
4752 kmem_cache_free(perf_event_cache, event);
4755 static void ring_buffer_attach(struct perf_event *event,
4756 struct perf_buffer *rb);
4758 static void detach_sb_event(struct perf_event *event)
4760 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4762 raw_spin_lock(&pel->lock);
4763 list_del_rcu(&event->sb_list);
4764 raw_spin_unlock(&pel->lock);
4767 static bool is_sb_event(struct perf_event *event)
4769 struct perf_event_attr *attr = &event->attr;
4774 if (event->attach_state & PERF_ATTACH_TASK)
4777 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4778 attr->comm || attr->comm_exec ||
4779 attr->task || attr->ksymbol ||
4780 attr->context_switch || attr->text_poke ||
4786 static void unaccount_pmu_sb_event(struct perf_event *event)
4788 if (is_sb_event(event))
4789 detach_sb_event(event);
4792 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4797 if (is_cgroup_event(event))
4798 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4801 #ifdef CONFIG_NO_HZ_FULL
4802 static DEFINE_SPINLOCK(nr_freq_lock);
4805 static void unaccount_freq_event_nohz(void)
4807 #ifdef CONFIG_NO_HZ_FULL
4808 spin_lock(&nr_freq_lock);
4809 if (atomic_dec_and_test(&nr_freq_events))
4810 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4811 spin_unlock(&nr_freq_lock);
4815 static void unaccount_freq_event(void)
4817 if (tick_nohz_full_enabled())
4818 unaccount_freq_event_nohz();
4820 atomic_dec(&nr_freq_events);
4823 static void unaccount_event(struct perf_event *event)
4830 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4832 if (event->attr.mmap || event->attr.mmap_data)
4833 atomic_dec(&nr_mmap_events);
4834 if (event->attr.build_id)
4835 atomic_dec(&nr_build_id_events);
4836 if (event->attr.comm)
4837 atomic_dec(&nr_comm_events);
4838 if (event->attr.namespaces)
4839 atomic_dec(&nr_namespaces_events);
4840 if (event->attr.cgroup)
4841 atomic_dec(&nr_cgroup_events);
4842 if (event->attr.task)
4843 atomic_dec(&nr_task_events);
4844 if (event->attr.freq)
4845 unaccount_freq_event();
4846 if (event->attr.context_switch) {
4848 atomic_dec(&nr_switch_events);
4850 if (is_cgroup_event(event))
4852 if (has_branch_stack(event))
4854 if (event->attr.ksymbol)
4855 atomic_dec(&nr_ksymbol_events);
4856 if (event->attr.bpf_event)
4857 atomic_dec(&nr_bpf_events);
4858 if (event->attr.text_poke)
4859 atomic_dec(&nr_text_poke_events);
4862 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4863 schedule_delayed_work(&perf_sched_work, HZ);
4866 unaccount_event_cpu(event, event->cpu);
4868 unaccount_pmu_sb_event(event);
4871 static void perf_sched_delayed(struct work_struct *work)
4873 mutex_lock(&perf_sched_mutex);
4874 if (atomic_dec_and_test(&perf_sched_count))
4875 static_branch_disable(&perf_sched_events);
4876 mutex_unlock(&perf_sched_mutex);
4880 * The following implement mutual exclusion of events on "exclusive" pmus
4881 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4882 * at a time, so we disallow creating events that might conflict, namely:
4884 * 1) cpu-wide events in the presence of per-task events,
4885 * 2) per-task events in the presence of cpu-wide events,
4886 * 3) two matching events on the same context.
4888 * The former two cases are handled in the allocation path (perf_event_alloc(),
4889 * _free_event()), the latter -- before the first perf_install_in_context().
4891 static int exclusive_event_init(struct perf_event *event)
4893 struct pmu *pmu = event->pmu;
4895 if (!is_exclusive_pmu(pmu))
4899 * Prevent co-existence of per-task and cpu-wide events on the
4900 * same exclusive pmu.
4902 * Negative pmu::exclusive_cnt means there are cpu-wide
4903 * events on this "exclusive" pmu, positive means there are
4906 * Since this is called in perf_event_alloc() path, event::ctx
4907 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4908 * to mean "per-task event", because unlike other attach states it
4909 * never gets cleared.
4911 if (event->attach_state & PERF_ATTACH_TASK) {
4912 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4915 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4922 static void exclusive_event_destroy(struct perf_event *event)
4924 struct pmu *pmu = event->pmu;
4926 if (!is_exclusive_pmu(pmu))
4929 /* see comment in exclusive_event_init() */
4930 if (event->attach_state & PERF_ATTACH_TASK)
4931 atomic_dec(&pmu->exclusive_cnt);
4933 atomic_inc(&pmu->exclusive_cnt);
4936 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4938 if ((e1->pmu == e2->pmu) &&
4939 (e1->cpu == e2->cpu ||
4946 static bool exclusive_event_installable(struct perf_event *event,
4947 struct perf_event_context *ctx)
4949 struct perf_event *iter_event;
4950 struct pmu *pmu = event->pmu;
4952 lockdep_assert_held(&ctx->mutex);
4954 if (!is_exclusive_pmu(pmu))
4957 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4958 if (exclusive_event_match(iter_event, event))
4965 static void perf_addr_filters_splice(struct perf_event *event,
4966 struct list_head *head);
4968 static void _free_event(struct perf_event *event)
4970 irq_work_sync(&event->pending_irq);
4972 unaccount_event(event);
4974 security_perf_event_free(event);
4978 * Can happen when we close an event with re-directed output.
4980 * Since we have a 0 refcount, perf_mmap_close() will skip
4981 * over us; possibly making our ring_buffer_put() the last.
4983 mutex_lock(&event->mmap_mutex);
4984 ring_buffer_attach(event, NULL);
4985 mutex_unlock(&event->mmap_mutex);
4988 if (is_cgroup_event(event))
4989 perf_detach_cgroup(event);
4991 if (!event->parent) {
4992 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4993 put_callchain_buffers();
4996 perf_event_free_bpf_prog(event);
4997 perf_addr_filters_splice(event, NULL);
4998 kfree(event->addr_filter_ranges);
5001 event->destroy(event);
5004 * Must be after ->destroy(), due to uprobe_perf_close() using
5007 if (event->hw.target)
5008 put_task_struct(event->hw.target);
5011 * perf_event_free_task() relies on put_ctx() being 'last', in particular
5012 * all task references must be cleaned up.
5015 put_ctx(event->ctx);
5017 exclusive_event_destroy(event);
5018 module_put(event->pmu->module);
5020 call_rcu(&event->rcu_head, free_event_rcu);
5024 * Used to free events which have a known refcount of 1, such as in error paths
5025 * where the event isn't exposed yet and inherited events.
5027 static void free_event(struct perf_event *event)
5029 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5030 "unexpected event refcount: %ld; ptr=%p\n",
5031 atomic_long_read(&event->refcount), event)) {
5032 /* leak to avoid use-after-free */
5040 * Remove user event from the owner task.
5042 static void perf_remove_from_owner(struct perf_event *event)
5044 struct task_struct *owner;
5048 * Matches the smp_store_release() in perf_event_exit_task(). If we
5049 * observe !owner it means the list deletion is complete and we can
5050 * indeed free this event, otherwise we need to serialize on
5051 * owner->perf_event_mutex.
5053 owner = READ_ONCE(event->owner);
5056 * Since delayed_put_task_struct() also drops the last
5057 * task reference we can safely take a new reference
5058 * while holding the rcu_read_lock().
5060 get_task_struct(owner);
5066 * If we're here through perf_event_exit_task() we're already
5067 * holding ctx->mutex which would be an inversion wrt. the
5068 * normal lock order.
5070 * However we can safely take this lock because its the child
5073 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5076 * We have to re-check the event->owner field, if it is cleared
5077 * we raced with perf_event_exit_task(), acquiring the mutex
5078 * ensured they're done, and we can proceed with freeing the
5082 list_del_init(&event->owner_entry);
5083 smp_store_release(&event->owner, NULL);
5085 mutex_unlock(&owner->perf_event_mutex);
5086 put_task_struct(owner);
5090 static void put_event(struct perf_event *event)
5092 if (!atomic_long_dec_and_test(&event->refcount))
5099 * Kill an event dead; while event:refcount will preserve the event
5100 * object, it will not preserve its functionality. Once the last 'user'
5101 * gives up the object, we'll destroy the thing.
5103 int perf_event_release_kernel(struct perf_event *event)
5105 struct perf_event_context *ctx = event->ctx;
5106 struct perf_event *child, *tmp;
5107 LIST_HEAD(free_list);
5110 * If we got here through err_file: fput(event_file); we will not have
5111 * attached to a context yet.
5114 WARN_ON_ONCE(event->attach_state &
5115 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5119 if (!is_kernel_event(event))
5120 perf_remove_from_owner(event);
5122 ctx = perf_event_ctx_lock(event);
5123 WARN_ON_ONCE(ctx->parent_ctx);
5124 perf_remove_from_context(event, DETACH_GROUP);
5126 raw_spin_lock_irq(&ctx->lock);
5128 * Mark this event as STATE_DEAD, there is no external reference to it
5131 * Anybody acquiring event->child_mutex after the below loop _must_
5132 * also see this, most importantly inherit_event() which will avoid
5133 * placing more children on the list.
5135 * Thus this guarantees that we will in fact observe and kill _ALL_
5138 event->state = PERF_EVENT_STATE_DEAD;
5139 raw_spin_unlock_irq(&ctx->lock);
5141 perf_event_ctx_unlock(event, ctx);
5144 mutex_lock(&event->child_mutex);
5145 list_for_each_entry(child, &event->child_list, child_list) {
5148 * Cannot change, child events are not migrated, see the
5149 * comment with perf_event_ctx_lock_nested().
5151 ctx = READ_ONCE(child->ctx);
5153 * Since child_mutex nests inside ctx::mutex, we must jump
5154 * through hoops. We start by grabbing a reference on the ctx.
5156 * Since the event cannot get freed while we hold the
5157 * child_mutex, the context must also exist and have a !0
5163 * Now that we have a ctx ref, we can drop child_mutex, and
5164 * acquire ctx::mutex without fear of it going away. Then we
5165 * can re-acquire child_mutex.
5167 mutex_unlock(&event->child_mutex);
5168 mutex_lock(&ctx->mutex);
5169 mutex_lock(&event->child_mutex);
5172 * Now that we hold ctx::mutex and child_mutex, revalidate our
5173 * state, if child is still the first entry, it didn't get freed
5174 * and we can continue doing so.
5176 tmp = list_first_entry_or_null(&event->child_list,
5177 struct perf_event, child_list);
5179 perf_remove_from_context(child, DETACH_GROUP);
5180 list_move(&child->child_list, &free_list);
5182 * This matches the refcount bump in inherit_event();
5183 * this can't be the last reference.
5188 mutex_unlock(&event->child_mutex);
5189 mutex_unlock(&ctx->mutex);
5193 mutex_unlock(&event->child_mutex);
5195 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5196 void *var = &child->ctx->refcount;
5198 list_del(&child->child_list);
5202 * Wake any perf_event_free_task() waiting for this event to be
5205 smp_mb(); /* pairs with wait_var_event() */
5210 put_event(event); /* Must be the 'last' reference */
5213 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5216 * Called when the last reference to the file is gone.
5218 static int perf_release(struct inode *inode, struct file *file)
5220 perf_event_release_kernel(file->private_data);
5224 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5226 struct perf_event *child;
5232 mutex_lock(&event->child_mutex);
5234 (void)perf_event_read(event, false);
5235 total += perf_event_count(event);
5237 *enabled += event->total_time_enabled +
5238 atomic64_read(&event->child_total_time_enabled);
5239 *running += event->total_time_running +
5240 atomic64_read(&event->child_total_time_running);
5242 list_for_each_entry(child, &event->child_list, child_list) {
5243 (void)perf_event_read(child, false);
5244 total += perf_event_count(child);
5245 *enabled += child->total_time_enabled;
5246 *running += child->total_time_running;
5248 mutex_unlock(&event->child_mutex);
5253 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5255 struct perf_event_context *ctx;
5258 ctx = perf_event_ctx_lock(event);
5259 count = __perf_event_read_value(event, enabled, running);
5260 perf_event_ctx_unlock(event, ctx);
5264 EXPORT_SYMBOL_GPL(perf_event_read_value);
5266 static int __perf_read_group_add(struct perf_event *leader,
5267 u64 read_format, u64 *values)
5269 struct perf_event_context *ctx = leader->ctx;
5270 struct perf_event *sub;
5271 unsigned long flags;
5272 int n = 1; /* skip @nr */
5275 ret = perf_event_read(leader, true);
5279 raw_spin_lock_irqsave(&ctx->lock, flags);
5282 * Since we co-schedule groups, {enabled,running} times of siblings
5283 * will be identical to those of the leader, so we only publish one
5286 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5287 values[n++] += leader->total_time_enabled +
5288 atomic64_read(&leader->child_total_time_enabled);
5291 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5292 values[n++] += leader->total_time_running +
5293 atomic64_read(&leader->child_total_time_running);
5297 * Write {count,id} tuples for every sibling.
5299 values[n++] += perf_event_count(leader);
5300 if (read_format & PERF_FORMAT_ID)
5301 values[n++] = primary_event_id(leader);
5302 if (read_format & PERF_FORMAT_LOST)
5303 values[n++] = atomic64_read(&leader->lost_samples);
5305 for_each_sibling_event(sub, leader) {
5306 values[n++] += perf_event_count(sub);
5307 if (read_format & PERF_FORMAT_ID)
5308 values[n++] = primary_event_id(sub);
5309 if (read_format & PERF_FORMAT_LOST)
5310 values[n++] = atomic64_read(&sub->lost_samples);
5313 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5317 static int perf_read_group(struct perf_event *event,
5318 u64 read_format, char __user *buf)
5320 struct perf_event *leader = event->group_leader, *child;
5321 struct perf_event_context *ctx = leader->ctx;
5325 lockdep_assert_held(&ctx->mutex);
5327 values = kzalloc(event->read_size, GFP_KERNEL);
5331 values[0] = 1 + leader->nr_siblings;
5334 * By locking the child_mutex of the leader we effectively
5335 * lock the child list of all siblings.. XXX explain how.
5337 mutex_lock(&leader->child_mutex);
5339 ret = __perf_read_group_add(leader, read_format, values);
5343 list_for_each_entry(child, &leader->child_list, child_list) {
5344 ret = __perf_read_group_add(child, read_format, values);
5349 mutex_unlock(&leader->child_mutex);
5351 ret = event->read_size;
5352 if (copy_to_user(buf, values, event->read_size))
5357 mutex_unlock(&leader->child_mutex);
5363 static int perf_read_one(struct perf_event *event,
5364 u64 read_format, char __user *buf)
5366 u64 enabled, running;
5370 values[n++] = __perf_event_read_value(event, &enabled, &running);
5371 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5372 values[n++] = enabled;
5373 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5374 values[n++] = running;
5375 if (read_format & PERF_FORMAT_ID)
5376 values[n++] = primary_event_id(event);
5377 if (read_format & PERF_FORMAT_LOST)
5378 values[n++] = atomic64_read(&event->lost_samples);
5380 if (copy_to_user(buf, values, n * sizeof(u64)))
5383 return n * sizeof(u64);
5386 static bool is_event_hup(struct perf_event *event)
5390 if (event->state > PERF_EVENT_STATE_EXIT)
5393 mutex_lock(&event->child_mutex);
5394 no_children = list_empty(&event->child_list);
5395 mutex_unlock(&event->child_mutex);
5400 * Read the performance event - simple non blocking version for now
5403 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5405 u64 read_format = event->attr.read_format;
5409 * Return end-of-file for a read on an event that is in
5410 * error state (i.e. because it was pinned but it couldn't be
5411 * scheduled on to the CPU at some point).
5413 if (event->state == PERF_EVENT_STATE_ERROR)
5416 if (count < event->read_size)
5419 WARN_ON_ONCE(event->ctx->parent_ctx);
5420 if (read_format & PERF_FORMAT_GROUP)
5421 ret = perf_read_group(event, read_format, buf);
5423 ret = perf_read_one(event, read_format, buf);
5429 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5431 struct perf_event *event = file->private_data;
5432 struct perf_event_context *ctx;
5435 ret = security_perf_event_read(event);
5439 ctx = perf_event_ctx_lock(event);
5440 ret = __perf_read(event, buf, count);
5441 perf_event_ctx_unlock(event, ctx);
5446 static __poll_t perf_poll(struct file *file, poll_table *wait)
5448 struct perf_event *event = file->private_data;
5449 struct perf_buffer *rb;
5450 __poll_t events = EPOLLHUP;
5452 poll_wait(file, &event->waitq, wait);
5454 if (is_event_hup(event))
5458 * Pin the event->rb by taking event->mmap_mutex; otherwise
5459 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5461 mutex_lock(&event->mmap_mutex);
5464 events = atomic_xchg(&rb->poll, 0);
5465 mutex_unlock(&event->mmap_mutex);
5469 static void _perf_event_reset(struct perf_event *event)
5471 (void)perf_event_read(event, false);
5472 local64_set(&event->count, 0);
5473 perf_event_update_userpage(event);
5476 /* Assume it's not an event with inherit set. */
5477 u64 perf_event_pause(struct perf_event *event, bool reset)
5479 struct perf_event_context *ctx;
5482 ctx = perf_event_ctx_lock(event);
5483 WARN_ON_ONCE(event->attr.inherit);
5484 _perf_event_disable(event);
5485 count = local64_read(&event->count);
5487 local64_set(&event->count, 0);
5488 perf_event_ctx_unlock(event, ctx);
5492 EXPORT_SYMBOL_GPL(perf_event_pause);
5495 * Holding the top-level event's child_mutex means that any
5496 * descendant process that has inherited this event will block
5497 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5498 * task existence requirements of perf_event_enable/disable.
5500 static void perf_event_for_each_child(struct perf_event *event,
5501 void (*func)(struct perf_event *))
5503 struct perf_event *child;
5505 WARN_ON_ONCE(event->ctx->parent_ctx);
5507 mutex_lock(&event->child_mutex);
5509 list_for_each_entry(child, &event->child_list, child_list)
5511 mutex_unlock(&event->child_mutex);
5514 static void perf_event_for_each(struct perf_event *event,
5515 void (*func)(struct perf_event *))
5517 struct perf_event_context *ctx = event->ctx;
5518 struct perf_event *sibling;
5520 lockdep_assert_held(&ctx->mutex);
5522 event = event->group_leader;
5524 perf_event_for_each_child(event, func);
5525 for_each_sibling_event(sibling, event)
5526 perf_event_for_each_child(sibling, func);
5529 static void __perf_event_period(struct perf_event *event,
5530 struct perf_cpu_context *cpuctx,
5531 struct perf_event_context *ctx,
5534 u64 value = *((u64 *)info);
5537 if (event->attr.freq) {
5538 event->attr.sample_freq = value;
5540 event->attr.sample_period = value;
5541 event->hw.sample_period = value;
5544 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5546 perf_pmu_disable(ctx->pmu);
5548 * We could be throttled; unthrottle now to avoid the tick
5549 * trying to unthrottle while we already re-started the event.
5551 if (event->hw.interrupts == MAX_INTERRUPTS) {
5552 event->hw.interrupts = 0;
5553 perf_log_throttle(event, 1);
5555 event->pmu->stop(event, PERF_EF_UPDATE);
5558 local64_set(&event->hw.period_left, 0);
5561 event->pmu->start(event, PERF_EF_RELOAD);
5562 perf_pmu_enable(ctx->pmu);
5566 static int perf_event_check_period(struct perf_event *event, u64 value)
5568 return event->pmu->check_period(event, value);
5571 static int _perf_event_period(struct perf_event *event, u64 value)
5573 if (!is_sampling_event(event))
5579 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5582 if (perf_event_check_period(event, value))
5585 if (!event->attr.freq && (value & (1ULL << 63)))
5588 event_function_call(event, __perf_event_period, &value);
5593 int perf_event_period(struct perf_event *event, u64 value)
5595 struct perf_event_context *ctx;
5598 ctx = perf_event_ctx_lock(event);
5599 ret = _perf_event_period(event, value);
5600 perf_event_ctx_unlock(event, ctx);
5604 EXPORT_SYMBOL_GPL(perf_event_period);
5606 static const struct file_operations perf_fops;
5608 static inline int perf_fget_light(int fd, struct fd *p)
5610 struct fd f = fdget(fd);
5614 if (f.file->f_op != &perf_fops) {
5622 static int perf_event_set_output(struct perf_event *event,
5623 struct perf_event *output_event);
5624 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5625 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5626 struct perf_event_attr *attr);
5628 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5630 void (*func)(struct perf_event *);
5634 case PERF_EVENT_IOC_ENABLE:
5635 func = _perf_event_enable;
5637 case PERF_EVENT_IOC_DISABLE:
5638 func = _perf_event_disable;
5640 case PERF_EVENT_IOC_RESET:
5641 func = _perf_event_reset;
5644 case PERF_EVENT_IOC_REFRESH:
5645 return _perf_event_refresh(event, arg);
5647 case PERF_EVENT_IOC_PERIOD:
5651 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5654 return _perf_event_period(event, value);
5656 case PERF_EVENT_IOC_ID:
5658 u64 id = primary_event_id(event);
5660 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5665 case PERF_EVENT_IOC_SET_OUTPUT:
5669 struct perf_event *output_event;
5671 ret = perf_fget_light(arg, &output);
5674 output_event = output.file->private_data;
5675 ret = perf_event_set_output(event, output_event);
5678 ret = perf_event_set_output(event, NULL);
5683 case PERF_EVENT_IOC_SET_FILTER:
5684 return perf_event_set_filter(event, (void __user *)arg);
5686 case PERF_EVENT_IOC_SET_BPF:
5688 struct bpf_prog *prog;
5691 prog = bpf_prog_get(arg);
5693 return PTR_ERR(prog);
5695 err = perf_event_set_bpf_prog(event, prog, 0);
5704 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5705 struct perf_buffer *rb;
5708 rb = rcu_dereference(event->rb);
5709 if (!rb || !rb->nr_pages) {
5713 rb_toggle_paused(rb, !!arg);
5718 case PERF_EVENT_IOC_QUERY_BPF:
5719 return perf_event_query_prog_array(event, (void __user *)arg);
5721 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5722 struct perf_event_attr new_attr;
5723 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5729 return perf_event_modify_attr(event, &new_attr);
5735 if (flags & PERF_IOC_FLAG_GROUP)
5736 perf_event_for_each(event, func);
5738 perf_event_for_each_child(event, func);
5743 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5745 struct perf_event *event = file->private_data;
5746 struct perf_event_context *ctx;
5749 /* Treat ioctl like writes as it is likely a mutating operation. */
5750 ret = security_perf_event_write(event);
5754 ctx = perf_event_ctx_lock(event);
5755 ret = _perf_ioctl(event, cmd, arg);
5756 perf_event_ctx_unlock(event, ctx);
5761 #ifdef CONFIG_COMPAT
5762 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5765 switch (_IOC_NR(cmd)) {
5766 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5767 case _IOC_NR(PERF_EVENT_IOC_ID):
5768 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5769 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5770 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5771 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5772 cmd &= ~IOCSIZE_MASK;
5773 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5777 return perf_ioctl(file, cmd, arg);
5780 # define perf_compat_ioctl NULL
5783 int perf_event_task_enable(void)
5785 struct perf_event_context *ctx;
5786 struct perf_event *event;
5788 mutex_lock(¤t->perf_event_mutex);
5789 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5790 ctx = perf_event_ctx_lock(event);
5791 perf_event_for_each_child(event, _perf_event_enable);
5792 perf_event_ctx_unlock(event, ctx);
5794 mutex_unlock(¤t->perf_event_mutex);
5799 int perf_event_task_disable(void)
5801 struct perf_event_context *ctx;
5802 struct perf_event *event;
5804 mutex_lock(¤t->perf_event_mutex);
5805 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5806 ctx = perf_event_ctx_lock(event);
5807 perf_event_for_each_child(event, _perf_event_disable);
5808 perf_event_ctx_unlock(event, ctx);
5810 mutex_unlock(¤t->perf_event_mutex);
5815 static int perf_event_index(struct perf_event *event)
5817 if (event->hw.state & PERF_HES_STOPPED)
5820 if (event->state != PERF_EVENT_STATE_ACTIVE)
5823 return event->pmu->event_idx(event);
5826 static void perf_event_init_userpage(struct perf_event *event)
5828 struct perf_event_mmap_page *userpg;
5829 struct perf_buffer *rb;
5832 rb = rcu_dereference(event->rb);
5836 userpg = rb->user_page;
5838 /* Allow new userspace to detect that bit 0 is deprecated */
5839 userpg->cap_bit0_is_deprecated = 1;
5840 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5841 userpg->data_offset = PAGE_SIZE;
5842 userpg->data_size = perf_data_size(rb);
5848 void __weak arch_perf_update_userpage(
5849 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5854 * Callers need to ensure there can be no nesting of this function, otherwise
5855 * the seqlock logic goes bad. We can not serialize this because the arch
5856 * code calls this from NMI context.
5858 void perf_event_update_userpage(struct perf_event *event)
5860 struct perf_event_mmap_page *userpg;
5861 struct perf_buffer *rb;
5862 u64 enabled, running, now;
5865 rb = rcu_dereference(event->rb);
5870 * compute total_time_enabled, total_time_running
5871 * based on snapshot values taken when the event
5872 * was last scheduled in.
5874 * we cannot simply called update_context_time()
5875 * because of locking issue as we can be called in
5878 calc_timer_values(event, &now, &enabled, &running);
5880 userpg = rb->user_page;
5882 * Disable preemption to guarantee consistent time stamps are stored to
5888 userpg->index = perf_event_index(event);
5889 userpg->offset = perf_event_count(event);
5891 userpg->offset -= local64_read(&event->hw.prev_count);
5893 userpg->time_enabled = enabled +
5894 atomic64_read(&event->child_total_time_enabled);
5896 userpg->time_running = running +
5897 atomic64_read(&event->child_total_time_running);
5899 arch_perf_update_userpage(event, userpg, now);
5907 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5909 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5911 struct perf_event *event = vmf->vma->vm_file->private_data;
5912 struct perf_buffer *rb;
5913 vm_fault_t ret = VM_FAULT_SIGBUS;
5915 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5916 if (vmf->pgoff == 0)
5922 rb = rcu_dereference(event->rb);
5926 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5929 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5933 get_page(vmf->page);
5934 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5935 vmf->page->index = vmf->pgoff;
5944 static void ring_buffer_attach(struct perf_event *event,
5945 struct perf_buffer *rb)
5947 struct perf_buffer *old_rb = NULL;
5948 unsigned long flags;
5950 WARN_ON_ONCE(event->parent);
5954 * Should be impossible, we set this when removing
5955 * event->rb_entry and wait/clear when adding event->rb_entry.
5957 WARN_ON_ONCE(event->rcu_pending);
5960 spin_lock_irqsave(&old_rb->event_lock, flags);
5961 list_del_rcu(&event->rb_entry);
5962 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5964 event->rcu_batches = get_state_synchronize_rcu();
5965 event->rcu_pending = 1;
5969 if (event->rcu_pending) {
5970 cond_synchronize_rcu(event->rcu_batches);
5971 event->rcu_pending = 0;
5974 spin_lock_irqsave(&rb->event_lock, flags);
5975 list_add_rcu(&event->rb_entry, &rb->event_list);
5976 spin_unlock_irqrestore(&rb->event_lock, flags);
5980 * Avoid racing with perf_mmap_close(AUX): stop the event
5981 * before swizzling the event::rb pointer; if it's getting
5982 * unmapped, its aux_mmap_count will be 0 and it won't
5983 * restart. See the comment in __perf_pmu_output_stop().
5985 * Data will inevitably be lost when set_output is done in
5986 * mid-air, but then again, whoever does it like this is
5987 * not in for the data anyway.
5990 perf_event_stop(event, 0);
5992 rcu_assign_pointer(event->rb, rb);
5995 ring_buffer_put(old_rb);
5997 * Since we detached before setting the new rb, so that we
5998 * could attach the new rb, we could have missed a wakeup.
6001 wake_up_all(&event->waitq);
6005 static void ring_buffer_wakeup(struct perf_event *event)
6007 struct perf_buffer *rb;
6010 event = event->parent;
6013 rb = rcu_dereference(event->rb);
6015 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6016 wake_up_all(&event->waitq);
6021 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6023 struct perf_buffer *rb;
6026 event = event->parent;
6029 rb = rcu_dereference(event->rb);
6031 if (!refcount_inc_not_zero(&rb->refcount))
6039 void ring_buffer_put(struct perf_buffer *rb)
6041 if (!refcount_dec_and_test(&rb->refcount))
6044 WARN_ON_ONCE(!list_empty(&rb->event_list));
6046 call_rcu(&rb->rcu_head, rb_free_rcu);
6049 static void perf_mmap_open(struct vm_area_struct *vma)
6051 struct perf_event *event = vma->vm_file->private_data;
6053 atomic_inc(&event->mmap_count);
6054 atomic_inc(&event->rb->mmap_count);
6057 atomic_inc(&event->rb->aux_mmap_count);
6059 if (event->pmu->event_mapped)
6060 event->pmu->event_mapped(event, vma->vm_mm);
6063 static void perf_pmu_output_stop(struct perf_event *event);
6066 * A buffer can be mmap()ed multiple times; either directly through the same
6067 * event, or through other events by use of perf_event_set_output().
6069 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6070 * the buffer here, where we still have a VM context. This means we need
6071 * to detach all events redirecting to us.
6073 static void perf_mmap_close(struct vm_area_struct *vma)
6075 struct perf_event *event = vma->vm_file->private_data;
6076 struct perf_buffer *rb = ring_buffer_get(event);
6077 struct user_struct *mmap_user = rb->mmap_user;
6078 int mmap_locked = rb->mmap_locked;
6079 unsigned long size = perf_data_size(rb);
6080 bool detach_rest = false;
6082 if (event->pmu->event_unmapped)
6083 event->pmu->event_unmapped(event, vma->vm_mm);
6086 * rb->aux_mmap_count will always drop before rb->mmap_count and
6087 * event->mmap_count, so it is ok to use event->mmap_mutex to
6088 * serialize with perf_mmap here.
6090 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6091 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6093 * Stop all AUX events that are writing to this buffer,
6094 * so that we can free its AUX pages and corresponding PMU
6095 * data. Note that after rb::aux_mmap_count dropped to zero,
6096 * they won't start any more (see perf_aux_output_begin()).
6098 perf_pmu_output_stop(event);
6100 /* now it's safe to free the pages */
6101 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6102 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6104 /* this has to be the last one */
6106 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6108 mutex_unlock(&event->mmap_mutex);
6111 if (atomic_dec_and_test(&rb->mmap_count))
6114 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6117 ring_buffer_attach(event, NULL);
6118 mutex_unlock(&event->mmap_mutex);
6120 /* If there's still other mmap()s of this buffer, we're done. */
6125 * No other mmap()s, detach from all other events that might redirect
6126 * into the now unreachable buffer. Somewhat complicated by the
6127 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6131 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6132 if (!atomic_long_inc_not_zero(&event->refcount)) {
6134 * This event is en-route to free_event() which will
6135 * detach it and remove it from the list.
6141 mutex_lock(&event->mmap_mutex);
6143 * Check we didn't race with perf_event_set_output() which can
6144 * swizzle the rb from under us while we were waiting to
6145 * acquire mmap_mutex.
6147 * If we find a different rb; ignore this event, a next
6148 * iteration will no longer find it on the list. We have to
6149 * still restart the iteration to make sure we're not now
6150 * iterating the wrong list.
6152 if (event->rb == rb)
6153 ring_buffer_attach(event, NULL);
6155 mutex_unlock(&event->mmap_mutex);
6159 * Restart the iteration; either we're on the wrong list or
6160 * destroyed its integrity by doing a deletion.
6167 * It could be there's still a few 0-ref events on the list; they'll
6168 * get cleaned up by free_event() -- they'll also still have their
6169 * ref on the rb and will free it whenever they are done with it.
6171 * Aside from that, this buffer is 'fully' detached and unmapped,
6172 * undo the VM accounting.
6175 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6176 &mmap_user->locked_vm);
6177 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6178 free_uid(mmap_user);
6181 ring_buffer_put(rb); /* could be last */
6184 static const struct vm_operations_struct perf_mmap_vmops = {
6185 .open = perf_mmap_open,
6186 .close = perf_mmap_close, /* non mergeable */
6187 .fault = perf_mmap_fault,
6188 .page_mkwrite = perf_mmap_fault,
6191 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6193 struct perf_event *event = file->private_data;
6194 unsigned long user_locked, user_lock_limit;
6195 struct user_struct *user = current_user();
6196 struct perf_buffer *rb = NULL;
6197 unsigned long locked, lock_limit;
6198 unsigned long vma_size;
6199 unsigned long nr_pages;
6200 long user_extra = 0, extra = 0;
6201 int ret = 0, flags = 0;
6204 * Don't allow mmap() of inherited per-task counters. This would
6205 * create a performance issue due to all children writing to the
6208 if (event->cpu == -1 && event->attr.inherit)
6211 if (!(vma->vm_flags & VM_SHARED))
6214 ret = security_perf_event_read(event);
6218 vma_size = vma->vm_end - vma->vm_start;
6220 if (vma->vm_pgoff == 0) {
6221 nr_pages = (vma_size / PAGE_SIZE) - 1;
6224 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6225 * mapped, all subsequent mappings should have the same size
6226 * and offset. Must be above the normal perf buffer.
6228 u64 aux_offset, aux_size;
6233 nr_pages = vma_size / PAGE_SIZE;
6235 mutex_lock(&event->mmap_mutex);
6242 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6243 aux_size = READ_ONCE(rb->user_page->aux_size);
6245 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6248 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6251 /* already mapped with a different offset */
6252 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6255 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6258 /* already mapped with a different size */
6259 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6262 if (!is_power_of_2(nr_pages))
6265 if (!atomic_inc_not_zero(&rb->mmap_count))
6268 if (rb_has_aux(rb)) {
6269 atomic_inc(&rb->aux_mmap_count);
6274 atomic_set(&rb->aux_mmap_count, 1);
6275 user_extra = nr_pages;
6281 * If we have rb pages ensure they're a power-of-two number, so we
6282 * can do bitmasks instead of modulo.
6284 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6287 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6290 WARN_ON_ONCE(event->ctx->parent_ctx);
6292 mutex_lock(&event->mmap_mutex);
6294 if (data_page_nr(event->rb) != nr_pages) {
6299 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6301 * Raced against perf_mmap_close(); remove the
6302 * event and try again.
6304 ring_buffer_attach(event, NULL);
6305 mutex_unlock(&event->mmap_mutex);
6312 user_extra = nr_pages + 1;
6315 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6318 * Increase the limit linearly with more CPUs:
6320 user_lock_limit *= num_online_cpus();
6322 user_locked = atomic_long_read(&user->locked_vm);
6325 * sysctl_perf_event_mlock may have changed, so that
6326 * user->locked_vm > user_lock_limit
6328 if (user_locked > user_lock_limit)
6329 user_locked = user_lock_limit;
6330 user_locked += user_extra;
6332 if (user_locked > user_lock_limit) {
6334 * charge locked_vm until it hits user_lock_limit;
6335 * charge the rest from pinned_vm
6337 extra = user_locked - user_lock_limit;
6338 user_extra -= extra;
6341 lock_limit = rlimit(RLIMIT_MEMLOCK);
6342 lock_limit >>= PAGE_SHIFT;
6343 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6345 if ((locked > lock_limit) && perf_is_paranoid() &&
6346 !capable(CAP_IPC_LOCK)) {
6351 WARN_ON(!rb && event->rb);
6353 if (vma->vm_flags & VM_WRITE)
6354 flags |= RING_BUFFER_WRITABLE;
6357 rb = rb_alloc(nr_pages,
6358 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6366 atomic_set(&rb->mmap_count, 1);
6367 rb->mmap_user = get_current_user();
6368 rb->mmap_locked = extra;
6370 ring_buffer_attach(event, rb);
6372 perf_event_update_time(event);
6373 perf_event_init_userpage(event);
6374 perf_event_update_userpage(event);
6376 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6377 event->attr.aux_watermark, flags);
6379 rb->aux_mmap_locked = extra;
6384 atomic_long_add(user_extra, &user->locked_vm);
6385 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6387 atomic_inc(&event->mmap_count);
6389 atomic_dec(&rb->mmap_count);
6392 mutex_unlock(&event->mmap_mutex);
6395 * Since pinned accounting is per vm we cannot allow fork() to copy our
6398 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6399 vma->vm_ops = &perf_mmap_vmops;
6401 if (event->pmu->event_mapped)
6402 event->pmu->event_mapped(event, vma->vm_mm);
6407 static int perf_fasync(int fd, struct file *filp, int on)
6409 struct inode *inode = file_inode(filp);
6410 struct perf_event *event = filp->private_data;
6414 retval = fasync_helper(fd, filp, on, &event->fasync);
6415 inode_unlock(inode);
6423 static const struct file_operations perf_fops = {
6424 .llseek = no_llseek,
6425 .release = perf_release,
6428 .unlocked_ioctl = perf_ioctl,
6429 .compat_ioctl = perf_compat_ioctl,
6431 .fasync = perf_fasync,
6437 * If there's data, ensure we set the poll() state and publish everything
6438 * to user-space before waking everybody up.
6441 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6443 /* only the parent has fasync state */
6445 event = event->parent;
6446 return &event->fasync;
6449 void perf_event_wakeup(struct perf_event *event)
6451 ring_buffer_wakeup(event);
6453 if (event->pending_kill) {
6454 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6455 event->pending_kill = 0;
6459 static void perf_sigtrap(struct perf_event *event)
6462 * We'd expect this to only occur if the irq_work is delayed and either
6463 * ctx->task or current has changed in the meantime. This can be the
6464 * case on architectures that do not implement arch_irq_work_raise().
6466 if (WARN_ON_ONCE(event->ctx->task != current))
6470 * Both perf_pending_task() and perf_pending_irq() can race with the
6473 if (current->flags & PF_EXITING)
6476 send_sig_perf((void __user *)event->pending_addr,
6477 event->attr.type, event->attr.sig_data);
6481 * Deliver the pending work in-event-context or follow the context.
6483 static void __perf_pending_irq(struct perf_event *event)
6485 int cpu = READ_ONCE(event->oncpu);
6488 * If the event isn't running; we done. event_sched_out() will have
6489 * taken care of things.
6495 * Yay, we hit home and are in the context of the event.
6497 if (cpu == smp_processor_id()) {
6498 if (event->pending_sigtrap) {
6499 event->pending_sigtrap = 0;
6500 perf_sigtrap(event);
6501 local_dec(&event->ctx->nr_pending);
6503 if (event->pending_disable) {
6504 event->pending_disable = 0;
6505 perf_event_disable_local(event);
6513 * perf_event_disable_inatomic()
6514 * @pending_disable = CPU-A;
6518 * @pending_disable = -1;
6521 * perf_event_disable_inatomic()
6522 * @pending_disable = CPU-B;
6523 * irq_work_queue(); // FAILS
6526 * perf_pending_irq()
6528 * But the event runs on CPU-B and wants disabling there.
6530 irq_work_queue_on(&event->pending_irq, cpu);
6533 static void perf_pending_irq(struct irq_work *entry)
6535 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6539 * If we 'fail' here, that's OK, it means recursion is already disabled
6540 * and we won't recurse 'further'.
6542 rctx = perf_swevent_get_recursion_context();
6545 * The wakeup isn't bound to the context of the event -- it can happen
6546 * irrespective of where the event is.
6548 if (event->pending_wakeup) {
6549 event->pending_wakeup = 0;
6550 perf_event_wakeup(event);
6553 __perf_pending_irq(event);
6556 perf_swevent_put_recursion_context(rctx);
6559 static void perf_pending_task(struct callback_head *head)
6561 struct perf_event *event = container_of(head, struct perf_event, pending_task);
6565 * If we 'fail' here, that's OK, it means recursion is already disabled
6566 * and we won't recurse 'further'.
6568 preempt_disable_notrace();
6569 rctx = perf_swevent_get_recursion_context();
6571 if (event->pending_work) {
6572 event->pending_work = 0;
6573 perf_sigtrap(event);
6574 local_dec(&event->ctx->nr_pending);
6578 perf_swevent_put_recursion_context(rctx);
6579 preempt_enable_notrace();
6582 #ifdef CONFIG_GUEST_PERF_EVENTS
6583 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6585 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
6586 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
6587 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
6589 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6591 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6594 rcu_assign_pointer(perf_guest_cbs, cbs);
6595 static_call_update(__perf_guest_state, cbs->state);
6596 static_call_update(__perf_guest_get_ip, cbs->get_ip);
6598 /* Implementing ->handle_intel_pt_intr is optional. */
6599 if (cbs->handle_intel_pt_intr)
6600 static_call_update(__perf_guest_handle_intel_pt_intr,
6601 cbs->handle_intel_pt_intr);
6603 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6605 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6607 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6610 rcu_assign_pointer(perf_guest_cbs, NULL);
6611 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
6612 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
6613 static_call_update(__perf_guest_handle_intel_pt_intr,
6614 (void *)&__static_call_return0);
6617 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6621 perf_output_sample_regs(struct perf_output_handle *handle,
6622 struct pt_regs *regs, u64 mask)
6625 DECLARE_BITMAP(_mask, 64);
6627 bitmap_from_u64(_mask, mask);
6628 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6631 val = perf_reg_value(regs, bit);
6632 perf_output_put(handle, val);
6636 static void perf_sample_regs_user(struct perf_regs *regs_user,
6637 struct pt_regs *regs)
6639 if (user_mode(regs)) {
6640 regs_user->abi = perf_reg_abi(current);
6641 regs_user->regs = regs;
6642 } else if (!(current->flags & PF_KTHREAD)) {
6643 perf_get_regs_user(regs_user, regs);
6645 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6646 regs_user->regs = NULL;
6650 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6651 struct pt_regs *regs)
6653 regs_intr->regs = regs;
6654 regs_intr->abi = perf_reg_abi(current);
6659 * Get remaining task size from user stack pointer.
6661 * It'd be better to take stack vma map and limit this more
6662 * precisely, but there's no way to get it safely under interrupt,
6663 * so using TASK_SIZE as limit.
6665 static u64 perf_ustack_task_size(struct pt_regs *regs)
6667 unsigned long addr = perf_user_stack_pointer(regs);
6669 if (!addr || addr >= TASK_SIZE)
6672 return TASK_SIZE - addr;
6676 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6677 struct pt_regs *regs)
6681 /* No regs, no stack pointer, no dump. */
6686 * Check if we fit in with the requested stack size into the:
6688 * If we don't, we limit the size to the TASK_SIZE.
6690 * - remaining sample size
6691 * If we don't, we customize the stack size to
6692 * fit in to the remaining sample size.
6695 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6696 stack_size = min(stack_size, (u16) task_size);
6698 /* Current header size plus static size and dynamic size. */
6699 header_size += 2 * sizeof(u64);
6701 /* Do we fit in with the current stack dump size? */
6702 if ((u16) (header_size + stack_size) < header_size) {
6704 * If we overflow the maximum size for the sample,
6705 * we customize the stack dump size to fit in.
6707 stack_size = USHRT_MAX - header_size - sizeof(u64);
6708 stack_size = round_up(stack_size, sizeof(u64));
6715 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6716 struct pt_regs *regs)
6718 /* Case of a kernel thread, nothing to dump */
6721 perf_output_put(handle, size);
6730 * - the size requested by user or the best one we can fit
6731 * in to the sample max size
6733 * - user stack dump data
6735 * - the actual dumped size
6739 perf_output_put(handle, dump_size);
6742 sp = perf_user_stack_pointer(regs);
6743 rem = __output_copy_user(handle, (void *) sp, dump_size);
6744 dyn_size = dump_size - rem;
6746 perf_output_skip(handle, rem);
6749 perf_output_put(handle, dyn_size);
6753 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6754 struct perf_sample_data *data,
6757 struct perf_event *sampler = event->aux_event;
6758 struct perf_buffer *rb;
6765 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6768 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6771 rb = ring_buffer_get(sampler);
6776 * If this is an NMI hit inside sampling code, don't take
6777 * the sample. See also perf_aux_sample_output().
6779 if (READ_ONCE(rb->aux_in_sampling)) {
6782 size = min_t(size_t, size, perf_aux_size(rb));
6783 data->aux_size = ALIGN(size, sizeof(u64));
6785 ring_buffer_put(rb);
6788 return data->aux_size;
6791 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6792 struct perf_event *event,
6793 struct perf_output_handle *handle,
6796 unsigned long flags;
6800 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6801 * paths. If we start calling them in NMI context, they may race with
6802 * the IRQ ones, that is, for example, re-starting an event that's just
6803 * been stopped, which is why we're using a separate callback that
6804 * doesn't change the event state.
6806 * IRQs need to be disabled to prevent IPIs from racing with us.
6808 local_irq_save(flags);
6810 * Guard against NMI hits inside the critical section;
6811 * see also perf_prepare_sample_aux().
6813 WRITE_ONCE(rb->aux_in_sampling, 1);
6816 ret = event->pmu->snapshot_aux(event, handle, size);
6819 WRITE_ONCE(rb->aux_in_sampling, 0);
6820 local_irq_restore(flags);
6825 static void perf_aux_sample_output(struct perf_event *event,
6826 struct perf_output_handle *handle,
6827 struct perf_sample_data *data)
6829 struct perf_event *sampler = event->aux_event;
6830 struct perf_buffer *rb;
6834 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6837 rb = ring_buffer_get(sampler);
6841 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6844 * An error here means that perf_output_copy() failed (returned a
6845 * non-zero surplus that it didn't copy), which in its current
6846 * enlightened implementation is not possible. If that changes, we'd
6849 if (WARN_ON_ONCE(size < 0))
6853 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6854 * perf_prepare_sample_aux(), so should not be more than that.
6856 pad = data->aux_size - size;
6857 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6862 perf_output_copy(handle, &zero, pad);
6866 ring_buffer_put(rb);
6869 static void __perf_event_header__init_id(struct perf_event_header *header,
6870 struct perf_sample_data *data,
6871 struct perf_event *event,
6874 data->type = event->attr.sample_type;
6875 header->size += event->id_header_size;
6877 if (sample_type & PERF_SAMPLE_TID) {
6878 /* namespace issues */
6879 data->tid_entry.pid = perf_event_pid(event, current);
6880 data->tid_entry.tid = perf_event_tid(event, current);
6883 if (sample_type & PERF_SAMPLE_TIME)
6884 data->time = perf_event_clock(event);
6886 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6887 data->id = primary_event_id(event);
6889 if (sample_type & PERF_SAMPLE_STREAM_ID)
6890 data->stream_id = event->id;
6892 if (sample_type & PERF_SAMPLE_CPU) {
6893 data->cpu_entry.cpu = raw_smp_processor_id();
6894 data->cpu_entry.reserved = 0;
6898 void perf_event_header__init_id(struct perf_event_header *header,
6899 struct perf_sample_data *data,
6900 struct perf_event *event)
6902 if (event->attr.sample_id_all)
6903 __perf_event_header__init_id(header, data, event, event->attr.sample_type);
6906 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6907 struct perf_sample_data *data)
6909 u64 sample_type = data->type;
6911 if (sample_type & PERF_SAMPLE_TID)
6912 perf_output_put(handle, data->tid_entry);
6914 if (sample_type & PERF_SAMPLE_TIME)
6915 perf_output_put(handle, data->time);
6917 if (sample_type & PERF_SAMPLE_ID)
6918 perf_output_put(handle, data->id);
6920 if (sample_type & PERF_SAMPLE_STREAM_ID)
6921 perf_output_put(handle, data->stream_id);
6923 if (sample_type & PERF_SAMPLE_CPU)
6924 perf_output_put(handle, data->cpu_entry);
6926 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6927 perf_output_put(handle, data->id);
6930 void perf_event__output_id_sample(struct perf_event *event,
6931 struct perf_output_handle *handle,
6932 struct perf_sample_data *sample)
6934 if (event->attr.sample_id_all)
6935 __perf_event__output_id_sample(handle, sample);
6938 static void perf_output_read_one(struct perf_output_handle *handle,
6939 struct perf_event *event,
6940 u64 enabled, u64 running)
6942 u64 read_format = event->attr.read_format;
6946 values[n++] = perf_event_count(event);
6947 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6948 values[n++] = enabled +
6949 atomic64_read(&event->child_total_time_enabled);
6951 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6952 values[n++] = running +
6953 atomic64_read(&event->child_total_time_running);
6955 if (read_format & PERF_FORMAT_ID)
6956 values[n++] = primary_event_id(event);
6957 if (read_format & PERF_FORMAT_LOST)
6958 values[n++] = atomic64_read(&event->lost_samples);
6960 __output_copy(handle, values, n * sizeof(u64));
6963 static void perf_output_read_group(struct perf_output_handle *handle,
6964 struct perf_event *event,
6965 u64 enabled, u64 running)
6967 struct perf_event *leader = event->group_leader, *sub;
6968 u64 read_format = event->attr.read_format;
6969 unsigned long flags;
6974 * Disabling interrupts avoids all counter scheduling
6975 * (context switches, timer based rotation and IPIs).
6977 local_irq_save(flags);
6979 values[n++] = 1 + leader->nr_siblings;
6981 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6982 values[n++] = enabled;
6984 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6985 values[n++] = running;
6987 if ((leader != event) &&
6988 (leader->state == PERF_EVENT_STATE_ACTIVE))
6989 leader->pmu->read(leader);
6991 values[n++] = perf_event_count(leader);
6992 if (read_format & PERF_FORMAT_ID)
6993 values[n++] = primary_event_id(leader);
6994 if (read_format & PERF_FORMAT_LOST)
6995 values[n++] = atomic64_read(&leader->lost_samples);
6997 __output_copy(handle, values, n * sizeof(u64));
6999 for_each_sibling_event(sub, leader) {
7002 if ((sub != event) &&
7003 (sub->state == PERF_EVENT_STATE_ACTIVE))
7004 sub->pmu->read(sub);
7006 values[n++] = perf_event_count(sub);
7007 if (read_format & PERF_FORMAT_ID)
7008 values[n++] = primary_event_id(sub);
7009 if (read_format & PERF_FORMAT_LOST)
7010 values[n++] = atomic64_read(&sub->lost_samples);
7012 __output_copy(handle, values, n * sizeof(u64));
7015 local_irq_restore(flags);
7018 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7019 PERF_FORMAT_TOTAL_TIME_RUNNING)
7022 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7024 * The problem is that its both hard and excessively expensive to iterate the
7025 * child list, not to mention that its impossible to IPI the children running
7026 * on another CPU, from interrupt/NMI context.
7028 static void perf_output_read(struct perf_output_handle *handle,
7029 struct perf_event *event)
7031 u64 enabled = 0, running = 0, now;
7032 u64 read_format = event->attr.read_format;
7035 * compute total_time_enabled, total_time_running
7036 * based on snapshot values taken when the event
7037 * was last scheduled in.
7039 * we cannot simply called update_context_time()
7040 * because of locking issue as we are called in
7043 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7044 calc_timer_values(event, &now, &enabled, &running);
7046 if (event->attr.read_format & PERF_FORMAT_GROUP)
7047 perf_output_read_group(handle, event, enabled, running);
7049 perf_output_read_one(handle, event, enabled, running);
7052 void perf_output_sample(struct perf_output_handle *handle,
7053 struct perf_event_header *header,
7054 struct perf_sample_data *data,
7055 struct perf_event *event)
7057 u64 sample_type = data->type;
7059 perf_output_put(handle, *header);
7061 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7062 perf_output_put(handle, data->id);
7064 if (sample_type & PERF_SAMPLE_IP)
7065 perf_output_put(handle, data->ip);
7067 if (sample_type & PERF_SAMPLE_TID)
7068 perf_output_put(handle, data->tid_entry);
7070 if (sample_type & PERF_SAMPLE_TIME)
7071 perf_output_put(handle, data->time);
7073 if (sample_type & PERF_SAMPLE_ADDR)
7074 perf_output_put(handle, data->addr);
7076 if (sample_type & PERF_SAMPLE_ID)
7077 perf_output_put(handle, data->id);
7079 if (sample_type & PERF_SAMPLE_STREAM_ID)
7080 perf_output_put(handle, data->stream_id);
7082 if (sample_type & PERF_SAMPLE_CPU)
7083 perf_output_put(handle, data->cpu_entry);
7085 if (sample_type & PERF_SAMPLE_PERIOD)
7086 perf_output_put(handle, data->period);
7088 if (sample_type & PERF_SAMPLE_READ)
7089 perf_output_read(handle, event);
7091 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7094 size += data->callchain->nr;
7095 size *= sizeof(u64);
7096 __output_copy(handle, data->callchain, size);
7099 if (sample_type & PERF_SAMPLE_RAW) {
7100 struct perf_raw_record *raw = data->raw;
7103 struct perf_raw_frag *frag = &raw->frag;
7105 perf_output_put(handle, raw->size);
7108 __output_custom(handle, frag->copy,
7109 frag->data, frag->size);
7111 __output_copy(handle, frag->data,
7114 if (perf_raw_frag_last(frag))
7119 __output_skip(handle, NULL, frag->pad);
7125 .size = sizeof(u32),
7128 perf_output_put(handle, raw);
7132 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7133 if (data->sample_flags & PERF_SAMPLE_BRANCH_STACK) {
7136 size = data->br_stack->nr
7137 * sizeof(struct perf_branch_entry);
7139 perf_output_put(handle, data->br_stack->nr);
7140 if (branch_sample_hw_index(event))
7141 perf_output_put(handle, data->br_stack->hw_idx);
7142 perf_output_copy(handle, data->br_stack->entries, size);
7145 * we always store at least the value of nr
7148 perf_output_put(handle, nr);
7152 if (sample_type & PERF_SAMPLE_REGS_USER) {
7153 u64 abi = data->regs_user.abi;
7156 * If there are no regs to dump, notice it through
7157 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7159 perf_output_put(handle, abi);
7162 u64 mask = event->attr.sample_regs_user;
7163 perf_output_sample_regs(handle,
7164 data->regs_user.regs,
7169 if (sample_type & PERF_SAMPLE_STACK_USER) {
7170 perf_output_sample_ustack(handle,
7171 data->stack_user_size,
7172 data->regs_user.regs);
7175 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7176 perf_output_put(handle, data->weight.full);
7178 if (sample_type & PERF_SAMPLE_DATA_SRC)
7179 perf_output_put(handle, data->data_src.val);
7181 if (sample_type & PERF_SAMPLE_TRANSACTION)
7182 perf_output_put(handle, data->txn);
7184 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7185 u64 abi = data->regs_intr.abi;
7187 * If there are no regs to dump, notice it through
7188 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7190 perf_output_put(handle, abi);
7193 u64 mask = event->attr.sample_regs_intr;
7195 perf_output_sample_regs(handle,
7196 data->regs_intr.regs,
7201 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7202 perf_output_put(handle, data->phys_addr);
7204 if (sample_type & PERF_SAMPLE_CGROUP)
7205 perf_output_put(handle, data->cgroup);
7207 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7208 perf_output_put(handle, data->data_page_size);
7210 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7211 perf_output_put(handle, data->code_page_size);
7213 if (sample_type & PERF_SAMPLE_AUX) {
7214 perf_output_put(handle, data->aux_size);
7217 perf_aux_sample_output(event, handle, data);
7220 if (!event->attr.watermark) {
7221 int wakeup_events = event->attr.wakeup_events;
7223 if (wakeup_events) {
7224 struct perf_buffer *rb = handle->rb;
7225 int events = local_inc_return(&rb->events);
7227 if (events >= wakeup_events) {
7228 local_sub(wakeup_events, &rb->events);
7229 local_inc(&rb->wakeup);
7235 static u64 perf_virt_to_phys(u64 virt)
7242 if (virt >= TASK_SIZE) {
7243 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7244 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7245 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7246 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7249 * Walking the pages tables for user address.
7250 * Interrupts are disabled, so it prevents any tear down
7251 * of the page tables.
7252 * Try IRQ-safe get_user_page_fast_only first.
7253 * If failed, leave phys_addr as 0.
7255 if (current->mm != NULL) {
7258 pagefault_disable();
7259 if (get_user_page_fast_only(virt, 0, &p)) {
7260 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7271 * Return the pagetable size of a given virtual address.
7273 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7277 #ifdef CONFIG_HAVE_FAST_GUP
7284 pgdp = pgd_offset(mm, addr);
7285 pgd = READ_ONCE(*pgdp);
7290 return pgd_leaf_size(pgd);
7292 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7293 p4d = READ_ONCE(*p4dp);
7294 if (!p4d_present(p4d))
7298 return p4d_leaf_size(p4d);
7300 pudp = pud_offset_lockless(p4dp, p4d, addr);
7301 pud = READ_ONCE(*pudp);
7302 if (!pud_present(pud))
7306 return pud_leaf_size(pud);
7308 pmdp = pmd_offset_lockless(pudp, pud, addr);
7309 pmd = READ_ONCE(*pmdp);
7310 if (!pmd_present(pmd))
7314 return pmd_leaf_size(pmd);
7316 ptep = pte_offset_map(&pmd, addr);
7317 pte = ptep_get_lockless(ptep);
7318 if (pte_present(pte))
7319 size = pte_leaf_size(pte);
7321 #endif /* CONFIG_HAVE_FAST_GUP */
7326 static u64 perf_get_page_size(unsigned long addr)
7328 struct mm_struct *mm;
7329 unsigned long flags;
7336 * Software page-table walkers must disable IRQs,
7337 * which prevents any tear down of the page tables.
7339 local_irq_save(flags);
7344 * For kernel threads and the like, use init_mm so that
7345 * we can find kernel memory.
7350 size = perf_get_pgtable_size(mm, addr);
7352 local_irq_restore(flags);
7357 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7359 struct perf_callchain_entry *
7360 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7362 bool kernel = !event->attr.exclude_callchain_kernel;
7363 bool user = !event->attr.exclude_callchain_user;
7364 /* Disallow cross-task user callchains. */
7365 bool crosstask = event->ctx->task && event->ctx->task != current;
7366 const u32 max_stack = event->attr.sample_max_stack;
7367 struct perf_callchain_entry *callchain;
7369 if (!kernel && !user)
7370 return &__empty_callchain;
7372 callchain = get_perf_callchain(regs, 0, kernel, user,
7373 max_stack, crosstask, true);
7374 return callchain ?: &__empty_callchain;
7377 void perf_prepare_sample(struct perf_event_header *header,
7378 struct perf_sample_data *data,
7379 struct perf_event *event,
7380 struct pt_regs *regs)
7382 u64 sample_type = event->attr.sample_type;
7383 u64 filtered_sample_type;
7385 header->type = PERF_RECORD_SAMPLE;
7386 header->size = sizeof(*header) + event->header_size;
7389 header->misc |= perf_misc_flags(regs);
7392 * Clear the sample flags that have already been done by the
7395 filtered_sample_type = sample_type & ~data->sample_flags;
7396 __perf_event_header__init_id(header, data, event, filtered_sample_type);
7398 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7399 data->ip = perf_instruction_pointer(regs);
7401 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7404 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7405 data->callchain = perf_callchain(event, regs);
7407 size += data->callchain->nr;
7409 header->size += size * sizeof(u64);
7412 if (sample_type & PERF_SAMPLE_RAW) {
7413 struct perf_raw_record *raw = data->raw;
7416 if (raw && (data->sample_flags & PERF_SAMPLE_RAW)) {
7417 struct perf_raw_frag *frag = &raw->frag;
7422 if (perf_raw_frag_last(frag))
7427 size = round_up(sum + sizeof(u32), sizeof(u64));
7428 raw->size = size - sizeof(u32);
7429 frag->pad = raw->size - sum;
7435 header->size += size;
7438 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7439 int size = sizeof(u64); /* nr */
7440 if (data->sample_flags & PERF_SAMPLE_BRANCH_STACK) {
7441 if (branch_sample_hw_index(event))
7442 size += sizeof(u64);
7444 size += data->br_stack->nr
7445 * sizeof(struct perf_branch_entry);
7447 header->size += size;
7450 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7451 perf_sample_regs_user(&data->regs_user, regs);
7453 if (sample_type & PERF_SAMPLE_REGS_USER) {
7454 /* regs dump ABI info */
7455 int size = sizeof(u64);
7457 if (data->regs_user.regs) {
7458 u64 mask = event->attr.sample_regs_user;
7459 size += hweight64(mask) * sizeof(u64);
7462 header->size += size;
7465 if (sample_type & PERF_SAMPLE_STACK_USER) {
7467 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7468 * processed as the last one or have additional check added
7469 * in case new sample type is added, because we could eat
7470 * up the rest of the sample size.
7472 u16 stack_size = event->attr.sample_stack_user;
7473 u16 size = sizeof(u64);
7475 stack_size = perf_sample_ustack_size(stack_size, header->size,
7476 data->regs_user.regs);
7479 * If there is something to dump, add space for the dump
7480 * itself and for the field that tells the dynamic size,
7481 * which is how many have been actually dumped.
7484 size += sizeof(u64) + stack_size;
7486 data->stack_user_size = stack_size;
7487 header->size += size;
7490 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7491 data->weight.full = 0;
7493 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC)
7494 data->data_src.val = PERF_MEM_NA;
7496 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION)
7499 if (sample_type & (PERF_SAMPLE_ADDR | PERF_SAMPLE_PHYS_ADDR | PERF_SAMPLE_DATA_PAGE_SIZE)) {
7500 if (filtered_sample_type & PERF_SAMPLE_ADDR)
7504 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7505 /* regs dump ABI info */
7506 int size = sizeof(u64);
7508 perf_sample_regs_intr(&data->regs_intr, regs);
7510 if (data->regs_intr.regs) {
7511 u64 mask = event->attr.sample_regs_intr;
7513 size += hweight64(mask) * sizeof(u64);
7516 header->size += size;
7519 if (sample_type & PERF_SAMPLE_PHYS_ADDR &&
7520 filtered_sample_type & PERF_SAMPLE_PHYS_ADDR)
7521 data->phys_addr = perf_virt_to_phys(data->addr);
7523 #ifdef CONFIG_CGROUP_PERF
7524 if (sample_type & PERF_SAMPLE_CGROUP) {
7525 struct cgroup *cgrp;
7527 /* protected by RCU */
7528 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7529 data->cgroup = cgroup_id(cgrp);
7534 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7535 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7536 * but the value will not dump to the userspace.
7538 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7539 data->data_page_size = perf_get_page_size(data->addr);
7541 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7542 data->code_page_size = perf_get_page_size(data->ip);
7544 if (sample_type & PERF_SAMPLE_AUX) {
7547 header->size += sizeof(u64); /* size */
7550 * Given the 16bit nature of header::size, an AUX sample can
7551 * easily overflow it, what with all the preceding sample bits.
7552 * Make sure this doesn't happen by using up to U16_MAX bytes
7553 * per sample in total (rounded down to 8 byte boundary).
7555 size = min_t(size_t, U16_MAX - header->size,
7556 event->attr.aux_sample_size);
7557 size = rounddown(size, 8);
7558 size = perf_prepare_sample_aux(event, data, size);
7560 WARN_ON_ONCE(size + header->size > U16_MAX);
7561 header->size += size;
7564 * If you're adding more sample types here, you likely need to do
7565 * something about the overflowing header::size, like repurpose the
7566 * lowest 3 bits of size, which should be always zero at the moment.
7567 * This raises a more important question, do we really need 512k sized
7568 * samples and why, so good argumentation is in order for whatever you
7571 WARN_ON_ONCE(header->size & 7);
7574 static __always_inline int
7575 __perf_event_output(struct perf_event *event,
7576 struct perf_sample_data *data,
7577 struct pt_regs *regs,
7578 int (*output_begin)(struct perf_output_handle *,
7579 struct perf_sample_data *,
7580 struct perf_event *,
7583 struct perf_output_handle handle;
7584 struct perf_event_header header;
7587 /* protect the callchain buffers */
7590 perf_prepare_sample(&header, data, event, regs);
7592 err = output_begin(&handle, data, event, header.size);
7596 perf_output_sample(&handle, &header, data, event);
7598 perf_output_end(&handle);
7606 perf_event_output_forward(struct perf_event *event,
7607 struct perf_sample_data *data,
7608 struct pt_regs *regs)
7610 __perf_event_output(event, data, regs, perf_output_begin_forward);
7614 perf_event_output_backward(struct perf_event *event,
7615 struct perf_sample_data *data,
7616 struct pt_regs *regs)
7618 __perf_event_output(event, data, regs, perf_output_begin_backward);
7622 perf_event_output(struct perf_event *event,
7623 struct perf_sample_data *data,
7624 struct pt_regs *regs)
7626 return __perf_event_output(event, data, regs, perf_output_begin);
7633 struct perf_read_event {
7634 struct perf_event_header header;
7641 perf_event_read_event(struct perf_event *event,
7642 struct task_struct *task)
7644 struct perf_output_handle handle;
7645 struct perf_sample_data sample;
7646 struct perf_read_event read_event = {
7648 .type = PERF_RECORD_READ,
7650 .size = sizeof(read_event) + event->read_size,
7652 .pid = perf_event_pid(event, task),
7653 .tid = perf_event_tid(event, task),
7657 perf_event_header__init_id(&read_event.header, &sample, event);
7658 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7662 perf_output_put(&handle, read_event);
7663 perf_output_read(&handle, event);
7664 perf_event__output_id_sample(event, &handle, &sample);
7666 perf_output_end(&handle);
7669 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7672 perf_iterate_ctx(struct perf_event_context *ctx,
7673 perf_iterate_f output,
7674 void *data, bool all)
7676 struct perf_event *event;
7678 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7680 if (event->state < PERF_EVENT_STATE_INACTIVE)
7682 if (!event_filter_match(event))
7686 output(event, data);
7690 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7692 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7693 struct perf_event *event;
7695 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7697 * Skip events that are not fully formed yet; ensure that
7698 * if we observe event->ctx, both event and ctx will be
7699 * complete enough. See perf_install_in_context().
7701 if (!smp_load_acquire(&event->ctx))
7704 if (event->state < PERF_EVENT_STATE_INACTIVE)
7706 if (!event_filter_match(event))
7708 output(event, data);
7713 * Iterate all events that need to receive side-band events.
7715 * For new callers; ensure that account_pmu_sb_event() includes
7716 * your event, otherwise it might not get delivered.
7719 perf_iterate_sb(perf_iterate_f output, void *data,
7720 struct perf_event_context *task_ctx)
7722 struct perf_event_context *ctx;
7729 * If we have task_ctx != NULL we only notify the task context itself.
7730 * The task_ctx is set only for EXIT events before releasing task
7734 perf_iterate_ctx(task_ctx, output, data, false);
7738 perf_iterate_sb_cpu(output, data);
7740 for_each_task_context_nr(ctxn) {
7741 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7743 perf_iterate_ctx(ctx, output, data, false);
7751 * Clear all file-based filters at exec, they'll have to be
7752 * re-instated when/if these objects are mmapped again.
7754 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7756 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7757 struct perf_addr_filter *filter;
7758 unsigned int restart = 0, count = 0;
7759 unsigned long flags;
7761 if (!has_addr_filter(event))
7764 raw_spin_lock_irqsave(&ifh->lock, flags);
7765 list_for_each_entry(filter, &ifh->list, entry) {
7766 if (filter->path.dentry) {
7767 event->addr_filter_ranges[count].start = 0;
7768 event->addr_filter_ranges[count].size = 0;
7776 event->addr_filters_gen++;
7777 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7780 perf_event_stop(event, 1);
7783 void perf_event_exec(void)
7785 struct perf_event_context *ctx;
7788 for_each_task_context_nr(ctxn) {
7789 perf_event_enable_on_exec(ctxn);
7790 perf_event_remove_on_exec(ctxn);
7793 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7795 perf_iterate_ctx(ctx, perf_event_addr_filters_exec,
7802 struct remote_output {
7803 struct perf_buffer *rb;
7807 static void __perf_event_output_stop(struct perf_event *event, void *data)
7809 struct perf_event *parent = event->parent;
7810 struct remote_output *ro = data;
7811 struct perf_buffer *rb = ro->rb;
7812 struct stop_event_data sd = {
7816 if (!has_aux(event))
7823 * In case of inheritance, it will be the parent that links to the
7824 * ring-buffer, but it will be the child that's actually using it.
7826 * We are using event::rb to determine if the event should be stopped,
7827 * however this may race with ring_buffer_attach() (through set_output),
7828 * which will make us skip the event that actually needs to be stopped.
7829 * So ring_buffer_attach() has to stop an aux event before re-assigning
7832 if (rcu_dereference(parent->rb) == rb)
7833 ro->err = __perf_event_stop(&sd);
7836 static int __perf_pmu_output_stop(void *info)
7838 struct perf_event *event = info;
7839 struct pmu *pmu = event->ctx->pmu;
7840 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7841 struct remote_output ro = {
7846 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7847 if (cpuctx->task_ctx)
7848 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7855 static void perf_pmu_output_stop(struct perf_event *event)
7857 struct perf_event *iter;
7862 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7864 * For per-CPU events, we need to make sure that neither they
7865 * nor their children are running; for cpu==-1 events it's
7866 * sufficient to stop the event itself if it's active, since
7867 * it can't have children.
7871 cpu = READ_ONCE(iter->oncpu);
7876 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7877 if (err == -EAGAIN) {
7886 * task tracking -- fork/exit
7888 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7891 struct perf_task_event {
7892 struct task_struct *task;
7893 struct perf_event_context *task_ctx;
7896 struct perf_event_header header;
7906 static int perf_event_task_match(struct perf_event *event)
7908 return event->attr.comm || event->attr.mmap ||
7909 event->attr.mmap2 || event->attr.mmap_data ||
7913 static void perf_event_task_output(struct perf_event *event,
7916 struct perf_task_event *task_event = data;
7917 struct perf_output_handle handle;
7918 struct perf_sample_data sample;
7919 struct task_struct *task = task_event->task;
7920 int ret, size = task_event->event_id.header.size;
7922 if (!perf_event_task_match(event))
7925 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7927 ret = perf_output_begin(&handle, &sample, event,
7928 task_event->event_id.header.size);
7932 task_event->event_id.pid = perf_event_pid(event, task);
7933 task_event->event_id.tid = perf_event_tid(event, task);
7935 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7936 task_event->event_id.ppid = perf_event_pid(event,
7938 task_event->event_id.ptid = perf_event_pid(event,
7940 } else { /* PERF_RECORD_FORK */
7941 task_event->event_id.ppid = perf_event_pid(event, current);
7942 task_event->event_id.ptid = perf_event_tid(event, current);
7945 task_event->event_id.time = perf_event_clock(event);
7947 perf_output_put(&handle, task_event->event_id);
7949 perf_event__output_id_sample(event, &handle, &sample);
7951 perf_output_end(&handle);
7953 task_event->event_id.header.size = size;
7956 static void perf_event_task(struct task_struct *task,
7957 struct perf_event_context *task_ctx,
7960 struct perf_task_event task_event;
7962 if (!atomic_read(&nr_comm_events) &&
7963 !atomic_read(&nr_mmap_events) &&
7964 !atomic_read(&nr_task_events))
7967 task_event = (struct perf_task_event){
7969 .task_ctx = task_ctx,
7972 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7974 .size = sizeof(task_event.event_id),
7984 perf_iterate_sb(perf_event_task_output,
7989 void perf_event_fork(struct task_struct *task)
7991 perf_event_task(task, NULL, 1);
7992 perf_event_namespaces(task);
7999 struct perf_comm_event {
8000 struct task_struct *task;
8005 struct perf_event_header header;
8012 static int perf_event_comm_match(struct perf_event *event)
8014 return event->attr.comm;
8017 static void perf_event_comm_output(struct perf_event *event,
8020 struct perf_comm_event *comm_event = data;
8021 struct perf_output_handle handle;
8022 struct perf_sample_data sample;
8023 int size = comm_event->event_id.header.size;
8026 if (!perf_event_comm_match(event))
8029 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8030 ret = perf_output_begin(&handle, &sample, event,
8031 comm_event->event_id.header.size);
8036 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8037 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8039 perf_output_put(&handle, comm_event->event_id);
8040 __output_copy(&handle, comm_event->comm,
8041 comm_event->comm_size);
8043 perf_event__output_id_sample(event, &handle, &sample);
8045 perf_output_end(&handle);
8047 comm_event->event_id.header.size = size;
8050 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8052 char comm[TASK_COMM_LEN];
8055 memset(comm, 0, sizeof(comm));
8056 strlcpy(comm, comm_event->task->comm, sizeof(comm));
8057 size = ALIGN(strlen(comm)+1, sizeof(u64));
8059 comm_event->comm = comm;
8060 comm_event->comm_size = size;
8062 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8064 perf_iterate_sb(perf_event_comm_output,
8069 void perf_event_comm(struct task_struct *task, bool exec)
8071 struct perf_comm_event comm_event;
8073 if (!atomic_read(&nr_comm_events))
8076 comm_event = (struct perf_comm_event){
8082 .type = PERF_RECORD_COMM,
8083 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8091 perf_event_comm_event(&comm_event);
8095 * namespaces tracking
8098 struct perf_namespaces_event {
8099 struct task_struct *task;
8102 struct perf_event_header header;
8107 struct perf_ns_link_info link_info[NR_NAMESPACES];
8111 static int perf_event_namespaces_match(struct perf_event *event)
8113 return event->attr.namespaces;
8116 static void perf_event_namespaces_output(struct perf_event *event,
8119 struct perf_namespaces_event *namespaces_event = data;
8120 struct perf_output_handle handle;
8121 struct perf_sample_data sample;
8122 u16 header_size = namespaces_event->event_id.header.size;
8125 if (!perf_event_namespaces_match(event))
8128 perf_event_header__init_id(&namespaces_event->event_id.header,
8130 ret = perf_output_begin(&handle, &sample, event,
8131 namespaces_event->event_id.header.size);
8135 namespaces_event->event_id.pid = perf_event_pid(event,
8136 namespaces_event->task);
8137 namespaces_event->event_id.tid = perf_event_tid(event,
8138 namespaces_event->task);
8140 perf_output_put(&handle, namespaces_event->event_id);
8142 perf_event__output_id_sample(event, &handle, &sample);
8144 perf_output_end(&handle);
8146 namespaces_event->event_id.header.size = header_size;
8149 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8150 struct task_struct *task,
8151 const struct proc_ns_operations *ns_ops)
8153 struct path ns_path;
8154 struct inode *ns_inode;
8157 error = ns_get_path(&ns_path, task, ns_ops);
8159 ns_inode = ns_path.dentry->d_inode;
8160 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8161 ns_link_info->ino = ns_inode->i_ino;
8166 void perf_event_namespaces(struct task_struct *task)
8168 struct perf_namespaces_event namespaces_event;
8169 struct perf_ns_link_info *ns_link_info;
8171 if (!atomic_read(&nr_namespaces_events))
8174 namespaces_event = (struct perf_namespaces_event){
8178 .type = PERF_RECORD_NAMESPACES,
8180 .size = sizeof(namespaces_event.event_id),
8184 .nr_namespaces = NR_NAMESPACES,
8185 /* .link_info[NR_NAMESPACES] */
8189 ns_link_info = namespaces_event.event_id.link_info;
8191 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8192 task, &mntns_operations);
8194 #ifdef CONFIG_USER_NS
8195 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8196 task, &userns_operations);
8198 #ifdef CONFIG_NET_NS
8199 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8200 task, &netns_operations);
8202 #ifdef CONFIG_UTS_NS
8203 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8204 task, &utsns_operations);
8206 #ifdef CONFIG_IPC_NS
8207 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8208 task, &ipcns_operations);
8210 #ifdef CONFIG_PID_NS
8211 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8212 task, &pidns_operations);
8214 #ifdef CONFIG_CGROUPS
8215 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8216 task, &cgroupns_operations);
8219 perf_iterate_sb(perf_event_namespaces_output,
8227 #ifdef CONFIG_CGROUP_PERF
8229 struct perf_cgroup_event {
8233 struct perf_event_header header;
8239 static int perf_event_cgroup_match(struct perf_event *event)
8241 return event->attr.cgroup;
8244 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8246 struct perf_cgroup_event *cgroup_event = data;
8247 struct perf_output_handle handle;
8248 struct perf_sample_data sample;
8249 u16 header_size = cgroup_event->event_id.header.size;
8252 if (!perf_event_cgroup_match(event))
8255 perf_event_header__init_id(&cgroup_event->event_id.header,
8257 ret = perf_output_begin(&handle, &sample, event,
8258 cgroup_event->event_id.header.size);
8262 perf_output_put(&handle, cgroup_event->event_id);
8263 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8265 perf_event__output_id_sample(event, &handle, &sample);
8267 perf_output_end(&handle);
8269 cgroup_event->event_id.header.size = header_size;
8272 static void perf_event_cgroup(struct cgroup *cgrp)
8274 struct perf_cgroup_event cgroup_event;
8275 char path_enomem[16] = "//enomem";
8279 if (!atomic_read(&nr_cgroup_events))
8282 cgroup_event = (struct perf_cgroup_event){
8285 .type = PERF_RECORD_CGROUP,
8287 .size = sizeof(cgroup_event.event_id),
8289 .id = cgroup_id(cgrp),
8293 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8294 if (pathname == NULL) {
8295 cgroup_event.path = path_enomem;
8297 /* just to be sure to have enough space for alignment */
8298 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8299 cgroup_event.path = pathname;
8303 * Since our buffer works in 8 byte units we need to align our string
8304 * size to a multiple of 8. However, we must guarantee the tail end is
8305 * zero'd out to avoid leaking random bits to userspace.
8307 size = strlen(cgroup_event.path) + 1;
8308 while (!IS_ALIGNED(size, sizeof(u64)))
8309 cgroup_event.path[size++] = '\0';
8311 cgroup_event.event_id.header.size += size;
8312 cgroup_event.path_size = size;
8314 perf_iterate_sb(perf_event_cgroup_output,
8327 struct perf_mmap_event {
8328 struct vm_area_struct *vma;
8330 const char *file_name;
8336 u8 build_id[BUILD_ID_SIZE_MAX];
8340 struct perf_event_header header;
8350 static int perf_event_mmap_match(struct perf_event *event,
8353 struct perf_mmap_event *mmap_event = data;
8354 struct vm_area_struct *vma = mmap_event->vma;
8355 int executable = vma->vm_flags & VM_EXEC;
8357 return (!executable && event->attr.mmap_data) ||
8358 (executable && (event->attr.mmap || event->attr.mmap2));
8361 static void perf_event_mmap_output(struct perf_event *event,
8364 struct perf_mmap_event *mmap_event = data;
8365 struct perf_output_handle handle;
8366 struct perf_sample_data sample;
8367 int size = mmap_event->event_id.header.size;
8368 u32 type = mmap_event->event_id.header.type;
8372 if (!perf_event_mmap_match(event, data))
8375 if (event->attr.mmap2) {
8376 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8377 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8378 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8379 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8380 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8381 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8382 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8385 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8386 ret = perf_output_begin(&handle, &sample, event,
8387 mmap_event->event_id.header.size);
8391 mmap_event->event_id.pid = perf_event_pid(event, current);
8392 mmap_event->event_id.tid = perf_event_tid(event, current);
8394 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8396 if (event->attr.mmap2 && use_build_id)
8397 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8399 perf_output_put(&handle, mmap_event->event_id);
8401 if (event->attr.mmap2) {
8403 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8405 __output_copy(&handle, size, 4);
8406 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8408 perf_output_put(&handle, mmap_event->maj);
8409 perf_output_put(&handle, mmap_event->min);
8410 perf_output_put(&handle, mmap_event->ino);
8411 perf_output_put(&handle, mmap_event->ino_generation);
8413 perf_output_put(&handle, mmap_event->prot);
8414 perf_output_put(&handle, mmap_event->flags);
8417 __output_copy(&handle, mmap_event->file_name,
8418 mmap_event->file_size);
8420 perf_event__output_id_sample(event, &handle, &sample);
8422 perf_output_end(&handle);
8424 mmap_event->event_id.header.size = size;
8425 mmap_event->event_id.header.type = type;
8428 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8430 struct vm_area_struct *vma = mmap_event->vma;
8431 struct file *file = vma->vm_file;
8432 int maj = 0, min = 0;
8433 u64 ino = 0, gen = 0;
8434 u32 prot = 0, flags = 0;
8440 if (vma->vm_flags & VM_READ)
8442 if (vma->vm_flags & VM_WRITE)
8444 if (vma->vm_flags & VM_EXEC)
8447 if (vma->vm_flags & VM_MAYSHARE)
8450 flags = MAP_PRIVATE;
8452 if (vma->vm_flags & VM_LOCKED)
8453 flags |= MAP_LOCKED;
8454 if (is_vm_hugetlb_page(vma))
8455 flags |= MAP_HUGETLB;
8458 struct inode *inode;
8461 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8467 * d_path() works from the end of the rb backwards, so we
8468 * need to add enough zero bytes after the string to handle
8469 * the 64bit alignment we do later.
8471 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8476 inode = file_inode(vma->vm_file);
8477 dev = inode->i_sb->s_dev;
8479 gen = inode->i_generation;
8485 if (vma->vm_ops && vma->vm_ops->name) {
8486 name = (char *) vma->vm_ops->name(vma);
8491 name = (char *)arch_vma_name(vma);
8495 if (vma->vm_start <= vma->vm_mm->start_brk &&
8496 vma->vm_end >= vma->vm_mm->brk) {
8500 if (vma->vm_start <= vma->vm_mm->start_stack &&
8501 vma->vm_end >= vma->vm_mm->start_stack) {
8511 strlcpy(tmp, name, sizeof(tmp));
8515 * Since our buffer works in 8 byte units we need to align our string
8516 * size to a multiple of 8. However, we must guarantee the tail end is
8517 * zero'd out to avoid leaking random bits to userspace.
8519 size = strlen(name)+1;
8520 while (!IS_ALIGNED(size, sizeof(u64)))
8521 name[size++] = '\0';
8523 mmap_event->file_name = name;
8524 mmap_event->file_size = size;
8525 mmap_event->maj = maj;
8526 mmap_event->min = min;
8527 mmap_event->ino = ino;
8528 mmap_event->ino_generation = gen;
8529 mmap_event->prot = prot;
8530 mmap_event->flags = flags;
8532 if (!(vma->vm_flags & VM_EXEC))
8533 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8535 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8537 if (atomic_read(&nr_build_id_events))
8538 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8540 perf_iterate_sb(perf_event_mmap_output,
8548 * Check whether inode and address range match filter criteria.
8550 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8551 struct file *file, unsigned long offset,
8554 /* d_inode(NULL) won't be equal to any mapped user-space file */
8555 if (!filter->path.dentry)
8558 if (d_inode(filter->path.dentry) != file_inode(file))
8561 if (filter->offset > offset + size)
8564 if (filter->offset + filter->size < offset)
8570 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8571 struct vm_area_struct *vma,
8572 struct perf_addr_filter_range *fr)
8574 unsigned long vma_size = vma->vm_end - vma->vm_start;
8575 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8576 struct file *file = vma->vm_file;
8578 if (!perf_addr_filter_match(filter, file, off, vma_size))
8581 if (filter->offset < off) {
8582 fr->start = vma->vm_start;
8583 fr->size = min(vma_size, filter->size - (off - filter->offset));
8585 fr->start = vma->vm_start + filter->offset - off;
8586 fr->size = min(vma->vm_end - fr->start, filter->size);
8592 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8594 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8595 struct vm_area_struct *vma = data;
8596 struct perf_addr_filter *filter;
8597 unsigned int restart = 0, count = 0;
8598 unsigned long flags;
8600 if (!has_addr_filter(event))
8606 raw_spin_lock_irqsave(&ifh->lock, flags);
8607 list_for_each_entry(filter, &ifh->list, entry) {
8608 if (perf_addr_filter_vma_adjust(filter, vma,
8609 &event->addr_filter_ranges[count]))
8616 event->addr_filters_gen++;
8617 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8620 perf_event_stop(event, 1);
8624 * Adjust all task's events' filters to the new vma
8626 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8628 struct perf_event_context *ctx;
8632 * Data tracing isn't supported yet and as such there is no need
8633 * to keep track of anything that isn't related to executable code:
8635 if (!(vma->vm_flags & VM_EXEC))
8639 for_each_task_context_nr(ctxn) {
8640 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8644 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8649 void perf_event_mmap(struct vm_area_struct *vma)
8651 struct perf_mmap_event mmap_event;
8653 if (!atomic_read(&nr_mmap_events))
8656 mmap_event = (struct perf_mmap_event){
8662 .type = PERF_RECORD_MMAP,
8663 .misc = PERF_RECORD_MISC_USER,
8668 .start = vma->vm_start,
8669 .len = vma->vm_end - vma->vm_start,
8670 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8672 /* .maj (attr_mmap2 only) */
8673 /* .min (attr_mmap2 only) */
8674 /* .ino (attr_mmap2 only) */
8675 /* .ino_generation (attr_mmap2 only) */
8676 /* .prot (attr_mmap2 only) */
8677 /* .flags (attr_mmap2 only) */
8680 perf_addr_filters_adjust(vma);
8681 perf_event_mmap_event(&mmap_event);
8684 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8685 unsigned long size, u64 flags)
8687 struct perf_output_handle handle;
8688 struct perf_sample_data sample;
8689 struct perf_aux_event {
8690 struct perf_event_header header;
8696 .type = PERF_RECORD_AUX,
8698 .size = sizeof(rec),
8706 perf_event_header__init_id(&rec.header, &sample, event);
8707 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8712 perf_output_put(&handle, rec);
8713 perf_event__output_id_sample(event, &handle, &sample);
8715 perf_output_end(&handle);
8719 * Lost/dropped samples logging
8721 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8723 struct perf_output_handle handle;
8724 struct perf_sample_data sample;
8728 struct perf_event_header header;
8730 } lost_samples_event = {
8732 .type = PERF_RECORD_LOST_SAMPLES,
8734 .size = sizeof(lost_samples_event),
8739 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8741 ret = perf_output_begin(&handle, &sample, event,
8742 lost_samples_event.header.size);
8746 perf_output_put(&handle, lost_samples_event);
8747 perf_event__output_id_sample(event, &handle, &sample);
8748 perf_output_end(&handle);
8752 * context_switch tracking
8755 struct perf_switch_event {
8756 struct task_struct *task;
8757 struct task_struct *next_prev;
8760 struct perf_event_header header;
8766 static int perf_event_switch_match(struct perf_event *event)
8768 return event->attr.context_switch;
8771 static void perf_event_switch_output(struct perf_event *event, void *data)
8773 struct perf_switch_event *se = data;
8774 struct perf_output_handle handle;
8775 struct perf_sample_data sample;
8778 if (!perf_event_switch_match(event))
8781 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8782 if (event->ctx->task) {
8783 se->event_id.header.type = PERF_RECORD_SWITCH;
8784 se->event_id.header.size = sizeof(se->event_id.header);
8786 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8787 se->event_id.header.size = sizeof(se->event_id);
8788 se->event_id.next_prev_pid =
8789 perf_event_pid(event, se->next_prev);
8790 se->event_id.next_prev_tid =
8791 perf_event_tid(event, se->next_prev);
8794 perf_event_header__init_id(&se->event_id.header, &sample, event);
8796 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8800 if (event->ctx->task)
8801 perf_output_put(&handle, se->event_id.header);
8803 perf_output_put(&handle, se->event_id);
8805 perf_event__output_id_sample(event, &handle, &sample);
8807 perf_output_end(&handle);
8810 static void perf_event_switch(struct task_struct *task,
8811 struct task_struct *next_prev, bool sched_in)
8813 struct perf_switch_event switch_event;
8815 /* N.B. caller checks nr_switch_events != 0 */
8817 switch_event = (struct perf_switch_event){
8819 .next_prev = next_prev,
8823 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8826 /* .next_prev_pid */
8827 /* .next_prev_tid */
8831 if (!sched_in && task->on_rq) {
8832 switch_event.event_id.header.misc |=
8833 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8836 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
8840 * IRQ throttle logging
8843 static void perf_log_throttle(struct perf_event *event, int enable)
8845 struct perf_output_handle handle;
8846 struct perf_sample_data sample;
8850 struct perf_event_header header;
8854 } throttle_event = {
8856 .type = PERF_RECORD_THROTTLE,
8858 .size = sizeof(throttle_event),
8860 .time = perf_event_clock(event),
8861 .id = primary_event_id(event),
8862 .stream_id = event->id,
8866 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8868 perf_event_header__init_id(&throttle_event.header, &sample, event);
8870 ret = perf_output_begin(&handle, &sample, event,
8871 throttle_event.header.size);
8875 perf_output_put(&handle, throttle_event);
8876 perf_event__output_id_sample(event, &handle, &sample);
8877 perf_output_end(&handle);
8881 * ksymbol register/unregister tracking
8884 struct perf_ksymbol_event {
8888 struct perf_event_header header;
8896 static int perf_event_ksymbol_match(struct perf_event *event)
8898 return event->attr.ksymbol;
8901 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8903 struct perf_ksymbol_event *ksymbol_event = data;
8904 struct perf_output_handle handle;
8905 struct perf_sample_data sample;
8908 if (!perf_event_ksymbol_match(event))
8911 perf_event_header__init_id(&ksymbol_event->event_id.header,
8913 ret = perf_output_begin(&handle, &sample, event,
8914 ksymbol_event->event_id.header.size);
8918 perf_output_put(&handle, ksymbol_event->event_id);
8919 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8920 perf_event__output_id_sample(event, &handle, &sample);
8922 perf_output_end(&handle);
8925 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8928 struct perf_ksymbol_event ksymbol_event;
8929 char name[KSYM_NAME_LEN];
8933 if (!atomic_read(&nr_ksymbol_events))
8936 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8937 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8940 strlcpy(name, sym, KSYM_NAME_LEN);
8941 name_len = strlen(name) + 1;
8942 while (!IS_ALIGNED(name_len, sizeof(u64)))
8943 name[name_len++] = '\0';
8944 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8947 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8949 ksymbol_event = (struct perf_ksymbol_event){
8951 .name_len = name_len,
8954 .type = PERF_RECORD_KSYMBOL,
8955 .size = sizeof(ksymbol_event.event_id) +
8960 .ksym_type = ksym_type,
8965 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8968 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8972 * bpf program load/unload tracking
8975 struct perf_bpf_event {
8976 struct bpf_prog *prog;
8978 struct perf_event_header header;
8982 u8 tag[BPF_TAG_SIZE];
8986 static int perf_event_bpf_match(struct perf_event *event)
8988 return event->attr.bpf_event;
8991 static void perf_event_bpf_output(struct perf_event *event, void *data)
8993 struct perf_bpf_event *bpf_event = data;
8994 struct perf_output_handle handle;
8995 struct perf_sample_data sample;
8998 if (!perf_event_bpf_match(event))
9001 perf_event_header__init_id(&bpf_event->event_id.header,
9003 ret = perf_output_begin(&handle, data, event,
9004 bpf_event->event_id.header.size);
9008 perf_output_put(&handle, bpf_event->event_id);
9009 perf_event__output_id_sample(event, &handle, &sample);
9011 perf_output_end(&handle);
9014 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9015 enum perf_bpf_event_type type)
9017 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9020 if (prog->aux->func_cnt == 0) {
9021 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9022 (u64)(unsigned long)prog->bpf_func,
9023 prog->jited_len, unregister,
9024 prog->aux->ksym.name);
9026 for (i = 0; i < prog->aux->func_cnt; i++) {
9027 struct bpf_prog *subprog = prog->aux->func[i];
9030 PERF_RECORD_KSYMBOL_TYPE_BPF,
9031 (u64)(unsigned long)subprog->bpf_func,
9032 subprog->jited_len, unregister,
9033 prog->aux->ksym.name);
9038 void perf_event_bpf_event(struct bpf_prog *prog,
9039 enum perf_bpf_event_type type,
9042 struct perf_bpf_event bpf_event;
9044 if (type <= PERF_BPF_EVENT_UNKNOWN ||
9045 type >= PERF_BPF_EVENT_MAX)
9049 case PERF_BPF_EVENT_PROG_LOAD:
9050 case PERF_BPF_EVENT_PROG_UNLOAD:
9051 if (atomic_read(&nr_ksymbol_events))
9052 perf_event_bpf_emit_ksymbols(prog, type);
9058 if (!atomic_read(&nr_bpf_events))
9061 bpf_event = (struct perf_bpf_event){
9065 .type = PERF_RECORD_BPF_EVENT,
9066 .size = sizeof(bpf_event.event_id),
9070 .id = prog->aux->id,
9074 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9076 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9077 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9080 struct perf_text_poke_event {
9081 const void *old_bytes;
9082 const void *new_bytes;
9088 struct perf_event_header header;
9094 static int perf_event_text_poke_match(struct perf_event *event)
9096 return event->attr.text_poke;
9099 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9101 struct perf_text_poke_event *text_poke_event = data;
9102 struct perf_output_handle handle;
9103 struct perf_sample_data sample;
9107 if (!perf_event_text_poke_match(event))
9110 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9112 ret = perf_output_begin(&handle, &sample, event,
9113 text_poke_event->event_id.header.size);
9117 perf_output_put(&handle, text_poke_event->event_id);
9118 perf_output_put(&handle, text_poke_event->old_len);
9119 perf_output_put(&handle, text_poke_event->new_len);
9121 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9122 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9124 if (text_poke_event->pad)
9125 __output_copy(&handle, &padding, text_poke_event->pad);
9127 perf_event__output_id_sample(event, &handle, &sample);
9129 perf_output_end(&handle);
9132 void perf_event_text_poke(const void *addr, const void *old_bytes,
9133 size_t old_len, const void *new_bytes, size_t new_len)
9135 struct perf_text_poke_event text_poke_event;
9138 if (!atomic_read(&nr_text_poke_events))
9141 tot = sizeof(text_poke_event.old_len) + old_len;
9142 tot += sizeof(text_poke_event.new_len) + new_len;
9143 pad = ALIGN(tot, sizeof(u64)) - tot;
9145 text_poke_event = (struct perf_text_poke_event){
9146 .old_bytes = old_bytes,
9147 .new_bytes = new_bytes,
9153 .type = PERF_RECORD_TEXT_POKE,
9154 .misc = PERF_RECORD_MISC_KERNEL,
9155 .size = sizeof(text_poke_event.event_id) + tot + pad,
9157 .addr = (unsigned long)addr,
9161 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9164 void perf_event_itrace_started(struct perf_event *event)
9166 event->attach_state |= PERF_ATTACH_ITRACE;
9169 static void perf_log_itrace_start(struct perf_event *event)
9171 struct perf_output_handle handle;
9172 struct perf_sample_data sample;
9173 struct perf_aux_event {
9174 struct perf_event_header header;
9181 event = event->parent;
9183 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9184 event->attach_state & PERF_ATTACH_ITRACE)
9187 rec.header.type = PERF_RECORD_ITRACE_START;
9188 rec.header.misc = 0;
9189 rec.header.size = sizeof(rec);
9190 rec.pid = perf_event_pid(event, current);
9191 rec.tid = perf_event_tid(event, current);
9193 perf_event_header__init_id(&rec.header, &sample, event);
9194 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9199 perf_output_put(&handle, rec);
9200 perf_event__output_id_sample(event, &handle, &sample);
9202 perf_output_end(&handle);
9205 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9207 struct perf_output_handle handle;
9208 struct perf_sample_data sample;
9209 struct perf_aux_event {
9210 struct perf_event_header header;
9216 event = event->parent;
9218 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9219 rec.header.misc = 0;
9220 rec.header.size = sizeof(rec);
9223 perf_event_header__init_id(&rec.header, &sample, event);
9224 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9229 perf_output_put(&handle, rec);
9230 perf_event__output_id_sample(event, &handle, &sample);
9232 perf_output_end(&handle);
9236 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9238 struct hw_perf_event *hwc = &event->hw;
9242 seq = __this_cpu_read(perf_throttled_seq);
9243 if (seq != hwc->interrupts_seq) {
9244 hwc->interrupts_seq = seq;
9245 hwc->interrupts = 1;
9248 if (unlikely(throttle
9249 && hwc->interrupts >= max_samples_per_tick)) {
9250 __this_cpu_inc(perf_throttled_count);
9251 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9252 hwc->interrupts = MAX_INTERRUPTS;
9253 perf_log_throttle(event, 0);
9258 if (event->attr.freq) {
9259 u64 now = perf_clock();
9260 s64 delta = now - hwc->freq_time_stamp;
9262 hwc->freq_time_stamp = now;
9264 if (delta > 0 && delta < 2*TICK_NSEC)
9265 perf_adjust_period(event, delta, hwc->last_period, true);
9271 int perf_event_account_interrupt(struct perf_event *event)
9273 return __perf_event_account_interrupt(event, 1);
9277 * Generic event overflow handling, sampling.
9280 static int __perf_event_overflow(struct perf_event *event,
9281 int throttle, struct perf_sample_data *data,
9282 struct pt_regs *regs)
9284 int events = atomic_read(&event->event_limit);
9288 * Non-sampling counters might still use the PMI to fold short
9289 * hardware counters, ignore those.
9291 if (unlikely(!is_sampling_event(event)))
9294 ret = __perf_event_account_interrupt(event, throttle);
9297 * XXX event_limit might not quite work as expected on inherited
9301 event->pending_kill = POLL_IN;
9302 if (events && atomic_dec_and_test(&event->event_limit)) {
9304 event->pending_kill = POLL_HUP;
9305 perf_event_disable_inatomic(event);
9308 if (event->attr.sigtrap) {
9310 * Should not be able to return to user space without processing
9311 * pending_sigtrap (kernel events can overflow multiple times).
9313 WARN_ON_ONCE(event->pending_sigtrap && event->attr.exclude_kernel);
9314 if (!event->pending_sigtrap) {
9315 event->pending_sigtrap = 1;
9316 local_inc(&event->ctx->nr_pending);
9318 event->pending_addr = data->addr;
9319 irq_work_queue(&event->pending_irq);
9322 READ_ONCE(event->overflow_handler)(event, data, regs);
9324 if (*perf_event_fasync(event) && event->pending_kill) {
9325 event->pending_wakeup = 1;
9326 irq_work_queue(&event->pending_irq);
9332 int perf_event_overflow(struct perf_event *event,
9333 struct perf_sample_data *data,
9334 struct pt_regs *regs)
9336 return __perf_event_overflow(event, 1, data, regs);
9340 * Generic software event infrastructure
9343 struct swevent_htable {
9344 struct swevent_hlist *swevent_hlist;
9345 struct mutex hlist_mutex;
9348 /* Recursion avoidance in each contexts */
9349 int recursion[PERF_NR_CONTEXTS];
9352 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9355 * We directly increment event->count and keep a second value in
9356 * event->hw.period_left to count intervals. This period event
9357 * is kept in the range [-sample_period, 0] so that we can use the
9361 u64 perf_swevent_set_period(struct perf_event *event)
9363 struct hw_perf_event *hwc = &event->hw;
9364 u64 period = hwc->last_period;
9368 hwc->last_period = hwc->sample_period;
9371 old = val = local64_read(&hwc->period_left);
9375 nr = div64_u64(period + val, period);
9376 offset = nr * period;
9378 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9384 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9385 struct perf_sample_data *data,
9386 struct pt_regs *regs)
9388 struct hw_perf_event *hwc = &event->hw;
9392 overflow = perf_swevent_set_period(event);
9394 if (hwc->interrupts == MAX_INTERRUPTS)
9397 for (; overflow; overflow--) {
9398 if (__perf_event_overflow(event, throttle,
9401 * We inhibit the overflow from happening when
9402 * hwc->interrupts == MAX_INTERRUPTS.
9410 static void perf_swevent_event(struct perf_event *event, u64 nr,
9411 struct perf_sample_data *data,
9412 struct pt_regs *regs)
9414 struct hw_perf_event *hwc = &event->hw;
9416 local64_add(nr, &event->count);
9421 if (!is_sampling_event(event))
9424 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9426 return perf_swevent_overflow(event, 1, data, regs);
9428 data->period = event->hw.last_period;
9430 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9431 return perf_swevent_overflow(event, 1, data, regs);
9433 if (local64_add_negative(nr, &hwc->period_left))
9436 perf_swevent_overflow(event, 0, data, regs);
9439 static int perf_exclude_event(struct perf_event *event,
9440 struct pt_regs *regs)
9442 if (event->hw.state & PERF_HES_STOPPED)
9446 if (event->attr.exclude_user && user_mode(regs))
9449 if (event->attr.exclude_kernel && !user_mode(regs))
9456 static int perf_swevent_match(struct perf_event *event,
9457 enum perf_type_id type,
9459 struct perf_sample_data *data,
9460 struct pt_regs *regs)
9462 if (event->attr.type != type)
9465 if (event->attr.config != event_id)
9468 if (perf_exclude_event(event, regs))
9474 static inline u64 swevent_hash(u64 type, u32 event_id)
9476 u64 val = event_id | (type << 32);
9478 return hash_64(val, SWEVENT_HLIST_BITS);
9481 static inline struct hlist_head *
9482 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9484 u64 hash = swevent_hash(type, event_id);
9486 return &hlist->heads[hash];
9489 /* For the read side: events when they trigger */
9490 static inline struct hlist_head *
9491 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9493 struct swevent_hlist *hlist;
9495 hlist = rcu_dereference(swhash->swevent_hlist);
9499 return __find_swevent_head(hlist, type, event_id);
9502 /* For the event head insertion and removal in the hlist */
9503 static inline struct hlist_head *
9504 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9506 struct swevent_hlist *hlist;
9507 u32 event_id = event->attr.config;
9508 u64 type = event->attr.type;
9511 * Event scheduling is always serialized against hlist allocation
9512 * and release. Which makes the protected version suitable here.
9513 * The context lock guarantees that.
9515 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9516 lockdep_is_held(&event->ctx->lock));
9520 return __find_swevent_head(hlist, type, event_id);
9523 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9525 struct perf_sample_data *data,
9526 struct pt_regs *regs)
9528 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9529 struct perf_event *event;
9530 struct hlist_head *head;
9533 head = find_swevent_head_rcu(swhash, type, event_id);
9537 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9538 if (perf_swevent_match(event, type, event_id, data, regs))
9539 perf_swevent_event(event, nr, data, regs);
9545 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9547 int perf_swevent_get_recursion_context(void)
9549 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9551 return get_recursion_context(swhash->recursion);
9553 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9555 void perf_swevent_put_recursion_context(int rctx)
9557 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9559 put_recursion_context(swhash->recursion, rctx);
9562 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9564 struct perf_sample_data data;
9566 if (WARN_ON_ONCE(!regs))
9569 perf_sample_data_init(&data, addr, 0);
9570 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9573 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9577 preempt_disable_notrace();
9578 rctx = perf_swevent_get_recursion_context();
9579 if (unlikely(rctx < 0))
9582 ___perf_sw_event(event_id, nr, regs, addr);
9584 perf_swevent_put_recursion_context(rctx);
9586 preempt_enable_notrace();
9589 static void perf_swevent_read(struct perf_event *event)
9593 static int perf_swevent_add(struct perf_event *event, int flags)
9595 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9596 struct hw_perf_event *hwc = &event->hw;
9597 struct hlist_head *head;
9599 if (is_sampling_event(event)) {
9600 hwc->last_period = hwc->sample_period;
9601 perf_swevent_set_period(event);
9604 hwc->state = !(flags & PERF_EF_START);
9606 head = find_swevent_head(swhash, event);
9607 if (WARN_ON_ONCE(!head))
9610 hlist_add_head_rcu(&event->hlist_entry, head);
9611 perf_event_update_userpage(event);
9616 static void perf_swevent_del(struct perf_event *event, int flags)
9618 hlist_del_rcu(&event->hlist_entry);
9621 static void perf_swevent_start(struct perf_event *event, int flags)
9623 event->hw.state = 0;
9626 static void perf_swevent_stop(struct perf_event *event, int flags)
9628 event->hw.state = PERF_HES_STOPPED;
9631 /* Deref the hlist from the update side */
9632 static inline struct swevent_hlist *
9633 swevent_hlist_deref(struct swevent_htable *swhash)
9635 return rcu_dereference_protected(swhash->swevent_hlist,
9636 lockdep_is_held(&swhash->hlist_mutex));
9639 static void swevent_hlist_release(struct swevent_htable *swhash)
9641 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9646 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9647 kfree_rcu(hlist, rcu_head);
9650 static void swevent_hlist_put_cpu(int cpu)
9652 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9654 mutex_lock(&swhash->hlist_mutex);
9656 if (!--swhash->hlist_refcount)
9657 swevent_hlist_release(swhash);
9659 mutex_unlock(&swhash->hlist_mutex);
9662 static void swevent_hlist_put(void)
9666 for_each_possible_cpu(cpu)
9667 swevent_hlist_put_cpu(cpu);
9670 static int swevent_hlist_get_cpu(int cpu)
9672 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9675 mutex_lock(&swhash->hlist_mutex);
9676 if (!swevent_hlist_deref(swhash) &&
9677 cpumask_test_cpu(cpu, perf_online_mask)) {
9678 struct swevent_hlist *hlist;
9680 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9685 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9687 swhash->hlist_refcount++;
9689 mutex_unlock(&swhash->hlist_mutex);
9694 static int swevent_hlist_get(void)
9696 int err, cpu, failed_cpu;
9698 mutex_lock(&pmus_lock);
9699 for_each_possible_cpu(cpu) {
9700 err = swevent_hlist_get_cpu(cpu);
9706 mutex_unlock(&pmus_lock);
9709 for_each_possible_cpu(cpu) {
9710 if (cpu == failed_cpu)
9712 swevent_hlist_put_cpu(cpu);
9714 mutex_unlock(&pmus_lock);
9718 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9720 static void sw_perf_event_destroy(struct perf_event *event)
9722 u64 event_id = event->attr.config;
9724 WARN_ON(event->parent);
9726 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9727 swevent_hlist_put();
9730 static int perf_swevent_init(struct perf_event *event)
9732 u64 event_id = event->attr.config;
9734 if (event->attr.type != PERF_TYPE_SOFTWARE)
9738 * no branch sampling for software events
9740 if (has_branch_stack(event))
9744 case PERF_COUNT_SW_CPU_CLOCK:
9745 case PERF_COUNT_SW_TASK_CLOCK:
9752 if (event_id >= PERF_COUNT_SW_MAX)
9755 if (!event->parent) {
9758 err = swevent_hlist_get();
9762 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9763 event->destroy = sw_perf_event_destroy;
9769 static struct pmu perf_swevent = {
9770 .task_ctx_nr = perf_sw_context,
9772 .capabilities = PERF_PMU_CAP_NO_NMI,
9774 .event_init = perf_swevent_init,
9775 .add = perf_swevent_add,
9776 .del = perf_swevent_del,
9777 .start = perf_swevent_start,
9778 .stop = perf_swevent_stop,
9779 .read = perf_swevent_read,
9782 #ifdef CONFIG_EVENT_TRACING
9784 static int perf_tp_filter_match(struct perf_event *event,
9785 struct perf_sample_data *data)
9787 void *record = data->raw->frag.data;
9789 /* only top level events have filters set */
9791 event = event->parent;
9793 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9798 static int perf_tp_event_match(struct perf_event *event,
9799 struct perf_sample_data *data,
9800 struct pt_regs *regs)
9802 if (event->hw.state & PERF_HES_STOPPED)
9805 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9807 if (event->attr.exclude_kernel && !user_mode(regs))
9810 if (!perf_tp_filter_match(event, data))
9816 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9817 struct trace_event_call *call, u64 count,
9818 struct pt_regs *regs, struct hlist_head *head,
9819 struct task_struct *task)
9821 if (bpf_prog_array_valid(call)) {
9822 *(struct pt_regs **)raw_data = regs;
9823 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9824 perf_swevent_put_recursion_context(rctx);
9828 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9831 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9833 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9834 struct pt_regs *regs, struct hlist_head *head, int rctx,
9835 struct task_struct *task)
9837 struct perf_sample_data data;
9838 struct perf_event *event;
9840 struct perf_raw_record raw = {
9847 perf_sample_data_init(&data, 0, 0);
9849 data.sample_flags |= PERF_SAMPLE_RAW;
9851 perf_trace_buf_update(record, event_type);
9853 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9854 if (perf_tp_event_match(event, &data, regs))
9855 perf_swevent_event(event, count, &data, regs);
9859 * If we got specified a target task, also iterate its context and
9860 * deliver this event there too.
9862 if (task && task != current) {
9863 struct perf_event_context *ctx;
9864 struct trace_entry *entry = record;
9867 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9871 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9872 if (event->cpu != smp_processor_id())
9874 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9876 if (event->attr.config != entry->type)
9878 /* Cannot deliver synchronous signal to other task. */
9879 if (event->attr.sigtrap)
9881 if (perf_tp_event_match(event, &data, regs))
9882 perf_swevent_event(event, count, &data, regs);
9888 perf_swevent_put_recursion_context(rctx);
9890 EXPORT_SYMBOL_GPL(perf_tp_event);
9892 static void tp_perf_event_destroy(struct perf_event *event)
9894 perf_trace_destroy(event);
9897 static int perf_tp_event_init(struct perf_event *event)
9901 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9905 * no branch sampling for tracepoint events
9907 if (has_branch_stack(event))
9910 err = perf_trace_init(event);
9914 event->destroy = tp_perf_event_destroy;
9919 static struct pmu perf_tracepoint = {
9920 .task_ctx_nr = perf_sw_context,
9922 .event_init = perf_tp_event_init,
9923 .add = perf_trace_add,
9924 .del = perf_trace_del,
9925 .start = perf_swevent_start,
9926 .stop = perf_swevent_stop,
9927 .read = perf_swevent_read,
9930 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9932 * Flags in config, used by dynamic PMU kprobe and uprobe
9933 * The flags should match following PMU_FORMAT_ATTR().
9935 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9936 * if not set, create kprobe/uprobe
9938 * The following values specify a reference counter (or semaphore in the
9939 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9940 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9942 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9943 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9945 enum perf_probe_config {
9946 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9947 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9948 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9951 PMU_FORMAT_ATTR(retprobe, "config:0");
9954 #ifdef CONFIG_KPROBE_EVENTS
9955 static struct attribute *kprobe_attrs[] = {
9956 &format_attr_retprobe.attr,
9960 static struct attribute_group kprobe_format_group = {
9962 .attrs = kprobe_attrs,
9965 static const struct attribute_group *kprobe_attr_groups[] = {
9966 &kprobe_format_group,
9970 static int perf_kprobe_event_init(struct perf_event *event);
9971 static struct pmu perf_kprobe = {
9972 .task_ctx_nr = perf_sw_context,
9973 .event_init = perf_kprobe_event_init,
9974 .add = perf_trace_add,
9975 .del = perf_trace_del,
9976 .start = perf_swevent_start,
9977 .stop = perf_swevent_stop,
9978 .read = perf_swevent_read,
9979 .attr_groups = kprobe_attr_groups,
9982 static int perf_kprobe_event_init(struct perf_event *event)
9987 if (event->attr.type != perf_kprobe.type)
9990 if (!perfmon_capable())
9994 * no branch sampling for probe events
9996 if (has_branch_stack(event))
9999 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10000 err = perf_kprobe_init(event, is_retprobe);
10004 event->destroy = perf_kprobe_destroy;
10008 #endif /* CONFIG_KPROBE_EVENTS */
10010 #ifdef CONFIG_UPROBE_EVENTS
10011 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10013 static struct attribute *uprobe_attrs[] = {
10014 &format_attr_retprobe.attr,
10015 &format_attr_ref_ctr_offset.attr,
10019 static struct attribute_group uprobe_format_group = {
10021 .attrs = uprobe_attrs,
10024 static const struct attribute_group *uprobe_attr_groups[] = {
10025 &uprobe_format_group,
10029 static int perf_uprobe_event_init(struct perf_event *event);
10030 static struct pmu perf_uprobe = {
10031 .task_ctx_nr = perf_sw_context,
10032 .event_init = perf_uprobe_event_init,
10033 .add = perf_trace_add,
10034 .del = perf_trace_del,
10035 .start = perf_swevent_start,
10036 .stop = perf_swevent_stop,
10037 .read = perf_swevent_read,
10038 .attr_groups = uprobe_attr_groups,
10041 static int perf_uprobe_event_init(struct perf_event *event)
10044 unsigned long ref_ctr_offset;
10047 if (event->attr.type != perf_uprobe.type)
10050 if (!perfmon_capable())
10054 * no branch sampling for probe events
10056 if (has_branch_stack(event))
10057 return -EOPNOTSUPP;
10059 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10060 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10061 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10065 event->destroy = perf_uprobe_destroy;
10069 #endif /* CONFIG_UPROBE_EVENTS */
10071 static inline void perf_tp_register(void)
10073 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10074 #ifdef CONFIG_KPROBE_EVENTS
10075 perf_pmu_register(&perf_kprobe, "kprobe", -1);
10077 #ifdef CONFIG_UPROBE_EVENTS
10078 perf_pmu_register(&perf_uprobe, "uprobe", -1);
10082 static void perf_event_free_filter(struct perf_event *event)
10084 ftrace_profile_free_filter(event);
10087 #ifdef CONFIG_BPF_SYSCALL
10088 static void bpf_overflow_handler(struct perf_event *event,
10089 struct perf_sample_data *data,
10090 struct pt_regs *regs)
10092 struct bpf_perf_event_data_kern ctx = {
10096 struct bpf_prog *prog;
10099 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10100 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10103 prog = READ_ONCE(event->prog);
10105 if (prog->call_get_stack &&
10106 (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) &&
10107 !(data->sample_flags & PERF_SAMPLE_CALLCHAIN)) {
10108 data->callchain = perf_callchain(event, regs);
10109 data->sample_flags |= PERF_SAMPLE_CALLCHAIN;
10112 ret = bpf_prog_run(prog, &ctx);
10116 __this_cpu_dec(bpf_prog_active);
10120 event->orig_overflow_handler(event, data, regs);
10123 static int perf_event_set_bpf_handler(struct perf_event *event,
10124 struct bpf_prog *prog,
10127 if (event->overflow_handler_context)
10128 /* hw breakpoint or kernel counter */
10134 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10137 if (event->attr.precise_ip &&
10138 prog->call_get_stack &&
10139 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10140 event->attr.exclude_callchain_kernel ||
10141 event->attr.exclude_callchain_user)) {
10143 * On perf_event with precise_ip, calling bpf_get_stack()
10144 * may trigger unwinder warnings and occasional crashes.
10145 * bpf_get_[stack|stackid] works around this issue by using
10146 * callchain attached to perf_sample_data. If the
10147 * perf_event does not full (kernel and user) callchain
10148 * attached to perf_sample_data, do not allow attaching BPF
10149 * program that calls bpf_get_[stack|stackid].
10154 event->prog = prog;
10155 event->bpf_cookie = bpf_cookie;
10156 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
10157 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
10161 static void perf_event_free_bpf_handler(struct perf_event *event)
10163 struct bpf_prog *prog = event->prog;
10168 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
10169 event->prog = NULL;
10170 bpf_prog_put(prog);
10173 static int perf_event_set_bpf_handler(struct perf_event *event,
10174 struct bpf_prog *prog,
10177 return -EOPNOTSUPP;
10179 static void perf_event_free_bpf_handler(struct perf_event *event)
10185 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10186 * with perf_event_open()
10188 static inline bool perf_event_is_tracing(struct perf_event *event)
10190 if (event->pmu == &perf_tracepoint)
10192 #ifdef CONFIG_KPROBE_EVENTS
10193 if (event->pmu == &perf_kprobe)
10196 #ifdef CONFIG_UPROBE_EVENTS
10197 if (event->pmu == &perf_uprobe)
10203 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10206 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10208 if (!perf_event_is_tracing(event))
10209 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10211 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10212 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10213 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10214 is_syscall_tp = is_syscall_trace_event(event->tp_event);
10215 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10216 /* bpf programs can only be attached to u/kprobe or tracepoint */
10219 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10220 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10221 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10224 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->aux->sleepable && !is_uprobe)
10225 /* only uprobe programs are allowed to be sleepable */
10228 /* Kprobe override only works for kprobes, not uprobes. */
10229 if (prog->kprobe_override && !is_kprobe)
10232 if (is_tracepoint || is_syscall_tp) {
10233 int off = trace_event_get_offsets(event->tp_event);
10235 if (prog->aux->max_ctx_offset > off)
10239 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10242 void perf_event_free_bpf_prog(struct perf_event *event)
10244 if (!perf_event_is_tracing(event)) {
10245 perf_event_free_bpf_handler(event);
10248 perf_event_detach_bpf_prog(event);
10253 static inline void perf_tp_register(void)
10257 static void perf_event_free_filter(struct perf_event *event)
10261 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10267 void perf_event_free_bpf_prog(struct perf_event *event)
10270 #endif /* CONFIG_EVENT_TRACING */
10272 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10273 void perf_bp_event(struct perf_event *bp, void *data)
10275 struct perf_sample_data sample;
10276 struct pt_regs *regs = data;
10278 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10280 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10281 perf_swevent_event(bp, 1, &sample, regs);
10286 * Allocate a new address filter
10288 static struct perf_addr_filter *
10289 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10291 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10292 struct perf_addr_filter *filter;
10294 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10298 INIT_LIST_HEAD(&filter->entry);
10299 list_add_tail(&filter->entry, filters);
10304 static void free_filters_list(struct list_head *filters)
10306 struct perf_addr_filter *filter, *iter;
10308 list_for_each_entry_safe(filter, iter, filters, entry) {
10309 path_put(&filter->path);
10310 list_del(&filter->entry);
10316 * Free existing address filters and optionally install new ones
10318 static void perf_addr_filters_splice(struct perf_event *event,
10319 struct list_head *head)
10321 unsigned long flags;
10324 if (!has_addr_filter(event))
10327 /* don't bother with children, they don't have their own filters */
10331 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10333 list_splice_init(&event->addr_filters.list, &list);
10335 list_splice(head, &event->addr_filters.list);
10337 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10339 free_filters_list(&list);
10343 * Scan through mm's vmas and see if one of them matches the
10344 * @filter; if so, adjust filter's address range.
10345 * Called with mm::mmap_lock down for reading.
10347 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10348 struct mm_struct *mm,
10349 struct perf_addr_filter_range *fr)
10351 struct vm_area_struct *vma;
10352 VMA_ITERATOR(vmi, mm, 0);
10354 for_each_vma(vmi, vma) {
10358 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10364 * Update event's address range filters based on the
10365 * task's existing mappings, if any.
10367 static void perf_event_addr_filters_apply(struct perf_event *event)
10369 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10370 struct task_struct *task = READ_ONCE(event->ctx->task);
10371 struct perf_addr_filter *filter;
10372 struct mm_struct *mm = NULL;
10373 unsigned int count = 0;
10374 unsigned long flags;
10377 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10378 * will stop on the parent's child_mutex that our caller is also holding
10380 if (task == TASK_TOMBSTONE)
10383 if (ifh->nr_file_filters) {
10384 mm = get_task_mm(task);
10388 mmap_read_lock(mm);
10391 raw_spin_lock_irqsave(&ifh->lock, flags);
10392 list_for_each_entry(filter, &ifh->list, entry) {
10393 if (filter->path.dentry) {
10395 * Adjust base offset if the filter is associated to a
10396 * binary that needs to be mapped:
10398 event->addr_filter_ranges[count].start = 0;
10399 event->addr_filter_ranges[count].size = 0;
10401 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10403 event->addr_filter_ranges[count].start = filter->offset;
10404 event->addr_filter_ranges[count].size = filter->size;
10410 event->addr_filters_gen++;
10411 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10413 if (ifh->nr_file_filters) {
10414 mmap_read_unlock(mm);
10420 perf_event_stop(event, 1);
10424 * Address range filtering: limiting the data to certain
10425 * instruction address ranges. Filters are ioctl()ed to us from
10426 * userspace as ascii strings.
10428 * Filter string format:
10430 * ACTION RANGE_SPEC
10431 * where ACTION is one of the
10432 * * "filter": limit the trace to this region
10433 * * "start": start tracing from this address
10434 * * "stop": stop tracing at this address/region;
10436 * * for kernel addresses: <start address>[/<size>]
10437 * * for object files: <start address>[/<size>]@</path/to/object/file>
10439 * if <size> is not specified or is zero, the range is treated as a single
10440 * address; not valid for ACTION=="filter".
10454 IF_STATE_ACTION = 0,
10459 static const match_table_t if_tokens = {
10460 { IF_ACT_FILTER, "filter" },
10461 { IF_ACT_START, "start" },
10462 { IF_ACT_STOP, "stop" },
10463 { IF_SRC_FILE, "%u/%u@%s" },
10464 { IF_SRC_KERNEL, "%u/%u" },
10465 { IF_SRC_FILEADDR, "%u@%s" },
10466 { IF_SRC_KERNELADDR, "%u" },
10467 { IF_ACT_NONE, NULL },
10471 * Address filter string parser
10474 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10475 struct list_head *filters)
10477 struct perf_addr_filter *filter = NULL;
10478 char *start, *orig, *filename = NULL;
10479 substring_t args[MAX_OPT_ARGS];
10480 int state = IF_STATE_ACTION, token;
10481 unsigned int kernel = 0;
10484 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10488 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10489 static const enum perf_addr_filter_action_t actions[] = {
10490 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10491 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10492 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10499 /* filter definition begins */
10500 if (state == IF_STATE_ACTION) {
10501 filter = perf_addr_filter_new(event, filters);
10506 token = match_token(start, if_tokens, args);
10508 case IF_ACT_FILTER:
10511 if (state != IF_STATE_ACTION)
10514 filter->action = actions[token];
10515 state = IF_STATE_SOURCE;
10518 case IF_SRC_KERNELADDR:
10519 case IF_SRC_KERNEL:
10523 case IF_SRC_FILEADDR:
10525 if (state != IF_STATE_SOURCE)
10529 ret = kstrtoul(args[0].from, 0, &filter->offset);
10533 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10535 ret = kstrtoul(args[1].from, 0, &filter->size);
10540 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10541 int fpos = token == IF_SRC_FILE ? 2 : 1;
10544 filename = match_strdup(&args[fpos]);
10551 state = IF_STATE_END;
10559 * Filter definition is fully parsed, validate and install it.
10560 * Make sure that it doesn't contradict itself or the event's
10563 if (state == IF_STATE_END) {
10567 * ACTION "filter" must have a non-zero length region
10570 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10579 * For now, we only support file-based filters
10580 * in per-task events; doing so for CPU-wide
10581 * events requires additional context switching
10582 * trickery, since same object code will be
10583 * mapped at different virtual addresses in
10584 * different processes.
10587 if (!event->ctx->task)
10590 /* look up the path and grab its inode */
10591 ret = kern_path(filename, LOOKUP_FOLLOW,
10597 if (!filter->path.dentry ||
10598 !S_ISREG(d_inode(filter->path.dentry)
10602 event->addr_filters.nr_file_filters++;
10605 /* ready to consume more filters */
10608 state = IF_STATE_ACTION;
10614 if (state != IF_STATE_ACTION)
10624 free_filters_list(filters);
10631 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10633 LIST_HEAD(filters);
10637 * Since this is called in perf_ioctl() path, we're already holding
10640 lockdep_assert_held(&event->ctx->mutex);
10642 if (WARN_ON_ONCE(event->parent))
10645 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10647 goto fail_clear_files;
10649 ret = event->pmu->addr_filters_validate(&filters);
10651 goto fail_free_filters;
10653 /* remove existing filters, if any */
10654 perf_addr_filters_splice(event, &filters);
10656 /* install new filters */
10657 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10662 free_filters_list(&filters);
10665 event->addr_filters.nr_file_filters = 0;
10670 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10675 filter_str = strndup_user(arg, PAGE_SIZE);
10676 if (IS_ERR(filter_str))
10677 return PTR_ERR(filter_str);
10679 #ifdef CONFIG_EVENT_TRACING
10680 if (perf_event_is_tracing(event)) {
10681 struct perf_event_context *ctx = event->ctx;
10684 * Beware, here be dragons!!
10686 * the tracepoint muck will deadlock against ctx->mutex, but
10687 * the tracepoint stuff does not actually need it. So
10688 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10689 * already have a reference on ctx.
10691 * This can result in event getting moved to a different ctx,
10692 * but that does not affect the tracepoint state.
10694 mutex_unlock(&ctx->mutex);
10695 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10696 mutex_lock(&ctx->mutex);
10699 if (has_addr_filter(event))
10700 ret = perf_event_set_addr_filter(event, filter_str);
10707 * hrtimer based swevent callback
10710 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10712 enum hrtimer_restart ret = HRTIMER_RESTART;
10713 struct perf_sample_data data;
10714 struct pt_regs *regs;
10715 struct perf_event *event;
10718 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10720 if (event->state != PERF_EVENT_STATE_ACTIVE)
10721 return HRTIMER_NORESTART;
10723 event->pmu->read(event);
10725 perf_sample_data_init(&data, 0, event->hw.last_period);
10726 regs = get_irq_regs();
10728 if (regs && !perf_exclude_event(event, regs)) {
10729 if (!(event->attr.exclude_idle && is_idle_task(current)))
10730 if (__perf_event_overflow(event, 1, &data, regs))
10731 ret = HRTIMER_NORESTART;
10734 period = max_t(u64, 10000, event->hw.sample_period);
10735 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10740 static void perf_swevent_start_hrtimer(struct perf_event *event)
10742 struct hw_perf_event *hwc = &event->hw;
10745 if (!is_sampling_event(event))
10748 period = local64_read(&hwc->period_left);
10753 local64_set(&hwc->period_left, 0);
10755 period = max_t(u64, 10000, hwc->sample_period);
10757 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10758 HRTIMER_MODE_REL_PINNED_HARD);
10761 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10763 struct hw_perf_event *hwc = &event->hw;
10765 if (is_sampling_event(event)) {
10766 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10767 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10769 hrtimer_cancel(&hwc->hrtimer);
10773 static void perf_swevent_init_hrtimer(struct perf_event *event)
10775 struct hw_perf_event *hwc = &event->hw;
10777 if (!is_sampling_event(event))
10780 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10781 hwc->hrtimer.function = perf_swevent_hrtimer;
10784 * Since hrtimers have a fixed rate, we can do a static freq->period
10785 * mapping and avoid the whole period adjust feedback stuff.
10787 if (event->attr.freq) {
10788 long freq = event->attr.sample_freq;
10790 event->attr.sample_period = NSEC_PER_SEC / freq;
10791 hwc->sample_period = event->attr.sample_period;
10792 local64_set(&hwc->period_left, hwc->sample_period);
10793 hwc->last_period = hwc->sample_period;
10794 event->attr.freq = 0;
10799 * Software event: cpu wall time clock
10802 static void cpu_clock_event_update(struct perf_event *event)
10807 now = local_clock();
10808 prev = local64_xchg(&event->hw.prev_count, now);
10809 local64_add(now - prev, &event->count);
10812 static void cpu_clock_event_start(struct perf_event *event, int flags)
10814 local64_set(&event->hw.prev_count, local_clock());
10815 perf_swevent_start_hrtimer(event);
10818 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10820 perf_swevent_cancel_hrtimer(event);
10821 cpu_clock_event_update(event);
10824 static int cpu_clock_event_add(struct perf_event *event, int flags)
10826 if (flags & PERF_EF_START)
10827 cpu_clock_event_start(event, flags);
10828 perf_event_update_userpage(event);
10833 static void cpu_clock_event_del(struct perf_event *event, int flags)
10835 cpu_clock_event_stop(event, flags);
10838 static void cpu_clock_event_read(struct perf_event *event)
10840 cpu_clock_event_update(event);
10843 static int cpu_clock_event_init(struct perf_event *event)
10845 if (event->attr.type != PERF_TYPE_SOFTWARE)
10848 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10852 * no branch sampling for software events
10854 if (has_branch_stack(event))
10855 return -EOPNOTSUPP;
10857 perf_swevent_init_hrtimer(event);
10862 static struct pmu perf_cpu_clock = {
10863 .task_ctx_nr = perf_sw_context,
10865 .capabilities = PERF_PMU_CAP_NO_NMI,
10867 .event_init = cpu_clock_event_init,
10868 .add = cpu_clock_event_add,
10869 .del = cpu_clock_event_del,
10870 .start = cpu_clock_event_start,
10871 .stop = cpu_clock_event_stop,
10872 .read = cpu_clock_event_read,
10876 * Software event: task time clock
10879 static void task_clock_event_update(struct perf_event *event, u64 now)
10884 prev = local64_xchg(&event->hw.prev_count, now);
10885 delta = now - prev;
10886 local64_add(delta, &event->count);
10889 static void task_clock_event_start(struct perf_event *event, int flags)
10891 local64_set(&event->hw.prev_count, event->ctx->time);
10892 perf_swevent_start_hrtimer(event);
10895 static void task_clock_event_stop(struct perf_event *event, int flags)
10897 perf_swevent_cancel_hrtimer(event);
10898 task_clock_event_update(event, event->ctx->time);
10901 static int task_clock_event_add(struct perf_event *event, int flags)
10903 if (flags & PERF_EF_START)
10904 task_clock_event_start(event, flags);
10905 perf_event_update_userpage(event);
10910 static void task_clock_event_del(struct perf_event *event, int flags)
10912 task_clock_event_stop(event, PERF_EF_UPDATE);
10915 static void task_clock_event_read(struct perf_event *event)
10917 u64 now = perf_clock();
10918 u64 delta = now - event->ctx->timestamp;
10919 u64 time = event->ctx->time + delta;
10921 task_clock_event_update(event, time);
10924 static int task_clock_event_init(struct perf_event *event)
10926 if (event->attr.type != PERF_TYPE_SOFTWARE)
10929 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10933 * no branch sampling for software events
10935 if (has_branch_stack(event))
10936 return -EOPNOTSUPP;
10938 perf_swevent_init_hrtimer(event);
10943 static struct pmu perf_task_clock = {
10944 .task_ctx_nr = perf_sw_context,
10946 .capabilities = PERF_PMU_CAP_NO_NMI,
10948 .event_init = task_clock_event_init,
10949 .add = task_clock_event_add,
10950 .del = task_clock_event_del,
10951 .start = task_clock_event_start,
10952 .stop = task_clock_event_stop,
10953 .read = task_clock_event_read,
10956 static void perf_pmu_nop_void(struct pmu *pmu)
10960 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10964 static int perf_pmu_nop_int(struct pmu *pmu)
10969 static int perf_event_nop_int(struct perf_event *event, u64 value)
10974 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10976 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10978 __this_cpu_write(nop_txn_flags, flags);
10980 if (flags & ~PERF_PMU_TXN_ADD)
10983 perf_pmu_disable(pmu);
10986 static int perf_pmu_commit_txn(struct pmu *pmu)
10988 unsigned int flags = __this_cpu_read(nop_txn_flags);
10990 __this_cpu_write(nop_txn_flags, 0);
10992 if (flags & ~PERF_PMU_TXN_ADD)
10995 perf_pmu_enable(pmu);
10999 static void perf_pmu_cancel_txn(struct pmu *pmu)
11001 unsigned int flags = __this_cpu_read(nop_txn_flags);
11003 __this_cpu_write(nop_txn_flags, 0);
11005 if (flags & ~PERF_PMU_TXN_ADD)
11008 perf_pmu_enable(pmu);
11011 static int perf_event_idx_default(struct perf_event *event)
11017 * Ensures all contexts with the same task_ctx_nr have the same
11018 * pmu_cpu_context too.
11020 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
11027 list_for_each_entry(pmu, &pmus, entry) {
11028 if (pmu->task_ctx_nr == ctxn)
11029 return pmu->pmu_cpu_context;
11035 static void free_pmu_context(struct pmu *pmu)
11038 * Static contexts such as perf_sw_context have a global lifetime
11039 * and may be shared between different PMUs. Avoid freeing them
11040 * when a single PMU is going away.
11042 if (pmu->task_ctx_nr > perf_invalid_context)
11045 free_percpu(pmu->pmu_cpu_context);
11049 * Let userspace know that this PMU supports address range filtering:
11051 static ssize_t nr_addr_filters_show(struct device *dev,
11052 struct device_attribute *attr,
11055 struct pmu *pmu = dev_get_drvdata(dev);
11057 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11059 DEVICE_ATTR_RO(nr_addr_filters);
11061 static struct idr pmu_idr;
11064 type_show(struct device *dev, struct device_attribute *attr, char *page)
11066 struct pmu *pmu = dev_get_drvdata(dev);
11068 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11070 static DEVICE_ATTR_RO(type);
11073 perf_event_mux_interval_ms_show(struct device *dev,
11074 struct device_attribute *attr,
11077 struct pmu *pmu = dev_get_drvdata(dev);
11079 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11082 static DEFINE_MUTEX(mux_interval_mutex);
11085 perf_event_mux_interval_ms_store(struct device *dev,
11086 struct device_attribute *attr,
11087 const char *buf, size_t count)
11089 struct pmu *pmu = dev_get_drvdata(dev);
11090 int timer, cpu, ret;
11092 ret = kstrtoint(buf, 0, &timer);
11099 /* same value, noting to do */
11100 if (timer == pmu->hrtimer_interval_ms)
11103 mutex_lock(&mux_interval_mutex);
11104 pmu->hrtimer_interval_ms = timer;
11106 /* update all cpuctx for this PMU */
11108 for_each_online_cpu(cpu) {
11109 struct perf_cpu_context *cpuctx;
11110 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11111 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11113 cpu_function_call(cpu,
11114 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
11116 cpus_read_unlock();
11117 mutex_unlock(&mux_interval_mutex);
11121 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11123 static struct attribute *pmu_dev_attrs[] = {
11124 &dev_attr_type.attr,
11125 &dev_attr_perf_event_mux_interval_ms.attr,
11128 ATTRIBUTE_GROUPS(pmu_dev);
11130 static int pmu_bus_running;
11131 static struct bus_type pmu_bus = {
11132 .name = "event_source",
11133 .dev_groups = pmu_dev_groups,
11136 static void pmu_dev_release(struct device *dev)
11141 static int pmu_dev_alloc(struct pmu *pmu)
11145 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11149 pmu->dev->groups = pmu->attr_groups;
11150 device_initialize(pmu->dev);
11151 ret = dev_set_name(pmu->dev, "%s", pmu->name);
11155 dev_set_drvdata(pmu->dev, pmu);
11156 pmu->dev->bus = &pmu_bus;
11157 pmu->dev->release = pmu_dev_release;
11158 ret = device_add(pmu->dev);
11162 /* For PMUs with address filters, throw in an extra attribute: */
11163 if (pmu->nr_addr_filters)
11164 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
11169 if (pmu->attr_update)
11170 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11179 device_del(pmu->dev);
11182 put_device(pmu->dev);
11186 static struct lock_class_key cpuctx_mutex;
11187 static struct lock_class_key cpuctx_lock;
11189 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11191 int cpu, ret, max = PERF_TYPE_MAX;
11193 mutex_lock(&pmus_lock);
11195 pmu->pmu_disable_count = alloc_percpu(int);
11196 if (!pmu->pmu_disable_count)
11204 if (type != PERF_TYPE_SOFTWARE) {
11208 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
11212 WARN_ON(type >= 0 && ret != type);
11218 if (pmu_bus_running) {
11219 ret = pmu_dev_alloc(pmu);
11225 if (pmu->task_ctx_nr == perf_hw_context) {
11226 static int hw_context_taken = 0;
11229 * Other than systems with heterogeneous CPUs, it never makes
11230 * sense for two PMUs to share perf_hw_context. PMUs which are
11231 * uncore must use perf_invalid_context.
11233 if (WARN_ON_ONCE(hw_context_taken &&
11234 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
11235 pmu->task_ctx_nr = perf_invalid_context;
11237 hw_context_taken = 1;
11240 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
11241 if (pmu->pmu_cpu_context)
11242 goto got_cpu_context;
11245 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
11246 if (!pmu->pmu_cpu_context)
11249 for_each_possible_cpu(cpu) {
11250 struct perf_cpu_context *cpuctx;
11252 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11253 __perf_event_init_context(&cpuctx->ctx);
11254 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
11255 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
11256 cpuctx->ctx.pmu = pmu;
11257 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
11259 __perf_mux_hrtimer_init(cpuctx, cpu);
11261 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
11262 cpuctx->heap = cpuctx->heap_default;
11266 if (!pmu->start_txn) {
11267 if (pmu->pmu_enable) {
11269 * If we have pmu_enable/pmu_disable calls, install
11270 * transaction stubs that use that to try and batch
11271 * hardware accesses.
11273 pmu->start_txn = perf_pmu_start_txn;
11274 pmu->commit_txn = perf_pmu_commit_txn;
11275 pmu->cancel_txn = perf_pmu_cancel_txn;
11277 pmu->start_txn = perf_pmu_nop_txn;
11278 pmu->commit_txn = perf_pmu_nop_int;
11279 pmu->cancel_txn = perf_pmu_nop_void;
11283 if (!pmu->pmu_enable) {
11284 pmu->pmu_enable = perf_pmu_nop_void;
11285 pmu->pmu_disable = perf_pmu_nop_void;
11288 if (!pmu->check_period)
11289 pmu->check_period = perf_event_nop_int;
11291 if (!pmu->event_idx)
11292 pmu->event_idx = perf_event_idx_default;
11295 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
11296 * since these cannot be in the IDR. This way the linear search
11297 * is fast, provided a valid software event is provided.
11299 if (type == PERF_TYPE_SOFTWARE || !name)
11300 list_add_rcu(&pmu->entry, &pmus);
11302 list_add_tail_rcu(&pmu->entry, &pmus);
11304 atomic_set(&pmu->exclusive_cnt, 0);
11307 mutex_unlock(&pmus_lock);
11312 device_del(pmu->dev);
11313 put_device(pmu->dev);
11316 if (pmu->type != PERF_TYPE_SOFTWARE)
11317 idr_remove(&pmu_idr, pmu->type);
11320 free_percpu(pmu->pmu_disable_count);
11323 EXPORT_SYMBOL_GPL(perf_pmu_register);
11325 void perf_pmu_unregister(struct pmu *pmu)
11327 mutex_lock(&pmus_lock);
11328 list_del_rcu(&pmu->entry);
11331 * We dereference the pmu list under both SRCU and regular RCU, so
11332 * synchronize against both of those.
11334 synchronize_srcu(&pmus_srcu);
11337 free_percpu(pmu->pmu_disable_count);
11338 if (pmu->type != PERF_TYPE_SOFTWARE)
11339 idr_remove(&pmu_idr, pmu->type);
11340 if (pmu_bus_running) {
11341 if (pmu->nr_addr_filters)
11342 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11343 device_del(pmu->dev);
11344 put_device(pmu->dev);
11346 free_pmu_context(pmu);
11347 mutex_unlock(&pmus_lock);
11349 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11351 static inline bool has_extended_regs(struct perf_event *event)
11353 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11354 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11357 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11359 struct perf_event_context *ctx = NULL;
11362 if (!try_module_get(pmu->module))
11366 * A number of pmu->event_init() methods iterate the sibling_list to,
11367 * for example, validate if the group fits on the PMU. Therefore,
11368 * if this is a sibling event, acquire the ctx->mutex to protect
11369 * the sibling_list.
11371 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11373 * This ctx->mutex can nest when we're called through
11374 * inheritance. See the perf_event_ctx_lock_nested() comment.
11376 ctx = perf_event_ctx_lock_nested(event->group_leader,
11377 SINGLE_DEPTH_NESTING);
11382 ret = pmu->event_init(event);
11385 perf_event_ctx_unlock(event->group_leader, ctx);
11388 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11389 has_extended_regs(event))
11392 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11393 event_has_any_exclude_flag(event))
11396 if (ret && event->destroy)
11397 event->destroy(event);
11401 module_put(pmu->module);
11406 static struct pmu *perf_init_event(struct perf_event *event)
11408 bool extended_type = false;
11409 int idx, type, ret;
11412 idx = srcu_read_lock(&pmus_srcu);
11414 /* Try parent's PMU first: */
11415 if (event->parent && event->parent->pmu) {
11416 pmu = event->parent->pmu;
11417 ret = perf_try_init_event(pmu, event);
11423 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11424 * are often aliases for PERF_TYPE_RAW.
11426 type = event->attr.type;
11427 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
11428 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
11430 type = PERF_TYPE_RAW;
11432 extended_type = true;
11433 event->attr.config &= PERF_HW_EVENT_MASK;
11439 pmu = idr_find(&pmu_idr, type);
11442 if (event->attr.type != type && type != PERF_TYPE_RAW &&
11443 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
11446 ret = perf_try_init_event(pmu, event);
11447 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
11448 type = event->attr.type;
11453 pmu = ERR_PTR(ret);
11458 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11459 ret = perf_try_init_event(pmu, event);
11463 if (ret != -ENOENT) {
11464 pmu = ERR_PTR(ret);
11469 pmu = ERR_PTR(-ENOENT);
11471 srcu_read_unlock(&pmus_srcu, idx);
11476 static void attach_sb_event(struct perf_event *event)
11478 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11480 raw_spin_lock(&pel->lock);
11481 list_add_rcu(&event->sb_list, &pel->list);
11482 raw_spin_unlock(&pel->lock);
11486 * We keep a list of all !task (and therefore per-cpu) events
11487 * that need to receive side-band records.
11489 * This avoids having to scan all the various PMU per-cpu contexts
11490 * looking for them.
11492 static void account_pmu_sb_event(struct perf_event *event)
11494 if (is_sb_event(event))
11495 attach_sb_event(event);
11498 static void account_event_cpu(struct perf_event *event, int cpu)
11503 if (is_cgroup_event(event))
11504 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11507 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11508 static void account_freq_event_nohz(void)
11510 #ifdef CONFIG_NO_HZ_FULL
11511 /* Lock so we don't race with concurrent unaccount */
11512 spin_lock(&nr_freq_lock);
11513 if (atomic_inc_return(&nr_freq_events) == 1)
11514 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11515 spin_unlock(&nr_freq_lock);
11519 static void account_freq_event(void)
11521 if (tick_nohz_full_enabled())
11522 account_freq_event_nohz();
11524 atomic_inc(&nr_freq_events);
11528 static void account_event(struct perf_event *event)
11535 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11537 if (event->attr.mmap || event->attr.mmap_data)
11538 atomic_inc(&nr_mmap_events);
11539 if (event->attr.build_id)
11540 atomic_inc(&nr_build_id_events);
11541 if (event->attr.comm)
11542 atomic_inc(&nr_comm_events);
11543 if (event->attr.namespaces)
11544 atomic_inc(&nr_namespaces_events);
11545 if (event->attr.cgroup)
11546 atomic_inc(&nr_cgroup_events);
11547 if (event->attr.task)
11548 atomic_inc(&nr_task_events);
11549 if (event->attr.freq)
11550 account_freq_event();
11551 if (event->attr.context_switch) {
11552 atomic_inc(&nr_switch_events);
11555 if (has_branch_stack(event))
11557 if (is_cgroup_event(event))
11559 if (event->attr.ksymbol)
11560 atomic_inc(&nr_ksymbol_events);
11561 if (event->attr.bpf_event)
11562 atomic_inc(&nr_bpf_events);
11563 if (event->attr.text_poke)
11564 atomic_inc(&nr_text_poke_events);
11568 * We need the mutex here because static_branch_enable()
11569 * must complete *before* the perf_sched_count increment
11572 if (atomic_inc_not_zero(&perf_sched_count))
11575 mutex_lock(&perf_sched_mutex);
11576 if (!atomic_read(&perf_sched_count)) {
11577 static_branch_enable(&perf_sched_events);
11579 * Guarantee that all CPUs observe they key change and
11580 * call the perf scheduling hooks before proceeding to
11581 * install events that need them.
11586 * Now that we have waited for the sync_sched(), allow further
11587 * increments to by-pass the mutex.
11589 atomic_inc(&perf_sched_count);
11590 mutex_unlock(&perf_sched_mutex);
11594 account_event_cpu(event, event->cpu);
11596 account_pmu_sb_event(event);
11600 * Allocate and initialize an event structure
11602 static struct perf_event *
11603 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11604 struct task_struct *task,
11605 struct perf_event *group_leader,
11606 struct perf_event *parent_event,
11607 perf_overflow_handler_t overflow_handler,
11608 void *context, int cgroup_fd)
11611 struct perf_event *event;
11612 struct hw_perf_event *hwc;
11613 long err = -EINVAL;
11616 if ((unsigned)cpu >= nr_cpu_ids) {
11617 if (!task || cpu != -1)
11618 return ERR_PTR(-EINVAL);
11620 if (attr->sigtrap && !task) {
11621 /* Requires a task: avoid signalling random tasks. */
11622 return ERR_PTR(-EINVAL);
11625 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11626 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11629 return ERR_PTR(-ENOMEM);
11632 * Single events are their own group leaders, with an
11633 * empty sibling list:
11636 group_leader = event;
11638 mutex_init(&event->child_mutex);
11639 INIT_LIST_HEAD(&event->child_list);
11641 INIT_LIST_HEAD(&event->event_entry);
11642 INIT_LIST_HEAD(&event->sibling_list);
11643 INIT_LIST_HEAD(&event->active_list);
11644 init_event_group(event);
11645 INIT_LIST_HEAD(&event->rb_entry);
11646 INIT_LIST_HEAD(&event->active_entry);
11647 INIT_LIST_HEAD(&event->addr_filters.list);
11648 INIT_HLIST_NODE(&event->hlist_entry);
11651 init_waitqueue_head(&event->waitq);
11652 init_irq_work(&event->pending_irq, perf_pending_irq);
11653 init_task_work(&event->pending_task, perf_pending_task);
11655 mutex_init(&event->mmap_mutex);
11656 raw_spin_lock_init(&event->addr_filters.lock);
11658 atomic_long_set(&event->refcount, 1);
11660 event->attr = *attr;
11661 event->group_leader = group_leader;
11665 event->parent = parent_event;
11667 event->ns = get_pid_ns(task_active_pid_ns(current));
11668 event->id = atomic64_inc_return(&perf_event_id);
11670 event->state = PERF_EVENT_STATE_INACTIVE;
11673 event->event_caps = parent_event->event_caps;
11676 event->attach_state = PERF_ATTACH_TASK;
11678 * XXX pmu::event_init needs to know what task to account to
11679 * and we cannot use the ctx information because we need the
11680 * pmu before we get a ctx.
11682 event->hw.target = get_task_struct(task);
11685 event->clock = &local_clock;
11687 event->clock = parent_event->clock;
11689 if (!overflow_handler && parent_event) {
11690 overflow_handler = parent_event->overflow_handler;
11691 context = parent_event->overflow_handler_context;
11692 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11693 if (overflow_handler == bpf_overflow_handler) {
11694 struct bpf_prog *prog = parent_event->prog;
11696 bpf_prog_inc(prog);
11697 event->prog = prog;
11698 event->orig_overflow_handler =
11699 parent_event->orig_overflow_handler;
11704 if (overflow_handler) {
11705 event->overflow_handler = overflow_handler;
11706 event->overflow_handler_context = context;
11707 } else if (is_write_backward(event)){
11708 event->overflow_handler = perf_event_output_backward;
11709 event->overflow_handler_context = NULL;
11711 event->overflow_handler = perf_event_output_forward;
11712 event->overflow_handler_context = NULL;
11715 perf_event__state_init(event);
11720 hwc->sample_period = attr->sample_period;
11721 if (attr->freq && attr->sample_freq)
11722 hwc->sample_period = 1;
11723 hwc->last_period = hwc->sample_period;
11725 local64_set(&hwc->period_left, hwc->sample_period);
11728 * We currently do not support PERF_SAMPLE_READ on inherited events.
11729 * See perf_output_read().
11731 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11734 if (!has_branch_stack(event))
11735 event->attr.branch_sample_type = 0;
11737 pmu = perf_init_event(event);
11739 err = PTR_ERR(pmu);
11744 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11745 * be different on other CPUs in the uncore mask.
11747 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11752 if (event->attr.aux_output &&
11753 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11758 if (cgroup_fd != -1) {
11759 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11764 err = exclusive_event_init(event);
11768 if (has_addr_filter(event)) {
11769 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11770 sizeof(struct perf_addr_filter_range),
11772 if (!event->addr_filter_ranges) {
11778 * Clone the parent's vma offsets: they are valid until exec()
11779 * even if the mm is not shared with the parent.
11781 if (event->parent) {
11782 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11784 raw_spin_lock_irq(&ifh->lock);
11785 memcpy(event->addr_filter_ranges,
11786 event->parent->addr_filter_ranges,
11787 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11788 raw_spin_unlock_irq(&ifh->lock);
11791 /* force hw sync on the address filters */
11792 event->addr_filters_gen = 1;
11795 if (!event->parent) {
11796 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11797 err = get_callchain_buffers(attr->sample_max_stack);
11799 goto err_addr_filters;
11803 err = security_perf_event_alloc(event);
11805 goto err_callchain_buffer;
11807 /* symmetric to unaccount_event() in _free_event() */
11808 account_event(event);
11812 err_callchain_buffer:
11813 if (!event->parent) {
11814 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11815 put_callchain_buffers();
11818 kfree(event->addr_filter_ranges);
11821 exclusive_event_destroy(event);
11824 if (is_cgroup_event(event))
11825 perf_detach_cgroup(event);
11826 if (event->destroy)
11827 event->destroy(event);
11828 module_put(pmu->module);
11830 if (event->hw.target)
11831 put_task_struct(event->hw.target);
11832 call_rcu(&event->rcu_head, free_event_rcu);
11834 return ERR_PTR(err);
11837 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11838 struct perf_event_attr *attr)
11843 /* Zero the full structure, so that a short copy will be nice. */
11844 memset(attr, 0, sizeof(*attr));
11846 ret = get_user(size, &uattr->size);
11850 /* ABI compatibility quirk: */
11852 size = PERF_ATTR_SIZE_VER0;
11853 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11856 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11865 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11868 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11871 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11874 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11875 u64 mask = attr->branch_sample_type;
11877 /* only using defined bits */
11878 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11881 /* at least one branch bit must be set */
11882 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11885 /* propagate priv level, when not set for branch */
11886 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11888 /* exclude_kernel checked on syscall entry */
11889 if (!attr->exclude_kernel)
11890 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11892 if (!attr->exclude_user)
11893 mask |= PERF_SAMPLE_BRANCH_USER;
11895 if (!attr->exclude_hv)
11896 mask |= PERF_SAMPLE_BRANCH_HV;
11898 * adjust user setting (for HW filter setup)
11900 attr->branch_sample_type = mask;
11902 /* privileged levels capture (kernel, hv): check permissions */
11903 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11904 ret = perf_allow_kernel(attr);
11910 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11911 ret = perf_reg_validate(attr->sample_regs_user);
11916 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11917 if (!arch_perf_have_user_stack_dump())
11921 * We have __u32 type for the size, but so far
11922 * we can only use __u16 as maximum due to the
11923 * __u16 sample size limit.
11925 if (attr->sample_stack_user >= USHRT_MAX)
11927 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11931 if (!attr->sample_max_stack)
11932 attr->sample_max_stack = sysctl_perf_event_max_stack;
11934 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11935 ret = perf_reg_validate(attr->sample_regs_intr);
11937 #ifndef CONFIG_CGROUP_PERF
11938 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11941 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
11942 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
11945 if (!attr->inherit && attr->inherit_thread)
11948 if (attr->remove_on_exec && attr->enable_on_exec)
11951 if (attr->sigtrap && !attr->remove_on_exec)
11958 put_user(sizeof(*attr), &uattr->size);
11963 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11969 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11973 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11975 struct perf_buffer *rb = NULL;
11978 if (!output_event) {
11979 mutex_lock(&event->mmap_mutex);
11983 /* don't allow circular references */
11984 if (event == output_event)
11988 * Don't allow cross-cpu buffers
11990 if (output_event->cpu != event->cpu)
11994 * If its not a per-cpu rb, it must be the same task.
11996 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
12000 * Mixing clocks in the same buffer is trouble you don't need.
12002 if (output_event->clock != event->clock)
12006 * Either writing ring buffer from beginning or from end.
12007 * Mixing is not allowed.
12009 if (is_write_backward(output_event) != is_write_backward(event))
12013 * If both events generate aux data, they must be on the same PMU
12015 if (has_aux(event) && has_aux(output_event) &&
12016 event->pmu != output_event->pmu)
12020 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12021 * output_event is already on rb->event_list, and the list iteration
12022 * restarts after every removal, it is guaranteed this new event is
12023 * observed *OR* if output_event is already removed, it's guaranteed we
12024 * observe !rb->mmap_count.
12026 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12028 /* Can't redirect output if we've got an active mmap() */
12029 if (atomic_read(&event->mmap_count))
12032 if (output_event) {
12033 /* get the rb we want to redirect to */
12034 rb = ring_buffer_get(output_event);
12038 /* did we race against perf_mmap_close() */
12039 if (!atomic_read(&rb->mmap_count)) {
12040 ring_buffer_put(rb);
12045 ring_buffer_attach(event, rb);
12049 mutex_unlock(&event->mmap_mutex);
12051 mutex_unlock(&output_event->mmap_mutex);
12057 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12059 bool nmi_safe = false;
12062 case CLOCK_MONOTONIC:
12063 event->clock = &ktime_get_mono_fast_ns;
12067 case CLOCK_MONOTONIC_RAW:
12068 event->clock = &ktime_get_raw_fast_ns;
12072 case CLOCK_REALTIME:
12073 event->clock = &ktime_get_real_ns;
12076 case CLOCK_BOOTTIME:
12077 event->clock = &ktime_get_boottime_ns;
12081 event->clock = &ktime_get_clocktai_ns;
12088 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12095 * Variation on perf_event_ctx_lock_nested(), except we take two context
12098 static struct perf_event_context *
12099 __perf_event_ctx_lock_double(struct perf_event *group_leader,
12100 struct perf_event_context *ctx)
12102 struct perf_event_context *gctx;
12106 gctx = READ_ONCE(group_leader->ctx);
12107 if (!refcount_inc_not_zero(&gctx->refcount)) {
12113 mutex_lock_double(&gctx->mutex, &ctx->mutex);
12115 if (group_leader->ctx != gctx) {
12116 mutex_unlock(&ctx->mutex);
12117 mutex_unlock(&gctx->mutex);
12126 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12128 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12129 bool is_capable = perfmon_capable();
12131 if (attr->sigtrap) {
12133 * perf_event_attr::sigtrap sends signals to the other task.
12134 * Require the current task to also have CAP_KILL.
12137 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12141 * If the required capabilities aren't available, checks for
12142 * ptrace permissions: upgrade to ATTACH, since sending signals
12143 * can effectively change the target task.
12145 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12149 * Preserve ptrace permission check for backwards compatibility. The
12150 * ptrace check also includes checks that the current task and other
12151 * task have matching uids, and is therefore not done here explicitly.
12153 return is_capable || ptrace_may_access(task, ptrace_mode);
12157 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12159 * @attr_uptr: event_id type attributes for monitoring/sampling
12162 * @group_fd: group leader event fd
12163 * @flags: perf event open flags
12165 SYSCALL_DEFINE5(perf_event_open,
12166 struct perf_event_attr __user *, attr_uptr,
12167 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12169 struct perf_event *group_leader = NULL, *output_event = NULL;
12170 struct perf_event *event, *sibling;
12171 struct perf_event_attr attr;
12172 struct perf_event_context *ctx, *gctx;
12173 struct file *event_file = NULL;
12174 struct fd group = {NULL, 0};
12175 struct task_struct *task = NULL;
12178 int move_group = 0;
12180 int f_flags = O_RDWR;
12181 int cgroup_fd = -1;
12183 /* for future expandability... */
12184 if (flags & ~PERF_FLAG_ALL)
12187 /* Do we allow access to perf_event_open(2) ? */
12188 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12192 err = perf_copy_attr(attr_uptr, &attr);
12196 if (!attr.exclude_kernel) {
12197 err = perf_allow_kernel(&attr);
12202 if (attr.namespaces) {
12203 if (!perfmon_capable())
12208 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12211 if (attr.sample_period & (1ULL << 63))
12215 /* Only privileged users can get physical addresses */
12216 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12217 err = perf_allow_kernel(&attr);
12222 /* REGS_INTR can leak data, lockdown must prevent this */
12223 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12224 err = security_locked_down(LOCKDOWN_PERF);
12230 * In cgroup mode, the pid argument is used to pass the fd
12231 * opened to the cgroup directory in cgroupfs. The cpu argument
12232 * designates the cpu on which to monitor threads from that
12235 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12238 if (flags & PERF_FLAG_FD_CLOEXEC)
12239 f_flags |= O_CLOEXEC;
12241 event_fd = get_unused_fd_flags(f_flags);
12245 if (group_fd != -1) {
12246 err = perf_fget_light(group_fd, &group);
12249 group_leader = group.file->private_data;
12250 if (flags & PERF_FLAG_FD_OUTPUT)
12251 output_event = group_leader;
12252 if (flags & PERF_FLAG_FD_NO_GROUP)
12253 group_leader = NULL;
12256 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12257 task = find_lively_task_by_vpid(pid);
12258 if (IS_ERR(task)) {
12259 err = PTR_ERR(task);
12264 if (task && group_leader &&
12265 group_leader->attr.inherit != attr.inherit) {
12270 if (flags & PERF_FLAG_PID_CGROUP)
12273 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12274 NULL, NULL, cgroup_fd);
12275 if (IS_ERR(event)) {
12276 err = PTR_ERR(event);
12280 if (is_sampling_event(event)) {
12281 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12288 * Special case software events and allow them to be part of
12289 * any hardware group.
12293 if (attr.use_clockid) {
12294 err = perf_event_set_clock(event, attr.clockid);
12299 if (pmu->task_ctx_nr == perf_sw_context)
12300 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12302 if (group_leader) {
12303 if (is_software_event(event) &&
12304 !in_software_context(group_leader)) {
12306 * If the event is a sw event, but the group_leader
12307 * is on hw context.
12309 * Allow the addition of software events to hw
12310 * groups, this is safe because software events
12311 * never fail to schedule.
12313 pmu = group_leader->ctx->pmu;
12314 } else if (!is_software_event(event) &&
12315 is_software_event(group_leader) &&
12316 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12318 * In case the group is a pure software group, and we
12319 * try to add a hardware event, move the whole group to
12320 * the hardware context.
12327 * Get the target context (task or percpu):
12329 ctx = find_get_context(pmu, task, event);
12331 err = PTR_ERR(ctx);
12336 * Look up the group leader (we will attach this event to it):
12338 if (group_leader) {
12342 * Do not allow a recursive hierarchy (this new sibling
12343 * becoming part of another group-sibling):
12345 if (group_leader->group_leader != group_leader)
12348 /* All events in a group should have the same clock */
12349 if (group_leader->clock != event->clock)
12353 * Make sure we're both events for the same CPU;
12354 * grouping events for different CPUs is broken; since
12355 * you can never concurrently schedule them anyhow.
12357 if (group_leader->cpu != event->cpu)
12361 * Make sure we're both on the same task, or both
12364 if (group_leader->ctx->task != ctx->task)
12368 * Do not allow to attach to a group in a different task
12369 * or CPU context. If we're moving SW events, we'll fix
12370 * this up later, so allow that.
12372 * Racy, not holding group_leader->ctx->mutex, see comment with
12373 * perf_event_ctx_lock().
12375 if (!move_group && group_leader->ctx != ctx)
12379 * Only a group leader can be exclusive or pinned
12381 if (attr.exclusive || attr.pinned)
12385 if (output_event) {
12386 err = perf_event_set_output(event, output_event);
12391 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
12393 if (IS_ERR(event_file)) {
12394 err = PTR_ERR(event_file);
12400 err = down_read_interruptible(&task->signal->exec_update_lock);
12405 * We must hold exec_update_lock across this and any potential
12406 * perf_install_in_context() call for this new event to
12407 * serialize against exec() altering our credentials (and the
12408 * perf_event_exit_task() that could imply).
12411 if (!perf_check_permission(&attr, task))
12416 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12418 if (gctx->task == TASK_TOMBSTONE) {
12424 * Check if we raced against another sys_perf_event_open() call
12425 * moving the software group underneath us.
12427 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12429 * If someone moved the group out from under us, check
12430 * if this new event wound up on the same ctx, if so
12431 * its the regular !move_group case, otherwise fail.
12437 perf_event_ctx_unlock(group_leader, gctx);
12439 goto not_move_group;
12444 * Failure to create exclusive events returns -EBUSY.
12447 if (!exclusive_event_installable(group_leader, ctx))
12450 for_each_sibling_event(sibling, group_leader) {
12451 if (!exclusive_event_installable(sibling, ctx))
12455 mutex_lock(&ctx->mutex);
12458 * Now that we hold ctx->lock, (re)validate group_leader->ctx == ctx,
12459 * see the group_leader && !move_group test earlier.
12461 if (group_leader && group_leader->ctx != ctx) {
12468 if (ctx->task == TASK_TOMBSTONE) {
12473 if (!perf_event_validate_size(event)) {
12480 * Check if the @cpu we're creating an event for is online.
12482 * We use the perf_cpu_context::ctx::mutex to serialize against
12483 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12485 struct perf_cpu_context *cpuctx =
12486 container_of(ctx, struct perf_cpu_context, ctx);
12488 if (!cpuctx->online) {
12494 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12500 * Must be under the same ctx::mutex as perf_install_in_context(),
12501 * because we need to serialize with concurrent event creation.
12503 if (!exclusive_event_installable(event, ctx)) {
12508 WARN_ON_ONCE(ctx->parent_ctx);
12511 * This is the point on no return; we cannot fail hereafter. This is
12512 * where we start modifying current state.
12517 * See perf_event_ctx_lock() for comments on the details
12518 * of swizzling perf_event::ctx.
12520 perf_remove_from_context(group_leader, 0);
12523 for_each_sibling_event(sibling, group_leader) {
12524 perf_remove_from_context(sibling, 0);
12529 * Wait for everybody to stop referencing the events through
12530 * the old lists, before installing it on new lists.
12535 * Install the group siblings before the group leader.
12537 * Because a group leader will try and install the entire group
12538 * (through the sibling list, which is still in-tact), we can
12539 * end up with siblings installed in the wrong context.
12541 * By installing siblings first we NO-OP because they're not
12542 * reachable through the group lists.
12544 for_each_sibling_event(sibling, group_leader) {
12545 perf_event__state_init(sibling);
12546 perf_install_in_context(ctx, sibling, sibling->cpu);
12551 * Removing from the context ends up with disabled
12552 * event. What we want here is event in the initial
12553 * startup state, ready to be add into new context.
12555 perf_event__state_init(group_leader);
12556 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12561 * Precalculate sample_data sizes; do while holding ctx::mutex such
12562 * that we're serialized against further additions and before
12563 * perf_install_in_context() which is the point the event is active and
12564 * can use these values.
12566 perf_event__header_size(event);
12567 perf_event__id_header_size(event);
12569 event->owner = current;
12571 perf_install_in_context(ctx, event, event->cpu);
12572 perf_unpin_context(ctx);
12575 perf_event_ctx_unlock(group_leader, gctx);
12576 mutex_unlock(&ctx->mutex);
12579 up_read(&task->signal->exec_update_lock);
12580 put_task_struct(task);
12583 mutex_lock(¤t->perf_event_mutex);
12584 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12585 mutex_unlock(¤t->perf_event_mutex);
12588 * Drop the reference on the group_event after placing the
12589 * new event on the sibling_list. This ensures destruction
12590 * of the group leader will find the pointer to itself in
12591 * perf_group_detach().
12594 fd_install(event_fd, event_file);
12599 perf_event_ctx_unlock(group_leader, gctx);
12600 mutex_unlock(&ctx->mutex);
12603 up_read(&task->signal->exec_update_lock);
12607 perf_unpin_context(ctx);
12611 * If event_file is set, the fput() above will have called ->release()
12612 * and that will take care of freeing the event.
12618 put_task_struct(task);
12622 put_unused_fd(event_fd);
12627 * perf_event_create_kernel_counter
12629 * @attr: attributes of the counter to create
12630 * @cpu: cpu in which the counter is bound
12631 * @task: task to profile (NULL for percpu)
12632 * @overflow_handler: callback to trigger when we hit the event
12633 * @context: context data could be used in overflow_handler callback
12635 struct perf_event *
12636 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12637 struct task_struct *task,
12638 perf_overflow_handler_t overflow_handler,
12641 struct perf_event_context *ctx;
12642 struct perf_event *event;
12646 * Grouping is not supported for kernel events, neither is 'AUX',
12647 * make sure the caller's intentions are adjusted.
12649 if (attr->aux_output)
12650 return ERR_PTR(-EINVAL);
12652 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12653 overflow_handler, context, -1);
12654 if (IS_ERR(event)) {
12655 err = PTR_ERR(event);
12659 /* Mark owner so we could distinguish it from user events. */
12660 event->owner = TASK_TOMBSTONE;
12663 * Get the target context (task or percpu):
12665 ctx = find_get_context(event->pmu, task, event);
12667 err = PTR_ERR(ctx);
12671 WARN_ON_ONCE(ctx->parent_ctx);
12672 mutex_lock(&ctx->mutex);
12673 if (ctx->task == TASK_TOMBSTONE) {
12680 * Check if the @cpu we're creating an event for is online.
12682 * We use the perf_cpu_context::ctx::mutex to serialize against
12683 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12685 struct perf_cpu_context *cpuctx =
12686 container_of(ctx, struct perf_cpu_context, ctx);
12687 if (!cpuctx->online) {
12693 if (!exclusive_event_installable(event, ctx)) {
12698 perf_install_in_context(ctx, event, event->cpu);
12699 perf_unpin_context(ctx);
12700 mutex_unlock(&ctx->mutex);
12705 mutex_unlock(&ctx->mutex);
12706 perf_unpin_context(ctx);
12711 return ERR_PTR(err);
12713 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12715 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12717 struct perf_event_context *src_ctx;
12718 struct perf_event_context *dst_ctx;
12719 struct perf_event *event, *tmp;
12722 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12723 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12726 * See perf_event_ctx_lock() for comments on the details
12727 * of swizzling perf_event::ctx.
12729 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12730 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12732 perf_remove_from_context(event, 0);
12733 unaccount_event_cpu(event, src_cpu);
12735 list_add(&event->migrate_entry, &events);
12739 * Wait for the events to quiesce before re-instating them.
12744 * Re-instate events in 2 passes.
12746 * Skip over group leaders and only install siblings on this first
12747 * pass, siblings will not get enabled without a leader, however a
12748 * leader will enable its siblings, even if those are still on the old
12751 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12752 if (event->group_leader == event)
12755 list_del(&event->migrate_entry);
12756 if (event->state >= PERF_EVENT_STATE_OFF)
12757 event->state = PERF_EVENT_STATE_INACTIVE;
12758 account_event_cpu(event, dst_cpu);
12759 perf_install_in_context(dst_ctx, event, dst_cpu);
12764 * Once all the siblings are setup properly, install the group leaders
12767 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12768 list_del(&event->migrate_entry);
12769 if (event->state >= PERF_EVENT_STATE_OFF)
12770 event->state = PERF_EVENT_STATE_INACTIVE;
12771 account_event_cpu(event, dst_cpu);
12772 perf_install_in_context(dst_ctx, event, dst_cpu);
12775 mutex_unlock(&dst_ctx->mutex);
12776 mutex_unlock(&src_ctx->mutex);
12778 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12780 static void sync_child_event(struct perf_event *child_event)
12782 struct perf_event *parent_event = child_event->parent;
12785 if (child_event->attr.inherit_stat) {
12786 struct task_struct *task = child_event->ctx->task;
12788 if (task && task != TASK_TOMBSTONE)
12789 perf_event_read_event(child_event, task);
12792 child_val = perf_event_count(child_event);
12795 * Add back the child's count to the parent's count:
12797 atomic64_add(child_val, &parent_event->child_count);
12798 atomic64_add(child_event->total_time_enabled,
12799 &parent_event->child_total_time_enabled);
12800 atomic64_add(child_event->total_time_running,
12801 &parent_event->child_total_time_running);
12805 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
12807 struct perf_event *parent_event = event->parent;
12808 unsigned long detach_flags = 0;
12810 if (parent_event) {
12812 * Do not destroy the 'original' grouping; because of the
12813 * context switch optimization the original events could've
12814 * ended up in a random child task.
12816 * If we were to destroy the original group, all group related
12817 * operations would cease to function properly after this
12818 * random child dies.
12820 * Do destroy all inherited groups, we don't care about those
12821 * and being thorough is better.
12823 detach_flags = DETACH_GROUP | DETACH_CHILD;
12824 mutex_lock(&parent_event->child_mutex);
12827 perf_remove_from_context(event, detach_flags);
12829 raw_spin_lock_irq(&ctx->lock);
12830 if (event->state > PERF_EVENT_STATE_EXIT)
12831 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
12832 raw_spin_unlock_irq(&ctx->lock);
12835 * Child events can be freed.
12837 if (parent_event) {
12838 mutex_unlock(&parent_event->child_mutex);
12840 * Kick perf_poll() for is_event_hup();
12842 perf_event_wakeup(parent_event);
12844 put_event(parent_event);
12849 * Parent events are governed by their filedesc, retain them.
12851 perf_event_wakeup(event);
12854 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12856 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12857 struct perf_event *child_event, *next;
12859 WARN_ON_ONCE(child != current);
12861 child_ctx = perf_pin_task_context(child, ctxn);
12866 * In order to reduce the amount of tricky in ctx tear-down, we hold
12867 * ctx::mutex over the entire thing. This serializes against almost
12868 * everything that wants to access the ctx.
12870 * The exception is sys_perf_event_open() /
12871 * perf_event_create_kernel_count() which does find_get_context()
12872 * without ctx::mutex (it cannot because of the move_group double mutex
12873 * lock thing). See the comments in perf_install_in_context().
12875 mutex_lock(&child_ctx->mutex);
12878 * In a single ctx::lock section, de-schedule the events and detach the
12879 * context from the task such that we cannot ever get it scheduled back
12882 raw_spin_lock_irq(&child_ctx->lock);
12883 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12886 * Now that the context is inactive, destroy the task <-> ctx relation
12887 * and mark the context dead.
12889 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12890 put_ctx(child_ctx); /* cannot be last */
12891 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12892 put_task_struct(current); /* cannot be last */
12894 clone_ctx = unclone_ctx(child_ctx);
12895 raw_spin_unlock_irq(&child_ctx->lock);
12898 put_ctx(clone_ctx);
12901 * Report the task dead after unscheduling the events so that we
12902 * won't get any samples after PERF_RECORD_EXIT. We can however still
12903 * get a few PERF_RECORD_READ events.
12905 perf_event_task(child, child_ctx, 0);
12907 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12908 perf_event_exit_event(child_event, child_ctx);
12910 mutex_unlock(&child_ctx->mutex);
12912 put_ctx(child_ctx);
12916 * When a child task exits, feed back event values to parent events.
12918 * Can be called with exec_update_lock held when called from
12919 * setup_new_exec().
12921 void perf_event_exit_task(struct task_struct *child)
12923 struct perf_event *event, *tmp;
12926 mutex_lock(&child->perf_event_mutex);
12927 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12929 list_del_init(&event->owner_entry);
12932 * Ensure the list deletion is visible before we clear
12933 * the owner, closes a race against perf_release() where
12934 * we need to serialize on the owner->perf_event_mutex.
12936 smp_store_release(&event->owner, NULL);
12938 mutex_unlock(&child->perf_event_mutex);
12940 for_each_task_context_nr(ctxn)
12941 perf_event_exit_task_context(child, ctxn);
12944 * The perf_event_exit_task_context calls perf_event_task
12945 * with child's task_ctx, which generates EXIT events for
12946 * child contexts and sets child->perf_event_ctxp[] to NULL.
12947 * At this point we need to send EXIT events to cpu contexts.
12949 perf_event_task(child, NULL, 0);
12952 static void perf_free_event(struct perf_event *event,
12953 struct perf_event_context *ctx)
12955 struct perf_event *parent = event->parent;
12957 if (WARN_ON_ONCE(!parent))
12960 mutex_lock(&parent->child_mutex);
12961 list_del_init(&event->child_list);
12962 mutex_unlock(&parent->child_mutex);
12966 raw_spin_lock_irq(&ctx->lock);
12967 perf_group_detach(event);
12968 list_del_event(event, ctx);
12969 raw_spin_unlock_irq(&ctx->lock);
12974 * Free a context as created by inheritance by perf_event_init_task() below,
12975 * used by fork() in case of fail.
12977 * Even though the task has never lived, the context and events have been
12978 * exposed through the child_list, so we must take care tearing it all down.
12980 void perf_event_free_task(struct task_struct *task)
12982 struct perf_event_context *ctx;
12983 struct perf_event *event, *tmp;
12986 for_each_task_context_nr(ctxn) {
12987 ctx = task->perf_event_ctxp[ctxn];
12991 mutex_lock(&ctx->mutex);
12992 raw_spin_lock_irq(&ctx->lock);
12994 * Destroy the task <-> ctx relation and mark the context dead.
12996 * This is important because even though the task hasn't been
12997 * exposed yet the context has been (through child_list).
12999 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
13000 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13001 put_task_struct(task); /* cannot be last */
13002 raw_spin_unlock_irq(&ctx->lock);
13004 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13005 perf_free_event(event, ctx);
13007 mutex_unlock(&ctx->mutex);
13010 * perf_event_release_kernel() could've stolen some of our
13011 * child events and still have them on its free_list. In that
13012 * case we must wait for these events to have been freed (in
13013 * particular all their references to this task must've been
13016 * Without this copy_process() will unconditionally free this
13017 * task (irrespective of its reference count) and
13018 * _free_event()'s put_task_struct(event->hw.target) will be a
13021 * Wait for all events to drop their context reference.
13023 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13024 put_ctx(ctx); /* must be last */
13028 void perf_event_delayed_put(struct task_struct *task)
13032 for_each_task_context_nr(ctxn)
13033 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
13036 struct file *perf_event_get(unsigned int fd)
13038 struct file *file = fget(fd);
13040 return ERR_PTR(-EBADF);
13042 if (file->f_op != &perf_fops) {
13044 return ERR_PTR(-EBADF);
13050 const struct perf_event *perf_get_event(struct file *file)
13052 if (file->f_op != &perf_fops)
13053 return ERR_PTR(-EINVAL);
13055 return file->private_data;
13058 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13061 return ERR_PTR(-EINVAL);
13063 return &event->attr;
13067 * Inherit an event from parent task to child task.
13070 * - valid pointer on success
13071 * - NULL for orphaned events
13072 * - IS_ERR() on error
13074 static struct perf_event *
13075 inherit_event(struct perf_event *parent_event,
13076 struct task_struct *parent,
13077 struct perf_event_context *parent_ctx,
13078 struct task_struct *child,
13079 struct perf_event *group_leader,
13080 struct perf_event_context *child_ctx)
13082 enum perf_event_state parent_state = parent_event->state;
13083 struct perf_event *child_event;
13084 unsigned long flags;
13087 * Instead of creating recursive hierarchies of events,
13088 * we link inherited events back to the original parent,
13089 * which has a filp for sure, which we use as the reference
13092 if (parent_event->parent)
13093 parent_event = parent_event->parent;
13095 child_event = perf_event_alloc(&parent_event->attr,
13098 group_leader, parent_event,
13100 if (IS_ERR(child_event))
13101 return child_event;
13104 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
13105 !child_ctx->task_ctx_data) {
13106 struct pmu *pmu = child_event->pmu;
13108 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
13109 if (!child_ctx->task_ctx_data) {
13110 free_event(child_event);
13111 return ERR_PTR(-ENOMEM);
13116 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13117 * must be under the same lock in order to serialize against
13118 * perf_event_release_kernel(), such that either we must observe
13119 * is_orphaned_event() or they will observe us on the child_list.
13121 mutex_lock(&parent_event->child_mutex);
13122 if (is_orphaned_event(parent_event) ||
13123 !atomic_long_inc_not_zero(&parent_event->refcount)) {
13124 mutex_unlock(&parent_event->child_mutex);
13125 /* task_ctx_data is freed with child_ctx */
13126 free_event(child_event);
13130 get_ctx(child_ctx);
13133 * Make the child state follow the state of the parent event,
13134 * not its attr.disabled bit. We hold the parent's mutex,
13135 * so we won't race with perf_event_{en, dis}able_family.
13137 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13138 child_event->state = PERF_EVENT_STATE_INACTIVE;
13140 child_event->state = PERF_EVENT_STATE_OFF;
13142 if (parent_event->attr.freq) {
13143 u64 sample_period = parent_event->hw.sample_period;
13144 struct hw_perf_event *hwc = &child_event->hw;
13146 hwc->sample_period = sample_period;
13147 hwc->last_period = sample_period;
13149 local64_set(&hwc->period_left, sample_period);
13152 child_event->ctx = child_ctx;
13153 child_event->overflow_handler = parent_event->overflow_handler;
13154 child_event->overflow_handler_context
13155 = parent_event->overflow_handler_context;
13158 * Precalculate sample_data sizes
13160 perf_event__header_size(child_event);
13161 perf_event__id_header_size(child_event);
13164 * Link it up in the child's context:
13166 raw_spin_lock_irqsave(&child_ctx->lock, flags);
13167 add_event_to_ctx(child_event, child_ctx);
13168 child_event->attach_state |= PERF_ATTACH_CHILD;
13169 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13172 * Link this into the parent event's child list
13174 list_add_tail(&child_event->child_list, &parent_event->child_list);
13175 mutex_unlock(&parent_event->child_mutex);
13177 return child_event;
13181 * Inherits an event group.
13183 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13184 * This matches with perf_event_release_kernel() removing all child events.
13190 static int inherit_group(struct perf_event *parent_event,
13191 struct task_struct *parent,
13192 struct perf_event_context *parent_ctx,
13193 struct task_struct *child,
13194 struct perf_event_context *child_ctx)
13196 struct perf_event *leader;
13197 struct perf_event *sub;
13198 struct perf_event *child_ctr;
13200 leader = inherit_event(parent_event, parent, parent_ctx,
13201 child, NULL, child_ctx);
13202 if (IS_ERR(leader))
13203 return PTR_ERR(leader);
13205 * @leader can be NULL here because of is_orphaned_event(). In this
13206 * case inherit_event() will create individual events, similar to what
13207 * perf_group_detach() would do anyway.
13209 for_each_sibling_event(sub, parent_event) {
13210 child_ctr = inherit_event(sub, parent, parent_ctx,
13211 child, leader, child_ctx);
13212 if (IS_ERR(child_ctr))
13213 return PTR_ERR(child_ctr);
13215 if (sub->aux_event == parent_event && child_ctr &&
13216 !perf_get_aux_event(child_ctr, leader))
13223 * Creates the child task context and tries to inherit the event-group.
13225 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13226 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13227 * consistent with perf_event_release_kernel() removing all child events.
13234 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13235 struct perf_event_context *parent_ctx,
13236 struct task_struct *child, int ctxn,
13237 u64 clone_flags, int *inherited_all)
13240 struct perf_event_context *child_ctx;
13242 if (!event->attr.inherit ||
13243 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13244 /* Do not inherit if sigtrap and signal handlers were cleared. */
13245 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13246 *inherited_all = 0;
13250 child_ctx = child->perf_event_ctxp[ctxn];
13253 * This is executed from the parent task context, so
13254 * inherit events that have been marked for cloning.
13255 * First allocate and initialize a context for the
13258 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
13262 child->perf_event_ctxp[ctxn] = child_ctx;
13265 ret = inherit_group(event, parent, parent_ctx,
13269 *inherited_all = 0;
13275 * Initialize the perf_event context in task_struct
13277 static int perf_event_init_context(struct task_struct *child, int ctxn,
13280 struct perf_event_context *child_ctx, *parent_ctx;
13281 struct perf_event_context *cloned_ctx;
13282 struct perf_event *event;
13283 struct task_struct *parent = current;
13284 int inherited_all = 1;
13285 unsigned long flags;
13288 if (likely(!parent->perf_event_ctxp[ctxn]))
13292 * If the parent's context is a clone, pin it so it won't get
13293 * swapped under us.
13295 parent_ctx = perf_pin_task_context(parent, ctxn);
13300 * No need to check if parent_ctx != NULL here; since we saw
13301 * it non-NULL earlier, the only reason for it to become NULL
13302 * is if we exit, and since we're currently in the middle of
13303 * a fork we can't be exiting at the same time.
13307 * Lock the parent list. No need to lock the child - not PID
13308 * hashed yet and not running, so nobody can access it.
13310 mutex_lock(&parent_ctx->mutex);
13313 * We dont have to disable NMIs - we are only looking at
13314 * the list, not manipulating it:
13316 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13317 ret = inherit_task_group(event, parent, parent_ctx,
13318 child, ctxn, clone_flags,
13325 * We can't hold ctx->lock when iterating the ->flexible_group list due
13326 * to allocations, but we need to prevent rotation because
13327 * rotate_ctx() will change the list from interrupt context.
13329 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13330 parent_ctx->rotate_disable = 1;
13331 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13333 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13334 ret = inherit_task_group(event, parent, parent_ctx,
13335 child, ctxn, clone_flags,
13341 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13342 parent_ctx->rotate_disable = 0;
13344 child_ctx = child->perf_event_ctxp[ctxn];
13346 if (child_ctx && inherited_all) {
13348 * Mark the child context as a clone of the parent
13349 * context, or of whatever the parent is a clone of.
13351 * Note that if the parent is a clone, the holding of
13352 * parent_ctx->lock avoids it from being uncloned.
13354 cloned_ctx = parent_ctx->parent_ctx;
13356 child_ctx->parent_ctx = cloned_ctx;
13357 child_ctx->parent_gen = parent_ctx->parent_gen;
13359 child_ctx->parent_ctx = parent_ctx;
13360 child_ctx->parent_gen = parent_ctx->generation;
13362 get_ctx(child_ctx->parent_ctx);
13365 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13367 mutex_unlock(&parent_ctx->mutex);
13369 perf_unpin_context(parent_ctx);
13370 put_ctx(parent_ctx);
13376 * Initialize the perf_event context in task_struct
13378 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
13382 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
13383 mutex_init(&child->perf_event_mutex);
13384 INIT_LIST_HEAD(&child->perf_event_list);
13386 for_each_task_context_nr(ctxn) {
13387 ret = perf_event_init_context(child, ctxn, clone_flags);
13389 perf_event_free_task(child);
13397 static void __init perf_event_init_all_cpus(void)
13399 struct swevent_htable *swhash;
13402 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13404 for_each_possible_cpu(cpu) {
13405 swhash = &per_cpu(swevent_htable, cpu);
13406 mutex_init(&swhash->hlist_mutex);
13407 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
13409 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13410 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13412 #ifdef CONFIG_CGROUP_PERF
13413 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13415 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13419 static void perf_swevent_init_cpu(unsigned int cpu)
13421 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13423 mutex_lock(&swhash->hlist_mutex);
13424 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13425 struct swevent_hlist *hlist;
13427 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13429 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13431 mutex_unlock(&swhash->hlist_mutex);
13434 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13435 static void __perf_event_exit_context(void *__info)
13437 struct perf_event_context *ctx = __info;
13438 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13439 struct perf_event *event;
13441 raw_spin_lock(&ctx->lock);
13442 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13443 list_for_each_entry(event, &ctx->event_list, event_entry)
13444 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13445 raw_spin_unlock(&ctx->lock);
13448 static void perf_event_exit_cpu_context(int cpu)
13450 struct perf_cpu_context *cpuctx;
13451 struct perf_event_context *ctx;
13454 mutex_lock(&pmus_lock);
13455 list_for_each_entry(pmu, &pmus, entry) {
13456 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13457 ctx = &cpuctx->ctx;
13459 mutex_lock(&ctx->mutex);
13460 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13461 cpuctx->online = 0;
13462 mutex_unlock(&ctx->mutex);
13464 cpumask_clear_cpu(cpu, perf_online_mask);
13465 mutex_unlock(&pmus_lock);
13469 static void perf_event_exit_cpu_context(int cpu) { }
13473 int perf_event_init_cpu(unsigned int cpu)
13475 struct perf_cpu_context *cpuctx;
13476 struct perf_event_context *ctx;
13479 perf_swevent_init_cpu(cpu);
13481 mutex_lock(&pmus_lock);
13482 cpumask_set_cpu(cpu, perf_online_mask);
13483 list_for_each_entry(pmu, &pmus, entry) {
13484 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13485 ctx = &cpuctx->ctx;
13487 mutex_lock(&ctx->mutex);
13488 cpuctx->online = 1;
13489 mutex_unlock(&ctx->mutex);
13491 mutex_unlock(&pmus_lock);
13496 int perf_event_exit_cpu(unsigned int cpu)
13498 perf_event_exit_cpu_context(cpu);
13503 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13507 for_each_online_cpu(cpu)
13508 perf_event_exit_cpu(cpu);
13514 * Run the perf reboot notifier at the very last possible moment so that
13515 * the generic watchdog code runs as long as possible.
13517 static struct notifier_block perf_reboot_notifier = {
13518 .notifier_call = perf_reboot,
13519 .priority = INT_MIN,
13522 void __init perf_event_init(void)
13526 idr_init(&pmu_idr);
13528 perf_event_init_all_cpus();
13529 init_srcu_struct(&pmus_srcu);
13530 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13531 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13532 perf_pmu_register(&perf_task_clock, NULL, -1);
13533 perf_tp_register();
13534 perf_event_init_cpu(smp_processor_id());
13535 register_reboot_notifier(&perf_reboot_notifier);
13537 ret = init_hw_breakpoint();
13538 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13540 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13543 * Build time assertion that we keep the data_head at the intended
13544 * location. IOW, validation we got the __reserved[] size right.
13546 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13550 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13553 struct perf_pmu_events_attr *pmu_attr =
13554 container_of(attr, struct perf_pmu_events_attr, attr);
13556 if (pmu_attr->event_str)
13557 return sprintf(page, "%s\n", pmu_attr->event_str);
13561 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13563 static int __init perf_event_sysfs_init(void)
13568 mutex_lock(&pmus_lock);
13570 ret = bus_register(&pmu_bus);
13574 list_for_each_entry(pmu, &pmus, entry) {
13575 if (!pmu->name || pmu->type < 0)
13578 ret = pmu_dev_alloc(pmu);
13579 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13581 pmu_bus_running = 1;
13585 mutex_unlock(&pmus_lock);
13589 device_initcall(perf_event_sysfs_init);
13591 #ifdef CONFIG_CGROUP_PERF
13592 static struct cgroup_subsys_state *
13593 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13595 struct perf_cgroup *jc;
13597 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13599 return ERR_PTR(-ENOMEM);
13601 jc->info = alloc_percpu(struct perf_cgroup_info);
13604 return ERR_PTR(-ENOMEM);
13610 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13612 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13614 free_percpu(jc->info);
13618 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13620 perf_event_cgroup(css->cgroup);
13624 static int __perf_cgroup_move(void *info)
13626 struct task_struct *task = info;
13628 perf_cgroup_switch(task);
13633 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13635 struct task_struct *task;
13636 struct cgroup_subsys_state *css;
13638 cgroup_taskset_for_each(task, css, tset)
13639 task_function_call(task, __perf_cgroup_move, task);
13642 struct cgroup_subsys perf_event_cgrp_subsys = {
13643 .css_alloc = perf_cgroup_css_alloc,
13644 .css_free = perf_cgroup_css_free,
13645 .css_online = perf_cgroup_css_online,
13646 .attach = perf_cgroup_attach,
13648 * Implicitly enable on dfl hierarchy so that perf events can
13649 * always be filtered by cgroup2 path as long as perf_event
13650 * controller is not mounted on a legacy hierarchy.
13652 .implicit_on_dfl = true,
13655 #endif /* CONFIG_CGROUP_PERF */
13657 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);