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 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
2295 task_work_add(current, &event->pending_task, TWA_RESUME);
2298 local_dec(&event->ctx->nr_pending);
2301 perf_event_set_state(event, state);
2303 if (!is_software_event(event))
2304 cpuctx->active_oncpu--;
2305 if (!--ctx->nr_active)
2306 perf_event_ctx_deactivate(ctx);
2307 if (event->attr.freq && event->attr.sample_freq)
2309 if (event->attr.exclusive || !cpuctx->active_oncpu)
2310 cpuctx->exclusive = 0;
2312 perf_pmu_enable(event->pmu);
2316 group_sched_out(struct perf_event *group_event,
2317 struct perf_cpu_context *cpuctx,
2318 struct perf_event_context *ctx)
2320 struct perf_event *event;
2322 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2325 perf_pmu_disable(ctx->pmu);
2327 event_sched_out(group_event, cpuctx, ctx);
2330 * Schedule out siblings (if any):
2332 for_each_sibling_event(event, group_event)
2333 event_sched_out(event, cpuctx, ctx);
2335 perf_pmu_enable(ctx->pmu);
2338 #define DETACH_GROUP 0x01UL
2339 #define DETACH_CHILD 0x02UL
2340 #define DETACH_DEAD 0x04UL
2343 * Cross CPU call to remove a performance event
2345 * We disable the event on the hardware level first. After that we
2346 * remove it from the context list.
2349 __perf_remove_from_context(struct perf_event *event,
2350 struct perf_cpu_context *cpuctx,
2351 struct perf_event_context *ctx,
2354 unsigned long flags = (unsigned long)info;
2356 if (ctx->is_active & EVENT_TIME) {
2357 update_context_time(ctx);
2358 update_cgrp_time_from_cpuctx(cpuctx, false);
2362 * Ensure event_sched_out() switches to OFF, at the very least
2363 * this avoids raising perf_pending_task() at this time.
2365 if (flags & DETACH_DEAD)
2366 event->pending_disable = 1;
2367 event_sched_out(event, cpuctx, ctx);
2368 if (flags & DETACH_GROUP)
2369 perf_group_detach(event);
2370 if (flags & DETACH_CHILD)
2371 perf_child_detach(event);
2372 list_del_event(event, ctx);
2373 if (flags & DETACH_DEAD)
2374 event->state = PERF_EVENT_STATE_DEAD;
2376 if (!ctx->nr_events && ctx->is_active) {
2377 if (ctx == &cpuctx->ctx)
2378 update_cgrp_time_from_cpuctx(cpuctx, true);
2381 ctx->rotate_necessary = 0;
2383 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2384 cpuctx->task_ctx = NULL;
2390 * Remove the event from a task's (or a CPU's) list of events.
2392 * If event->ctx is a cloned context, callers must make sure that
2393 * every task struct that event->ctx->task could possibly point to
2394 * remains valid. This is OK when called from perf_release since
2395 * that only calls us on the top-level context, which can't be a clone.
2396 * When called from perf_event_exit_task, it's OK because the
2397 * context has been detached from its task.
2399 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2401 struct perf_event_context *ctx = event->ctx;
2403 lockdep_assert_held(&ctx->mutex);
2406 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2407 * to work in the face of TASK_TOMBSTONE, unlike every other
2408 * event_function_call() user.
2410 raw_spin_lock_irq(&ctx->lock);
2412 * Cgroup events are per-cpu events, and must IPI because of
2415 if (!ctx->is_active && !is_cgroup_event(event)) {
2416 __perf_remove_from_context(event, __get_cpu_context(ctx),
2417 ctx, (void *)flags);
2418 raw_spin_unlock_irq(&ctx->lock);
2421 raw_spin_unlock_irq(&ctx->lock);
2423 event_function_call(event, __perf_remove_from_context, (void *)flags);
2427 * Cross CPU call to disable a performance event
2429 static void __perf_event_disable(struct perf_event *event,
2430 struct perf_cpu_context *cpuctx,
2431 struct perf_event_context *ctx,
2434 if (event->state < PERF_EVENT_STATE_INACTIVE)
2437 if (ctx->is_active & EVENT_TIME) {
2438 update_context_time(ctx);
2439 update_cgrp_time_from_event(event);
2442 if (event == event->group_leader)
2443 group_sched_out(event, cpuctx, ctx);
2445 event_sched_out(event, cpuctx, ctx);
2447 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2448 perf_cgroup_event_disable(event, ctx);
2454 * If event->ctx is a cloned context, callers must make sure that
2455 * every task struct that event->ctx->task could possibly point to
2456 * remains valid. This condition is satisfied when called through
2457 * perf_event_for_each_child or perf_event_for_each because they
2458 * hold the top-level event's child_mutex, so any descendant that
2459 * goes to exit will block in perf_event_exit_event().
2461 * When called from perf_pending_irq it's OK because event->ctx
2462 * is the current context on this CPU and preemption is disabled,
2463 * hence we can't get into perf_event_task_sched_out for this context.
2465 static void _perf_event_disable(struct perf_event *event)
2467 struct perf_event_context *ctx = event->ctx;
2469 raw_spin_lock_irq(&ctx->lock);
2470 if (event->state <= PERF_EVENT_STATE_OFF) {
2471 raw_spin_unlock_irq(&ctx->lock);
2474 raw_spin_unlock_irq(&ctx->lock);
2476 event_function_call(event, __perf_event_disable, NULL);
2479 void perf_event_disable_local(struct perf_event *event)
2481 event_function_local(event, __perf_event_disable, NULL);
2485 * Strictly speaking kernel users cannot create groups and therefore this
2486 * interface does not need the perf_event_ctx_lock() magic.
2488 void perf_event_disable(struct perf_event *event)
2490 struct perf_event_context *ctx;
2492 ctx = perf_event_ctx_lock(event);
2493 _perf_event_disable(event);
2494 perf_event_ctx_unlock(event, ctx);
2496 EXPORT_SYMBOL_GPL(perf_event_disable);
2498 void perf_event_disable_inatomic(struct perf_event *event)
2500 event->pending_disable = 1;
2501 irq_work_queue(&event->pending_irq);
2504 #define MAX_INTERRUPTS (~0ULL)
2506 static void perf_log_throttle(struct perf_event *event, int enable);
2507 static void perf_log_itrace_start(struct perf_event *event);
2510 event_sched_in(struct perf_event *event,
2511 struct perf_cpu_context *cpuctx,
2512 struct perf_event_context *ctx)
2516 WARN_ON_ONCE(event->ctx != ctx);
2518 lockdep_assert_held(&ctx->lock);
2520 if (event->state <= PERF_EVENT_STATE_OFF)
2523 WRITE_ONCE(event->oncpu, smp_processor_id());
2525 * Order event::oncpu write to happen before the ACTIVE state is
2526 * visible. This allows perf_event_{stop,read}() to observe the correct
2527 * ->oncpu if it sees ACTIVE.
2530 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2533 * Unthrottle events, since we scheduled we might have missed several
2534 * ticks already, also for a heavily scheduling task there is little
2535 * guarantee it'll get a tick in a timely manner.
2537 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2538 perf_log_throttle(event, 1);
2539 event->hw.interrupts = 0;
2542 perf_pmu_disable(event->pmu);
2544 perf_log_itrace_start(event);
2546 if (event->pmu->add(event, PERF_EF_START)) {
2547 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2553 if (!is_software_event(event))
2554 cpuctx->active_oncpu++;
2555 if (!ctx->nr_active++)
2556 perf_event_ctx_activate(ctx);
2557 if (event->attr.freq && event->attr.sample_freq)
2560 if (event->attr.exclusive)
2561 cpuctx->exclusive = 1;
2564 perf_pmu_enable(event->pmu);
2570 group_sched_in(struct perf_event *group_event,
2571 struct perf_cpu_context *cpuctx,
2572 struct perf_event_context *ctx)
2574 struct perf_event *event, *partial_group = NULL;
2575 struct pmu *pmu = ctx->pmu;
2577 if (group_event->state == PERF_EVENT_STATE_OFF)
2580 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2582 if (event_sched_in(group_event, cpuctx, ctx))
2586 * Schedule in siblings as one group (if any):
2588 for_each_sibling_event(event, group_event) {
2589 if (event_sched_in(event, cpuctx, ctx)) {
2590 partial_group = event;
2595 if (!pmu->commit_txn(pmu))
2600 * Groups can be scheduled in as one unit only, so undo any
2601 * partial group before returning:
2602 * The events up to the failed event are scheduled out normally.
2604 for_each_sibling_event(event, group_event) {
2605 if (event == partial_group)
2608 event_sched_out(event, cpuctx, ctx);
2610 event_sched_out(group_event, cpuctx, ctx);
2613 pmu->cancel_txn(pmu);
2618 * Work out whether we can put this event group on the CPU now.
2620 static int group_can_go_on(struct perf_event *event,
2621 struct perf_cpu_context *cpuctx,
2625 * Groups consisting entirely of software events can always go on.
2627 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2630 * If an exclusive group is already on, no other hardware
2633 if (cpuctx->exclusive)
2636 * If this group is exclusive and there are already
2637 * events on the CPU, it can't go on.
2639 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2642 * Otherwise, try to add it if all previous groups were able
2648 static void add_event_to_ctx(struct perf_event *event,
2649 struct perf_event_context *ctx)
2651 list_add_event(event, ctx);
2652 perf_group_attach(event);
2655 static void ctx_sched_out(struct perf_event_context *ctx,
2656 struct perf_cpu_context *cpuctx,
2657 enum event_type_t event_type);
2659 ctx_sched_in(struct perf_event_context *ctx,
2660 struct perf_cpu_context *cpuctx,
2661 enum event_type_t event_type);
2663 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2664 struct perf_event_context *ctx,
2665 enum event_type_t event_type)
2667 if (!cpuctx->task_ctx)
2670 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2673 ctx_sched_out(ctx, cpuctx, event_type);
2676 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2677 struct perf_event_context *ctx)
2679 cpu_ctx_sched_in(cpuctx, EVENT_PINNED);
2681 ctx_sched_in(ctx, cpuctx, EVENT_PINNED);
2682 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
2684 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE);
2688 * We want to maintain the following priority of scheduling:
2689 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2690 * - task pinned (EVENT_PINNED)
2691 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2692 * - task flexible (EVENT_FLEXIBLE).
2694 * In order to avoid unscheduling and scheduling back in everything every
2695 * time an event is added, only do it for the groups of equal priority and
2698 * This can be called after a batch operation on task events, in which case
2699 * event_type is a bit mask of the types of events involved. For CPU events,
2700 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2702 static void ctx_resched(struct perf_cpu_context *cpuctx,
2703 struct perf_event_context *task_ctx,
2704 enum event_type_t event_type)
2706 enum event_type_t ctx_event_type;
2707 bool cpu_event = !!(event_type & EVENT_CPU);
2710 * If pinned groups are involved, flexible groups also need to be
2713 if (event_type & EVENT_PINNED)
2714 event_type |= EVENT_FLEXIBLE;
2716 ctx_event_type = event_type & EVENT_ALL;
2718 perf_pmu_disable(cpuctx->ctx.pmu);
2720 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2723 * Decide which cpu ctx groups to schedule out based on the types
2724 * of events that caused rescheduling:
2725 * - EVENT_CPU: schedule out corresponding groups;
2726 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2727 * - otherwise, do nothing more.
2730 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2731 else if (ctx_event_type & EVENT_PINNED)
2732 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2734 perf_event_sched_in(cpuctx, task_ctx);
2735 perf_pmu_enable(cpuctx->ctx.pmu);
2738 void perf_pmu_resched(struct pmu *pmu)
2740 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2741 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2743 perf_ctx_lock(cpuctx, task_ctx);
2744 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2745 perf_ctx_unlock(cpuctx, task_ctx);
2749 * Cross CPU call to install and enable a performance event
2751 * Very similar to remote_function() + event_function() but cannot assume that
2752 * things like ctx->is_active and cpuctx->task_ctx are set.
2754 static int __perf_install_in_context(void *info)
2756 struct perf_event *event = info;
2757 struct perf_event_context *ctx = event->ctx;
2758 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2759 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2760 bool reprogram = true;
2763 raw_spin_lock(&cpuctx->ctx.lock);
2765 raw_spin_lock(&ctx->lock);
2768 reprogram = (ctx->task == current);
2771 * If the task is running, it must be running on this CPU,
2772 * otherwise we cannot reprogram things.
2774 * If its not running, we don't care, ctx->lock will
2775 * serialize against it becoming runnable.
2777 if (task_curr(ctx->task) && !reprogram) {
2782 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2783 } else if (task_ctx) {
2784 raw_spin_lock(&task_ctx->lock);
2787 #ifdef CONFIG_CGROUP_PERF
2788 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2790 * If the current cgroup doesn't match the event's
2791 * cgroup, we should not try to schedule it.
2793 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2794 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2795 event->cgrp->css.cgroup);
2800 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2801 add_event_to_ctx(event, ctx);
2802 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2804 add_event_to_ctx(event, ctx);
2808 perf_ctx_unlock(cpuctx, task_ctx);
2813 static bool exclusive_event_installable(struct perf_event *event,
2814 struct perf_event_context *ctx);
2817 * Attach a performance event to a context.
2819 * Very similar to event_function_call, see comment there.
2822 perf_install_in_context(struct perf_event_context *ctx,
2823 struct perf_event *event,
2826 struct task_struct *task = READ_ONCE(ctx->task);
2828 lockdep_assert_held(&ctx->mutex);
2830 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2832 if (event->cpu != -1)
2836 * Ensures that if we can observe event->ctx, both the event and ctx
2837 * will be 'complete'. See perf_iterate_sb_cpu().
2839 smp_store_release(&event->ctx, ctx);
2842 * perf_event_attr::disabled events will not run and can be initialized
2843 * without IPI. Except when this is the first event for the context, in
2844 * that case we need the magic of the IPI to set ctx->is_active.
2845 * Similarly, cgroup events for the context also needs the IPI to
2846 * manipulate the cgrp_cpuctx_list.
2848 * The IOC_ENABLE that is sure to follow the creation of a disabled
2849 * event will issue the IPI and reprogram the hardware.
2851 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2852 ctx->nr_events && !is_cgroup_event(event)) {
2853 raw_spin_lock_irq(&ctx->lock);
2854 if (ctx->task == TASK_TOMBSTONE) {
2855 raw_spin_unlock_irq(&ctx->lock);
2858 add_event_to_ctx(event, ctx);
2859 raw_spin_unlock_irq(&ctx->lock);
2864 cpu_function_call(cpu, __perf_install_in_context, event);
2869 * Should not happen, we validate the ctx is still alive before calling.
2871 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2875 * Installing events is tricky because we cannot rely on ctx->is_active
2876 * to be set in case this is the nr_events 0 -> 1 transition.
2878 * Instead we use task_curr(), which tells us if the task is running.
2879 * However, since we use task_curr() outside of rq::lock, we can race
2880 * against the actual state. This means the result can be wrong.
2882 * If we get a false positive, we retry, this is harmless.
2884 * If we get a false negative, things are complicated. If we are after
2885 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2886 * value must be correct. If we're before, it doesn't matter since
2887 * perf_event_context_sched_in() will program the counter.
2889 * However, this hinges on the remote context switch having observed
2890 * our task->perf_event_ctxp[] store, such that it will in fact take
2891 * ctx::lock in perf_event_context_sched_in().
2893 * We do this by task_function_call(), if the IPI fails to hit the task
2894 * we know any future context switch of task must see the
2895 * perf_event_ctpx[] store.
2899 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2900 * task_cpu() load, such that if the IPI then does not find the task
2901 * running, a future context switch of that task must observe the
2906 if (!task_function_call(task, __perf_install_in_context, event))
2909 raw_spin_lock_irq(&ctx->lock);
2911 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2913 * Cannot happen because we already checked above (which also
2914 * cannot happen), and we hold ctx->mutex, which serializes us
2915 * against perf_event_exit_task_context().
2917 raw_spin_unlock_irq(&ctx->lock);
2921 * If the task is not running, ctx->lock will avoid it becoming so,
2922 * thus we can safely install the event.
2924 if (task_curr(task)) {
2925 raw_spin_unlock_irq(&ctx->lock);
2928 add_event_to_ctx(event, ctx);
2929 raw_spin_unlock_irq(&ctx->lock);
2933 * Cross CPU call to enable a performance event
2935 static void __perf_event_enable(struct perf_event *event,
2936 struct perf_cpu_context *cpuctx,
2937 struct perf_event_context *ctx,
2940 struct perf_event *leader = event->group_leader;
2941 struct perf_event_context *task_ctx;
2943 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2944 event->state <= PERF_EVENT_STATE_ERROR)
2948 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2950 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2951 perf_cgroup_event_enable(event, ctx);
2953 if (!ctx->is_active)
2956 if (!event_filter_match(event)) {
2957 ctx_sched_in(ctx, cpuctx, EVENT_TIME);
2962 * If the event is in a group and isn't the group leader,
2963 * then don't put it on unless the group is on.
2965 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2966 ctx_sched_in(ctx, cpuctx, EVENT_TIME);
2970 task_ctx = cpuctx->task_ctx;
2972 WARN_ON_ONCE(task_ctx != ctx);
2974 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2980 * If event->ctx is a cloned context, callers must make sure that
2981 * every task struct that event->ctx->task could possibly point to
2982 * remains valid. This condition is satisfied when called through
2983 * perf_event_for_each_child or perf_event_for_each as described
2984 * for perf_event_disable.
2986 static void _perf_event_enable(struct perf_event *event)
2988 struct perf_event_context *ctx = event->ctx;
2990 raw_spin_lock_irq(&ctx->lock);
2991 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2992 event->state < PERF_EVENT_STATE_ERROR) {
2994 raw_spin_unlock_irq(&ctx->lock);
2999 * If the event is in error state, clear that first.
3001 * That way, if we see the event in error state below, we know that it
3002 * has gone back into error state, as distinct from the task having
3003 * been scheduled away before the cross-call arrived.
3005 if (event->state == PERF_EVENT_STATE_ERROR) {
3007 * Detached SIBLING events cannot leave ERROR state.
3009 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3010 event->group_leader == event)
3013 event->state = PERF_EVENT_STATE_OFF;
3015 raw_spin_unlock_irq(&ctx->lock);
3017 event_function_call(event, __perf_event_enable, NULL);
3021 * See perf_event_disable();
3023 void perf_event_enable(struct perf_event *event)
3025 struct perf_event_context *ctx;
3027 ctx = perf_event_ctx_lock(event);
3028 _perf_event_enable(event);
3029 perf_event_ctx_unlock(event, ctx);
3031 EXPORT_SYMBOL_GPL(perf_event_enable);
3033 struct stop_event_data {
3034 struct perf_event *event;
3035 unsigned int restart;
3038 static int __perf_event_stop(void *info)
3040 struct stop_event_data *sd = info;
3041 struct perf_event *event = sd->event;
3043 /* if it's already INACTIVE, do nothing */
3044 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3047 /* matches smp_wmb() in event_sched_in() */
3051 * There is a window with interrupts enabled before we get here,
3052 * so we need to check again lest we try to stop another CPU's event.
3054 if (READ_ONCE(event->oncpu) != smp_processor_id())
3057 event->pmu->stop(event, PERF_EF_UPDATE);
3060 * May race with the actual stop (through perf_pmu_output_stop()),
3061 * but it is only used for events with AUX ring buffer, and such
3062 * events will refuse to restart because of rb::aux_mmap_count==0,
3063 * see comments in perf_aux_output_begin().
3065 * Since this is happening on an event-local CPU, no trace is lost
3069 event->pmu->start(event, 0);
3074 static int perf_event_stop(struct perf_event *event, int restart)
3076 struct stop_event_data sd = {
3083 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3086 /* matches smp_wmb() in event_sched_in() */
3090 * We only want to restart ACTIVE events, so if the event goes
3091 * inactive here (event->oncpu==-1), there's nothing more to do;
3092 * fall through with ret==-ENXIO.
3094 ret = cpu_function_call(READ_ONCE(event->oncpu),
3095 __perf_event_stop, &sd);
3096 } while (ret == -EAGAIN);
3102 * In order to contain the amount of racy and tricky in the address filter
3103 * configuration management, it is a two part process:
3105 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3106 * we update the addresses of corresponding vmas in
3107 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3108 * (p2) when an event is scheduled in (pmu::add), it calls
3109 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3110 * if the generation has changed since the previous call.
3112 * If (p1) happens while the event is active, we restart it to force (p2).
3114 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3115 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3117 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3118 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3120 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3123 void perf_event_addr_filters_sync(struct perf_event *event)
3125 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3127 if (!has_addr_filter(event))
3130 raw_spin_lock(&ifh->lock);
3131 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3132 event->pmu->addr_filters_sync(event);
3133 event->hw.addr_filters_gen = event->addr_filters_gen;
3135 raw_spin_unlock(&ifh->lock);
3137 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3139 static int _perf_event_refresh(struct perf_event *event, int refresh)
3142 * not supported on inherited events
3144 if (event->attr.inherit || !is_sampling_event(event))
3147 atomic_add(refresh, &event->event_limit);
3148 _perf_event_enable(event);
3154 * See perf_event_disable()
3156 int perf_event_refresh(struct perf_event *event, int refresh)
3158 struct perf_event_context *ctx;
3161 ctx = perf_event_ctx_lock(event);
3162 ret = _perf_event_refresh(event, refresh);
3163 perf_event_ctx_unlock(event, ctx);
3167 EXPORT_SYMBOL_GPL(perf_event_refresh);
3169 static int perf_event_modify_breakpoint(struct perf_event *bp,
3170 struct perf_event_attr *attr)
3174 _perf_event_disable(bp);
3176 err = modify_user_hw_breakpoint_check(bp, attr, true);
3178 if (!bp->attr.disabled)
3179 _perf_event_enable(bp);
3185 * Copy event-type-independent attributes that may be modified.
3187 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3188 const struct perf_event_attr *from)
3190 to->sig_data = from->sig_data;
3193 static int perf_event_modify_attr(struct perf_event *event,
3194 struct perf_event_attr *attr)
3196 int (*func)(struct perf_event *, struct perf_event_attr *);
3197 struct perf_event *child;
3200 if (event->attr.type != attr->type)
3203 switch (event->attr.type) {
3204 case PERF_TYPE_BREAKPOINT:
3205 func = perf_event_modify_breakpoint;
3208 /* Place holder for future additions. */
3212 WARN_ON_ONCE(event->ctx->parent_ctx);
3214 mutex_lock(&event->child_mutex);
3216 * Event-type-independent attributes must be copied before event-type
3217 * modification, which will validate that final attributes match the
3218 * source attributes after all relevant attributes have been copied.
3220 perf_event_modify_copy_attr(&event->attr, attr);
3221 err = func(event, attr);
3224 list_for_each_entry(child, &event->child_list, child_list) {
3225 perf_event_modify_copy_attr(&child->attr, attr);
3226 err = func(child, attr);
3231 mutex_unlock(&event->child_mutex);
3235 static void ctx_sched_out(struct perf_event_context *ctx,
3236 struct perf_cpu_context *cpuctx,
3237 enum event_type_t event_type)
3239 struct perf_event *event, *tmp;
3240 int is_active = ctx->is_active;
3242 lockdep_assert_held(&ctx->lock);
3244 if (likely(!ctx->nr_events)) {
3246 * See __perf_remove_from_context().
3248 WARN_ON_ONCE(ctx->is_active);
3250 WARN_ON_ONCE(cpuctx->task_ctx);
3255 * Always update time if it was set; not only when it changes.
3256 * Otherwise we can 'forget' to update time for any but the last
3257 * context we sched out. For example:
3259 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3260 * ctx_sched_out(.event_type = EVENT_PINNED)
3262 * would only update time for the pinned events.
3264 if (is_active & EVENT_TIME) {
3265 /* update (and stop) ctx time */
3266 update_context_time(ctx);
3267 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3269 * CPU-release for the below ->is_active store,
3270 * see __load_acquire() in perf_event_time_now()
3275 ctx->is_active &= ~event_type;
3276 if (!(ctx->is_active & EVENT_ALL))
3280 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3281 if (!ctx->is_active)
3282 cpuctx->task_ctx = NULL;
3285 is_active ^= ctx->is_active; /* changed bits */
3287 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3290 perf_pmu_disable(ctx->pmu);
3291 if (is_active & EVENT_PINNED) {
3292 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3293 group_sched_out(event, cpuctx, ctx);
3296 if (is_active & EVENT_FLEXIBLE) {
3297 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3298 group_sched_out(event, cpuctx, ctx);
3301 * Since we cleared EVENT_FLEXIBLE, also clear
3302 * rotate_necessary, is will be reset by
3303 * ctx_flexible_sched_in() when needed.
3305 ctx->rotate_necessary = 0;
3307 perf_pmu_enable(ctx->pmu);
3311 * Test whether two contexts are equivalent, i.e. whether they have both been
3312 * cloned from the same version of the same context.
3314 * Equivalence is measured using a generation number in the context that is
3315 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3316 * and list_del_event().
3318 static int context_equiv(struct perf_event_context *ctx1,
3319 struct perf_event_context *ctx2)
3321 lockdep_assert_held(&ctx1->lock);
3322 lockdep_assert_held(&ctx2->lock);
3324 /* Pinning disables the swap optimization */
3325 if (ctx1->pin_count || ctx2->pin_count)
3328 /* If ctx1 is the parent of ctx2 */
3329 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3332 /* If ctx2 is the parent of ctx1 */
3333 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3337 * If ctx1 and ctx2 have the same parent; we flatten the parent
3338 * hierarchy, see perf_event_init_context().
3340 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3341 ctx1->parent_gen == ctx2->parent_gen)
3348 static void __perf_event_sync_stat(struct perf_event *event,
3349 struct perf_event *next_event)
3353 if (!event->attr.inherit_stat)
3357 * Update the event value, we cannot use perf_event_read()
3358 * because we're in the middle of a context switch and have IRQs
3359 * disabled, which upsets smp_call_function_single(), however
3360 * we know the event must be on the current CPU, therefore we
3361 * don't need to use it.
3363 if (event->state == PERF_EVENT_STATE_ACTIVE)
3364 event->pmu->read(event);
3366 perf_event_update_time(event);
3369 * In order to keep per-task stats reliable we need to flip the event
3370 * values when we flip the contexts.
3372 value = local64_read(&next_event->count);
3373 value = local64_xchg(&event->count, value);
3374 local64_set(&next_event->count, value);
3376 swap(event->total_time_enabled, next_event->total_time_enabled);
3377 swap(event->total_time_running, next_event->total_time_running);
3380 * Since we swizzled the values, update the user visible data too.
3382 perf_event_update_userpage(event);
3383 perf_event_update_userpage(next_event);
3386 static void perf_event_sync_stat(struct perf_event_context *ctx,
3387 struct perf_event_context *next_ctx)
3389 struct perf_event *event, *next_event;
3394 update_context_time(ctx);
3396 event = list_first_entry(&ctx->event_list,
3397 struct perf_event, event_entry);
3399 next_event = list_first_entry(&next_ctx->event_list,
3400 struct perf_event, event_entry);
3402 while (&event->event_entry != &ctx->event_list &&
3403 &next_event->event_entry != &next_ctx->event_list) {
3405 __perf_event_sync_stat(event, next_event);
3407 event = list_next_entry(event, event_entry);
3408 next_event = list_next_entry(next_event, event_entry);
3412 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3413 struct task_struct *next)
3415 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3416 struct perf_event_context *next_ctx;
3417 struct perf_event_context *parent, *next_parent;
3418 struct perf_cpu_context *cpuctx;
3426 cpuctx = __get_cpu_context(ctx);
3427 if (!cpuctx->task_ctx)
3431 next_ctx = next->perf_event_ctxp[ctxn];
3435 parent = rcu_dereference(ctx->parent_ctx);
3436 next_parent = rcu_dereference(next_ctx->parent_ctx);
3438 /* If neither context have a parent context; they cannot be clones. */
3439 if (!parent && !next_parent)
3442 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3444 * Looks like the two contexts are clones, so we might be
3445 * able to optimize the context switch. We lock both
3446 * contexts and check that they are clones under the
3447 * lock (including re-checking that neither has been
3448 * uncloned in the meantime). It doesn't matter which
3449 * order we take the locks because no other cpu could
3450 * be trying to lock both of these tasks.
3452 raw_spin_lock(&ctx->lock);
3453 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3454 if (context_equiv(ctx, next_ctx)) {
3456 perf_pmu_disable(pmu);
3458 /* PMIs are disabled; ctx->nr_pending is stable. */
3459 if (local_read(&ctx->nr_pending) ||
3460 local_read(&next_ctx->nr_pending)) {
3462 * Must not swap out ctx when there's pending
3463 * events that rely on the ctx->task relation.
3465 raw_spin_unlock(&next_ctx->lock);
3470 WRITE_ONCE(ctx->task, next);
3471 WRITE_ONCE(next_ctx->task, task);
3473 if (cpuctx->sched_cb_usage && pmu->sched_task)
3474 pmu->sched_task(ctx, false);
3477 * PMU specific parts of task perf context can require
3478 * additional synchronization. As an example of such
3479 * synchronization see implementation details of Intel
3480 * LBR call stack data profiling;
3482 if (pmu->swap_task_ctx)
3483 pmu->swap_task_ctx(ctx, next_ctx);
3485 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3487 perf_pmu_enable(pmu);
3490 * RCU_INIT_POINTER here is safe because we've not
3491 * modified the ctx and the above modification of
3492 * ctx->task and ctx->task_ctx_data are immaterial
3493 * since those values are always verified under
3494 * ctx->lock which we're now holding.
3496 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3497 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3501 perf_event_sync_stat(ctx, next_ctx);
3503 raw_spin_unlock(&next_ctx->lock);
3504 raw_spin_unlock(&ctx->lock);
3510 raw_spin_lock(&ctx->lock);
3511 perf_pmu_disable(pmu);
3514 if (cpuctx->sched_cb_usage && pmu->sched_task)
3515 pmu->sched_task(ctx, false);
3516 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3518 perf_pmu_enable(pmu);
3519 raw_spin_unlock(&ctx->lock);
3523 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3525 void perf_sched_cb_dec(struct pmu *pmu)
3527 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3529 this_cpu_dec(perf_sched_cb_usages);
3531 if (!--cpuctx->sched_cb_usage)
3532 list_del(&cpuctx->sched_cb_entry);
3536 void perf_sched_cb_inc(struct pmu *pmu)
3538 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3540 if (!cpuctx->sched_cb_usage++)
3541 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3543 this_cpu_inc(perf_sched_cb_usages);
3547 * This function provides the context switch callback to the lower code
3548 * layer. It is invoked ONLY when the context switch callback is enabled.
3550 * This callback is relevant even to per-cpu events; for example multi event
3551 * PEBS requires this to provide PID/TID information. This requires we flush
3552 * all queued PEBS records before we context switch to a new task.
3554 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3558 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3560 if (WARN_ON_ONCE(!pmu->sched_task))
3563 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3564 perf_pmu_disable(pmu);
3566 pmu->sched_task(cpuctx->task_ctx, sched_in);
3568 perf_pmu_enable(pmu);
3569 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3572 static void perf_pmu_sched_task(struct task_struct *prev,
3573 struct task_struct *next,
3576 struct perf_cpu_context *cpuctx;
3581 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3582 /* will be handled in perf_event_context_sched_in/out */
3583 if (cpuctx->task_ctx)
3586 __perf_pmu_sched_task(cpuctx, sched_in);
3590 static void perf_event_switch(struct task_struct *task,
3591 struct task_struct *next_prev, bool sched_in);
3593 #define for_each_task_context_nr(ctxn) \
3594 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3597 * Called from scheduler to remove the events of the current task,
3598 * with interrupts disabled.
3600 * We stop each event and update the event value in event->count.
3602 * This does not protect us against NMI, but disable()
3603 * sets the disabled bit in the control field of event _before_
3604 * accessing the event control register. If a NMI hits, then it will
3605 * not restart the event.
3607 void __perf_event_task_sched_out(struct task_struct *task,
3608 struct task_struct *next)
3612 if (__this_cpu_read(perf_sched_cb_usages))
3613 perf_pmu_sched_task(task, next, false);
3615 if (atomic_read(&nr_switch_events))
3616 perf_event_switch(task, next, false);
3618 for_each_task_context_nr(ctxn)
3619 perf_event_context_sched_out(task, ctxn, next);
3622 * if cgroup events exist on this CPU, then we need
3623 * to check if we have to switch out PMU state.
3624 * cgroup event are system-wide mode only
3626 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3627 perf_cgroup_switch(next);
3631 * Called with IRQs disabled
3633 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3634 enum event_type_t event_type)
3636 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3639 static bool perf_less_group_idx(const void *l, const void *r)
3641 const struct perf_event *le = *(const struct perf_event **)l;
3642 const struct perf_event *re = *(const struct perf_event **)r;
3644 return le->group_index < re->group_index;
3647 static void swap_ptr(void *l, void *r)
3649 void **lp = l, **rp = r;
3654 static const struct min_heap_callbacks perf_min_heap = {
3655 .elem_size = sizeof(struct perf_event *),
3656 .less = perf_less_group_idx,
3660 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3662 struct perf_event **itrs = heap->data;
3665 itrs[heap->nr] = event;
3670 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3671 struct perf_event_groups *groups, int cpu,
3672 int (*func)(struct perf_event *, void *),
3675 #ifdef CONFIG_CGROUP_PERF
3676 struct cgroup_subsys_state *css = NULL;
3678 /* Space for per CPU and/or any CPU event iterators. */
3679 struct perf_event *itrs[2];
3680 struct min_heap event_heap;
3681 struct perf_event **evt;
3685 event_heap = (struct min_heap){
3686 .data = cpuctx->heap,
3688 .size = cpuctx->heap_size,
3691 lockdep_assert_held(&cpuctx->ctx.lock);
3693 #ifdef CONFIG_CGROUP_PERF
3695 css = &cpuctx->cgrp->css;
3698 event_heap = (struct min_heap){
3701 .size = ARRAY_SIZE(itrs),
3703 /* Events not within a CPU context may be on any CPU. */
3704 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3706 evt = event_heap.data;
3708 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3710 #ifdef CONFIG_CGROUP_PERF
3711 for (; css; css = css->parent)
3712 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3715 min_heapify_all(&event_heap, &perf_min_heap);
3717 while (event_heap.nr) {
3718 ret = func(*evt, data);
3722 *evt = perf_event_groups_next(*evt);
3724 min_heapify(&event_heap, 0, &perf_min_heap);
3726 min_heap_pop(&event_heap, &perf_min_heap);
3733 * Because the userpage is strictly per-event (there is no concept of context,
3734 * so there cannot be a context indirection), every userpage must be updated
3735 * when context time starts :-(
3737 * IOW, we must not miss EVENT_TIME edges.
3739 static inline bool event_update_userpage(struct perf_event *event)
3741 if (likely(!atomic_read(&event->mmap_count)))
3744 perf_event_update_time(event);
3745 perf_event_update_userpage(event);
3750 static inline void group_update_userpage(struct perf_event *group_event)
3752 struct perf_event *event;
3754 if (!event_update_userpage(group_event))
3757 for_each_sibling_event(event, group_event)
3758 event_update_userpage(event);
3761 static int merge_sched_in(struct perf_event *event, void *data)
3763 struct perf_event_context *ctx = event->ctx;
3764 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3765 int *can_add_hw = data;
3767 if (event->state <= PERF_EVENT_STATE_OFF)
3770 if (!event_filter_match(event))
3773 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3774 if (!group_sched_in(event, cpuctx, ctx))
3775 list_add_tail(&event->active_list, get_event_list(event));
3778 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3780 if (event->attr.pinned) {
3781 perf_cgroup_event_disable(event, ctx);
3782 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3784 ctx->rotate_necessary = 1;
3785 perf_mux_hrtimer_restart(cpuctx);
3786 group_update_userpage(event);
3794 ctx_pinned_sched_in(struct perf_event_context *ctx,
3795 struct perf_cpu_context *cpuctx)
3799 if (ctx != &cpuctx->ctx)
3802 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3804 merge_sched_in, &can_add_hw);
3808 ctx_flexible_sched_in(struct perf_event_context *ctx,
3809 struct perf_cpu_context *cpuctx)
3813 if (ctx != &cpuctx->ctx)
3816 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3818 merge_sched_in, &can_add_hw);
3822 ctx_sched_in(struct perf_event_context *ctx,
3823 struct perf_cpu_context *cpuctx,
3824 enum event_type_t event_type)
3826 int is_active = ctx->is_active;
3828 lockdep_assert_held(&ctx->lock);
3830 if (likely(!ctx->nr_events))
3833 if (is_active ^ EVENT_TIME) {
3834 /* start ctx time */
3835 __update_context_time(ctx, false);
3836 perf_cgroup_set_timestamp(cpuctx);
3838 * CPU-release for the below ->is_active store,
3839 * see __load_acquire() in perf_event_time_now()
3844 ctx->is_active |= (event_type | EVENT_TIME);
3847 cpuctx->task_ctx = ctx;
3849 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3852 is_active ^= ctx->is_active; /* changed bits */
3855 * First go through the list and put on any pinned groups
3856 * in order to give them the best chance of going on.
3858 if (is_active & EVENT_PINNED)
3859 ctx_pinned_sched_in(ctx, cpuctx);
3861 /* Then walk through the lower prio flexible groups */
3862 if (is_active & EVENT_FLEXIBLE)
3863 ctx_flexible_sched_in(ctx, cpuctx);
3866 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3867 enum event_type_t event_type)
3869 struct perf_event_context *ctx = &cpuctx->ctx;
3871 ctx_sched_in(ctx, cpuctx, event_type);
3874 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3875 struct task_struct *task)
3877 struct perf_cpu_context *cpuctx;
3880 cpuctx = __get_cpu_context(ctx);
3883 * HACK: for HETEROGENEOUS the task context might have switched to a
3884 * different PMU, force (re)set the context,
3886 pmu = ctx->pmu = cpuctx->ctx.pmu;
3888 if (cpuctx->task_ctx == ctx) {
3889 if (cpuctx->sched_cb_usage)
3890 __perf_pmu_sched_task(cpuctx, true);
3894 perf_ctx_lock(cpuctx, ctx);
3896 * We must check ctx->nr_events while holding ctx->lock, such
3897 * that we serialize against perf_install_in_context().
3899 if (!ctx->nr_events)
3902 perf_pmu_disable(pmu);
3904 * We want to keep the following priority order:
3905 * cpu pinned (that don't need to move), task pinned,
3906 * cpu flexible, task flexible.
3908 * However, if task's ctx is not carrying any pinned
3909 * events, no need to flip the cpuctx's events around.
3911 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3912 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3913 perf_event_sched_in(cpuctx, ctx);
3915 if (cpuctx->sched_cb_usage && pmu->sched_task)
3916 pmu->sched_task(cpuctx->task_ctx, true);
3918 perf_pmu_enable(pmu);
3921 perf_ctx_unlock(cpuctx, ctx);
3925 * Called from scheduler to add the events of the current task
3926 * with interrupts disabled.
3928 * We restore the event value and then enable it.
3930 * This does not protect us against NMI, but enable()
3931 * sets the enabled bit in the control field of event _before_
3932 * accessing the event control register. If a NMI hits, then it will
3933 * keep the event running.
3935 void __perf_event_task_sched_in(struct task_struct *prev,
3936 struct task_struct *task)
3938 struct perf_event_context *ctx;
3941 for_each_task_context_nr(ctxn) {
3942 ctx = task->perf_event_ctxp[ctxn];
3946 perf_event_context_sched_in(ctx, task);
3949 if (atomic_read(&nr_switch_events))
3950 perf_event_switch(task, prev, true);
3952 if (__this_cpu_read(perf_sched_cb_usages))
3953 perf_pmu_sched_task(prev, task, true);
3956 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3958 u64 frequency = event->attr.sample_freq;
3959 u64 sec = NSEC_PER_SEC;
3960 u64 divisor, dividend;
3962 int count_fls, nsec_fls, frequency_fls, sec_fls;
3964 count_fls = fls64(count);
3965 nsec_fls = fls64(nsec);
3966 frequency_fls = fls64(frequency);
3970 * We got @count in @nsec, with a target of sample_freq HZ
3971 * the target period becomes:
3974 * period = -------------------
3975 * @nsec * sample_freq
3980 * Reduce accuracy by one bit such that @a and @b converge
3981 * to a similar magnitude.
3983 #define REDUCE_FLS(a, b) \
3985 if (a##_fls > b##_fls) { \
3995 * Reduce accuracy until either term fits in a u64, then proceed with
3996 * the other, so that finally we can do a u64/u64 division.
3998 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3999 REDUCE_FLS(nsec, frequency);
4000 REDUCE_FLS(sec, count);
4003 if (count_fls + sec_fls > 64) {
4004 divisor = nsec * frequency;
4006 while (count_fls + sec_fls > 64) {
4007 REDUCE_FLS(count, sec);
4011 dividend = count * sec;
4013 dividend = count * sec;
4015 while (nsec_fls + frequency_fls > 64) {
4016 REDUCE_FLS(nsec, frequency);
4020 divisor = nsec * frequency;
4026 return div64_u64(dividend, divisor);
4029 static DEFINE_PER_CPU(int, perf_throttled_count);
4030 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4032 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4034 struct hw_perf_event *hwc = &event->hw;
4035 s64 period, sample_period;
4038 period = perf_calculate_period(event, nsec, count);
4040 delta = (s64)(period - hwc->sample_period);
4041 delta = (delta + 7) / 8; /* low pass filter */
4043 sample_period = hwc->sample_period + delta;
4048 hwc->sample_period = sample_period;
4050 if (local64_read(&hwc->period_left) > 8*sample_period) {
4052 event->pmu->stop(event, PERF_EF_UPDATE);
4054 local64_set(&hwc->period_left, 0);
4057 event->pmu->start(event, PERF_EF_RELOAD);
4062 * combine freq adjustment with unthrottling to avoid two passes over the
4063 * events. At the same time, make sure, having freq events does not change
4064 * the rate of unthrottling as that would introduce bias.
4066 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
4069 struct perf_event *event;
4070 struct hw_perf_event *hwc;
4071 u64 now, period = TICK_NSEC;
4075 * only need to iterate over all events iff:
4076 * - context have events in frequency mode (needs freq adjust)
4077 * - there are events to unthrottle on this cpu
4079 if (!(ctx->nr_freq || needs_unthr))
4082 raw_spin_lock(&ctx->lock);
4083 perf_pmu_disable(ctx->pmu);
4085 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4086 if (event->state != PERF_EVENT_STATE_ACTIVE)
4089 if (!event_filter_match(event))
4092 perf_pmu_disable(event->pmu);
4096 if (hwc->interrupts == MAX_INTERRUPTS) {
4097 hwc->interrupts = 0;
4098 perf_log_throttle(event, 1);
4099 event->pmu->start(event, 0);
4102 if (!event->attr.freq || !event->attr.sample_freq)
4106 * stop the event and update event->count
4108 event->pmu->stop(event, PERF_EF_UPDATE);
4110 now = local64_read(&event->count);
4111 delta = now - hwc->freq_count_stamp;
4112 hwc->freq_count_stamp = now;
4116 * reload only if value has changed
4117 * we have stopped the event so tell that
4118 * to perf_adjust_period() to avoid stopping it
4122 perf_adjust_period(event, period, delta, false);
4124 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4126 perf_pmu_enable(event->pmu);
4129 perf_pmu_enable(ctx->pmu);
4130 raw_spin_unlock(&ctx->lock);
4134 * Move @event to the tail of the @ctx's elegible events.
4136 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4139 * Rotate the first entry last of non-pinned groups. Rotation might be
4140 * disabled by the inheritance code.
4142 if (ctx->rotate_disable)
4145 perf_event_groups_delete(&ctx->flexible_groups, event);
4146 perf_event_groups_insert(&ctx->flexible_groups, event);
4149 /* pick an event from the flexible_groups to rotate */
4150 static inline struct perf_event *
4151 ctx_event_to_rotate(struct perf_event_context *ctx)
4153 struct perf_event *event;
4155 /* pick the first active flexible event */
4156 event = list_first_entry_or_null(&ctx->flexible_active,
4157 struct perf_event, active_list);
4159 /* if no active flexible event, pick the first event */
4161 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4162 typeof(*event), group_node);
4166 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4167 * finds there are unschedulable events, it will set it again.
4169 ctx->rotate_necessary = 0;
4174 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4176 struct perf_event *cpu_event = NULL, *task_event = NULL;
4177 struct perf_event_context *task_ctx = NULL;
4178 int cpu_rotate, task_rotate;
4181 * Since we run this from IRQ context, nobody can install new
4182 * events, thus the event count values are stable.
4185 cpu_rotate = cpuctx->ctx.rotate_necessary;
4186 task_ctx = cpuctx->task_ctx;
4187 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4189 if (!(cpu_rotate || task_rotate))
4192 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4193 perf_pmu_disable(cpuctx->ctx.pmu);
4196 task_event = ctx_event_to_rotate(task_ctx);
4198 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4201 * As per the order given at ctx_resched() first 'pop' task flexible
4202 * and then, if needed CPU flexible.
4204 if (task_event || (task_ctx && cpu_event))
4205 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4207 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4210 rotate_ctx(task_ctx, task_event);
4212 rotate_ctx(&cpuctx->ctx, cpu_event);
4214 perf_event_sched_in(cpuctx, task_ctx);
4216 perf_pmu_enable(cpuctx->ctx.pmu);
4217 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4222 void perf_event_task_tick(void)
4224 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4225 struct perf_event_context *ctx, *tmp;
4228 lockdep_assert_irqs_disabled();
4230 __this_cpu_inc(perf_throttled_seq);
4231 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4232 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4234 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4235 perf_adjust_freq_unthr_context(ctx, throttled);
4238 static int event_enable_on_exec(struct perf_event *event,
4239 struct perf_event_context *ctx)
4241 if (!event->attr.enable_on_exec)
4244 event->attr.enable_on_exec = 0;
4245 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4248 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4254 * Enable all of a task's events that have been marked enable-on-exec.
4255 * This expects task == current.
4257 static void perf_event_enable_on_exec(int ctxn)
4259 struct perf_event_context *ctx, *clone_ctx = NULL;
4260 enum event_type_t event_type = 0;
4261 struct perf_cpu_context *cpuctx;
4262 struct perf_event *event;
4263 unsigned long flags;
4266 local_irq_save(flags);
4267 ctx = current->perf_event_ctxp[ctxn];
4268 if (!ctx || !ctx->nr_events)
4271 cpuctx = __get_cpu_context(ctx);
4272 perf_ctx_lock(cpuctx, ctx);
4273 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4274 list_for_each_entry(event, &ctx->event_list, event_entry) {
4275 enabled |= event_enable_on_exec(event, ctx);
4276 event_type |= get_event_type(event);
4280 * Unclone and reschedule this context if we enabled any event.
4283 clone_ctx = unclone_ctx(ctx);
4284 ctx_resched(cpuctx, ctx, event_type);
4286 ctx_sched_in(ctx, cpuctx, EVENT_TIME);
4288 perf_ctx_unlock(cpuctx, ctx);
4291 local_irq_restore(flags);
4297 static void perf_remove_from_owner(struct perf_event *event);
4298 static void perf_event_exit_event(struct perf_event *event,
4299 struct perf_event_context *ctx);
4302 * Removes all events from the current task that have been marked
4303 * remove-on-exec, and feeds their values back to parent events.
4305 static void perf_event_remove_on_exec(int ctxn)
4307 struct perf_event_context *ctx, *clone_ctx = NULL;
4308 struct perf_event *event, *next;
4309 unsigned long flags;
4310 bool modified = false;
4312 ctx = perf_pin_task_context(current, ctxn);
4316 mutex_lock(&ctx->mutex);
4318 if (WARN_ON_ONCE(ctx->task != current))
4321 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4322 if (!event->attr.remove_on_exec)
4325 if (!is_kernel_event(event))
4326 perf_remove_from_owner(event);
4330 perf_event_exit_event(event, ctx);
4333 raw_spin_lock_irqsave(&ctx->lock, flags);
4335 clone_ctx = unclone_ctx(ctx);
4337 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4340 mutex_unlock(&ctx->mutex);
4347 struct perf_read_data {
4348 struct perf_event *event;
4353 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4355 u16 local_pkg, event_pkg;
4357 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4358 int local_cpu = smp_processor_id();
4360 event_pkg = topology_physical_package_id(event_cpu);
4361 local_pkg = topology_physical_package_id(local_cpu);
4363 if (event_pkg == local_pkg)
4371 * Cross CPU call to read the hardware event
4373 static void __perf_event_read(void *info)
4375 struct perf_read_data *data = info;
4376 struct perf_event *sub, *event = data->event;
4377 struct perf_event_context *ctx = event->ctx;
4378 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4379 struct pmu *pmu = event->pmu;
4382 * If this is a task context, we need to check whether it is
4383 * the current task context of this cpu. If not it has been
4384 * scheduled out before the smp call arrived. In that case
4385 * event->count would have been updated to a recent sample
4386 * when the event was scheduled out.
4388 if (ctx->task && cpuctx->task_ctx != ctx)
4391 raw_spin_lock(&ctx->lock);
4392 if (ctx->is_active & EVENT_TIME) {
4393 update_context_time(ctx);
4394 update_cgrp_time_from_event(event);
4397 perf_event_update_time(event);
4399 perf_event_update_sibling_time(event);
4401 if (event->state != PERF_EVENT_STATE_ACTIVE)
4410 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4414 for_each_sibling_event(sub, event) {
4415 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4417 * Use sibling's PMU rather than @event's since
4418 * sibling could be on different (eg: software) PMU.
4420 sub->pmu->read(sub);
4424 data->ret = pmu->commit_txn(pmu);
4427 raw_spin_unlock(&ctx->lock);
4430 static inline u64 perf_event_count(struct perf_event *event)
4432 return local64_read(&event->count) + atomic64_read(&event->child_count);
4435 static void calc_timer_values(struct perf_event *event,
4442 *now = perf_clock();
4443 ctx_time = perf_event_time_now(event, *now);
4444 __perf_update_times(event, ctx_time, enabled, running);
4448 * NMI-safe method to read a local event, that is an event that
4450 * - either for the current task, or for this CPU
4451 * - does not have inherit set, for inherited task events
4452 * will not be local and we cannot read them atomically
4453 * - must not have a pmu::count method
4455 int perf_event_read_local(struct perf_event *event, u64 *value,
4456 u64 *enabled, u64 *running)
4458 unsigned long flags;
4462 * Disabling interrupts avoids all counter scheduling (context
4463 * switches, timer based rotation and IPIs).
4465 local_irq_save(flags);
4468 * It must not be an event with inherit set, we cannot read
4469 * all child counters from atomic context.
4471 if (event->attr.inherit) {
4476 /* If this is a per-task event, it must be for current */
4477 if ((event->attach_state & PERF_ATTACH_TASK) &&
4478 event->hw.target != current) {
4483 /* If this is a per-CPU event, it must be for this CPU */
4484 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4485 event->cpu != smp_processor_id()) {
4490 /* If this is a pinned event it must be running on this CPU */
4491 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4497 * If the event is currently on this CPU, its either a per-task event,
4498 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4501 if (event->oncpu == smp_processor_id())
4502 event->pmu->read(event);
4504 *value = local64_read(&event->count);
4505 if (enabled || running) {
4506 u64 __enabled, __running, __now;
4508 calc_timer_values(event, &__now, &__enabled, &__running);
4510 *enabled = __enabled;
4512 *running = __running;
4515 local_irq_restore(flags);
4520 static int perf_event_read(struct perf_event *event, bool group)
4522 enum perf_event_state state = READ_ONCE(event->state);
4523 int event_cpu, ret = 0;
4526 * If event is enabled and currently active on a CPU, update the
4527 * value in the event structure:
4530 if (state == PERF_EVENT_STATE_ACTIVE) {
4531 struct perf_read_data data;
4534 * Orders the ->state and ->oncpu loads such that if we see
4535 * ACTIVE we must also see the right ->oncpu.
4537 * Matches the smp_wmb() from event_sched_in().
4541 event_cpu = READ_ONCE(event->oncpu);
4542 if ((unsigned)event_cpu >= nr_cpu_ids)
4545 data = (struct perf_read_data){
4552 event_cpu = __perf_event_read_cpu(event, event_cpu);
4555 * Purposely ignore the smp_call_function_single() return
4558 * If event_cpu isn't a valid CPU it means the event got
4559 * scheduled out and that will have updated the event count.
4561 * Therefore, either way, we'll have an up-to-date event count
4564 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4568 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4569 struct perf_event_context *ctx = event->ctx;
4570 unsigned long flags;
4572 raw_spin_lock_irqsave(&ctx->lock, flags);
4573 state = event->state;
4574 if (state != PERF_EVENT_STATE_INACTIVE) {
4575 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4580 * May read while context is not active (e.g., thread is
4581 * blocked), in that case we cannot update context time
4583 if (ctx->is_active & EVENT_TIME) {
4584 update_context_time(ctx);
4585 update_cgrp_time_from_event(event);
4588 perf_event_update_time(event);
4590 perf_event_update_sibling_time(event);
4591 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4598 * Initialize the perf_event context in a task_struct:
4600 static void __perf_event_init_context(struct perf_event_context *ctx)
4602 raw_spin_lock_init(&ctx->lock);
4603 mutex_init(&ctx->mutex);
4604 INIT_LIST_HEAD(&ctx->active_ctx_list);
4605 perf_event_groups_init(&ctx->pinned_groups);
4606 perf_event_groups_init(&ctx->flexible_groups);
4607 INIT_LIST_HEAD(&ctx->event_list);
4608 INIT_LIST_HEAD(&ctx->pinned_active);
4609 INIT_LIST_HEAD(&ctx->flexible_active);
4610 refcount_set(&ctx->refcount, 1);
4613 static struct perf_event_context *
4614 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4616 struct perf_event_context *ctx;
4618 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4622 __perf_event_init_context(ctx);
4624 ctx->task = get_task_struct(task);
4630 static struct task_struct *
4631 find_lively_task_by_vpid(pid_t vpid)
4633 struct task_struct *task;
4639 task = find_task_by_vpid(vpid);
4641 get_task_struct(task);
4645 return ERR_PTR(-ESRCH);
4651 * Returns a matching context with refcount and pincount.
4653 static struct perf_event_context *
4654 find_get_context(struct pmu *pmu, struct task_struct *task,
4655 struct perf_event *event)
4657 struct perf_event_context *ctx, *clone_ctx = NULL;
4658 struct perf_cpu_context *cpuctx;
4659 void *task_ctx_data = NULL;
4660 unsigned long flags;
4662 int cpu = event->cpu;
4665 /* Must be root to operate on a CPU event: */
4666 err = perf_allow_cpu(&event->attr);
4668 return ERR_PTR(err);
4670 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4673 raw_spin_lock_irqsave(&ctx->lock, flags);
4675 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4681 ctxn = pmu->task_ctx_nr;
4685 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4686 task_ctx_data = alloc_task_ctx_data(pmu);
4687 if (!task_ctx_data) {
4694 ctx = perf_lock_task_context(task, ctxn, &flags);
4696 clone_ctx = unclone_ctx(ctx);
4699 if (task_ctx_data && !ctx->task_ctx_data) {
4700 ctx->task_ctx_data = task_ctx_data;
4701 task_ctx_data = NULL;
4703 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4708 ctx = alloc_perf_context(pmu, task);
4713 if (task_ctx_data) {
4714 ctx->task_ctx_data = task_ctx_data;
4715 task_ctx_data = NULL;
4719 mutex_lock(&task->perf_event_mutex);
4721 * If it has already passed perf_event_exit_task().
4722 * we must see PF_EXITING, it takes this mutex too.
4724 if (task->flags & PF_EXITING)
4726 else if (task->perf_event_ctxp[ctxn])
4731 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4733 mutex_unlock(&task->perf_event_mutex);
4735 if (unlikely(err)) {
4744 free_task_ctx_data(pmu, task_ctx_data);
4748 free_task_ctx_data(pmu, task_ctx_data);
4749 return ERR_PTR(err);
4752 static void perf_event_free_filter(struct perf_event *event);
4754 static void free_event_rcu(struct rcu_head *head)
4756 struct perf_event *event;
4758 event = container_of(head, struct perf_event, rcu_head);
4760 put_pid_ns(event->ns);
4761 perf_event_free_filter(event);
4762 kmem_cache_free(perf_event_cache, event);
4765 static void ring_buffer_attach(struct perf_event *event,
4766 struct perf_buffer *rb);
4768 static void detach_sb_event(struct perf_event *event)
4770 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4772 raw_spin_lock(&pel->lock);
4773 list_del_rcu(&event->sb_list);
4774 raw_spin_unlock(&pel->lock);
4777 static bool is_sb_event(struct perf_event *event)
4779 struct perf_event_attr *attr = &event->attr;
4784 if (event->attach_state & PERF_ATTACH_TASK)
4787 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4788 attr->comm || attr->comm_exec ||
4789 attr->task || attr->ksymbol ||
4790 attr->context_switch || attr->text_poke ||
4796 static void unaccount_pmu_sb_event(struct perf_event *event)
4798 if (is_sb_event(event))
4799 detach_sb_event(event);
4802 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4807 if (is_cgroup_event(event))
4808 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4811 #ifdef CONFIG_NO_HZ_FULL
4812 static DEFINE_SPINLOCK(nr_freq_lock);
4815 static void unaccount_freq_event_nohz(void)
4817 #ifdef CONFIG_NO_HZ_FULL
4818 spin_lock(&nr_freq_lock);
4819 if (atomic_dec_and_test(&nr_freq_events))
4820 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4821 spin_unlock(&nr_freq_lock);
4825 static void unaccount_freq_event(void)
4827 if (tick_nohz_full_enabled())
4828 unaccount_freq_event_nohz();
4830 atomic_dec(&nr_freq_events);
4833 static void unaccount_event(struct perf_event *event)
4840 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4842 if (event->attr.mmap || event->attr.mmap_data)
4843 atomic_dec(&nr_mmap_events);
4844 if (event->attr.build_id)
4845 atomic_dec(&nr_build_id_events);
4846 if (event->attr.comm)
4847 atomic_dec(&nr_comm_events);
4848 if (event->attr.namespaces)
4849 atomic_dec(&nr_namespaces_events);
4850 if (event->attr.cgroup)
4851 atomic_dec(&nr_cgroup_events);
4852 if (event->attr.task)
4853 atomic_dec(&nr_task_events);
4854 if (event->attr.freq)
4855 unaccount_freq_event();
4856 if (event->attr.context_switch) {
4858 atomic_dec(&nr_switch_events);
4860 if (is_cgroup_event(event))
4862 if (has_branch_stack(event))
4864 if (event->attr.ksymbol)
4865 atomic_dec(&nr_ksymbol_events);
4866 if (event->attr.bpf_event)
4867 atomic_dec(&nr_bpf_events);
4868 if (event->attr.text_poke)
4869 atomic_dec(&nr_text_poke_events);
4872 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4873 schedule_delayed_work(&perf_sched_work, HZ);
4876 unaccount_event_cpu(event, event->cpu);
4878 unaccount_pmu_sb_event(event);
4881 static void perf_sched_delayed(struct work_struct *work)
4883 mutex_lock(&perf_sched_mutex);
4884 if (atomic_dec_and_test(&perf_sched_count))
4885 static_branch_disable(&perf_sched_events);
4886 mutex_unlock(&perf_sched_mutex);
4890 * The following implement mutual exclusion of events on "exclusive" pmus
4891 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4892 * at a time, so we disallow creating events that might conflict, namely:
4894 * 1) cpu-wide events in the presence of per-task events,
4895 * 2) per-task events in the presence of cpu-wide events,
4896 * 3) two matching events on the same context.
4898 * The former two cases are handled in the allocation path (perf_event_alloc(),
4899 * _free_event()), the latter -- before the first perf_install_in_context().
4901 static int exclusive_event_init(struct perf_event *event)
4903 struct pmu *pmu = event->pmu;
4905 if (!is_exclusive_pmu(pmu))
4909 * Prevent co-existence of per-task and cpu-wide events on the
4910 * same exclusive pmu.
4912 * Negative pmu::exclusive_cnt means there are cpu-wide
4913 * events on this "exclusive" pmu, positive means there are
4916 * Since this is called in perf_event_alloc() path, event::ctx
4917 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4918 * to mean "per-task event", because unlike other attach states it
4919 * never gets cleared.
4921 if (event->attach_state & PERF_ATTACH_TASK) {
4922 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4925 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4932 static void exclusive_event_destroy(struct perf_event *event)
4934 struct pmu *pmu = event->pmu;
4936 if (!is_exclusive_pmu(pmu))
4939 /* see comment in exclusive_event_init() */
4940 if (event->attach_state & PERF_ATTACH_TASK)
4941 atomic_dec(&pmu->exclusive_cnt);
4943 atomic_inc(&pmu->exclusive_cnt);
4946 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4948 if ((e1->pmu == e2->pmu) &&
4949 (e1->cpu == e2->cpu ||
4956 static bool exclusive_event_installable(struct perf_event *event,
4957 struct perf_event_context *ctx)
4959 struct perf_event *iter_event;
4960 struct pmu *pmu = event->pmu;
4962 lockdep_assert_held(&ctx->mutex);
4964 if (!is_exclusive_pmu(pmu))
4967 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4968 if (exclusive_event_match(iter_event, event))
4975 static void perf_addr_filters_splice(struct perf_event *event,
4976 struct list_head *head);
4978 static void _free_event(struct perf_event *event)
4980 irq_work_sync(&event->pending_irq);
4982 unaccount_event(event);
4984 security_perf_event_free(event);
4988 * Can happen when we close an event with re-directed output.
4990 * Since we have a 0 refcount, perf_mmap_close() will skip
4991 * over us; possibly making our ring_buffer_put() the last.
4993 mutex_lock(&event->mmap_mutex);
4994 ring_buffer_attach(event, NULL);
4995 mutex_unlock(&event->mmap_mutex);
4998 if (is_cgroup_event(event))
4999 perf_detach_cgroup(event);
5001 if (!event->parent) {
5002 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
5003 put_callchain_buffers();
5006 perf_event_free_bpf_prog(event);
5007 perf_addr_filters_splice(event, NULL);
5008 kfree(event->addr_filter_ranges);
5011 event->destroy(event);
5014 * Must be after ->destroy(), due to uprobe_perf_close() using
5017 if (event->hw.target)
5018 put_task_struct(event->hw.target);
5021 * perf_event_free_task() relies on put_ctx() being 'last', in particular
5022 * all task references must be cleaned up.
5025 put_ctx(event->ctx);
5027 exclusive_event_destroy(event);
5028 module_put(event->pmu->module);
5030 call_rcu(&event->rcu_head, free_event_rcu);
5034 * Used to free events which have a known refcount of 1, such as in error paths
5035 * where the event isn't exposed yet and inherited events.
5037 static void free_event(struct perf_event *event)
5039 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5040 "unexpected event refcount: %ld; ptr=%p\n",
5041 atomic_long_read(&event->refcount), event)) {
5042 /* leak to avoid use-after-free */
5050 * Remove user event from the owner task.
5052 static void perf_remove_from_owner(struct perf_event *event)
5054 struct task_struct *owner;
5058 * Matches the smp_store_release() in perf_event_exit_task(). If we
5059 * observe !owner it means the list deletion is complete and we can
5060 * indeed free this event, otherwise we need to serialize on
5061 * owner->perf_event_mutex.
5063 owner = READ_ONCE(event->owner);
5066 * Since delayed_put_task_struct() also drops the last
5067 * task reference we can safely take a new reference
5068 * while holding the rcu_read_lock().
5070 get_task_struct(owner);
5076 * If we're here through perf_event_exit_task() we're already
5077 * holding ctx->mutex which would be an inversion wrt. the
5078 * normal lock order.
5080 * However we can safely take this lock because its the child
5083 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5086 * We have to re-check the event->owner field, if it is cleared
5087 * we raced with perf_event_exit_task(), acquiring the mutex
5088 * ensured they're done, and we can proceed with freeing the
5092 list_del_init(&event->owner_entry);
5093 smp_store_release(&event->owner, NULL);
5095 mutex_unlock(&owner->perf_event_mutex);
5096 put_task_struct(owner);
5100 static void put_event(struct perf_event *event)
5102 if (!atomic_long_dec_and_test(&event->refcount))
5109 * Kill an event dead; while event:refcount will preserve the event
5110 * object, it will not preserve its functionality. Once the last 'user'
5111 * gives up the object, we'll destroy the thing.
5113 int perf_event_release_kernel(struct perf_event *event)
5115 struct perf_event_context *ctx = event->ctx;
5116 struct perf_event *child, *tmp;
5117 LIST_HEAD(free_list);
5120 * If we got here through err_file: fput(event_file); we will not have
5121 * attached to a context yet.
5124 WARN_ON_ONCE(event->attach_state &
5125 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5129 if (!is_kernel_event(event))
5130 perf_remove_from_owner(event);
5132 ctx = perf_event_ctx_lock(event);
5133 WARN_ON_ONCE(ctx->parent_ctx);
5136 * Mark this event as STATE_DEAD, there is no external reference to it
5139 * Anybody acquiring event->child_mutex after the below loop _must_
5140 * also see this, most importantly inherit_event() which will avoid
5141 * placing more children on the list.
5143 * Thus this guarantees that we will in fact observe and kill _ALL_
5146 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5148 perf_event_ctx_unlock(event, ctx);
5151 mutex_lock(&event->child_mutex);
5152 list_for_each_entry(child, &event->child_list, child_list) {
5155 * Cannot change, child events are not migrated, see the
5156 * comment with perf_event_ctx_lock_nested().
5158 ctx = READ_ONCE(child->ctx);
5160 * Since child_mutex nests inside ctx::mutex, we must jump
5161 * through hoops. We start by grabbing a reference on the ctx.
5163 * Since the event cannot get freed while we hold the
5164 * child_mutex, the context must also exist and have a !0
5170 * Now that we have a ctx ref, we can drop child_mutex, and
5171 * acquire ctx::mutex without fear of it going away. Then we
5172 * can re-acquire child_mutex.
5174 mutex_unlock(&event->child_mutex);
5175 mutex_lock(&ctx->mutex);
5176 mutex_lock(&event->child_mutex);
5179 * Now that we hold ctx::mutex and child_mutex, revalidate our
5180 * state, if child is still the first entry, it didn't get freed
5181 * and we can continue doing so.
5183 tmp = list_first_entry_or_null(&event->child_list,
5184 struct perf_event, child_list);
5186 perf_remove_from_context(child, DETACH_GROUP);
5187 list_move(&child->child_list, &free_list);
5189 * This matches the refcount bump in inherit_event();
5190 * this can't be the last reference.
5195 mutex_unlock(&event->child_mutex);
5196 mutex_unlock(&ctx->mutex);
5200 mutex_unlock(&event->child_mutex);
5202 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5203 void *var = &child->ctx->refcount;
5205 list_del(&child->child_list);
5209 * Wake any perf_event_free_task() waiting for this event to be
5212 smp_mb(); /* pairs with wait_var_event() */
5217 put_event(event); /* Must be the 'last' reference */
5220 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5223 * Called when the last reference to the file is gone.
5225 static int perf_release(struct inode *inode, struct file *file)
5227 perf_event_release_kernel(file->private_data);
5231 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5233 struct perf_event *child;
5239 mutex_lock(&event->child_mutex);
5241 (void)perf_event_read(event, false);
5242 total += perf_event_count(event);
5244 *enabled += event->total_time_enabled +
5245 atomic64_read(&event->child_total_time_enabled);
5246 *running += event->total_time_running +
5247 atomic64_read(&event->child_total_time_running);
5249 list_for_each_entry(child, &event->child_list, child_list) {
5250 (void)perf_event_read(child, false);
5251 total += perf_event_count(child);
5252 *enabled += child->total_time_enabled;
5253 *running += child->total_time_running;
5255 mutex_unlock(&event->child_mutex);
5260 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5262 struct perf_event_context *ctx;
5265 ctx = perf_event_ctx_lock(event);
5266 count = __perf_event_read_value(event, enabled, running);
5267 perf_event_ctx_unlock(event, ctx);
5271 EXPORT_SYMBOL_GPL(perf_event_read_value);
5273 static int __perf_read_group_add(struct perf_event *leader,
5274 u64 read_format, u64 *values)
5276 struct perf_event_context *ctx = leader->ctx;
5277 struct perf_event *sub;
5278 unsigned long flags;
5279 int n = 1; /* skip @nr */
5282 ret = perf_event_read(leader, true);
5286 raw_spin_lock_irqsave(&ctx->lock, flags);
5289 * Since we co-schedule groups, {enabled,running} times of siblings
5290 * will be identical to those of the leader, so we only publish one
5293 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5294 values[n++] += leader->total_time_enabled +
5295 atomic64_read(&leader->child_total_time_enabled);
5298 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5299 values[n++] += leader->total_time_running +
5300 atomic64_read(&leader->child_total_time_running);
5304 * Write {count,id} tuples for every sibling.
5306 values[n++] += perf_event_count(leader);
5307 if (read_format & PERF_FORMAT_ID)
5308 values[n++] = primary_event_id(leader);
5309 if (read_format & PERF_FORMAT_LOST)
5310 values[n++] = atomic64_read(&leader->lost_samples);
5312 for_each_sibling_event(sub, leader) {
5313 values[n++] += perf_event_count(sub);
5314 if (read_format & PERF_FORMAT_ID)
5315 values[n++] = primary_event_id(sub);
5316 if (read_format & PERF_FORMAT_LOST)
5317 values[n++] = atomic64_read(&sub->lost_samples);
5320 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5324 static int perf_read_group(struct perf_event *event,
5325 u64 read_format, char __user *buf)
5327 struct perf_event *leader = event->group_leader, *child;
5328 struct perf_event_context *ctx = leader->ctx;
5332 lockdep_assert_held(&ctx->mutex);
5334 values = kzalloc(event->read_size, GFP_KERNEL);
5338 values[0] = 1 + leader->nr_siblings;
5341 * By locking the child_mutex of the leader we effectively
5342 * lock the child list of all siblings.. XXX explain how.
5344 mutex_lock(&leader->child_mutex);
5346 ret = __perf_read_group_add(leader, read_format, values);
5350 list_for_each_entry(child, &leader->child_list, child_list) {
5351 ret = __perf_read_group_add(child, read_format, values);
5356 mutex_unlock(&leader->child_mutex);
5358 ret = event->read_size;
5359 if (copy_to_user(buf, values, event->read_size))
5364 mutex_unlock(&leader->child_mutex);
5370 static int perf_read_one(struct perf_event *event,
5371 u64 read_format, char __user *buf)
5373 u64 enabled, running;
5377 values[n++] = __perf_event_read_value(event, &enabled, &running);
5378 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5379 values[n++] = enabled;
5380 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5381 values[n++] = running;
5382 if (read_format & PERF_FORMAT_ID)
5383 values[n++] = primary_event_id(event);
5384 if (read_format & PERF_FORMAT_LOST)
5385 values[n++] = atomic64_read(&event->lost_samples);
5387 if (copy_to_user(buf, values, n * sizeof(u64)))
5390 return n * sizeof(u64);
5393 static bool is_event_hup(struct perf_event *event)
5397 if (event->state > PERF_EVENT_STATE_EXIT)
5400 mutex_lock(&event->child_mutex);
5401 no_children = list_empty(&event->child_list);
5402 mutex_unlock(&event->child_mutex);
5407 * Read the performance event - simple non blocking version for now
5410 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5412 u64 read_format = event->attr.read_format;
5416 * Return end-of-file for a read on an event that is in
5417 * error state (i.e. because it was pinned but it couldn't be
5418 * scheduled on to the CPU at some point).
5420 if (event->state == PERF_EVENT_STATE_ERROR)
5423 if (count < event->read_size)
5426 WARN_ON_ONCE(event->ctx->parent_ctx);
5427 if (read_format & PERF_FORMAT_GROUP)
5428 ret = perf_read_group(event, read_format, buf);
5430 ret = perf_read_one(event, read_format, buf);
5436 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5438 struct perf_event *event = file->private_data;
5439 struct perf_event_context *ctx;
5442 ret = security_perf_event_read(event);
5446 ctx = perf_event_ctx_lock(event);
5447 ret = __perf_read(event, buf, count);
5448 perf_event_ctx_unlock(event, ctx);
5453 static __poll_t perf_poll(struct file *file, poll_table *wait)
5455 struct perf_event *event = file->private_data;
5456 struct perf_buffer *rb;
5457 __poll_t events = EPOLLHUP;
5459 poll_wait(file, &event->waitq, wait);
5461 if (is_event_hup(event))
5465 * Pin the event->rb by taking event->mmap_mutex; otherwise
5466 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5468 mutex_lock(&event->mmap_mutex);
5471 events = atomic_xchg(&rb->poll, 0);
5472 mutex_unlock(&event->mmap_mutex);
5476 static void _perf_event_reset(struct perf_event *event)
5478 (void)perf_event_read(event, false);
5479 local64_set(&event->count, 0);
5480 perf_event_update_userpage(event);
5483 /* Assume it's not an event with inherit set. */
5484 u64 perf_event_pause(struct perf_event *event, bool reset)
5486 struct perf_event_context *ctx;
5489 ctx = perf_event_ctx_lock(event);
5490 WARN_ON_ONCE(event->attr.inherit);
5491 _perf_event_disable(event);
5492 count = local64_read(&event->count);
5494 local64_set(&event->count, 0);
5495 perf_event_ctx_unlock(event, ctx);
5499 EXPORT_SYMBOL_GPL(perf_event_pause);
5502 * Holding the top-level event's child_mutex means that any
5503 * descendant process that has inherited this event will block
5504 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5505 * task existence requirements of perf_event_enable/disable.
5507 static void perf_event_for_each_child(struct perf_event *event,
5508 void (*func)(struct perf_event *))
5510 struct perf_event *child;
5512 WARN_ON_ONCE(event->ctx->parent_ctx);
5514 mutex_lock(&event->child_mutex);
5516 list_for_each_entry(child, &event->child_list, child_list)
5518 mutex_unlock(&event->child_mutex);
5521 static void perf_event_for_each(struct perf_event *event,
5522 void (*func)(struct perf_event *))
5524 struct perf_event_context *ctx = event->ctx;
5525 struct perf_event *sibling;
5527 lockdep_assert_held(&ctx->mutex);
5529 event = event->group_leader;
5531 perf_event_for_each_child(event, func);
5532 for_each_sibling_event(sibling, event)
5533 perf_event_for_each_child(sibling, func);
5536 static void __perf_event_period(struct perf_event *event,
5537 struct perf_cpu_context *cpuctx,
5538 struct perf_event_context *ctx,
5541 u64 value = *((u64 *)info);
5544 if (event->attr.freq) {
5545 event->attr.sample_freq = value;
5547 event->attr.sample_period = value;
5548 event->hw.sample_period = value;
5551 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5553 perf_pmu_disable(ctx->pmu);
5555 * We could be throttled; unthrottle now to avoid the tick
5556 * trying to unthrottle while we already re-started the event.
5558 if (event->hw.interrupts == MAX_INTERRUPTS) {
5559 event->hw.interrupts = 0;
5560 perf_log_throttle(event, 1);
5562 event->pmu->stop(event, PERF_EF_UPDATE);
5565 local64_set(&event->hw.period_left, 0);
5568 event->pmu->start(event, PERF_EF_RELOAD);
5569 perf_pmu_enable(ctx->pmu);
5573 static int perf_event_check_period(struct perf_event *event, u64 value)
5575 return event->pmu->check_period(event, value);
5578 static int _perf_event_period(struct perf_event *event, u64 value)
5580 if (!is_sampling_event(event))
5586 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5589 if (perf_event_check_period(event, value))
5592 if (!event->attr.freq && (value & (1ULL << 63)))
5595 event_function_call(event, __perf_event_period, &value);
5600 int perf_event_period(struct perf_event *event, u64 value)
5602 struct perf_event_context *ctx;
5605 ctx = perf_event_ctx_lock(event);
5606 ret = _perf_event_period(event, value);
5607 perf_event_ctx_unlock(event, ctx);
5611 EXPORT_SYMBOL_GPL(perf_event_period);
5613 static const struct file_operations perf_fops;
5615 static inline int perf_fget_light(int fd, struct fd *p)
5617 struct fd f = fdget(fd);
5621 if (f.file->f_op != &perf_fops) {
5629 static int perf_event_set_output(struct perf_event *event,
5630 struct perf_event *output_event);
5631 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5632 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5633 struct perf_event_attr *attr);
5635 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5637 void (*func)(struct perf_event *);
5641 case PERF_EVENT_IOC_ENABLE:
5642 func = _perf_event_enable;
5644 case PERF_EVENT_IOC_DISABLE:
5645 func = _perf_event_disable;
5647 case PERF_EVENT_IOC_RESET:
5648 func = _perf_event_reset;
5651 case PERF_EVENT_IOC_REFRESH:
5652 return _perf_event_refresh(event, arg);
5654 case PERF_EVENT_IOC_PERIOD:
5658 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5661 return _perf_event_period(event, value);
5663 case PERF_EVENT_IOC_ID:
5665 u64 id = primary_event_id(event);
5667 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5672 case PERF_EVENT_IOC_SET_OUTPUT:
5676 struct perf_event *output_event;
5678 ret = perf_fget_light(arg, &output);
5681 output_event = output.file->private_data;
5682 ret = perf_event_set_output(event, output_event);
5685 ret = perf_event_set_output(event, NULL);
5690 case PERF_EVENT_IOC_SET_FILTER:
5691 return perf_event_set_filter(event, (void __user *)arg);
5693 case PERF_EVENT_IOC_SET_BPF:
5695 struct bpf_prog *prog;
5698 prog = bpf_prog_get(arg);
5700 return PTR_ERR(prog);
5702 err = perf_event_set_bpf_prog(event, prog, 0);
5711 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5712 struct perf_buffer *rb;
5715 rb = rcu_dereference(event->rb);
5716 if (!rb || !rb->nr_pages) {
5720 rb_toggle_paused(rb, !!arg);
5725 case PERF_EVENT_IOC_QUERY_BPF:
5726 return perf_event_query_prog_array(event, (void __user *)arg);
5728 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5729 struct perf_event_attr new_attr;
5730 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5736 return perf_event_modify_attr(event, &new_attr);
5742 if (flags & PERF_IOC_FLAG_GROUP)
5743 perf_event_for_each(event, func);
5745 perf_event_for_each_child(event, func);
5750 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5752 struct perf_event *event = file->private_data;
5753 struct perf_event_context *ctx;
5756 /* Treat ioctl like writes as it is likely a mutating operation. */
5757 ret = security_perf_event_write(event);
5761 ctx = perf_event_ctx_lock(event);
5762 ret = _perf_ioctl(event, cmd, arg);
5763 perf_event_ctx_unlock(event, ctx);
5768 #ifdef CONFIG_COMPAT
5769 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5772 switch (_IOC_NR(cmd)) {
5773 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5774 case _IOC_NR(PERF_EVENT_IOC_ID):
5775 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5776 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5777 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5778 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5779 cmd &= ~IOCSIZE_MASK;
5780 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5784 return perf_ioctl(file, cmd, arg);
5787 # define perf_compat_ioctl NULL
5790 int perf_event_task_enable(void)
5792 struct perf_event_context *ctx;
5793 struct perf_event *event;
5795 mutex_lock(¤t->perf_event_mutex);
5796 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5797 ctx = perf_event_ctx_lock(event);
5798 perf_event_for_each_child(event, _perf_event_enable);
5799 perf_event_ctx_unlock(event, ctx);
5801 mutex_unlock(¤t->perf_event_mutex);
5806 int perf_event_task_disable(void)
5808 struct perf_event_context *ctx;
5809 struct perf_event *event;
5811 mutex_lock(¤t->perf_event_mutex);
5812 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5813 ctx = perf_event_ctx_lock(event);
5814 perf_event_for_each_child(event, _perf_event_disable);
5815 perf_event_ctx_unlock(event, ctx);
5817 mutex_unlock(¤t->perf_event_mutex);
5822 static int perf_event_index(struct perf_event *event)
5824 if (event->hw.state & PERF_HES_STOPPED)
5827 if (event->state != PERF_EVENT_STATE_ACTIVE)
5830 return event->pmu->event_idx(event);
5833 static void perf_event_init_userpage(struct perf_event *event)
5835 struct perf_event_mmap_page *userpg;
5836 struct perf_buffer *rb;
5839 rb = rcu_dereference(event->rb);
5843 userpg = rb->user_page;
5845 /* Allow new userspace to detect that bit 0 is deprecated */
5846 userpg->cap_bit0_is_deprecated = 1;
5847 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5848 userpg->data_offset = PAGE_SIZE;
5849 userpg->data_size = perf_data_size(rb);
5855 void __weak arch_perf_update_userpage(
5856 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5861 * Callers need to ensure there can be no nesting of this function, otherwise
5862 * the seqlock logic goes bad. We can not serialize this because the arch
5863 * code calls this from NMI context.
5865 void perf_event_update_userpage(struct perf_event *event)
5867 struct perf_event_mmap_page *userpg;
5868 struct perf_buffer *rb;
5869 u64 enabled, running, now;
5872 rb = rcu_dereference(event->rb);
5877 * compute total_time_enabled, total_time_running
5878 * based on snapshot values taken when the event
5879 * was last scheduled in.
5881 * we cannot simply called update_context_time()
5882 * because of locking issue as we can be called in
5885 calc_timer_values(event, &now, &enabled, &running);
5887 userpg = rb->user_page;
5889 * Disable preemption to guarantee consistent time stamps are stored to
5895 userpg->index = perf_event_index(event);
5896 userpg->offset = perf_event_count(event);
5898 userpg->offset -= local64_read(&event->hw.prev_count);
5900 userpg->time_enabled = enabled +
5901 atomic64_read(&event->child_total_time_enabled);
5903 userpg->time_running = running +
5904 atomic64_read(&event->child_total_time_running);
5906 arch_perf_update_userpage(event, userpg, now);
5914 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5916 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5918 struct perf_event *event = vmf->vma->vm_file->private_data;
5919 struct perf_buffer *rb;
5920 vm_fault_t ret = VM_FAULT_SIGBUS;
5922 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5923 if (vmf->pgoff == 0)
5929 rb = rcu_dereference(event->rb);
5933 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5936 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5940 get_page(vmf->page);
5941 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5942 vmf->page->index = vmf->pgoff;
5951 static void ring_buffer_attach(struct perf_event *event,
5952 struct perf_buffer *rb)
5954 struct perf_buffer *old_rb = NULL;
5955 unsigned long flags;
5957 WARN_ON_ONCE(event->parent);
5961 * Should be impossible, we set this when removing
5962 * event->rb_entry and wait/clear when adding event->rb_entry.
5964 WARN_ON_ONCE(event->rcu_pending);
5967 spin_lock_irqsave(&old_rb->event_lock, flags);
5968 list_del_rcu(&event->rb_entry);
5969 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5971 event->rcu_batches = get_state_synchronize_rcu();
5972 event->rcu_pending = 1;
5976 if (event->rcu_pending) {
5977 cond_synchronize_rcu(event->rcu_batches);
5978 event->rcu_pending = 0;
5981 spin_lock_irqsave(&rb->event_lock, flags);
5982 list_add_rcu(&event->rb_entry, &rb->event_list);
5983 spin_unlock_irqrestore(&rb->event_lock, flags);
5987 * Avoid racing with perf_mmap_close(AUX): stop the event
5988 * before swizzling the event::rb pointer; if it's getting
5989 * unmapped, its aux_mmap_count will be 0 and it won't
5990 * restart. See the comment in __perf_pmu_output_stop().
5992 * Data will inevitably be lost when set_output is done in
5993 * mid-air, but then again, whoever does it like this is
5994 * not in for the data anyway.
5997 perf_event_stop(event, 0);
5999 rcu_assign_pointer(event->rb, rb);
6002 ring_buffer_put(old_rb);
6004 * Since we detached before setting the new rb, so that we
6005 * could attach the new rb, we could have missed a wakeup.
6008 wake_up_all(&event->waitq);
6012 static void ring_buffer_wakeup(struct perf_event *event)
6014 struct perf_buffer *rb;
6017 event = event->parent;
6020 rb = rcu_dereference(event->rb);
6022 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6023 wake_up_all(&event->waitq);
6028 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6030 struct perf_buffer *rb;
6033 event = event->parent;
6036 rb = rcu_dereference(event->rb);
6038 if (!refcount_inc_not_zero(&rb->refcount))
6046 void ring_buffer_put(struct perf_buffer *rb)
6048 if (!refcount_dec_and_test(&rb->refcount))
6051 WARN_ON_ONCE(!list_empty(&rb->event_list));
6053 call_rcu(&rb->rcu_head, rb_free_rcu);
6056 static void perf_mmap_open(struct vm_area_struct *vma)
6058 struct perf_event *event = vma->vm_file->private_data;
6060 atomic_inc(&event->mmap_count);
6061 atomic_inc(&event->rb->mmap_count);
6064 atomic_inc(&event->rb->aux_mmap_count);
6066 if (event->pmu->event_mapped)
6067 event->pmu->event_mapped(event, vma->vm_mm);
6070 static void perf_pmu_output_stop(struct perf_event *event);
6073 * A buffer can be mmap()ed multiple times; either directly through the same
6074 * event, or through other events by use of perf_event_set_output().
6076 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6077 * the buffer here, where we still have a VM context. This means we need
6078 * to detach all events redirecting to us.
6080 static void perf_mmap_close(struct vm_area_struct *vma)
6082 struct perf_event *event = vma->vm_file->private_data;
6083 struct perf_buffer *rb = ring_buffer_get(event);
6084 struct user_struct *mmap_user = rb->mmap_user;
6085 int mmap_locked = rb->mmap_locked;
6086 unsigned long size = perf_data_size(rb);
6087 bool detach_rest = false;
6089 if (event->pmu->event_unmapped)
6090 event->pmu->event_unmapped(event, vma->vm_mm);
6093 * rb->aux_mmap_count will always drop before rb->mmap_count and
6094 * event->mmap_count, so it is ok to use event->mmap_mutex to
6095 * serialize with perf_mmap here.
6097 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6098 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6100 * Stop all AUX events that are writing to this buffer,
6101 * so that we can free its AUX pages and corresponding PMU
6102 * data. Note that after rb::aux_mmap_count dropped to zero,
6103 * they won't start any more (see perf_aux_output_begin()).
6105 perf_pmu_output_stop(event);
6107 /* now it's safe to free the pages */
6108 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6109 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6111 /* this has to be the last one */
6113 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6115 mutex_unlock(&event->mmap_mutex);
6118 if (atomic_dec_and_test(&rb->mmap_count))
6121 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6124 ring_buffer_attach(event, NULL);
6125 mutex_unlock(&event->mmap_mutex);
6127 /* If there's still other mmap()s of this buffer, we're done. */
6132 * No other mmap()s, detach from all other events that might redirect
6133 * into the now unreachable buffer. Somewhat complicated by the
6134 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6138 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6139 if (!atomic_long_inc_not_zero(&event->refcount)) {
6141 * This event is en-route to free_event() which will
6142 * detach it and remove it from the list.
6148 mutex_lock(&event->mmap_mutex);
6150 * Check we didn't race with perf_event_set_output() which can
6151 * swizzle the rb from under us while we were waiting to
6152 * acquire mmap_mutex.
6154 * If we find a different rb; ignore this event, a next
6155 * iteration will no longer find it on the list. We have to
6156 * still restart the iteration to make sure we're not now
6157 * iterating the wrong list.
6159 if (event->rb == rb)
6160 ring_buffer_attach(event, NULL);
6162 mutex_unlock(&event->mmap_mutex);
6166 * Restart the iteration; either we're on the wrong list or
6167 * destroyed its integrity by doing a deletion.
6174 * It could be there's still a few 0-ref events on the list; they'll
6175 * get cleaned up by free_event() -- they'll also still have their
6176 * ref on the rb and will free it whenever they are done with it.
6178 * Aside from that, this buffer is 'fully' detached and unmapped,
6179 * undo the VM accounting.
6182 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6183 &mmap_user->locked_vm);
6184 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6185 free_uid(mmap_user);
6188 ring_buffer_put(rb); /* could be last */
6191 static const struct vm_operations_struct perf_mmap_vmops = {
6192 .open = perf_mmap_open,
6193 .close = perf_mmap_close, /* non mergeable */
6194 .fault = perf_mmap_fault,
6195 .page_mkwrite = perf_mmap_fault,
6198 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6200 struct perf_event *event = file->private_data;
6201 unsigned long user_locked, user_lock_limit;
6202 struct user_struct *user = current_user();
6203 struct perf_buffer *rb = NULL;
6204 unsigned long locked, lock_limit;
6205 unsigned long vma_size;
6206 unsigned long nr_pages;
6207 long user_extra = 0, extra = 0;
6208 int ret = 0, flags = 0;
6211 * Don't allow mmap() of inherited per-task counters. This would
6212 * create a performance issue due to all children writing to the
6215 if (event->cpu == -1 && event->attr.inherit)
6218 if (!(vma->vm_flags & VM_SHARED))
6221 ret = security_perf_event_read(event);
6225 vma_size = vma->vm_end - vma->vm_start;
6227 if (vma->vm_pgoff == 0) {
6228 nr_pages = (vma_size / PAGE_SIZE) - 1;
6231 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6232 * mapped, all subsequent mappings should have the same size
6233 * and offset. Must be above the normal perf buffer.
6235 u64 aux_offset, aux_size;
6240 nr_pages = vma_size / PAGE_SIZE;
6242 mutex_lock(&event->mmap_mutex);
6249 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6250 aux_size = READ_ONCE(rb->user_page->aux_size);
6252 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6255 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6258 /* already mapped with a different offset */
6259 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6262 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6265 /* already mapped with a different size */
6266 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6269 if (!is_power_of_2(nr_pages))
6272 if (!atomic_inc_not_zero(&rb->mmap_count))
6275 if (rb_has_aux(rb)) {
6276 atomic_inc(&rb->aux_mmap_count);
6281 atomic_set(&rb->aux_mmap_count, 1);
6282 user_extra = nr_pages;
6288 * If we have rb pages ensure they're a power-of-two number, so we
6289 * can do bitmasks instead of modulo.
6291 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6294 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6297 WARN_ON_ONCE(event->ctx->parent_ctx);
6299 mutex_lock(&event->mmap_mutex);
6301 if (data_page_nr(event->rb) != nr_pages) {
6306 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6308 * Raced against perf_mmap_close(); remove the
6309 * event and try again.
6311 ring_buffer_attach(event, NULL);
6312 mutex_unlock(&event->mmap_mutex);
6319 user_extra = nr_pages + 1;
6322 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6325 * Increase the limit linearly with more CPUs:
6327 user_lock_limit *= num_online_cpus();
6329 user_locked = atomic_long_read(&user->locked_vm);
6332 * sysctl_perf_event_mlock may have changed, so that
6333 * user->locked_vm > user_lock_limit
6335 if (user_locked > user_lock_limit)
6336 user_locked = user_lock_limit;
6337 user_locked += user_extra;
6339 if (user_locked > user_lock_limit) {
6341 * charge locked_vm until it hits user_lock_limit;
6342 * charge the rest from pinned_vm
6344 extra = user_locked - user_lock_limit;
6345 user_extra -= extra;
6348 lock_limit = rlimit(RLIMIT_MEMLOCK);
6349 lock_limit >>= PAGE_SHIFT;
6350 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6352 if ((locked > lock_limit) && perf_is_paranoid() &&
6353 !capable(CAP_IPC_LOCK)) {
6358 WARN_ON(!rb && event->rb);
6360 if (vma->vm_flags & VM_WRITE)
6361 flags |= RING_BUFFER_WRITABLE;
6364 rb = rb_alloc(nr_pages,
6365 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6373 atomic_set(&rb->mmap_count, 1);
6374 rb->mmap_user = get_current_user();
6375 rb->mmap_locked = extra;
6377 ring_buffer_attach(event, rb);
6379 perf_event_update_time(event);
6380 perf_event_init_userpage(event);
6381 perf_event_update_userpage(event);
6383 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6384 event->attr.aux_watermark, flags);
6386 rb->aux_mmap_locked = extra;
6391 atomic_long_add(user_extra, &user->locked_vm);
6392 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6394 atomic_inc(&event->mmap_count);
6396 atomic_dec(&rb->mmap_count);
6399 mutex_unlock(&event->mmap_mutex);
6402 * Since pinned accounting is per vm we cannot allow fork() to copy our
6405 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6406 vma->vm_ops = &perf_mmap_vmops;
6408 if (event->pmu->event_mapped)
6409 event->pmu->event_mapped(event, vma->vm_mm);
6414 static int perf_fasync(int fd, struct file *filp, int on)
6416 struct inode *inode = file_inode(filp);
6417 struct perf_event *event = filp->private_data;
6421 retval = fasync_helper(fd, filp, on, &event->fasync);
6422 inode_unlock(inode);
6430 static const struct file_operations perf_fops = {
6431 .llseek = no_llseek,
6432 .release = perf_release,
6435 .unlocked_ioctl = perf_ioctl,
6436 .compat_ioctl = perf_compat_ioctl,
6438 .fasync = perf_fasync,
6444 * If there's data, ensure we set the poll() state and publish everything
6445 * to user-space before waking everybody up.
6448 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6450 /* only the parent has fasync state */
6452 event = event->parent;
6453 return &event->fasync;
6456 void perf_event_wakeup(struct perf_event *event)
6458 ring_buffer_wakeup(event);
6460 if (event->pending_kill) {
6461 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6462 event->pending_kill = 0;
6466 static void perf_sigtrap(struct perf_event *event)
6469 * We'd expect this to only occur if the irq_work is delayed and either
6470 * ctx->task or current has changed in the meantime. This can be the
6471 * case on architectures that do not implement arch_irq_work_raise().
6473 if (WARN_ON_ONCE(event->ctx->task != current))
6477 * Both perf_pending_task() and perf_pending_irq() can race with the
6480 if (current->flags & PF_EXITING)
6483 send_sig_perf((void __user *)event->pending_addr,
6484 event->attr.type, event->attr.sig_data);
6488 * Deliver the pending work in-event-context or follow the context.
6490 static void __perf_pending_irq(struct perf_event *event)
6492 int cpu = READ_ONCE(event->oncpu);
6495 * If the event isn't running; we done. event_sched_out() will have
6496 * taken care of things.
6502 * Yay, we hit home and are in the context of the event.
6504 if (cpu == smp_processor_id()) {
6505 if (event->pending_sigtrap) {
6506 event->pending_sigtrap = 0;
6507 perf_sigtrap(event);
6508 local_dec(&event->ctx->nr_pending);
6510 if (event->pending_disable) {
6511 event->pending_disable = 0;
6512 perf_event_disable_local(event);
6520 * perf_event_disable_inatomic()
6521 * @pending_disable = CPU-A;
6525 * @pending_disable = -1;
6528 * perf_event_disable_inatomic()
6529 * @pending_disable = CPU-B;
6530 * irq_work_queue(); // FAILS
6533 * perf_pending_irq()
6535 * But the event runs on CPU-B and wants disabling there.
6537 irq_work_queue_on(&event->pending_irq, cpu);
6540 static void perf_pending_irq(struct irq_work *entry)
6542 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6546 * If we 'fail' here, that's OK, it means recursion is already disabled
6547 * and we won't recurse 'further'.
6549 rctx = perf_swevent_get_recursion_context();
6552 * The wakeup isn't bound to the context of the event -- it can happen
6553 * irrespective of where the event is.
6555 if (event->pending_wakeup) {
6556 event->pending_wakeup = 0;
6557 perf_event_wakeup(event);
6560 __perf_pending_irq(event);
6563 perf_swevent_put_recursion_context(rctx);
6566 static void perf_pending_task(struct callback_head *head)
6568 struct perf_event *event = container_of(head, struct perf_event, pending_task);
6572 * If we 'fail' here, that's OK, it means recursion is already disabled
6573 * and we won't recurse 'further'.
6575 preempt_disable_notrace();
6576 rctx = perf_swevent_get_recursion_context();
6578 if (event->pending_work) {
6579 event->pending_work = 0;
6580 perf_sigtrap(event);
6581 local_dec(&event->ctx->nr_pending);
6585 perf_swevent_put_recursion_context(rctx);
6586 preempt_enable_notrace();
6591 #ifdef CONFIG_GUEST_PERF_EVENTS
6592 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6594 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
6595 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
6596 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
6598 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6600 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6603 rcu_assign_pointer(perf_guest_cbs, cbs);
6604 static_call_update(__perf_guest_state, cbs->state);
6605 static_call_update(__perf_guest_get_ip, cbs->get_ip);
6607 /* Implementing ->handle_intel_pt_intr is optional. */
6608 if (cbs->handle_intel_pt_intr)
6609 static_call_update(__perf_guest_handle_intel_pt_intr,
6610 cbs->handle_intel_pt_intr);
6612 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6614 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6616 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6619 rcu_assign_pointer(perf_guest_cbs, NULL);
6620 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
6621 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
6622 static_call_update(__perf_guest_handle_intel_pt_intr,
6623 (void *)&__static_call_return0);
6626 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6630 perf_output_sample_regs(struct perf_output_handle *handle,
6631 struct pt_regs *regs, u64 mask)
6634 DECLARE_BITMAP(_mask, 64);
6636 bitmap_from_u64(_mask, mask);
6637 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6640 val = perf_reg_value(regs, bit);
6641 perf_output_put(handle, val);
6645 static void perf_sample_regs_user(struct perf_regs *regs_user,
6646 struct pt_regs *regs)
6648 if (user_mode(regs)) {
6649 regs_user->abi = perf_reg_abi(current);
6650 regs_user->regs = regs;
6651 } else if (!(current->flags & PF_KTHREAD)) {
6652 perf_get_regs_user(regs_user, regs);
6654 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6655 regs_user->regs = NULL;
6659 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6660 struct pt_regs *regs)
6662 regs_intr->regs = regs;
6663 regs_intr->abi = perf_reg_abi(current);
6668 * Get remaining task size from user stack pointer.
6670 * It'd be better to take stack vma map and limit this more
6671 * precisely, but there's no way to get it safely under interrupt,
6672 * so using TASK_SIZE as limit.
6674 static u64 perf_ustack_task_size(struct pt_regs *regs)
6676 unsigned long addr = perf_user_stack_pointer(regs);
6678 if (!addr || addr >= TASK_SIZE)
6681 return TASK_SIZE - addr;
6685 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6686 struct pt_regs *regs)
6690 /* No regs, no stack pointer, no dump. */
6695 * Check if we fit in with the requested stack size into the:
6697 * If we don't, we limit the size to the TASK_SIZE.
6699 * - remaining sample size
6700 * If we don't, we customize the stack size to
6701 * fit in to the remaining sample size.
6704 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6705 stack_size = min(stack_size, (u16) task_size);
6707 /* Current header size plus static size and dynamic size. */
6708 header_size += 2 * sizeof(u64);
6710 /* Do we fit in with the current stack dump size? */
6711 if ((u16) (header_size + stack_size) < header_size) {
6713 * If we overflow the maximum size for the sample,
6714 * we customize the stack dump size to fit in.
6716 stack_size = USHRT_MAX - header_size - sizeof(u64);
6717 stack_size = round_up(stack_size, sizeof(u64));
6724 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6725 struct pt_regs *regs)
6727 /* Case of a kernel thread, nothing to dump */
6730 perf_output_put(handle, size);
6739 * - the size requested by user or the best one we can fit
6740 * in to the sample max size
6742 * - user stack dump data
6744 * - the actual dumped size
6748 perf_output_put(handle, dump_size);
6751 sp = perf_user_stack_pointer(regs);
6752 rem = __output_copy_user(handle, (void *) sp, dump_size);
6753 dyn_size = dump_size - rem;
6755 perf_output_skip(handle, rem);
6758 perf_output_put(handle, dyn_size);
6762 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6763 struct perf_sample_data *data,
6766 struct perf_event *sampler = event->aux_event;
6767 struct perf_buffer *rb;
6774 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6777 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6780 rb = ring_buffer_get(sampler);
6785 * If this is an NMI hit inside sampling code, don't take
6786 * the sample. See also perf_aux_sample_output().
6788 if (READ_ONCE(rb->aux_in_sampling)) {
6791 size = min_t(size_t, size, perf_aux_size(rb));
6792 data->aux_size = ALIGN(size, sizeof(u64));
6794 ring_buffer_put(rb);
6797 return data->aux_size;
6800 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6801 struct perf_event *event,
6802 struct perf_output_handle *handle,
6805 unsigned long flags;
6809 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6810 * paths. If we start calling them in NMI context, they may race with
6811 * the IRQ ones, that is, for example, re-starting an event that's just
6812 * been stopped, which is why we're using a separate callback that
6813 * doesn't change the event state.
6815 * IRQs need to be disabled to prevent IPIs from racing with us.
6817 local_irq_save(flags);
6819 * Guard against NMI hits inside the critical section;
6820 * see also perf_prepare_sample_aux().
6822 WRITE_ONCE(rb->aux_in_sampling, 1);
6825 ret = event->pmu->snapshot_aux(event, handle, size);
6828 WRITE_ONCE(rb->aux_in_sampling, 0);
6829 local_irq_restore(flags);
6834 static void perf_aux_sample_output(struct perf_event *event,
6835 struct perf_output_handle *handle,
6836 struct perf_sample_data *data)
6838 struct perf_event *sampler = event->aux_event;
6839 struct perf_buffer *rb;
6843 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6846 rb = ring_buffer_get(sampler);
6850 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6853 * An error here means that perf_output_copy() failed (returned a
6854 * non-zero surplus that it didn't copy), which in its current
6855 * enlightened implementation is not possible. If that changes, we'd
6858 if (WARN_ON_ONCE(size < 0))
6862 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6863 * perf_prepare_sample_aux(), so should not be more than that.
6865 pad = data->aux_size - size;
6866 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6871 perf_output_copy(handle, &zero, pad);
6875 ring_buffer_put(rb);
6878 static void __perf_event_header__init_id(struct perf_event_header *header,
6879 struct perf_sample_data *data,
6880 struct perf_event *event,
6883 data->type = event->attr.sample_type;
6884 header->size += event->id_header_size;
6886 if (sample_type & PERF_SAMPLE_TID) {
6887 /* namespace issues */
6888 data->tid_entry.pid = perf_event_pid(event, current);
6889 data->tid_entry.tid = perf_event_tid(event, current);
6892 if (sample_type & PERF_SAMPLE_TIME)
6893 data->time = perf_event_clock(event);
6895 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6896 data->id = primary_event_id(event);
6898 if (sample_type & PERF_SAMPLE_STREAM_ID)
6899 data->stream_id = event->id;
6901 if (sample_type & PERF_SAMPLE_CPU) {
6902 data->cpu_entry.cpu = raw_smp_processor_id();
6903 data->cpu_entry.reserved = 0;
6907 void perf_event_header__init_id(struct perf_event_header *header,
6908 struct perf_sample_data *data,
6909 struct perf_event *event)
6911 if (event->attr.sample_id_all)
6912 __perf_event_header__init_id(header, data, event, event->attr.sample_type);
6915 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6916 struct perf_sample_data *data)
6918 u64 sample_type = data->type;
6920 if (sample_type & PERF_SAMPLE_TID)
6921 perf_output_put(handle, data->tid_entry);
6923 if (sample_type & PERF_SAMPLE_TIME)
6924 perf_output_put(handle, data->time);
6926 if (sample_type & PERF_SAMPLE_ID)
6927 perf_output_put(handle, data->id);
6929 if (sample_type & PERF_SAMPLE_STREAM_ID)
6930 perf_output_put(handle, data->stream_id);
6932 if (sample_type & PERF_SAMPLE_CPU)
6933 perf_output_put(handle, data->cpu_entry);
6935 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6936 perf_output_put(handle, data->id);
6939 void perf_event__output_id_sample(struct perf_event *event,
6940 struct perf_output_handle *handle,
6941 struct perf_sample_data *sample)
6943 if (event->attr.sample_id_all)
6944 __perf_event__output_id_sample(handle, sample);
6947 static void perf_output_read_one(struct perf_output_handle *handle,
6948 struct perf_event *event,
6949 u64 enabled, u64 running)
6951 u64 read_format = event->attr.read_format;
6955 values[n++] = perf_event_count(event);
6956 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6957 values[n++] = enabled +
6958 atomic64_read(&event->child_total_time_enabled);
6960 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6961 values[n++] = running +
6962 atomic64_read(&event->child_total_time_running);
6964 if (read_format & PERF_FORMAT_ID)
6965 values[n++] = primary_event_id(event);
6966 if (read_format & PERF_FORMAT_LOST)
6967 values[n++] = atomic64_read(&event->lost_samples);
6969 __output_copy(handle, values, n * sizeof(u64));
6972 static void perf_output_read_group(struct perf_output_handle *handle,
6973 struct perf_event *event,
6974 u64 enabled, u64 running)
6976 struct perf_event *leader = event->group_leader, *sub;
6977 u64 read_format = event->attr.read_format;
6978 unsigned long flags;
6983 * Disabling interrupts avoids all counter scheduling
6984 * (context switches, timer based rotation and IPIs).
6986 local_irq_save(flags);
6988 values[n++] = 1 + leader->nr_siblings;
6990 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6991 values[n++] = enabled;
6993 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6994 values[n++] = running;
6996 if ((leader != event) &&
6997 (leader->state == PERF_EVENT_STATE_ACTIVE))
6998 leader->pmu->read(leader);
7000 values[n++] = perf_event_count(leader);
7001 if (read_format & PERF_FORMAT_ID)
7002 values[n++] = primary_event_id(leader);
7003 if (read_format & PERF_FORMAT_LOST)
7004 values[n++] = atomic64_read(&leader->lost_samples);
7006 __output_copy(handle, values, n * sizeof(u64));
7008 for_each_sibling_event(sub, leader) {
7011 if ((sub != event) &&
7012 (sub->state == PERF_EVENT_STATE_ACTIVE))
7013 sub->pmu->read(sub);
7015 values[n++] = perf_event_count(sub);
7016 if (read_format & PERF_FORMAT_ID)
7017 values[n++] = primary_event_id(sub);
7018 if (read_format & PERF_FORMAT_LOST)
7019 values[n++] = atomic64_read(&sub->lost_samples);
7021 __output_copy(handle, values, n * sizeof(u64));
7024 local_irq_restore(flags);
7027 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7028 PERF_FORMAT_TOTAL_TIME_RUNNING)
7031 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7033 * The problem is that its both hard and excessively expensive to iterate the
7034 * child list, not to mention that its impossible to IPI the children running
7035 * on another CPU, from interrupt/NMI context.
7037 static void perf_output_read(struct perf_output_handle *handle,
7038 struct perf_event *event)
7040 u64 enabled = 0, running = 0, now;
7041 u64 read_format = event->attr.read_format;
7044 * compute total_time_enabled, total_time_running
7045 * based on snapshot values taken when the event
7046 * was last scheduled in.
7048 * we cannot simply called update_context_time()
7049 * because of locking issue as we are called in
7052 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7053 calc_timer_values(event, &now, &enabled, &running);
7055 if (event->attr.read_format & PERF_FORMAT_GROUP)
7056 perf_output_read_group(handle, event, enabled, running);
7058 perf_output_read_one(handle, event, enabled, running);
7061 void perf_output_sample(struct perf_output_handle *handle,
7062 struct perf_event_header *header,
7063 struct perf_sample_data *data,
7064 struct perf_event *event)
7066 u64 sample_type = data->type;
7068 perf_output_put(handle, *header);
7070 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7071 perf_output_put(handle, data->id);
7073 if (sample_type & PERF_SAMPLE_IP)
7074 perf_output_put(handle, data->ip);
7076 if (sample_type & PERF_SAMPLE_TID)
7077 perf_output_put(handle, data->tid_entry);
7079 if (sample_type & PERF_SAMPLE_TIME)
7080 perf_output_put(handle, data->time);
7082 if (sample_type & PERF_SAMPLE_ADDR)
7083 perf_output_put(handle, data->addr);
7085 if (sample_type & PERF_SAMPLE_ID)
7086 perf_output_put(handle, data->id);
7088 if (sample_type & PERF_SAMPLE_STREAM_ID)
7089 perf_output_put(handle, data->stream_id);
7091 if (sample_type & PERF_SAMPLE_CPU)
7092 perf_output_put(handle, data->cpu_entry);
7094 if (sample_type & PERF_SAMPLE_PERIOD)
7095 perf_output_put(handle, data->period);
7097 if (sample_type & PERF_SAMPLE_READ)
7098 perf_output_read(handle, event);
7100 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7103 size += data->callchain->nr;
7104 size *= sizeof(u64);
7105 __output_copy(handle, data->callchain, size);
7108 if (sample_type & PERF_SAMPLE_RAW) {
7109 struct perf_raw_record *raw = data->raw;
7112 struct perf_raw_frag *frag = &raw->frag;
7114 perf_output_put(handle, raw->size);
7117 __output_custom(handle, frag->copy,
7118 frag->data, frag->size);
7120 __output_copy(handle, frag->data,
7123 if (perf_raw_frag_last(frag))
7128 __output_skip(handle, NULL, frag->pad);
7134 .size = sizeof(u32),
7137 perf_output_put(handle, raw);
7141 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7142 if (data->sample_flags & PERF_SAMPLE_BRANCH_STACK) {
7145 size = data->br_stack->nr
7146 * sizeof(struct perf_branch_entry);
7148 perf_output_put(handle, data->br_stack->nr);
7149 if (branch_sample_hw_index(event))
7150 perf_output_put(handle, data->br_stack->hw_idx);
7151 perf_output_copy(handle, data->br_stack->entries, size);
7154 * we always store at least the value of nr
7157 perf_output_put(handle, nr);
7161 if (sample_type & PERF_SAMPLE_REGS_USER) {
7162 u64 abi = data->regs_user.abi;
7165 * If there are no regs to dump, notice it through
7166 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7168 perf_output_put(handle, abi);
7171 u64 mask = event->attr.sample_regs_user;
7172 perf_output_sample_regs(handle,
7173 data->regs_user.regs,
7178 if (sample_type & PERF_SAMPLE_STACK_USER) {
7179 perf_output_sample_ustack(handle,
7180 data->stack_user_size,
7181 data->regs_user.regs);
7184 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7185 perf_output_put(handle, data->weight.full);
7187 if (sample_type & PERF_SAMPLE_DATA_SRC)
7188 perf_output_put(handle, data->data_src.val);
7190 if (sample_type & PERF_SAMPLE_TRANSACTION)
7191 perf_output_put(handle, data->txn);
7193 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7194 u64 abi = data->regs_intr.abi;
7196 * If there are no regs to dump, notice it through
7197 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7199 perf_output_put(handle, abi);
7202 u64 mask = event->attr.sample_regs_intr;
7204 perf_output_sample_regs(handle,
7205 data->regs_intr.regs,
7210 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7211 perf_output_put(handle, data->phys_addr);
7213 if (sample_type & PERF_SAMPLE_CGROUP)
7214 perf_output_put(handle, data->cgroup);
7216 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7217 perf_output_put(handle, data->data_page_size);
7219 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7220 perf_output_put(handle, data->code_page_size);
7222 if (sample_type & PERF_SAMPLE_AUX) {
7223 perf_output_put(handle, data->aux_size);
7226 perf_aux_sample_output(event, handle, data);
7229 if (!event->attr.watermark) {
7230 int wakeup_events = event->attr.wakeup_events;
7232 if (wakeup_events) {
7233 struct perf_buffer *rb = handle->rb;
7234 int events = local_inc_return(&rb->events);
7236 if (events >= wakeup_events) {
7237 local_sub(wakeup_events, &rb->events);
7238 local_inc(&rb->wakeup);
7244 static u64 perf_virt_to_phys(u64 virt)
7251 if (virt >= TASK_SIZE) {
7252 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7253 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7254 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7255 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7258 * Walking the pages tables for user address.
7259 * Interrupts are disabled, so it prevents any tear down
7260 * of the page tables.
7261 * Try IRQ-safe get_user_page_fast_only first.
7262 * If failed, leave phys_addr as 0.
7264 if (current->mm != NULL) {
7267 pagefault_disable();
7268 if (get_user_page_fast_only(virt, 0, &p)) {
7269 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7280 * Return the pagetable size of a given virtual address.
7282 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7286 #ifdef CONFIG_HAVE_FAST_GUP
7293 pgdp = pgd_offset(mm, addr);
7294 pgd = READ_ONCE(*pgdp);
7299 return pgd_leaf_size(pgd);
7301 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7302 p4d = READ_ONCE(*p4dp);
7303 if (!p4d_present(p4d))
7307 return p4d_leaf_size(p4d);
7309 pudp = pud_offset_lockless(p4dp, p4d, addr);
7310 pud = READ_ONCE(*pudp);
7311 if (!pud_present(pud))
7315 return pud_leaf_size(pud);
7317 pmdp = pmd_offset_lockless(pudp, pud, addr);
7318 pmd = READ_ONCE(*pmdp);
7319 if (!pmd_present(pmd))
7323 return pmd_leaf_size(pmd);
7325 ptep = pte_offset_map(&pmd, addr);
7326 pte = ptep_get_lockless(ptep);
7327 if (pte_present(pte))
7328 size = pte_leaf_size(pte);
7330 #endif /* CONFIG_HAVE_FAST_GUP */
7335 static u64 perf_get_page_size(unsigned long addr)
7337 struct mm_struct *mm;
7338 unsigned long flags;
7345 * Software page-table walkers must disable IRQs,
7346 * which prevents any tear down of the page tables.
7348 local_irq_save(flags);
7353 * For kernel threads and the like, use init_mm so that
7354 * we can find kernel memory.
7359 size = perf_get_pgtable_size(mm, addr);
7361 local_irq_restore(flags);
7366 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7368 struct perf_callchain_entry *
7369 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7371 bool kernel = !event->attr.exclude_callchain_kernel;
7372 bool user = !event->attr.exclude_callchain_user;
7373 /* Disallow cross-task user callchains. */
7374 bool crosstask = event->ctx->task && event->ctx->task != current;
7375 const u32 max_stack = event->attr.sample_max_stack;
7376 struct perf_callchain_entry *callchain;
7378 if (!kernel && !user)
7379 return &__empty_callchain;
7381 callchain = get_perf_callchain(regs, 0, kernel, user,
7382 max_stack, crosstask, true);
7383 return callchain ?: &__empty_callchain;
7386 void perf_prepare_sample(struct perf_event_header *header,
7387 struct perf_sample_data *data,
7388 struct perf_event *event,
7389 struct pt_regs *regs)
7391 u64 sample_type = event->attr.sample_type;
7392 u64 filtered_sample_type;
7394 header->type = PERF_RECORD_SAMPLE;
7395 header->size = sizeof(*header) + event->header_size;
7398 header->misc |= perf_misc_flags(regs);
7401 * Clear the sample flags that have already been done by the
7404 filtered_sample_type = sample_type & ~data->sample_flags;
7405 __perf_event_header__init_id(header, data, event, filtered_sample_type);
7407 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7408 data->ip = perf_instruction_pointer(regs);
7410 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7413 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7414 data->callchain = perf_callchain(event, regs);
7416 size += data->callchain->nr;
7418 header->size += size * sizeof(u64);
7421 if (sample_type & PERF_SAMPLE_RAW) {
7422 struct perf_raw_record *raw = data->raw;
7425 if (raw && (data->sample_flags & PERF_SAMPLE_RAW)) {
7426 struct perf_raw_frag *frag = &raw->frag;
7431 if (perf_raw_frag_last(frag))
7436 size = round_up(sum + sizeof(u32), sizeof(u64));
7437 raw->size = size - sizeof(u32);
7438 frag->pad = raw->size - sum;
7444 header->size += size;
7447 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7448 int size = sizeof(u64); /* nr */
7449 if (data->sample_flags & PERF_SAMPLE_BRANCH_STACK) {
7450 if (branch_sample_hw_index(event))
7451 size += sizeof(u64);
7453 size += data->br_stack->nr
7454 * sizeof(struct perf_branch_entry);
7456 header->size += size;
7459 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7460 perf_sample_regs_user(&data->regs_user, regs);
7462 if (sample_type & PERF_SAMPLE_REGS_USER) {
7463 /* regs dump ABI info */
7464 int size = sizeof(u64);
7466 if (data->regs_user.regs) {
7467 u64 mask = event->attr.sample_regs_user;
7468 size += hweight64(mask) * sizeof(u64);
7471 header->size += size;
7474 if (sample_type & PERF_SAMPLE_STACK_USER) {
7476 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7477 * processed as the last one or have additional check added
7478 * in case new sample type is added, because we could eat
7479 * up the rest of the sample size.
7481 u16 stack_size = event->attr.sample_stack_user;
7482 u16 size = sizeof(u64);
7484 stack_size = perf_sample_ustack_size(stack_size, header->size,
7485 data->regs_user.regs);
7488 * If there is something to dump, add space for the dump
7489 * itself and for the field that tells the dynamic size,
7490 * which is how many have been actually dumped.
7493 size += sizeof(u64) + stack_size;
7495 data->stack_user_size = stack_size;
7496 header->size += size;
7499 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7500 data->weight.full = 0;
7502 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC)
7503 data->data_src.val = PERF_MEM_NA;
7505 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION)
7508 if (sample_type & (PERF_SAMPLE_ADDR | PERF_SAMPLE_PHYS_ADDR | PERF_SAMPLE_DATA_PAGE_SIZE)) {
7509 if (filtered_sample_type & PERF_SAMPLE_ADDR)
7513 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7514 /* regs dump ABI info */
7515 int size = sizeof(u64);
7517 perf_sample_regs_intr(&data->regs_intr, regs);
7519 if (data->regs_intr.regs) {
7520 u64 mask = event->attr.sample_regs_intr;
7522 size += hweight64(mask) * sizeof(u64);
7525 header->size += size;
7528 if (sample_type & PERF_SAMPLE_PHYS_ADDR &&
7529 filtered_sample_type & PERF_SAMPLE_PHYS_ADDR)
7530 data->phys_addr = perf_virt_to_phys(data->addr);
7532 #ifdef CONFIG_CGROUP_PERF
7533 if (sample_type & PERF_SAMPLE_CGROUP) {
7534 struct cgroup *cgrp;
7536 /* protected by RCU */
7537 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7538 data->cgroup = cgroup_id(cgrp);
7543 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7544 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7545 * but the value will not dump to the userspace.
7547 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7548 data->data_page_size = perf_get_page_size(data->addr);
7550 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7551 data->code_page_size = perf_get_page_size(data->ip);
7553 if (sample_type & PERF_SAMPLE_AUX) {
7556 header->size += sizeof(u64); /* size */
7559 * Given the 16bit nature of header::size, an AUX sample can
7560 * easily overflow it, what with all the preceding sample bits.
7561 * Make sure this doesn't happen by using up to U16_MAX bytes
7562 * per sample in total (rounded down to 8 byte boundary).
7564 size = min_t(size_t, U16_MAX - header->size,
7565 event->attr.aux_sample_size);
7566 size = rounddown(size, 8);
7567 size = perf_prepare_sample_aux(event, data, size);
7569 WARN_ON_ONCE(size + header->size > U16_MAX);
7570 header->size += size;
7573 * If you're adding more sample types here, you likely need to do
7574 * something about the overflowing header::size, like repurpose the
7575 * lowest 3 bits of size, which should be always zero at the moment.
7576 * This raises a more important question, do we really need 512k sized
7577 * samples and why, so good argumentation is in order for whatever you
7580 WARN_ON_ONCE(header->size & 7);
7583 static __always_inline int
7584 __perf_event_output(struct perf_event *event,
7585 struct perf_sample_data *data,
7586 struct pt_regs *regs,
7587 int (*output_begin)(struct perf_output_handle *,
7588 struct perf_sample_data *,
7589 struct perf_event *,
7592 struct perf_output_handle handle;
7593 struct perf_event_header header;
7596 /* protect the callchain buffers */
7599 perf_prepare_sample(&header, data, event, regs);
7601 err = output_begin(&handle, data, event, header.size);
7605 perf_output_sample(&handle, &header, data, event);
7607 perf_output_end(&handle);
7615 perf_event_output_forward(struct perf_event *event,
7616 struct perf_sample_data *data,
7617 struct pt_regs *regs)
7619 __perf_event_output(event, data, regs, perf_output_begin_forward);
7623 perf_event_output_backward(struct perf_event *event,
7624 struct perf_sample_data *data,
7625 struct pt_regs *regs)
7627 __perf_event_output(event, data, regs, perf_output_begin_backward);
7631 perf_event_output(struct perf_event *event,
7632 struct perf_sample_data *data,
7633 struct pt_regs *regs)
7635 return __perf_event_output(event, data, regs, perf_output_begin);
7642 struct perf_read_event {
7643 struct perf_event_header header;
7650 perf_event_read_event(struct perf_event *event,
7651 struct task_struct *task)
7653 struct perf_output_handle handle;
7654 struct perf_sample_data sample;
7655 struct perf_read_event read_event = {
7657 .type = PERF_RECORD_READ,
7659 .size = sizeof(read_event) + event->read_size,
7661 .pid = perf_event_pid(event, task),
7662 .tid = perf_event_tid(event, task),
7666 perf_event_header__init_id(&read_event.header, &sample, event);
7667 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7671 perf_output_put(&handle, read_event);
7672 perf_output_read(&handle, event);
7673 perf_event__output_id_sample(event, &handle, &sample);
7675 perf_output_end(&handle);
7678 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7681 perf_iterate_ctx(struct perf_event_context *ctx,
7682 perf_iterate_f output,
7683 void *data, bool all)
7685 struct perf_event *event;
7687 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7689 if (event->state < PERF_EVENT_STATE_INACTIVE)
7691 if (!event_filter_match(event))
7695 output(event, data);
7699 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7701 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7702 struct perf_event *event;
7704 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7706 * Skip events that are not fully formed yet; ensure that
7707 * if we observe event->ctx, both event and ctx will be
7708 * complete enough. See perf_install_in_context().
7710 if (!smp_load_acquire(&event->ctx))
7713 if (event->state < PERF_EVENT_STATE_INACTIVE)
7715 if (!event_filter_match(event))
7717 output(event, data);
7722 * Iterate all events that need to receive side-band events.
7724 * For new callers; ensure that account_pmu_sb_event() includes
7725 * your event, otherwise it might not get delivered.
7728 perf_iterate_sb(perf_iterate_f output, void *data,
7729 struct perf_event_context *task_ctx)
7731 struct perf_event_context *ctx;
7738 * If we have task_ctx != NULL we only notify the task context itself.
7739 * The task_ctx is set only for EXIT events before releasing task
7743 perf_iterate_ctx(task_ctx, output, data, false);
7747 perf_iterate_sb_cpu(output, data);
7749 for_each_task_context_nr(ctxn) {
7750 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7752 perf_iterate_ctx(ctx, output, data, false);
7760 * Clear all file-based filters at exec, they'll have to be
7761 * re-instated when/if these objects are mmapped again.
7763 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7765 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7766 struct perf_addr_filter *filter;
7767 unsigned int restart = 0, count = 0;
7768 unsigned long flags;
7770 if (!has_addr_filter(event))
7773 raw_spin_lock_irqsave(&ifh->lock, flags);
7774 list_for_each_entry(filter, &ifh->list, entry) {
7775 if (filter->path.dentry) {
7776 event->addr_filter_ranges[count].start = 0;
7777 event->addr_filter_ranges[count].size = 0;
7785 event->addr_filters_gen++;
7786 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7789 perf_event_stop(event, 1);
7792 void perf_event_exec(void)
7794 struct perf_event_context *ctx;
7797 for_each_task_context_nr(ctxn) {
7798 perf_event_enable_on_exec(ctxn);
7799 perf_event_remove_on_exec(ctxn);
7802 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7804 perf_iterate_ctx(ctx, perf_event_addr_filters_exec,
7811 struct remote_output {
7812 struct perf_buffer *rb;
7816 static void __perf_event_output_stop(struct perf_event *event, void *data)
7818 struct perf_event *parent = event->parent;
7819 struct remote_output *ro = data;
7820 struct perf_buffer *rb = ro->rb;
7821 struct stop_event_data sd = {
7825 if (!has_aux(event))
7832 * In case of inheritance, it will be the parent that links to the
7833 * ring-buffer, but it will be the child that's actually using it.
7835 * We are using event::rb to determine if the event should be stopped,
7836 * however this may race with ring_buffer_attach() (through set_output),
7837 * which will make us skip the event that actually needs to be stopped.
7838 * So ring_buffer_attach() has to stop an aux event before re-assigning
7841 if (rcu_dereference(parent->rb) == rb)
7842 ro->err = __perf_event_stop(&sd);
7845 static int __perf_pmu_output_stop(void *info)
7847 struct perf_event *event = info;
7848 struct pmu *pmu = event->ctx->pmu;
7849 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7850 struct remote_output ro = {
7855 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7856 if (cpuctx->task_ctx)
7857 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7864 static void perf_pmu_output_stop(struct perf_event *event)
7866 struct perf_event *iter;
7871 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7873 * For per-CPU events, we need to make sure that neither they
7874 * nor their children are running; for cpu==-1 events it's
7875 * sufficient to stop the event itself if it's active, since
7876 * it can't have children.
7880 cpu = READ_ONCE(iter->oncpu);
7885 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7886 if (err == -EAGAIN) {
7895 * task tracking -- fork/exit
7897 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7900 struct perf_task_event {
7901 struct task_struct *task;
7902 struct perf_event_context *task_ctx;
7905 struct perf_event_header header;
7915 static int perf_event_task_match(struct perf_event *event)
7917 return event->attr.comm || event->attr.mmap ||
7918 event->attr.mmap2 || event->attr.mmap_data ||
7922 static void perf_event_task_output(struct perf_event *event,
7925 struct perf_task_event *task_event = data;
7926 struct perf_output_handle handle;
7927 struct perf_sample_data sample;
7928 struct task_struct *task = task_event->task;
7929 int ret, size = task_event->event_id.header.size;
7931 if (!perf_event_task_match(event))
7934 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7936 ret = perf_output_begin(&handle, &sample, event,
7937 task_event->event_id.header.size);
7941 task_event->event_id.pid = perf_event_pid(event, task);
7942 task_event->event_id.tid = perf_event_tid(event, task);
7944 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7945 task_event->event_id.ppid = perf_event_pid(event,
7947 task_event->event_id.ptid = perf_event_pid(event,
7949 } else { /* PERF_RECORD_FORK */
7950 task_event->event_id.ppid = perf_event_pid(event, current);
7951 task_event->event_id.ptid = perf_event_tid(event, current);
7954 task_event->event_id.time = perf_event_clock(event);
7956 perf_output_put(&handle, task_event->event_id);
7958 perf_event__output_id_sample(event, &handle, &sample);
7960 perf_output_end(&handle);
7962 task_event->event_id.header.size = size;
7965 static void perf_event_task(struct task_struct *task,
7966 struct perf_event_context *task_ctx,
7969 struct perf_task_event task_event;
7971 if (!atomic_read(&nr_comm_events) &&
7972 !atomic_read(&nr_mmap_events) &&
7973 !atomic_read(&nr_task_events))
7976 task_event = (struct perf_task_event){
7978 .task_ctx = task_ctx,
7981 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7983 .size = sizeof(task_event.event_id),
7993 perf_iterate_sb(perf_event_task_output,
7998 void perf_event_fork(struct task_struct *task)
8000 perf_event_task(task, NULL, 1);
8001 perf_event_namespaces(task);
8008 struct perf_comm_event {
8009 struct task_struct *task;
8014 struct perf_event_header header;
8021 static int perf_event_comm_match(struct perf_event *event)
8023 return event->attr.comm;
8026 static void perf_event_comm_output(struct perf_event *event,
8029 struct perf_comm_event *comm_event = data;
8030 struct perf_output_handle handle;
8031 struct perf_sample_data sample;
8032 int size = comm_event->event_id.header.size;
8035 if (!perf_event_comm_match(event))
8038 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8039 ret = perf_output_begin(&handle, &sample, event,
8040 comm_event->event_id.header.size);
8045 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8046 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8048 perf_output_put(&handle, comm_event->event_id);
8049 __output_copy(&handle, comm_event->comm,
8050 comm_event->comm_size);
8052 perf_event__output_id_sample(event, &handle, &sample);
8054 perf_output_end(&handle);
8056 comm_event->event_id.header.size = size;
8059 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8061 char comm[TASK_COMM_LEN];
8064 memset(comm, 0, sizeof(comm));
8065 strlcpy(comm, comm_event->task->comm, sizeof(comm));
8066 size = ALIGN(strlen(comm)+1, sizeof(u64));
8068 comm_event->comm = comm;
8069 comm_event->comm_size = size;
8071 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8073 perf_iterate_sb(perf_event_comm_output,
8078 void perf_event_comm(struct task_struct *task, bool exec)
8080 struct perf_comm_event comm_event;
8082 if (!atomic_read(&nr_comm_events))
8085 comm_event = (struct perf_comm_event){
8091 .type = PERF_RECORD_COMM,
8092 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8100 perf_event_comm_event(&comm_event);
8104 * namespaces tracking
8107 struct perf_namespaces_event {
8108 struct task_struct *task;
8111 struct perf_event_header header;
8116 struct perf_ns_link_info link_info[NR_NAMESPACES];
8120 static int perf_event_namespaces_match(struct perf_event *event)
8122 return event->attr.namespaces;
8125 static void perf_event_namespaces_output(struct perf_event *event,
8128 struct perf_namespaces_event *namespaces_event = data;
8129 struct perf_output_handle handle;
8130 struct perf_sample_data sample;
8131 u16 header_size = namespaces_event->event_id.header.size;
8134 if (!perf_event_namespaces_match(event))
8137 perf_event_header__init_id(&namespaces_event->event_id.header,
8139 ret = perf_output_begin(&handle, &sample, event,
8140 namespaces_event->event_id.header.size);
8144 namespaces_event->event_id.pid = perf_event_pid(event,
8145 namespaces_event->task);
8146 namespaces_event->event_id.tid = perf_event_tid(event,
8147 namespaces_event->task);
8149 perf_output_put(&handle, namespaces_event->event_id);
8151 perf_event__output_id_sample(event, &handle, &sample);
8153 perf_output_end(&handle);
8155 namespaces_event->event_id.header.size = header_size;
8158 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8159 struct task_struct *task,
8160 const struct proc_ns_operations *ns_ops)
8162 struct path ns_path;
8163 struct inode *ns_inode;
8166 error = ns_get_path(&ns_path, task, ns_ops);
8168 ns_inode = ns_path.dentry->d_inode;
8169 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8170 ns_link_info->ino = ns_inode->i_ino;
8175 void perf_event_namespaces(struct task_struct *task)
8177 struct perf_namespaces_event namespaces_event;
8178 struct perf_ns_link_info *ns_link_info;
8180 if (!atomic_read(&nr_namespaces_events))
8183 namespaces_event = (struct perf_namespaces_event){
8187 .type = PERF_RECORD_NAMESPACES,
8189 .size = sizeof(namespaces_event.event_id),
8193 .nr_namespaces = NR_NAMESPACES,
8194 /* .link_info[NR_NAMESPACES] */
8198 ns_link_info = namespaces_event.event_id.link_info;
8200 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8201 task, &mntns_operations);
8203 #ifdef CONFIG_USER_NS
8204 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8205 task, &userns_operations);
8207 #ifdef CONFIG_NET_NS
8208 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8209 task, &netns_operations);
8211 #ifdef CONFIG_UTS_NS
8212 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8213 task, &utsns_operations);
8215 #ifdef CONFIG_IPC_NS
8216 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8217 task, &ipcns_operations);
8219 #ifdef CONFIG_PID_NS
8220 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8221 task, &pidns_operations);
8223 #ifdef CONFIG_CGROUPS
8224 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8225 task, &cgroupns_operations);
8228 perf_iterate_sb(perf_event_namespaces_output,
8236 #ifdef CONFIG_CGROUP_PERF
8238 struct perf_cgroup_event {
8242 struct perf_event_header header;
8248 static int perf_event_cgroup_match(struct perf_event *event)
8250 return event->attr.cgroup;
8253 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8255 struct perf_cgroup_event *cgroup_event = data;
8256 struct perf_output_handle handle;
8257 struct perf_sample_data sample;
8258 u16 header_size = cgroup_event->event_id.header.size;
8261 if (!perf_event_cgroup_match(event))
8264 perf_event_header__init_id(&cgroup_event->event_id.header,
8266 ret = perf_output_begin(&handle, &sample, event,
8267 cgroup_event->event_id.header.size);
8271 perf_output_put(&handle, cgroup_event->event_id);
8272 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8274 perf_event__output_id_sample(event, &handle, &sample);
8276 perf_output_end(&handle);
8278 cgroup_event->event_id.header.size = header_size;
8281 static void perf_event_cgroup(struct cgroup *cgrp)
8283 struct perf_cgroup_event cgroup_event;
8284 char path_enomem[16] = "//enomem";
8288 if (!atomic_read(&nr_cgroup_events))
8291 cgroup_event = (struct perf_cgroup_event){
8294 .type = PERF_RECORD_CGROUP,
8296 .size = sizeof(cgroup_event.event_id),
8298 .id = cgroup_id(cgrp),
8302 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8303 if (pathname == NULL) {
8304 cgroup_event.path = path_enomem;
8306 /* just to be sure to have enough space for alignment */
8307 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8308 cgroup_event.path = pathname;
8312 * Since our buffer works in 8 byte units we need to align our string
8313 * size to a multiple of 8. However, we must guarantee the tail end is
8314 * zero'd out to avoid leaking random bits to userspace.
8316 size = strlen(cgroup_event.path) + 1;
8317 while (!IS_ALIGNED(size, sizeof(u64)))
8318 cgroup_event.path[size++] = '\0';
8320 cgroup_event.event_id.header.size += size;
8321 cgroup_event.path_size = size;
8323 perf_iterate_sb(perf_event_cgroup_output,
8336 struct perf_mmap_event {
8337 struct vm_area_struct *vma;
8339 const char *file_name;
8345 u8 build_id[BUILD_ID_SIZE_MAX];
8349 struct perf_event_header header;
8359 static int perf_event_mmap_match(struct perf_event *event,
8362 struct perf_mmap_event *mmap_event = data;
8363 struct vm_area_struct *vma = mmap_event->vma;
8364 int executable = vma->vm_flags & VM_EXEC;
8366 return (!executable && event->attr.mmap_data) ||
8367 (executable && (event->attr.mmap || event->attr.mmap2));
8370 static void perf_event_mmap_output(struct perf_event *event,
8373 struct perf_mmap_event *mmap_event = data;
8374 struct perf_output_handle handle;
8375 struct perf_sample_data sample;
8376 int size = mmap_event->event_id.header.size;
8377 u32 type = mmap_event->event_id.header.type;
8381 if (!perf_event_mmap_match(event, data))
8384 if (event->attr.mmap2) {
8385 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8386 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8387 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8388 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8389 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8390 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8391 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8394 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8395 ret = perf_output_begin(&handle, &sample, event,
8396 mmap_event->event_id.header.size);
8400 mmap_event->event_id.pid = perf_event_pid(event, current);
8401 mmap_event->event_id.tid = perf_event_tid(event, current);
8403 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8405 if (event->attr.mmap2 && use_build_id)
8406 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8408 perf_output_put(&handle, mmap_event->event_id);
8410 if (event->attr.mmap2) {
8412 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8414 __output_copy(&handle, size, 4);
8415 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8417 perf_output_put(&handle, mmap_event->maj);
8418 perf_output_put(&handle, mmap_event->min);
8419 perf_output_put(&handle, mmap_event->ino);
8420 perf_output_put(&handle, mmap_event->ino_generation);
8422 perf_output_put(&handle, mmap_event->prot);
8423 perf_output_put(&handle, mmap_event->flags);
8426 __output_copy(&handle, mmap_event->file_name,
8427 mmap_event->file_size);
8429 perf_event__output_id_sample(event, &handle, &sample);
8431 perf_output_end(&handle);
8433 mmap_event->event_id.header.size = size;
8434 mmap_event->event_id.header.type = type;
8437 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8439 struct vm_area_struct *vma = mmap_event->vma;
8440 struct file *file = vma->vm_file;
8441 int maj = 0, min = 0;
8442 u64 ino = 0, gen = 0;
8443 u32 prot = 0, flags = 0;
8449 if (vma->vm_flags & VM_READ)
8451 if (vma->vm_flags & VM_WRITE)
8453 if (vma->vm_flags & VM_EXEC)
8456 if (vma->vm_flags & VM_MAYSHARE)
8459 flags = MAP_PRIVATE;
8461 if (vma->vm_flags & VM_LOCKED)
8462 flags |= MAP_LOCKED;
8463 if (is_vm_hugetlb_page(vma))
8464 flags |= MAP_HUGETLB;
8467 struct inode *inode;
8470 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8476 * d_path() works from the end of the rb backwards, so we
8477 * need to add enough zero bytes after the string to handle
8478 * the 64bit alignment we do later.
8480 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8485 inode = file_inode(vma->vm_file);
8486 dev = inode->i_sb->s_dev;
8488 gen = inode->i_generation;
8494 if (vma->vm_ops && vma->vm_ops->name) {
8495 name = (char *) vma->vm_ops->name(vma);
8500 name = (char *)arch_vma_name(vma);
8504 if (vma->vm_start <= vma->vm_mm->start_brk &&
8505 vma->vm_end >= vma->vm_mm->brk) {
8509 if (vma->vm_start <= vma->vm_mm->start_stack &&
8510 vma->vm_end >= vma->vm_mm->start_stack) {
8520 strlcpy(tmp, name, sizeof(tmp));
8524 * Since our buffer works in 8 byte units we need to align our string
8525 * size to a multiple of 8. However, we must guarantee the tail end is
8526 * zero'd out to avoid leaking random bits to userspace.
8528 size = strlen(name)+1;
8529 while (!IS_ALIGNED(size, sizeof(u64)))
8530 name[size++] = '\0';
8532 mmap_event->file_name = name;
8533 mmap_event->file_size = size;
8534 mmap_event->maj = maj;
8535 mmap_event->min = min;
8536 mmap_event->ino = ino;
8537 mmap_event->ino_generation = gen;
8538 mmap_event->prot = prot;
8539 mmap_event->flags = flags;
8541 if (!(vma->vm_flags & VM_EXEC))
8542 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8544 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8546 if (atomic_read(&nr_build_id_events))
8547 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8549 perf_iterate_sb(perf_event_mmap_output,
8557 * Check whether inode and address range match filter criteria.
8559 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8560 struct file *file, unsigned long offset,
8563 /* d_inode(NULL) won't be equal to any mapped user-space file */
8564 if (!filter->path.dentry)
8567 if (d_inode(filter->path.dentry) != file_inode(file))
8570 if (filter->offset > offset + size)
8573 if (filter->offset + filter->size < offset)
8579 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8580 struct vm_area_struct *vma,
8581 struct perf_addr_filter_range *fr)
8583 unsigned long vma_size = vma->vm_end - vma->vm_start;
8584 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8585 struct file *file = vma->vm_file;
8587 if (!perf_addr_filter_match(filter, file, off, vma_size))
8590 if (filter->offset < off) {
8591 fr->start = vma->vm_start;
8592 fr->size = min(vma_size, filter->size - (off - filter->offset));
8594 fr->start = vma->vm_start + filter->offset - off;
8595 fr->size = min(vma->vm_end - fr->start, filter->size);
8601 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8603 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8604 struct vm_area_struct *vma = data;
8605 struct perf_addr_filter *filter;
8606 unsigned int restart = 0, count = 0;
8607 unsigned long flags;
8609 if (!has_addr_filter(event))
8615 raw_spin_lock_irqsave(&ifh->lock, flags);
8616 list_for_each_entry(filter, &ifh->list, entry) {
8617 if (perf_addr_filter_vma_adjust(filter, vma,
8618 &event->addr_filter_ranges[count]))
8625 event->addr_filters_gen++;
8626 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8629 perf_event_stop(event, 1);
8633 * Adjust all task's events' filters to the new vma
8635 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8637 struct perf_event_context *ctx;
8641 * Data tracing isn't supported yet and as such there is no need
8642 * to keep track of anything that isn't related to executable code:
8644 if (!(vma->vm_flags & VM_EXEC))
8648 for_each_task_context_nr(ctxn) {
8649 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8653 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8658 void perf_event_mmap(struct vm_area_struct *vma)
8660 struct perf_mmap_event mmap_event;
8662 if (!atomic_read(&nr_mmap_events))
8665 mmap_event = (struct perf_mmap_event){
8671 .type = PERF_RECORD_MMAP,
8672 .misc = PERF_RECORD_MISC_USER,
8677 .start = vma->vm_start,
8678 .len = vma->vm_end - vma->vm_start,
8679 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8681 /* .maj (attr_mmap2 only) */
8682 /* .min (attr_mmap2 only) */
8683 /* .ino (attr_mmap2 only) */
8684 /* .ino_generation (attr_mmap2 only) */
8685 /* .prot (attr_mmap2 only) */
8686 /* .flags (attr_mmap2 only) */
8689 perf_addr_filters_adjust(vma);
8690 perf_event_mmap_event(&mmap_event);
8693 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8694 unsigned long size, u64 flags)
8696 struct perf_output_handle handle;
8697 struct perf_sample_data sample;
8698 struct perf_aux_event {
8699 struct perf_event_header header;
8705 .type = PERF_RECORD_AUX,
8707 .size = sizeof(rec),
8715 perf_event_header__init_id(&rec.header, &sample, event);
8716 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8721 perf_output_put(&handle, rec);
8722 perf_event__output_id_sample(event, &handle, &sample);
8724 perf_output_end(&handle);
8728 * Lost/dropped samples logging
8730 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8732 struct perf_output_handle handle;
8733 struct perf_sample_data sample;
8737 struct perf_event_header header;
8739 } lost_samples_event = {
8741 .type = PERF_RECORD_LOST_SAMPLES,
8743 .size = sizeof(lost_samples_event),
8748 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8750 ret = perf_output_begin(&handle, &sample, event,
8751 lost_samples_event.header.size);
8755 perf_output_put(&handle, lost_samples_event);
8756 perf_event__output_id_sample(event, &handle, &sample);
8757 perf_output_end(&handle);
8761 * context_switch tracking
8764 struct perf_switch_event {
8765 struct task_struct *task;
8766 struct task_struct *next_prev;
8769 struct perf_event_header header;
8775 static int perf_event_switch_match(struct perf_event *event)
8777 return event->attr.context_switch;
8780 static void perf_event_switch_output(struct perf_event *event, void *data)
8782 struct perf_switch_event *se = data;
8783 struct perf_output_handle handle;
8784 struct perf_sample_data sample;
8787 if (!perf_event_switch_match(event))
8790 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8791 if (event->ctx->task) {
8792 se->event_id.header.type = PERF_RECORD_SWITCH;
8793 se->event_id.header.size = sizeof(se->event_id.header);
8795 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8796 se->event_id.header.size = sizeof(se->event_id);
8797 se->event_id.next_prev_pid =
8798 perf_event_pid(event, se->next_prev);
8799 se->event_id.next_prev_tid =
8800 perf_event_tid(event, se->next_prev);
8803 perf_event_header__init_id(&se->event_id.header, &sample, event);
8805 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8809 if (event->ctx->task)
8810 perf_output_put(&handle, se->event_id.header);
8812 perf_output_put(&handle, se->event_id);
8814 perf_event__output_id_sample(event, &handle, &sample);
8816 perf_output_end(&handle);
8819 static void perf_event_switch(struct task_struct *task,
8820 struct task_struct *next_prev, bool sched_in)
8822 struct perf_switch_event switch_event;
8824 /* N.B. caller checks nr_switch_events != 0 */
8826 switch_event = (struct perf_switch_event){
8828 .next_prev = next_prev,
8832 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8835 /* .next_prev_pid */
8836 /* .next_prev_tid */
8840 if (!sched_in && task->on_rq) {
8841 switch_event.event_id.header.misc |=
8842 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8845 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
8849 * IRQ throttle logging
8852 static void perf_log_throttle(struct perf_event *event, int enable)
8854 struct perf_output_handle handle;
8855 struct perf_sample_data sample;
8859 struct perf_event_header header;
8863 } throttle_event = {
8865 .type = PERF_RECORD_THROTTLE,
8867 .size = sizeof(throttle_event),
8869 .time = perf_event_clock(event),
8870 .id = primary_event_id(event),
8871 .stream_id = event->id,
8875 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8877 perf_event_header__init_id(&throttle_event.header, &sample, event);
8879 ret = perf_output_begin(&handle, &sample, event,
8880 throttle_event.header.size);
8884 perf_output_put(&handle, throttle_event);
8885 perf_event__output_id_sample(event, &handle, &sample);
8886 perf_output_end(&handle);
8890 * ksymbol register/unregister tracking
8893 struct perf_ksymbol_event {
8897 struct perf_event_header header;
8905 static int perf_event_ksymbol_match(struct perf_event *event)
8907 return event->attr.ksymbol;
8910 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8912 struct perf_ksymbol_event *ksymbol_event = data;
8913 struct perf_output_handle handle;
8914 struct perf_sample_data sample;
8917 if (!perf_event_ksymbol_match(event))
8920 perf_event_header__init_id(&ksymbol_event->event_id.header,
8922 ret = perf_output_begin(&handle, &sample, event,
8923 ksymbol_event->event_id.header.size);
8927 perf_output_put(&handle, ksymbol_event->event_id);
8928 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8929 perf_event__output_id_sample(event, &handle, &sample);
8931 perf_output_end(&handle);
8934 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8937 struct perf_ksymbol_event ksymbol_event;
8938 char name[KSYM_NAME_LEN];
8942 if (!atomic_read(&nr_ksymbol_events))
8945 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8946 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8949 strlcpy(name, sym, KSYM_NAME_LEN);
8950 name_len = strlen(name) + 1;
8951 while (!IS_ALIGNED(name_len, sizeof(u64)))
8952 name[name_len++] = '\0';
8953 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8956 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8958 ksymbol_event = (struct perf_ksymbol_event){
8960 .name_len = name_len,
8963 .type = PERF_RECORD_KSYMBOL,
8964 .size = sizeof(ksymbol_event.event_id) +
8969 .ksym_type = ksym_type,
8974 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8977 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8981 * bpf program load/unload tracking
8984 struct perf_bpf_event {
8985 struct bpf_prog *prog;
8987 struct perf_event_header header;
8991 u8 tag[BPF_TAG_SIZE];
8995 static int perf_event_bpf_match(struct perf_event *event)
8997 return event->attr.bpf_event;
9000 static void perf_event_bpf_output(struct perf_event *event, void *data)
9002 struct perf_bpf_event *bpf_event = data;
9003 struct perf_output_handle handle;
9004 struct perf_sample_data sample;
9007 if (!perf_event_bpf_match(event))
9010 perf_event_header__init_id(&bpf_event->event_id.header,
9012 ret = perf_output_begin(&handle, data, event,
9013 bpf_event->event_id.header.size);
9017 perf_output_put(&handle, bpf_event->event_id);
9018 perf_event__output_id_sample(event, &handle, &sample);
9020 perf_output_end(&handle);
9023 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9024 enum perf_bpf_event_type type)
9026 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9029 if (prog->aux->func_cnt == 0) {
9030 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9031 (u64)(unsigned long)prog->bpf_func,
9032 prog->jited_len, unregister,
9033 prog->aux->ksym.name);
9035 for (i = 0; i < prog->aux->func_cnt; i++) {
9036 struct bpf_prog *subprog = prog->aux->func[i];
9039 PERF_RECORD_KSYMBOL_TYPE_BPF,
9040 (u64)(unsigned long)subprog->bpf_func,
9041 subprog->jited_len, unregister,
9042 subprog->aux->ksym.name);
9047 void perf_event_bpf_event(struct bpf_prog *prog,
9048 enum perf_bpf_event_type type,
9051 struct perf_bpf_event bpf_event;
9053 if (type <= PERF_BPF_EVENT_UNKNOWN ||
9054 type >= PERF_BPF_EVENT_MAX)
9058 case PERF_BPF_EVENT_PROG_LOAD:
9059 case PERF_BPF_EVENT_PROG_UNLOAD:
9060 if (atomic_read(&nr_ksymbol_events))
9061 perf_event_bpf_emit_ksymbols(prog, type);
9067 if (!atomic_read(&nr_bpf_events))
9070 bpf_event = (struct perf_bpf_event){
9074 .type = PERF_RECORD_BPF_EVENT,
9075 .size = sizeof(bpf_event.event_id),
9079 .id = prog->aux->id,
9083 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9085 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9086 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9089 struct perf_text_poke_event {
9090 const void *old_bytes;
9091 const void *new_bytes;
9097 struct perf_event_header header;
9103 static int perf_event_text_poke_match(struct perf_event *event)
9105 return event->attr.text_poke;
9108 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9110 struct perf_text_poke_event *text_poke_event = data;
9111 struct perf_output_handle handle;
9112 struct perf_sample_data sample;
9116 if (!perf_event_text_poke_match(event))
9119 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9121 ret = perf_output_begin(&handle, &sample, event,
9122 text_poke_event->event_id.header.size);
9126 perf_output_put(&handle, text_poke_event->event_id);
9127 perf_output_put(&handle, text_poke_event->old_len);
9128 perf_output_put(&handle, text_poke_event->new_len);
9130 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9131 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9133 if (text_poke_event->pad)
9134 __output_copy(&handle, &padding, text_poke_event->pad);
9136 perf_event__output_id_sample(event, &handle, &sample);
9138 perf_output_end(&handle);
9141 void perf_event_text_poke(const void *addr, const void *old_bytes,
9142 size_t old_len, const void *new_bytes, size_t new_len)
9144 struct perf_text_poke_event text_poke_event;
9147 if (!atomic_read(&nr_text_poke_events))
9150 tot = sizeof(text_poke_event.old_len) + old_len;
9151 tot += sizeof(text_poke_event.new_len) + new_len;
9152 pad = ALIGN(tot, sizeof(u64)) - tot;
9154 text_poke_event = (struct perf_text_poke_event){
9155 .old_bytes = old_bytes,
9156 .new_bytes = new_bytes,
9162 .type = PERF_RECORD_TEXT_POKE,
9163 .misc = PERF_RECORD_MISC_KERNEL,
9164 .size = sizeof(text_poke_event.event_id) + tot + pad,
9166 .addr = (unsigned long)addr,
9170 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9173 void perf_event_itrace_started(struct perf_event *event)
9175 event->attach_state |= PERF_ATTACH_ITRACE;
9178 static void perf_log_itrace_start(struct perf_event *event)
9180 struct perf_output_handle handle;
9181 struct perf_sample_data sample;
9182 struct perf_aux_event {
9183 struct perf_event_header header;
9190 event = event->parent;
9192 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9193 event->attach_state & PERF_ATTACH_ITRACE)
9196 rec.header.type = PERF_RECORD_ITRACE_START;
9197 rec.header.misc = 0;
9198 rec.header.size = sizeof(rec);
9199 rec.pid = perf_event_pid(event, current);
9200 rec.tid = perf_event_tid(event, current);
9202 perf_event_header__init_id(&rec.header, &sample, event);
9203 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9208 perf_output_put(&handle, rec);
9209 perf_event__output_id_sample(event, &handle, &sample);
9211 perf_output_end(&handle);
9214 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9216 struct perf_output_handle handle;
9217 struct perf_sample_data sample;
9218 struct perf_aux_event {
9219 struct perf_event_header header;
9225 event = event->parent;
9227 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9228 rec.header.misc = 0;
9229 rec.header.size = sizeof(rec);
9232 perf_event_header__init_id(&rec.header, &sample, event);
9233 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9238 perf_output_put(&handle, rec);
9239 perf_event__output_id_sample(event, &handle, &sample);
9241 perf_output_end(&handle);
9245 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9247 struct hw_perf_event *hwc = &event->hw;
9251 seq = __this_cpu_read(perf_throttled_seq);
9252 if (seq != hwc->interrupts_seq) {
9253 hwc->interrupts_seq = seq;
9254 hwc->interrupts = 1;
9257 if (unlikely(throttle
9258 && hwc->interrupts >= max_samples_per_tick)) {
9259 __this_cpu_inc(perf_throttled_count);
9260 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9261 hwc->interrupts = MAX_INTERRUPTS;
9262 perf_log_throttle(event, 0);
9267 if (event->attr.freq) {
9268 u64 now = perf_clock();
9269 s64 delta = now - hwc->freq_time_stamp;
9271 hwc->freq_time_stamp = now;
9273 if (delta > 0 && delta < 2*TICK_NSEC)
9274 perf_adjust_period(event, delta, hwc->last_period, true);
9280 int perf_event_account_interrupt(struct perf_event *event)
9282 return __perf_event_account_interrupt(event, 1);
9285 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
9288 * Due to interrupt latency (AKA "skid"), we may enter the
9289 * kernel before taking an overflow, even if the PMU is only
9290 * counting user events.
9292 if (event->attr.exclude_kernel && !user_mode(regs))
9299 * Generic event overflow handling, sampling.
9302 static int __perf_event_overflow(struct perf_event *event,
9303 int throttle, struct perf_sample_data *data,
9304 struct pt_regs *regs)
9306 int events = atomic_read(&event->event_limit);
9310 * Non-sampling counters might still use the PMI to fold short
9311 * hardware counters, ignore those.
9313 if (unlikely(!is_sampling_event(event)))
9316 ret = __perf_event_account_interrupt(event, throttle);
9319 * XXX event_limit might not quite work as expected on inherited
9323 event->pending_kill = POLL_IN;
9324 if (events && atomic_dec_and_test(&event->event_limit)) {
9326 event->pending_kill = POLL_HUP;
9327 perf_event_disable_inatomic(event);
9330 if (event->attr.sigtrap) {
9332 * The desired behaviour of sigtrap vs invalid samples is a bit
9333 * tricky; on the one hand, one should not loose the SIGTRAP if
9334 * it is the first event, on the other hand, we should also not
9335 * trigger the WARN or override the data address.
9337 bool valid_sample = sample_is_allowed(event, regs);
9338 unsigned int pending_id = 1;
9341 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
9342 if (!event->pending_sigtrap) {
9343 event->pending_sigtrap = pending_id;
9344 local_inc(&event->ctx->nr_pending);
9345 } else if (event->attr.exclude_kernel && valid_sample) {
9347 * Should not be able to return to user space without
9348 * consuming pending_sigtrap; with exceptions:
9350 * 1. Where !exclude_kernel, events can overflow again
9351 * in the kernel without returning to user space.
9353 * 2. Events that can overflow again before the IRQ-
9354 * work without user space progress (e.g. hrtimer).
9355 * To approximate progress (with false negatives),
9356 * check 32-bit hash of the current IP.
9358 WARN_ON_ONCE(event->pending_sigtrap != pending_id);
9361 event->pending_addr = 0;
9362 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
9363 event->pending_addr = data->addr;
9364 irq_work_queue(&event->pending_irq);
9367 READ_ONCE(event->overflow_handler)(event, data, regs);
9369 if (*perf_event_fasync(event) && event->pending_kill) {
9370 event->pending_wakeup = 1;
9371 irq_work_queue(&event->pending_irq);
9377 int perf_event_overflow(struct perf_event *event,
9378 struct perf_sample_data *data,
9379 struct pt_regs *regs)
9381 return __perf_event_overflow(event, 1, data, regs);
9385 * Generic software event infrastructure
9388 struct swevent_htable {
9389 struct swevent_hlist *swevent_hlist;
9390 struct mutex hlist_mutex;
9393 /* Recursion avoidance in each contexts */
9394 int recursion[PERF_NR_CONTEXTS];
9397 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9400 * We directly increment event->count and keep a second value in
9401 * event->hw.period_left to count intervals. This period event
9402 * is kept in the range [-sample_period, 0] so that we can use the
9406 u64 perf_swevent_set_period(struct perf_event *event)
9408 struct hw_perf_event *hwc = &event->hw;
9409 u64 period = hwc->last_period;
9413 hwc->last_period = hwc->sample_period;
9416 old = val = local64_read(&hwc->period_left);
9420 nr = div64_u64(period + val, period);
9421 offset = nr * period;
9423 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9429 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9430 struct perf_sample_data *data,
9431 struct pt_regs *regs)
9433 struct hw_perf_event *hwc = &event->hw;
9437 overflow = perf_swevent_set_period(event);
9439 if (hwc->interrupts == MAX_INTERRUPTS)
9442 for (; overflow; overflow--) {
9443 if (__perf_event_overflow(event, throttle,
9446 * We inhibit the overflow from happening when
9447 * hwc->interrupts == MAX_INTERRUPTS.
9455 static void perf_swevent_event(struct perf_event *event, u64 nr,
9456 struct perf_sample_data *data,
9457 struct pt_regs *regs)
9459 struct hw_perf_event *hwc = &event->hw;
9461 local64_add(nr, &event->count);
9466 if (!is_sampling_event(event))
9469 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9471 return perf_swevent_overflow(event, 1, data, regs);
9473 data->period = event->hw.last_period;
9475 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9476 return perf_swevent_overflow(event, 1, data, regs);
9478 if (local64_add_negative(nr, &hwc->period_left))
9481 perf_swevent_overflow(event, 0, data, regs);
9484 static int perf_exclude_event(struct perf_event *event,
9485 struct pt_regs *regs)
9487 if (event->hw.state & PERF_HES_STOPPED)
9491 if (event->attr.exclude_user && user_mode(regs))
9494 if (event->attr.exclude_kernel && !user_mode(regs))
9501 static int perf_swevent_match(struct perf_event *event,
9502 enum perf_type_id type,
9504 struct perf_sample_data *data,
9505 struct pt_regs *regs)
9507 if (event->attr.type != type)
9510 if (event->attr.config != event_id)
9513 if (perf_exclude_event(event, regs))
9519 static inline u64 swevent_hash(u64 type, u32 event_id)
9521 u64 val = event_id | (type << 32);
9523 return hash_64(val, SWEVENT_HLIST_BITS);
9526 static inline struct hlist_head *
9527 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9529 u64 hash = swevent_hash(type, event_id);
9531 return &hlist->heads[hash];
9534 /* For the read side: events when they trigger */
9535 static inline struct hlist_head *
9536 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9538 struct swevent_hlist *hlist;
9540 hlist = rcu_dereference(swhash->swevent_hlist);
9544 return __find_swevent_head(hlist, type, event_id);
9547 /* For the event head insertion and removal in the hlist */
9548 static inline struct hlist_head *
9549 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9551 struct swevent_hlist *hlist;
9552 u32 event_id = event->attr.config;
9553 u64 type = event->attr.type;
9556 * Event scheduling is always serialized against hlist allocation
9557 * and release. Which makes the protected version suitable here.
9558 * The context lock guarantees that.
9560 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9561 lockdep_is_held(&event->ctx->lock));
9565 return __find_swevent_head(hlist, type, event_id);
9568 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9570 struct perf_sample_data *data,
9571 struct pt_regs *regs)
9573 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9574 struct perf_event *event;
9575 struct hlist_head *head;
9578 head = find_swevent_head_rcu(swhash, type, event_id);
9582 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9583 if (perf_swevent_match(event, type, event_id, data, regs))
9584 perf_swevent_event(event, nr, data, regs);
9590 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9592 int perf_swevent_get_recursion_context(void)
9594 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9596 return get_recursion_context(swhash->recursion);
9598 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9600 void perf_swevent_put_recursion_context(int rctx)
9602 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9604 put_recursion_context(swhash->recursion, rctx);
9607 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9609 struct perf_sample_data data;
9611 if (WARN_ON_ONCE(!regs))
9614 perf_sample_data_init(&data, addr, 0);
9615 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9618 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9622 preempt_disable_notrace();
9623 rctx = perf_swevent_get_recursion_context();
9624 if (unlikely(rctx < 0))
9627 ___perf_sw_event(event_id, nr, regs, addr);
9629 perf_swevent_put_recursion_context(rctx);
9631 preempt_enable_notrace();
9634 static void perf_swevent_read(struct perf_event *event)
9638 static int perf_swevent_add(struct perf_event *event, int flags)
9640 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9641 struct hw_perf_event *hwc = &event->hw;
9642 struct hlist_head *head;
9644 if (is_sampling_event(event)) {
9645 hwc->last_period = hwc->sample_period;
9646 perf_swevent_set_period(event);
9649 hwc->state = !(flags & PERF_EF_START);
9651 head = find_swevent_head(swhash, event);
9652 if (WARN_ON_ONCE(!head))
9655 hlist_add_head_rcu(&event->hlist_entry, head);
9656 perf_event_update_userpage(event);
9661 static void perf_swevent_del(struct perf_event *event, int flags)
9663 hlist_del_rcu(&event->hlist_entry);
9666 static void perf_swevent_start(struct perf_event *event, int flags)
9668 event->hw.state = 0;
9671 static void perf_swevent_stop(struct perf_event *event, int flags)
9673 event->hw.state = PERF_HES_STOPPED;
9676 /* Deref the hlist from the update side */
9677 static inline struct swevent_hlist *
9678 swevent_hlist_deref(struct swevent_htable *swhash)
9680 return rcu_dereference_protected(swhash->swevent_hlist,
9681 lockdep_is_held(&swhash->hlist_mutex));
9684 static void swevent_hlist_release(struct swevent_htable *swhash)
9686 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9691 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9692 kfree_rcu(hlist, rcu_head);
9695 static void swevent_hlist_put_cpu(int cpu)
9697 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9699 mutex_lock(&swhash->hlist_mutex);
9701 if (!--swhash->hlist_refcount)
9702 swevent_hlist_release(swhash);
9704 mutex_unlock(&swhash->hlist_mutex);
9707 static void swevent_hlist_put(void)
9711 for_each_possible_cpu(cpu)
9712 swevent_hlist_put_cpu(cpu);
9715 static int swevent_hlist_get_cpu(int cpu)
9717 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9720 mutex_lock(&swhash->hlist_mutex);
9721 if (!swevent_hlist_deref(swhash) &&
9722 cpumask_test_cpu(cpu, perf_online_mask)) {
9723 struct swevent_hlist *hlist;
9725 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9730 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9732 swhash->hlist_refcount++;
9734 mutex_unlock(&swhash->hlist_mutex);
9739 static int swevent_hlist_get(void)
9741 int err, cpu, failed_cpu;
9743 mutex_lock(&pmus_lock);
9744 for_each_possible_cpu(cpu) {
9745 err = swevent_hlist_get_cpu(cpu);
9751 mutex_unlock(&pmus_lock);
9754 for_each_possible_cpu(cpu) {
9755 if (cpu == failed_cpu)
9757 swevent_hlist_put_cpu(cpu);
9759 mutex_unlock(&pmus_lock);
9763 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9765 static void sw_perf_event_destroy(struct perf_event *event)
9767 u64 event_id = event->attr.config;
9769 WARN_ON(event->parent);
9771 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9772 swevent_hlist_put();
9775 static int perf_swevent_init(struct perf_event *event)
9777 u64 event_id = event->attr.config;
9779 if (event->attr.type != PERF_TYPE_SOFTWARE)
9783 * no branch sampling for software events
9785 if (has_branch_stack(event))
9789 case PERF_COUNT_SW_CPU_CLOCK:
9790 case PERF_COUNT_SW_TASK_CLOCK:
9797 if (event_id >= PERF_COUNT_SW_MAX)
9800 if (!event->parent) {
9803 err = swevent_hlist_get();
9807 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9808 event->destroy = sw_perf_event_destroy;
9814 static struct pmu perf_swevent = {
9815 .task_ctx_nr = perf_sw_context,
9817 .capabilities = PERF_PMU_CAP_NO_NMI,
9819 .event_init = perf_swevent_init,
9820 .add = perf_swevent_add,
9821 .del = perf_swevent_del,
9822 .start = perf_swevent_start,
9823 .stop = perf_swevent_stop,
9824 .read = perf_swevent_read,
9827 #ifdef CONFIG_EVENT_TRACING
9829 static int perf_tp_filter_match(struct perf_event *event,
9830 struct perf_sample_data *data)
9832 void *record = data->raw->frag.data;
9834 /* only top level events have filters set */
9836 event = event->parent;
9838 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9843 static int perf_tp_event_match(struct perf_event *event,
9844 struct perf_sample_data *data,
9845 struct pt_regs *regs)
9847 if (event->hw.state & PERF_HES_STOPPED)
9850 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9852 if (event->attr.exclude_kernel && !user_mode(regs))
9855 if (!perf_tp_filter_match(event, data))
9861 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9862 struct trace_event_call *call, u64 count,
9863 struct pt_regs *regs, struct hlist_head *head,
9864 struct task_struct *task)
9866 if (bpf_prog_array_valid(call)) {
9867 *(struct pt_regs **)raw_data = regs;
9868 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9869 perf_swevent_put_recursion_context(rctx);
9873 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9876 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9878 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9879 struct pt_regs *regs, struct hlist_head *head, int rctx,
9880 struct task_struct *task)
9882 struct perf_sample_data data;
9883 struct perf_event *event;
9885 struct perf_raw_record raw = {
9892 perf_sample_data_init(&data, 0, 0);
9894 data.sample_flags |= PERF_SAMPLE_RAW;
9896 perf_trace_buf_update(record, event_type);
9898 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9899 if (perf_tp_event_match(event, &data, regs))
9900 perf_swevent_event(event, count, &data, regs);
9904 * If we got specified a target task, also iterate its context and
9905 * deliver this event there too.
9907 if (task && task != current) {
9908 struct perf_event_context *ctx;
9909 struct trace_entry *entry = record;
9912 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9916 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9917 if (event->cpu != smp_processor_id())
9919 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9921 if (event->attr.config != entry->type)
9923 /* Cannot deliver synchronous signal to other task. */
9924 if (event->attr.sigtrap)
9926 if (perf_tp_event_match(event, &data, regs))
9927 perf_swevent_event(event, count, &data, regs);
9933 perf_swevent_put_recursion_context(rctx);
9935 EXPORT_SYMBOL_GPL(perf_tp_event);
9937 static void tp_perf_event_destroy(struct perf_event *event)
9939 perf_trace_destroy(event);
9942 static int perf_tp_event_init(struct perf_event *event)
9946 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9950 * no branch sampling for tracepoint events
9952 if (has_branch_stack(event))
9955 err = perf_trace_init(event);
9959 event->destroy = tp_perf_event_destroy;
9964 static struct pmu perf_tracepoint = {
9965 .task_ctx_nr = perf_sw_context,
9967 .event_init = perf_tp_event_init,
9968 .add = perf_trace_add,
9969 .del = perf_trace_del,
9970 .start = perf_swevent_start,
9971 .stop = perf_swevent_stop,
9972 .read = perf_swevent_read,
9975 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9977 * Flags in config, used by dynamic PMU kprobe and uprobe
9978 * The flags should match following PMU_FORMAT_ATTR().
9980 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9981 * if not set, create kprobe/uprobe
9983 * The following values specify a reference counter (or semaphore in the
9984 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9985 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9987 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9988 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9990 enum perf_probe_config {
9991 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9992 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9993 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9996 PMU_FORMAT_ATTR(retprobe, "config:0");
9999 #ifdef CONFIG_KPROBE_EVENTS
10000 static struct attribute *kprobe_attrs[] = {
10001 &format_attr_retprobe.attr,
10005 static struct attribute_group kprobe_format_group = {
10007 .attrs = kprobe_attrs,
10010 static const struct attribute_group *kprobe_attr_groups[] = {
10011 &kprobe_format_group,
10015 static int perf_kprobe_event_init(struct perf_event *event);
10016 static struct pmu perf_kprobe = {
10017 .task_ctx_nr = perf_sw_context,
10018 .event_init = perf_kprobe_event_init,
10019 .add = perf_trace_add,
10020 .del = perf_trace_del,
10021 .start = perf_swevent_start,
10022 .stop = perf_swevent_stop,
10023 .read = perf_swevent_read,
10024 .attr_groups = kprobe_attr_groups,
10027 static int perf_kprobe_event_init(struct perf_event *event)
10032 if (event->attr.type != perf_kprobe.type)
10035 if (!perfmon_capable())
10039 * no branch sampling for probe events
10041 if (has_branch_stack(event))
10042 return -EOPNOTSUPP;
10044 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10045 err = perf_kprobe_init(event, is_retprobe);
10049 event->destroy = perf_kprobe_destroy;
10053 #endif /* CONFIG_KPROBE_EVENTS */
10055 #ifdef CONFIG_UPROBE_EVENTS
10056 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10058 static struct attribute *uprobe_attrs[] = {
10059 &format_attr_retprobe.attr,
10060 &format_attr_ref_ctr_offset.attr,
10064 static struct attribute_group uprobe_format_group = {
10066 .attrs = uprobe_attrs,
10069 static const struct attribute_group *uprobe_attr_groups[] = {
10070 &uprobe_format_group,
10074 static int perf_uprobe_event_init(struct perf_event *event);
10075 static struct pmu perf_uprobe = {
10076 .task_ctx_nr = perf_sw_context,
10077 .event_init = perf_uprobe_event_init,
10078 .add = perf_trace_add,
10079 .del = perf_trace_del,
10080 .start = perf_swevent_start,
10081 .stop = perf_swevent_stop,
10082 .read = perf_swevent_read,
10083 .attr_groups = uprobe_attr_groups,
10086 static int perf_uprobe_event_init(struct perf_event *event)
10089 unsigned long ref_ctr_offset;
10092 if (event->attr.type != perf_uprobe.type)
10095 if (!perfmon_capable())
10099 * no branch sampling for probe events
10101 if (has_branch_stack(event))
10102 return -EOPNOTSUPP;
10104 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10105 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10106 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10110 event->destroy = perf_uprobe_destroy;
10114 #endif /* CONFIG_UPROBE_EVENTS */
10116 static inline void perf_tp_register(void)
10118 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10119 #ifdef CONFIG_KPROBE_EVENTS
10120 perf_pmu_register(&perf_kprobe, "kprobe", -1);
10122 #ifdef CONFIG_UPROBE_EVENTS
10123 perf_pmu_register(&perf_uprobe, "uprobe", -1);
10127 static void perf_event_free_filter(struct perf_event *event)
10129 ftrace_profile_free_filter(event);
10132 #ifdef CONFIG_BPF_SYSCALL
10133 static void bpf_overflow_handler(struct perf_event *event,
10134 struct perf_sample_data *data,
10135 struct pt_regs *regs)
10137 struct bpf_perf_event_data_kern ctx = {
10141 struct bpf_prog *prog;
10144 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10145 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10148 prog = READ_ONCE(event->prog);
10150 if (prog->call_get_stack &&
10151 (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) &&
10152 !(data->sample_flags & PERF_SAMPLE_CALLCHAIN)) {
10153 data->callchain = perf_callchain(event, regs);
10154 data->sample_flags |= PERF_SAMPLE_CALLCHAIN;
10157 ret = bpf_prog_run(prog, &ctx);
10161 __this_cpu_dec(bpf_prog_active);
10165 event->orig_overflow_handler(event, data, regs);
10168 static int perf_event_set_bpf_handler(struct perf_event *event,
10169 struct bpf_prog *prog,
10172 if (event->overflow_handler_context)
10173 /* hw breakpoint or kernel counter */
10179 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10182 if (event->attr.precise_ip &&
10183 prog->call_get_stack &&
10184 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10185 event->attr.exclude_callchain_kernel ||
10186 event->attr.exclude_callchain_user)) {
10188 * On perf_event with precise_ip, calling bpf_get_stack()
10189 * may trigger unwinder warnings and occasional crashes.
10190 * bpf_get_[stack|stackid] works around this issue by using
10191 * callchain attached to perf_sample_data. If the
10192 * perf_event does not full (kernel and user) callchain
10193 * attached to perf_sample_data, do not allow attaching BPF
10194 * program that calls bpf_get_[stack|stackid].
10199 event->prog = prog;
10200 event->bpf_cookie = bpf_cookie;
10201 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
10202 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
10206 static void perf_event_free_bpf_handler(struct perf_event *event)
10208 struct bpf_prog *prog = event->prog;
10213 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
10214 event->prog = NULL;
10215 bpf_prog_put(prog);
10218 static int perf_event_set_bpf_handler(struct perf_event *event,
10219 struct bpf_prog *prog,
10222 return -EOPNOTSUPP;
10224 static void perf_event_free_bpf_handler(struct perf_event *event)
10230 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10231 * with perf_event_open()
10233 static inline bool perf_event_is_tracing(struct perf_event *event)
10235 if (event->pmu == &perf_tracepoint)
10237 #ifdef CONFIG_KPROBE_EVENTS
10238 if (event->pmu == &perf_kprobe)
10241 #ifdef CONFIG_UPROBE_EVENTS
10242 if (event->pmu == &perf_uprobe)
10248 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10251 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10253 if (!perf_event_is_tracing(event))
10254 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10256 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10257 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10258 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10259 is_syscall_tp = is_syscall_trace_event(event->tp_event);
10260 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10261 /* bpf programs can only be attached to u/kprobe or tracepoint */
10264 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10265 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10266 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10269 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->aux->sleepable && !is_uprobe)
10270 /* only uprobe programs are allowed to be sleepable */
10273 /* Kprobe override only works for kprobes, not uprobes. */
10274 if (prog->kprobe_override && !is_kprobe)
10277 if (is_tracepoint || is_syscall_tp) {
10278 int off = trace_event_get_offsets(event->tp_event);
10280 if (prog->aux->max_ctx_offset > off)
10284 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10287 void perf_event_free_bpf_prog(struct perf_event *event)
10289 if (!perf_event_is_tracing(event)) {
10290 perf_event_free_bpf_handler(event);
10293 perf_event_detach_bpf_prog(event);
10298 static inline void perf_tp_register(void)
10302 static void perf_event_free_filter(struct perf_event *event)
10306 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10312 void perf_event_free_bpf_prog(struct perf_event *event)
10315 #endif /* CONFIG_EVENT_TRACING */
10317 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10318 void perf_bp_event(struct perf_event *bp, void *data)
10320 struct perf_sample_data sample;
10321 struct pt_regs *regs = data;
10323 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10325 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10326 perf_swevent_event(bp, 1, &sample, regs);
10331 * Allocate a new address filter
10333 static struct perf_addr_filter *
10334 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10336 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10337 struct perf_addr_filter *filter;
10339 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10343 INIT_LIST_HEAD(&filter->entry);
10344 list_add_tail(&filter->entry, filters);
10349 static void free_filters_list(struct list_head *filters)
10351 struct perf_addr_filter *filter, *iter;
10353 list_for_each_entry_safe(filter, iter, filters, entry) {
10354 path_put(&filter->path);
10355 list_del(&filter->entry);
10361 * Free existing address filters and optionally install new ones
10363 static void perf_addr_filters_splice(struct perf_event *event,
10364 struct list_head *head)
10366 unsigned long flags;
10369 if (!has_addr_filter(event))
10372 /* don't bother with children, they don't have their own filters */
10376 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10378 list_splice_init(&event->addr_filters.list, &list);
10380 list_splice(head, &event->addr_filters.list);
10382 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10384 free_filters_list(&list);
10388 * Scan through mm's vmas and see if one of them matches the
10389 * @filter; if so, adjust filter's address range.
10390 * Called with mm::mmap_lock down for reading.
10392 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10393 struct mm_struct *mm,
10394 struct perf_addr_filter_range *fr)
10396 struct vm_area_struct *vma;
10397 VMA_ITERATOR(vmi, mm, 0);
10399 for_each_vma(vmi, vma) {
10403 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10409 * Update event's address range filters based on the
10410 * task's existing mappings, if any.
10412 static void perf_event_addr_filters_apply(struct perf_event *event)
10414 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10415 struct task_struct *task = READ_ONCE(event->ctx->task);
10416 struct perf_addr_filter *filter;
10417 struct mm_struct *mm = NULL;
10418 unsigned int count = 0;
10419 unsigned long flags;
10422 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10423 * will stop on the parent's child_mutex that our caller is also holding
10425 if (task == TASK_TOMBSTONE)
10428 if (ifh->nr_file_filters) {
10429 mm = get_task_mm(task);
10433 mmap_read_lock(mm);
10436 raw_spin_lock_irqsave(&ifh->lock, flags);
10437 list_for_each_entry(filter, &ifh->list, entry) {
10438 if (filter->path.dentry) {
10440 * Adjust base offset if the filter is associated to a
10441 * binary that needs to be mapped:
10443 event->addr_filter_ranges[count].start = 0;
10444 event->addr_filter_ranges[count].size = 0;
10446 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10448 event->addr_filter_ranges[count].start = filter->offset;
10449 event->addr_filter_ranges[count].size = filter->size;
10455 event->addr_filters_gen++;
10456 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10458 if (ifh->nr_file_filters) {
10459 mmap_read_unlock(mm);
10465 perf_event_stop(event, 1);
10469 * Address range filtering: limiting the data to certain
10470 * instruction address ranges. Filters are ioctl()ed to us from
10471 * userspace as ascii strings.
10473 * Filter string format:
10475 * ACTION RANGE_SPEC
10476 * where ACTION is one of the
10477 * * "filter": limit the trace to this region
10478 * * "start": start tracing from this address
10479 * * "stop": stop tracing at this address/region;
10481 * * for kernel addresses: <start address>[/<size>]
10482 * * for object files: <start address>[/<size>]@</path/to/object/file>
10484 * if <size> is not specified or is zero, the range is treated as a single
10485 * address; not valid for ACTION=="filter".
10499 IF_STATE_ACTION = 0,
10504 static const match_table_t if_tokens = {
10505 { IF_ACT_FILTER, "filter" },
10506 { IF_ACT_START, "start" },
10507 { IF_ACT_STOP, "stop" },
10508 { IF_SRC_FILE, "%u/%u@%s" },
10509 { IF_SRC_KERNEL, "%u/%u" },
10510 { IF_SRC_FILEADDR, "%u@%s" },
10511 { IF_SRC_KERNELADDR, "%u" },
10512 { IF_ACT_NONE, NULL },
10516 * Address filter string parser
10519 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10520 struct list_head *filters)
10522 struct perf_addr_filter *filter = NULL;
10523 char *start, *orig, *filename = NULL;
10524 substring_t args[MAX_OPT_ARGS];
10525 int state = IF_STATE_ACTION, token;
10526 unsigned int kernel = 0;
10529 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10533 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10534 static const enum perf_addr_filter_action_t actions[] = {
10535 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10536 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10537 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10544 /* filter definition begins */
10545 if (state == IF_STATE_ACTION) {
10546 filter = perf_addr_filter_new(event, filters);
10551 token = match_token(start, if_tokens, args);
10553 case IF_ACT_FILTER:
10556 if (state != IF_STATE_ACTION)
10559 filter->action = actions[token];
10560 state = IF_STATE_SOURCE;
10563 case IF_SRC_KERNELADDR:
10564 case IF_SRC_KERNEL:
10568 case IF_SRC_FILEADDR:
10570 if (state != IF_STATE_SOURCE)
10574 ret = kstrtoul(args[0].from, 0, &filter->offset);
10578 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10580 ret = kstrtoul(args[1].from, 0, &filter->size);
10585 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10586 int fpos = token == IF_SRC_FILE ? 2 : 1;
10589 filename = match_strdup(&args[fpos]);
10596 state = IF_STATE_END;
10604 * Filter definition is fully parsed, validate and install it.
10605 * Make sure that it doesn't contradict itself or the event's
10608 if (state == IF_STATE_END) {
10612 * ACTION "filter" must have a non-zero length region
10615 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10624 * For now, we only support file-based filters
10625 * in per-task events; doing so for CPU-wide
10626 * events requires additional context switching
10627 * trickery, since same object code will be
10628 * mapped at different virtual addresses in
10629 * different processes.
10632 if (!event->ctx->task)
10635 /* look up the path and grab its inode */
10636 ret = kern_path(filename, LOOKUP_FOLLOW,
10642 if (!filter->path.dentry ||
10643 !S_ISREG(d_inode(filter->path.dentry)
10647 event->addr_filters.nr_file_filters++;
10650 /* ready to consume more filters */
10653 state = IF_STATE_ACTION;
10659 if (state != IF_STATE_ACTION)
10669 free_filters_list(filters);
10676 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10678 LIST_HEAD(filters);
10682 * Since this is called in perf_ioctl() path, we're already holding
10685 lockdep_assert_held(&event->ctx->mutex);
10687 if (WARN_ON_ONCE(event->parent))
10690 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10692 goto fail_clear_files;
10694 ret = event->pmu->addr_filters_validate(&filters);
10696 goto fail_free_filters;
10698 /* remove existing filters, if any */
10699 perf_addr_filters_splice(event, &filters);
10701 /* install new filters */
10702 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10707 free_filters_list(&filters);
10710 event->addr_filters.nr_file_filters = 0;
10715 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10720 filter_str = strndup_user(arg, PAGE_SIZE);
10721 if (IS_ERR(filter_str))
10722 return PTR_ERR(filter_str);
10724 #ifdef CONFIG_EVENT_TRACING
10725 if (perf_event_is_tracing(event)) {
10726 struct perf_event_context *ctx = event->ctx;
10729 * Beware, here be dragons!!
10731 * the tracepoint muck will deadlock against ctx->mutex, but
10732 * the tracepoint stuff does not actually need it. So
10733 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10734 * already have a reference on ctx.
10736 * This can result in event getting moved to a different ctx,
10737 * but that does not affect the tracepoint state.
10739 mutex_unlock(&ctx->mutex);
10740 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10741 mutex_lock(&ctx->mutex);
10744 if (has_addr_filter(event))
10745 ret = perf_event_set_addr_filter(event, filter_str);
10752 * hrtimer based swevent callback
10755 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10757 enum hrtimer_restart ret = HRTIMER_RESTART;
10758 struct perf_sample_data data;
10759 struct pt_regs *regs;
10760 struct perf_event *event;
10763 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10765 if (event->state != PERF_EVENT_STATE_ACTIVE)
10766 return HRTIMER_NORESTART;
10768 event->pmu->read(event);
10770 perf_sample_data_init(&data, 0, event->hw.last_period);
10771 regs = get_irq_regs();
10773 if (regs && !perf_exclude_event(event, regs)) {
10774 if (!(event->attr.exclude_idle && is_idle_task(current)))
10775 if (__perf_event_overflow(event, 1, &data, regs))
10776 ret = HRTIMER_NORESTART;
10779 period = max_t(u64, 10000, event->hw.sample_period);
10780 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10785 static void perf_swevent_start_hrtimer(struct perf_event *event)
10787 struct hw_perf_event *hwc = &event->hw;
10790 if (!is_sampling_event(event))
10793 period = local64_read(&hwc->period_left);
10798 local64_set(&hwc->period_left, 0);
10800 period = max_t(u64, 10000, hwc->sample_period);
10802 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10803 HRTIMER_MODE_REL_PINNED_HARD);
10806 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10808 struct hw_perf_event *hwc = &event->hw;
10810 if (is_sampling_event(event)) {
10811 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10812 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10814 hrtimer_cancel(&hwc->hrtimer);
10818 static void perf_swevent_init_hrtimer(struct perf_event *event)
10820 struct hw_perf_event *hwc = &event->hw;
10822 if (!is_sampling_event(event))
10825 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10826 hwc->hrtimer.function = perf_swevent_hrtimer;
10829 * Since hrtimers have a fixed rate, we can do a static freq->period
10830 * mapping and avoid the whole period adjust feedback stuff.
10832 if (event->attr.freq) {
10833 long freq = event->attr.sample_freq;
10835 event->attr.sample_period = NSEC_PER_SEC / freq;
10836 hwc->sample_period = event->attr.sample_period;
10837 local64_set(&hwc->period_left, hwc->sample_period);
10838 hwc->last_period = hwc->sample_period;
10839 event->attr.freq = 0;
10844 * Software event: cpu wall time clock
10847 static void cpu_clock_event_update(struct perf_event *event)
10852 now = local_clock();
10853 prev = local64_xchg(&event->hw.prev_count, now);
10854 local64_add(now - prev, &event->count);
10857 static void cpu_clock_event_start(struct perf_event *event, int flags)
10859 local64_set(&event->hw.prev_count, local_clock());
10860 perf_swevent_start_hrtimer(event);
10863 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10865 perf_swevent_cancel_hrtimer(event);
10866 cpu_clock_event_update(event);
10869 static int cpu_clock_event_add(struct perf_event *event, int flags)
10871 if (flags & PERF_EF_START)
10872 cpu_clock_event_start(event, flags);
10873 perf_event_update_userpage(event);
10878 static void cpu_clock_event_del(struct perf_event *event, int flags)
10880 cpu_clock_event_stop(event, flags);
10883 static void cpu_clock_event_read(struct perf_event *event)
10885 cpu_clock_event_update(event);
10888 static int cpu_clock_event_init(struct perf_event *event)
10890 if (event->attr.type != PERF_TYPE_SOFTWARE)
10893 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10897 * no branch sampling for software events
10899 if (has_branch_stack(event))
10900 return -EOPNOTSUPP;
10902 perf_swevent_init_hrtimer(event);
10907 static struct pmu perf_cpu_clock = {
10908 .task_ctx_nr = perf_sw_context,
10910 .capabilities = PERF_PMU_CAP_NO_NMI,
10912 .event_init = cpu_clock_event_init,
10913 .add = cpu_clock_event_add,
10914 .del = cpu_clock_event_del,
10915 .start = cpu_clock_event_start,
10916 .stop = cpu_clock_event_stop,
10917 .read = cpu_clock_event_read,
10921 * Software event: task time clock
10924 static void task_clock_event_update(struct perf_event *event, u64 now)
10929 prev = local64_xchg(&event->hw.prev_count, now);
10930 delta = now - prev;
10931 local64_add(delta, &event->count);
10934 static void task_clock_event_start(struct perf_event *event, int flags)
10936 local64_set(&event->hw.prev_count, event->ctx->time);
10937 perf_swevent_start_hrtimer(event);
10940 static void task_clock_event_stop(struct perf_event *event, int flags)
10942 perf_swevent_cancel_hrtimer(event);
10943 task_clock_event_update(event, event->ctx->time);
10946 static int task_clock_event_add(struct perf_event *event, int flags)
10948 if (flags & PERF_EF_START)
10949 task_clock_event_start(event, flags);
10950 perf_event_update_userpage(event);
10955 static void task_clock_event_del(struct perf_event *event, int flags)
10957 task_clock_event_stop(event, PERF_EF_UPDATE);
10960 static void task_clock_event_read(struct perf_event *event)
10962 u64 now = perf_clock();
10963 u64 delta = now - event->ctx->timestamp;
10964 u64 time = event->ctx->time + delta;
10966 task_clock_event_update(event, time);
10969 static int task_clock_event_init(struct perf_event *event)
10971 if (event->attr.type != PERF_TYPE_SOFTWARE)
10974 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10978 * no branch sampling for software events
10980 if (has_branch_stack(event))
10981 return -EOPNOTSUPP;
10983 perf_swevent_init_hrtimer(event);
10988 static struct pmu perf_task_clock = {
10989 .task_ctx_nr = perf_sw_context,
10991 .capabilities = PERF_PMU_CAP_NO_NMI,
10993 .event_init = task_clock_event_init,
10994 .add = task_clock_event_add,
10995 .del = task_clock_event_del,
10996 .start = task_clock_event_start,
10997 .stop = task_clock_event_stop,
10998 .read = task_clock_event_read,
11001 static void perf_pmu_nop_void(struct pmu *pmu)
11005 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11009 static int perf_pmu_nop_int(struct pmu *pmu)
11014 static int perf_event_nop_int(struct perf_event *event, u64 value)
11019 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11021 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11023 __this_cpu_write(nop_txn_flags, flags);
11025 if (flags & ~PERF_PMU_TXN_ADD)
11028 perf_pmu_disable(pmu);
11031 static int perf_pmu_commit_txn(struct pmu *pmu)
11033 unsigned int flags = __this_cpu_read(nop_txn_flags);
11035 __this_cpu_write(nop_txn_flags, 0);
11037 if (flags & ~PERF_PMU_TXN_ADD)
11040 perf_pmu_enable(pmu);
11044 static void perf_pmu_cancel_txn(struct pmu *pmu)
11046 unsigned int flags = __this_cpu_read(nop_txn_flags);
11048 __this_cpu_write(nop_txn_flags, 0);
11050 if (flags & ~PERF_PMU_TXN_ADD)
11053 perf_pmu_enable(pmu);
11056 static int perf_event_idx_default(struct perf_event *event)
11062 * Ensures all contexts with the same task_ctx_nr have the same
11063 * pmu_cpu_context too.
11065 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
11072 list_for_each_entry(pmu, &pmus, entry) {
11073 if (pmu->task_ctx_nr == ctxn)
11074 return pmu->pmu_cpu_context;
11080 static void free_pmu_context(struct pmu *pmu)
11083 * Static contexts such as perf_sw_context have a global lifetime
11084 * and may be shared between different PMUs. Avoid freeing them
11085 * when a single PMU is going away.
11087 if (pmu->task_ctx_nr > perf_invalid_context)
11090 free_percpu(pmu->pmu_cpu_context);
11094 * Let userspace know that this PMU supports address range filtering:
11096 static ssize_t nr_addr_filters_show(struct device *dev,
11097 struct device_attribute *attr,
11100 struct pmu *pmu = dev_get_drvdata(dev);
11102 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11104 DEVICE_ATTR_RO(nr_addr_filters);
11106 static struct idr pmu_idr;
11109 type_show(struct device *dev, struct device_attribute *attr, char *page)
11111 struct pmu *pmu = dev_get_drvdata(dev);
11113 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11115 static DEVICE_ATTR_RO(type);
11118 perf_event_mux_interval_ms_show(struct device *dev,
11119 struct device_attribute *attr,
11122 struct pmu *pmu = dev_get_drvdata(dev);
11124 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11127 static DEFINE_MUTEX(mux_interval_mutex);
11130 perf_event_mux_interval_ms_store(struct device *dev,
11131 struct device_attribute *attr,
11132 const char *buf, size_t count)
11134 struct pmu *pmu = dev_get_drvdata(dev);
11135 int timer, cpu, ret;
11137 ret = kstrtoint(buf, 0, &timer);
11144 /* same value, noting to do */
11145 if (timer == pmu->hrtimer_interval_ms)
11148 mutex_lock(&mux_interval_mutex);
11149 pmu->hrtimer_interval_ms = timer;
11151 /* update all cpuctx for this PMU */
11153 for_each_online_cpu(cpu) {
11154 struct perf_cpu_context *cpuctx;
11155 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11156 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11158 cpu_function_call(cpu,
11159 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
11161 cpus_read_unlock();
11162 mutex_unlock(&mux_interval_mutex);
11166 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11168 static struct attribute *pmu_dev_attrs[] = {
11169 &dev_attr_type.attr,
11170 &dev_attr_perf_event_mux_interval_ms.attr,
11173 ATTRIBUTE_GROUPS(pmu_dev);
11175 static int pmu_bus_running;
11176 static struct bus_type pmu_bus = {
11177 .name = "event_source",
11178 .dev_groups = pmu_dev_groups,
11181 static void pmu_dev_release(struct device *dev)
11186 static int pmu_dev_alloc(struct pmu *pmu)
11190 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11194 pmu->dev->groups = pmu->attr_groups;
11195 device_initialize(pmu->dev);
11197 dev_set_drvdata(pmu->dev, pmu);
11198 pmu->dev->bus = &pmu_bus;
11199 pmu->dev->release = pmu_dev_release;
11201 ret = dev_set_name(pmu->dev, "%s", pmu->name);
11205 ret = device_add(pmu->dev);
11209 /* For PMUs with address filters, throw in an extra attribute: */
11210 if (pmu->nr_addr_filters)
11211 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
11216 if (pmu->attr_update)
11217 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11226 device_del(pmu->dev);
11229 put_device(pmu->dev);
11233 static struct lock_class_key cpuctx_mutex;
11234 static struct lock_class_key cpuctx_lock;
11236 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11238 int cpu, ret, max = PERF_TYPE_MAX;
11240 mutex_lock(&pmus_lock);
11242 pmu->pmu_disable_count = alloc_percpu(int);
11243 if (!pmu->pmu_disable_count)
11251 if (type != PERF_TYPE_SOFTWARE) {
11255 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
11259 WARN_ON(type >= 0 && ret != type);
11265 if (pmu_bus_running) {
11266 ret = pmu_dev_alloc(pmu);
11272 if (pmu->task_ctx_nr == perf_hw_context) {
11273 static int hw_context_taken = 0;
11276 * Other than systems with heterogeneous CPUs, it never makes
11277 * sense for two PMUs to share perf_hw_context. PMUs which are
11278 * uncore must use perf_invalid_context.
11280 if (WARN_ON_ONCE(hw_context_taken &&
11281 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
11282 pmu->task_ctx_nr = perf_invalid_context;
11284 hw_context_taken = 1;
11287 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
11288 if (pmu->pmu_cpu_context)
11289 goto got_cpu_context;
11292 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
11293 if (!pmu->pmu_cpu_context)
11296 for_each_possible_cpu(cpu) {
11297 struct perf_cpu_context *cpuctx;
11299 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11300 __perf_event_init_context(&cpuctx->ctx);
11301 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
11302 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
11303 cpuctx->ctx.pmu = pmu;
11304 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
11306 __perf_mux_hrtimer_init(cpuctx, cpu);
11308 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
11309 cpuctx->heap = cpuctx->heap_default;
11313 if (!pmu->start_txn) {
11314 if (pmu->pmu_enable) {
11316 * If we have pmu_enable/pmu_disable calls, install
11317 * transaction stubs that use that to try and batch
11318 * hardware accesses.
11320 pmu->start_txn = perf_pmu_start_txn;
11321 pmu->commit_txn = perf_pmu_commit_txn;
11322 pmu->cancel_txn = perf_pmu_cancel_txn;
11324 pmu->start_txn = perf_pmu_nop_txn;
11325 pmu->commit_txn = perf_pmu_nop_int;
11326 pmu->cancel_txn = perf_pmu_nop_void;
11330 if (!pmu->pmu_enable) {
11331 pmu->pmu_enable = perf_pmu_nop_void;
11332 pmu->pmu_disable = perf_pmu_nop_void;
11335 if (!pmu->check_period)
11336 pmu->check_period = perf_event_nop_int;
11338 if (!pmu->event_idx)
11339 pmu->event_idx = perf_event_idx_default;
11342 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
11343 * since these cannot be in the IDR. This way the linear search
11344 * is fast, provided a valid software event is provided.
11346 if (type == PERF_TYPE_SOFTWARE || !name)
11347 list_add_rcu(&pmu->entry, &pmus);
11349 list_add_tail_rcu(&pmu->entry, &pmus);
11351 atomic_set(&pmu->exclusive_cnt, 0);
11354 mutex_unlock(&pmus_lock);
11359 device_del(pmu->dev);
11360 put_device(pmu->dev);
11363 if (pmu->type != PERF_TYPE_SOFTWARE)
11364 idr_remove(&pmu_idr, pmu->type);
11367 free_percpu(pmu->pmu_disable_count);
11370 EXPORT_SYMBOL_GPL(perf_pmu_register);
11372 void perf_pmu_unregister(struct pmu *pmu)
11374 mutex_lock(&pmus_lock);
11375 list_del_rcu(&pmu->entry);
11378 * We dereference the pmu list under both SRCU and regular RCU, so
11379 * synchronize against both of those.
11381 synchronize_srcu(&pmus_srcu);
11384 free_percpu(pmu->pmu_disable_count);
11385 if (pmu->type != PERF_TYPE_SOFTWARE)
11386 idr_remove(&pmu_idr, pmu->type);
11387 if (pmu_bus_running) {
11388 if (pmu->nr_addr_filters)
11389 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11390 device_del(pmu->dev);
11391 put_device(pmu->dev);
11393 free_pmu_context(pmu);
11394 mutex_unlock(&pmus_lock);
11396 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11398 static inline bool has_extended_regs(struct perf_event *event)
11400 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11401 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11404 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11406 struct perf_event_context *ctx = NULL;
11409 if (!try_module_get(pmu->module))
11413 * A number of pmu->event_init() methods iterate the sibling_list to,
11414 * for example, validate if the group fits on the PMU. Therefore,
11415 * if this is a sibling event, acquire the ctx->mutex to protect
11416 * the sibling_list.
11418 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11420 * This ctx->mutex can nest when we're called through
11421 * inheritance. See the perf_event_ctx_lock_nested() comment.
11423 ctx = perf_event_ctx_lock_nested(event->group_leader,
11424 SINGLE_DEPTH_NESTING);
11429 ret = pmu->event_init(event);
11432 perf_event_ctx_unlock(event->group_leader, ctx);
11435 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11436 has_extended_regs(event))
11439 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11440 event_has_any_exclude_flag(event))
11443 if (ret && event->destroy)
11444 event->destroy(event);
11448 module_put(pmu->module);
11453 static struct pmu *perf_init_event(struct perf_event *event)
11455 bool extended_type = false;
11456 int idx, type, ret;
11459 idx = srcu_read_lock(&pmus_srcu);
11461 /* Try parent's PMU first: */
11462 if (event->parent && event->parent->pmu) {
11463 pmu = event->parent->pmu;
11464 ret = perf_try_init_event(pmu, event);
11470 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11471 * are often aliases for PERF_TYPE_RAW.
11473 type = event->attr.type;
11474 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
11475 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
11477 type = PERF_TYPE_RAW;
11479 extended_type = true;
11480 event->attr.config &= PERF_HW_EVENT_MASK;
11486 pmu = idr_find(&pmu_idr, type);
11489 if (event->attr.type != type && type != PERF_TYPE_RAW &&
11490 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
11493 ret = perf_try_init_event(pmu, event);
11494 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
11495 type = event->attr.type;
11500 pmu = ERR_PTR(ret);
11505 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11506 ret = perf_try_init_event(pmu, event);
11510 if (ret != -ENOENT) {
11511 pmu = ERR_PTR(ret);
11516 pmu = ERR_PTR(-ENOENT);
11518 srcu_read_unlock(&pmus_srcu, idx);
11523 static void attach_sb_event(struct perf_event *event)
11525 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11527 raw_spin_lock(&pel->lock);
11528 list_add_rcu(&event->sb_list, &pel->list);
11529 raw_spin_unlock(&pel->lock);
11533 * We keep a list of all !task (and therefore per-cpu) events
11534 * that need to receive side-band records.
11536 * This avoids having to scan all the various PMU per-cpu contexts
11537 * looking for them.
11539 static void account_pmu_sb_event(struct perf_event *event)
11541 if (is_sb_event(event))
11542 attach_sb_event(event);
11545 static void account_event_cpu(struct perf_event *event, int cpu)
11550 if (is_cgroup_event(event))
11551 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11554 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11555 static void account_freq_event_nohz(void)
11557 #ifdef CONFIG_NO_HZ_FULL
11558 /* Lock so we don't race with concurrent unaccount */
11559 spin_lock(&nr_freq_lock);
11560 if (atomic_inc_return(&nr_freq_events) == 1)
11561 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11562 spin_unlock(&nr_freq_lock);
11566 static void account_freq_event(void)
11568 if (tick_nohz_full_enabled())
11569 account_freq_event_nohz();
11571 atomic_inc(&nr_freq_events);
11575 static void account_event(struct perf_event *event)
11582 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11584 if (event->attr.mmap || event->attr.mmap_data)
11585 atomic_inc(&nr_mmap_events);
11586 if (event->attr.build_id)
11587 atomic_inc(&nr_build_id_events);
11588 if (event->attr.comm)
11589 atomic_inc(&nr_comm_events);
11590 if (event->attr.namespaces)
11591 atomic_inc(&nr_namespaces_events);
11592 if (event->attr.cgroup)
11593 atomic_inc(&nr_cgroup_events);
11594 if (event->attr.task)
11595 atomic_inc(&nr_task_events);
11596 if (event->attr.freq)
11597 account_freq_event();
11598 if (event->attr.context_switch) {
11599 atomic_inc(&nr_switch_events);
11602 if (has_branch_stack(event))
11604 if (is_cgroup_event(event))
11606 if (event->attr.ksymbol)
11607 atomic_inc(&nr_ksymbol_events);
11608 if (event->attr.bpf_event)
11609 atomic_inc(&nr_bpf_events);
11610 if (event->attr.text_poke)
11611 atomic_inc(&nr_text_poke_events);
11615 * We need the mutex here because static_branch_enable()
11616 * must complete *before* the perf_sched_count increment
11619 if (atomic_inc_not_zero(&perf_sched_count))
11622 mutex_lock(&perf_sched_mutex);
11623 if (!atomic_read(&perf_sched_count)) {
11624 static_branch_enable(&perf_sched_events);
11626 * Guarantee that all CPUs observe they key change and
11627 * call the perf scheduling hooks before proceeding to
11628 * install events that need them.
11633 * Now that we have waited for the sync_sched(), allow further
11634 * increments to by-pass the mutex.
11636 atomic_inc(&perf_sched_count);
11637 mutex_unlock(&perf_sched_mutex);
11641 account_event_cpu(event, event->cpu);
11643 account_pmu_sb_event(event);
11647 * Allocate and initialize an event structure
11649 static struct perf_event *
11650 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11651 struct task_struct *task,
11652 struct perf_event *group_leader,
11653 struct perf_event *parent_event,
11654 perf_overflow_handler_t overflow_handler,
11655 void *context, int cgroup_fd)
11658 struct perf_event *event;
11659 struct hw_perf_event *hwc;
11660 long err = -EINVAL;
11663 if ((unsigned)cpu >= nr_cpu_ids) {
11664 if (!task || cpu != -1)
11665 return ERR_PTR(-EINVAL);
11667 if (attr->sigtrap && !task) {
11668 /* Requires a task: avoid signalling random tasks. */
11669 return ERR_PTR(-EINVAL);
11672 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11673 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11676 return ERR_PTR(-ENOMEM);
11679 * Single events are their own group leaders, with an
11680 * empty sibling list:
11683 group_leader = event;
11685 mutex_init(&event->child_mutex);
11686 INIT_LIST_HEAD(&event->child_list);
11688 INIT_LIST_HEAD(&event->event_entry);
11689 INIT_LIST_HEAD(&event->sibling_list);
11690 INIT_LIST_HEAD(&event->active_list);
11691 init_event_group(event);
11692 INIT_LIST_HEAD(&event->rb_entry);
11693 INIT_LIST_HEAD(&event->active_entry);
11694 INIT_LIST_HEAD(&event->addr_filters.list);
11695 INIT_HLIST_NODE(&event->hlist_entry);
11698 init_waitqueue_head(&event->waitq);
11699 init_irq_work(&event->pending_irq, perf_pending_irq);
11700 init_task_work(&event->pending_task, perf_pending_task);
11702 mutex_init(&event->mmap_mutex);
11703 raw_spin_lock_init(&event->addr_filters.lock);
11705 atomic_long_set(&event->refcount, 1);
11707 event->attr = *attr;
11708 event->group_leader = group_leader;
11712 event->parent = parent_event;
11714 event->ns = get_pid_ns(task_active_pid_ns(current));
11715 event->id = atomic64_inc_return(&perf_event_id);
11717 event->state = PERF_EVENT_STATE_INACTIVE;
11720 event->event_caps = parent_event->event_caps;
11723 event->attach_state = PERF_ATTACH_TASK;
11725 * XXX pmu::event_init needs to know what task to account to
11726 * and we cannot use the ctx information because we need the
11727 * pmu before we get a ctx.
11729 event->hw.target = get_task_struct(task);
11732 event->clock = &local_clock;
11734 event->clock = parent_event->clock;
11736 if (!overflow_handler && parent_event) {
11737 overflow_handler = parent_event->overflow_handler;
11738 context = parent_event->overflow_handler_context;
11739 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11740 if (overflow_handler == bpf_overflow_handler) {
11741 struct bpf_prog *prog = parent_event->prog;
11743 bpf_prog_inc(prog);
11744 event->prog = prog;
11745 event->orig_overflow_handler =
11746 parent_event->orig_overflow_handler;
11751 if (overflow_handler) {
11752 event->overflow_handler = overflow_handler;
11753 event->overflow_handler_context = context;
11754 } else if (is_write_backward(event)){
11755 event->overflow_handler = perf_event_output_backward;
11756 event->overflow_handler_context = NULL;
11758 event->overflow_handler = perf_event_output_forward;
11759 event->overflow_handler_context = NULL;
11762 perf_event__state_init(event);
11767 hwc->sample_period = attr->sample_period;
11768 if (attr->freq && attr->sample_freq)
11769 hwc->sample_period = 1;
11770 hwc->last_period = hwc->sample_period;
11772 local64_set(&hwc->period_left, hwc->sample_period);
11775 * We currently do not support PERF_SAMPLE_READ on inherited events.
11776 * See perf_output_read().
11778 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11781 if (!has_branch_stack(event))
11782 event->attr.branch_sample_type = 0;
11784 pmu = perf_init_event(event);
11786 err = PTR_ERR(pmu);
11791 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11792 * be different on other CPUs in the uncore mask.
11794 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11799 if (event->attr.aux_output &&
11800 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11805 if (cgroup_fd != -1) {
11806 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11811 err = exclusive_event_init(event);
11815 if (has_addr_filter(event)) {
11816 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11817 sizeof(struct perf_addr_filter_range),
11819 if (!event->addr_filter_ranges) {
11825 * Clone the parent's vma offsets: they are valid until exec()
11826 * even if the mm is not shared with the parent.
11828 if (event->parent) {
11829 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11831 raw_spin_lock_irq(&ifh->lock);
11832 memcpy(event->addr_filter_ranges,
11833 event->parent->addr_filter_ranges,
11834 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11835 raw_spin_unlock_irq(&ifh->lock);
11838 /* force hw sync on the address filters */
11839 event->addr_filters_gen = 1;
11842 if (!event->parent) {
11843 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11844 err = get_callchain_buffers(attr->sample_max_stack);
11846 goto err_addr_filters;
11850 err = security_perf_event_alloc(event);
11852 goto err_callchain_buffer;
11854 /* symmetric to unaccount_event() in _free_event() */
11855 account_event(event);
11859 err_callchain_buffer:
11860 if (!event->parent) {
11861 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11862 put_callchain_buffers();
11865 kfree(event->addr_filter_ranges);
11868 exclusive_event_destroy(event);
11871 if (is_cgroup_event(event))
11872 perf_detach_cgroup(event);
11873 if (event->destroy)
11874 event->destroy(event);
11875 module_put(pmu->module);
11877 if (event->hw.target)
11878 put_task_struct(event->hw.target);
11879 call_rcu(&event->rcu_head, free_event_rcu);
11881 return ERR_PTR(err);
11884 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11885 struct perf_event_attr *attr)
11890 /* Zero the full structure, so that a short copy will be nice. */
11891 memset(attr, 0, sizeof(*attr));
11893 ret = get_user(size, &uattr->size);
11897 /* ABI compatibility quirk: */
11899 size = PERF_ATTR_SIZE_VER0;
11900 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11903 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11912 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11915 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11918 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11921 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11922 u64 mask = attr->branch_sample_type;
11924 /* only using defined bits */
11925 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11928 /* at least one branch bit must be set */
11929 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11932 /* propagate priv level, when not set for branch */
11933 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11935 /* exclude_kernel checked on syscall entry */
11936 if (!attr->exclude_kernel)
11937 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11939 if (!attr->exclude_user)
11940 mask |= PERF_SAMPLE_BRANCH_USER;
11942 if (!attr->exclude_hv)
11943 mask |= PERF_SAMPLE_BRANCH_HV;
11945 * adjust user setting (for HW filter setup)
11947 attr->branch_sample_type = mask;
11949 /* privileged levels capture (kernel, hv): check permissions */
11950 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11951 ret = perf_allow_kernel(attr);
11957 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11958 ret = perf_reg_validate(attr->sample_regs_user);
11963 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11964 if (!arch_perf_have_user_stack_dump())
11968 * We have __u32 type for the size, but so far
11969 * we can only use __u16 as maximum due to the
11970 * __u16 sample size limit.
11972 if (attr->sample_stack_user >= USHRT_MAX)
11974 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11978 if (!attr->sample_max_stack)
11979 attr->sample_max_stack = sysctl_perf_event_max_stack;
11981 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11982 ret = perf_reg_validate(attr->sample_regs_intr);
11984 #ifndef CONFIG_CGROUP_PERF
11985 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11988 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
11989 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
11992 if (!attr->inherit && attr->inherit_thread)
11995 if (attr->remove_on_exec && attr->enable_on_exec)
11998 if (attr->sigtrap && !attr->remove_on_exec)
12005 put_user(sizeof(*attr), &uattr->size);
12010 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12016 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12020 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12022 struct perf_buffer *rb = NULL;
12025 if (!output_event) {
12026 mutex_lock(&event->mmap_mutex);
12030 /* don't allow circular references */
12031 if (event == output_event)
12035 * Don't allow cross-cpu buffers
12037 if (output_event->cpu != event->cpu)
12041 * If its not a per-cpu rb, it must be the same task.
12043 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
12047 * Mixing clocks in the same buffer is trouble you don't need.
12049 if (output_event->clock != event->clock)
12053 * Either writing ring buffer from beginning or from end.
12054 * Mixing is not allowed.
12056 if (is_write_backward(output_event) != is_write_backward(event))
12060 * If both events generate aux data, they must be on the same PMU
12062 if (has_aux(event) && has_aux(output_event) &&
12063 event->pmu != output_event->pmu)
12067 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12068 * output_event is already on rb->event_list, and the list iteration
12069 * restarts after every removal, it is guaranteed this new event is
12070 * observed *OR* if output_event is already removed, it's guaranteed we
12071 * observe !rb->mmap_count.
12073 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12075 /* Can't redirect output if we've got an active mmap() */
12076 if (atomic_read(&event->mmap_count))
12079 if (output_event) {
12080 /* get the rb we want to redirect to */
12081 rb = ring_buffer_get(output_event);
12085 /* did we race against perf_mmap_close() */
12086 if (!atomic_read(&rb->mmap_count)) {
12087 ring_buffer_put(rb);
12092 ring_buffer_attach(event, rb);
12096 mutex_unlock(&event->mmap_mutex);
12098 mutex_unlock(&output_event->mmap_mutex);
12104 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12106 bool nmi_safe = false;
12109 case CLOCK_MONOTONIC:
12110 event->clock = &ktime_get_mono_fast_ns;
12114 case CLOCK_MONOTONIC_RAW:
12115 event->clock = &ktime_get_raw_fast_ns;
12119 case CLOCK_REALTIME:
12120 event->clock = &ktime_get_real_ns;
12123 case CLOCK_BOOTTIME:
12124 event->clock = &ktime_get_boottime_ns;
12128 event->clock = &ktime_get_clocktai_ns;
12135 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12142 * Variation on perf_event_ctx_lock_nested(), except we take two context
12145 static struct perf_event_context *
12146 __perf_event_ctx_lock_double(struct perf_event *group_leader,
12147 struct perf_event_context *ctx)
12149 struct perf_event_context *gctx;
12153 gctx = READ_ONCE(group_leader->ctx);
12154 if (!refcount_inc_not_zero(&gctx->refcount)) {
12160 mutex_lock_double(&gctx->mutex, &ctx->mutex);
12162 if (group_leader->ctx != gctx) {
12163 mutex_unlock(&ctx->mutex);
12164 mutex_unlock(&gctx->mutex);
12173 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12175 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12176 bool is_capable = perfmon_capable();
12178 if (attr->sigtrap) {
12180 * perf_event_attr::sigtrap sends signals to the other task.
12181 * Require the current task to also have CAP_KILL.
12184 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12188 * If the required capabilities aren't available, checks for
12189 * ptrace permissions: upgrade to ATTACH, since sending signals
12190 * can effectively change the target task.
12192 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12196 * Preserve ptrace permission check for backwards compatibility. The
12197 * ptrace check also includes checks that the current task and other
12198 * task have matching uids, and is therefore not done here explicitly.
12200 return is_capable || ptrace_may_access(task, ptrace_mode);
12204 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12206 * @attr_uptr: event_id type attributes for monitoring/sampling
12209 * @group_fd: group leader event fd
12210 * @flags: perf event open flags
12212 SYSCALL_DEFINE5(perf_event_open,
12213 struct perf_event_attr __user *, attr_uptr,
12214 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12216 struct perf_event *group_leader = NULL, *output_event = NULL;
12217 struct perf_event *event, *sibling;
12218 struct perf_event_attr attr;
12219 struct perf_event_context *ctx, *gctx;
12220 struct file *event_file = NULL;
12221 struct fd group = {NULL, 0};
12222 struct task_struct *task = NULL;
12225 int move_group = 0;
12227 int f_flags = O_RDWR;
12228 int cgroup_fd = -1;
12230 /* for future expandability... */
12231 if (flags & ~PERF_FLAG_ALL)
12234 /* Do we allow access to perf_event_open(2) ? */
12235 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12239 err = perf_copy_attr(attr_uptr, &attr);
12243 if (!attr.exclude_kernel) {
12244 err = perf_allow_kernel(&attr);
12249 if (attr.namespaces) {
12250 if (!perfmon_capable())
12255 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12258 if (attr.sample_period & (1ULL << 63))
12262 /* Only privileged users can get physical addresses */
12263 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12264 err = perf_allow_kernel(&attr);
12269 /* REGS_INTR can leak data, lockdown must prevent this */
12270 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12271 err = security_locked_down(LOCKDOWN_PERF);
12277 * In cgroup mode, the pid argument is used to pass the fd
12278 * opened to the cgroup directory in cgroupfs. The cpu argument
12279 * designates the cpu on which to monitor threads from that
12282 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12285 if (flags & PERF_FLAG_FD_CLOEXEC)
12286 f_flags |= O_CLOEXEC;
12288 event_fd = get_unused_fd_flags(f_flags);
12292 if (group_fd != -1) {
12293 err = perf_fget_light(group_fd, &group);
12296 group_leader = group.file->private_data;
12297 if (flags & PERF_FLAG_FD_OUTPUT)
12298 output_event = group_leader;
12299 if (flags & PERF_FLAG_FD_NO_GROUP)
12300 group_leader = NULL;
12303 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12304 task = find_lively_task_by_vpid(pid);
12305 if (IS_ERR(task)) {
12306 err = PTR_ERR(task);
12311 if (task && group_leader &&
12312 group_leader->attr.inherit != attr.inherit) {
12317 if (flags & PERF_FLAG_PID_CGROUP)
12320 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12321 NULL, NULL, cgroup_fd);
12322 if (IS_ERR(event)) {
12323 err = PTR_ERR(event);
12327 if (is_sampling_event(event)) {
12328 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12335 * Special case software events and allow them to be part of
12336 * any hardware group.
12340 if (attr.use_clockid) {
12341 err = perf_event_set_clock(event, attr.clockid);
12346 if (pmu->task_ctx_nr == perf_sw_context)
12347 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12349 if (group_leader) {
12350 if (is_software_event(event) &&
12351 !in_software_context(group_leader)) {
12353 * If the event is a sw event, but the group_leader
12354 * is on hw context.
12356 * Allow the addition of software events to hw
12357 * groups, this is safe because software events
12358 * never fail to schedule.
12360 pmu = group_leader->ctx->pmu;
12361 } else if (!is_software_event(event) &&
12362 is_software_event(group_leader) &&
12363 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12365 * In case the group is a pure software group, and we
12366 * try to add a hardware event, move the whole group to
12367 * the hardware context.
12374 * Get the target context (task or percpu):
12376 ctx = find_get_context(pmu, task, event);
12378 err = PTR_ERR(ctx);
12383 * Look up the group leader (we will attach this event to it):
12385 if (group_leader) {
12389 * Do not allow a recursive hierarchy (this new sibling
12390 * becoming part of another group-sibling):
12392 if (group_leader->group_leader != group_leader)
12395 /* All events in a group should have the same clock */
12396 if (group_leader->clock != event->clock)
12400 * Make sure we're both events for the same CPU;
12401 * grouping events for different CPUs is broken; since
12402 * you can never concurrently schedule them anyhow.
12404 if (group_leader->cpu != event->cpu)
12408 * Make sure we're both on the same task, or both
12411 if (group_leader->ctx->task != ctx->task)
12415 * Do not allow to attach to a group in a different task
12416 * or CPU context. If we're moving SW events, we'll fix
12417 * this up later, so allow that.
12419 * Racy, not holding group_leader->ctx->mutex, see comment with
12420 * perf_event_ctx_lock().
12422 if (!move_group && group_leader->ctx != ctx)
12426 * Only a group leader can be exclusive or pinned
12428 if (attr.exclusive || attr.pinned)
12432 if (output_event) {
12433 err = perf_event_set_output(event, output_event);
12438 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
12440 if (IS_ERR(event_file)) {
12441 err = PTR_ERR(event_file);
12447 err = down_read_interruptible(&task->signal->exec_update_lock);
12452 * We must hold exec_update_lock across this and any potential
12453 * perf_install_in_context() call for this new event to
12454 * serialize against exec() altering our credentials (and the
12455 * perf_event_exit_task() that could imply).
12458 if (!perf_check_permission(&attr, task))
12463 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12465 if (gctx->task == TASK_TOMBSTONE) {
12471 * Check if we raced against another sys_perf_event_open() call
12472 * moving the software group underneath us.
12474 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12476 * If someone moved the group out from under us, check
12477 * if this new event wound up on the same ctx, if so
12478 * its the regular !move_group case, otherwise fail.
12484 perf_event_ctx_unlock(group_leader, gctx);
12486 goto not_move_group;
12491 * Failure to create exclusive events returns -EBUSY.
12494 if (!exclusive_event_installable(group_leader, ctx))
12497 for_each_sibling_event(sibling, group_leader) {
12498 if (!exclusive_event_installable(sibling, ctx))
12502 mutex_lock(&ctx->mutex);
12505 * Now that we hold ctx->lock, (re)validate group_leader->ctx == ctx,
12506 * see the group_leader && !move_group test earlier.
12508 if (group_leader && group_leader->ctx != ctx) {
12515 if (ctx->task == TASK_TOMBSTONE) {
12520 if (!perf_event_validate_size(event)) {
12527 * Check if the @cpu we're creating an event for is online.
12529 * We use the perf_cpu_context::ctx::mutex to serialize against
12530 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12532 struct perf_cpu_context *cpuctx =
12533 container_of(ctx, struct perf_cpu_context, ctx);
12535 if (!cpuctx->online) {
12541 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12547 * Must be under the same ctx::mutex as perf_install_in_context(),
12548 * because we need to serialize with concurrent event creation.
12550 if (!exclusive_event_installable(event, ctx)) {
12555 WARN_ON_ONCE(ctx->parent_ctx);
12558 * This is the point on no return; we cannot fail hereafter. This is
12559 * where we start modifying current state.
12564 * See perf_event_ctx_lock() for comments on the details
12565 * of swizzling perf_event::ctx.
12567 perf_remove_from_context(group_leader, 0);
12570 for_each_sibling_event(sibling, group_leader) {
12571 perf_remove_from_context(sibling, 0);
12576 * Wait for everybody to stop referencing the events through
12577 * the old lists, before installing it on new lists.
12582 * Install the group siblings before the group leader.
12584 * Because a group leader will try and install the entire group
12585 * (through the sibling list, which is still in-tact), we can
12586 * end up with siblings installed in the wrong context.
12588 * By installing siblings first we NO-OP because they're not
12589 * reachable through the group lists.
12591 for_each_sibling_event(sibling, group_leader) {
12592 perf_event__state_init(sibling);
12593 perf_install_in_context(ctx, sibling, sibling->cpu);
12598 * Removing from the context ends up with disabled
12599 * event. What we want here is event in the initial
12600 * startup state, ready to be add into new context.
12602 perf_event__state_init(group_leader);
12603 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12608 * Precalculate sample_data sizes; do while holding ctx::mutex such
12609 * that we're serialized against further additions and before
12610 * perf_install_in_context() which is the point the event is active and
12611 * can use these values.
12613 perf_event__header_size(event);
12614 perf_event__id_header_size(event);
12616 event->owner = current;
12618 perf_install_in_context(ctx, event, event->cpu);
12619 perf_unpin_context(ctx);
12622 perf_event_ctx_unlock(group_leader, gctx);
12623 mutex_unlock(&ctx->mutex);
12626 up_read(&task->signal->exec_update_lock);
12627 put_task_struct(task);
12630 mutex_lock(¤t->perf_event_mutex);
12631 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12632 mutex_unlock(¤t->perf_event_mutex);
12635 * Drop the reference on the group_event after placing the
12636 * new event on the sibling_list. This ensures destruction
12637 * of the group leader will find the pointer to itself in
12638 * perf_group_detach().
12641 fd_install(event_fd, event_file);
12646 perf_event_ctx_unlock(group_leader, gctx);
12647 mutex_unlock(&ctx->mutex);
12650 up_read(&task->signal->exec_update_lock);
12654 perf_unpin_context(ctx);
12658 * If event_file is set, the fput() above will have called ->release()
12659 * and that will take care of freeing the event.
12665 put_task_struct(task);
12669 put_unused_fd(event_fd);
12674 * perf_event_create_kernel_counter
12676 * @attr: attributes of the counter to create
12677 * @cpu: cpu in which the counter is bound
12678 * @task: task to profile (NULL for percpu)
12679 * @overflow_handler: callback to trigger when we hit the event
12680 * @context: context data could be used in overflow_handler callback
12682 struct perf_event *
12683 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12684 struct task_struct *task,
12685 perf_overflow_handler_t overflow_handler,
12688 struct perf_event_context *ctx;
12689 struct perf_event *event;
12693 * Grouping is not supported for kernel events, neither is 'AUX',
12694 * make sure the caller's intentions are adjusted.
12696 if (attr->aux_output)
12697 return ERR_PTR(-EINVAL);
12699 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12700 overflow_handler, context, -1);
12701 if (IS_ERR(event)) {
12702 err = PTR_ERR(event);
12706 /* Mark owner so we could distinguish it from user events. */
12707 event->owner = TASK_TOMBSTONE;
12710 * Get the target context (task or percpu):
12712 ctx = find_get_context(event->pmu, task, event);
12714 err = PTR_ERR(ctx);
12718 WARN_ON_ONCE(ctx->parent_ctx);
12719 mutex_lock(&ctx->mutex);
12720 if (ctx->task == TASK_TOMBSTONE) {
12727 * Check if the @cpu we're creating an event for is online.
12729 * We use the perf_cpu_context::ctx::mutex to serialize against
12730 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12732 struct perf_cpu_context *cpuctx =
12733 container_of(ctx, struct perf_cpu_context, ctx);
12734 if (!cpuctx->online) {
12740 if (!exclusive_event_installable(event, ctx)) {
12745 perf_install_in_context(ctx, event, event->cpu);
12746 perf_unpin_context(ctx);
12747 mutex_unlock(&ctx->mutex);
12752 mutex_unlock(&ctx->mutex);
12753 perf_unpin_context(ctx);
12758 return ERR_PTR(err);
12760 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12762 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12764 struct perf_event_context *src_ctx;
12765 struct perf_event_context *dst_ctx;
12766 struct perf_event *event, *tmp;
12769 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12770 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12773 * See perf_event_ctx_lock() for comments on the details
12774 * of swizzling perf_event::ctx.
12776 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12777 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12779 perf_remove_from_context(event, 0);
12780 unaccount_event_cpu(event, src_cpu);
12782 list_add(&event->migrate_entry, &events);
12786 * Wait for the events to quiesce before re-instating them.
12791 * Re-instate events in 2 passes.
12793 * Skip over group leaders and only install siblings on this first
12794 * pass, siblings will not get enabled without a leader, however a
12795 * leader will enable its siblings, even if those are still on the old
12798 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12799 if (event->group_leader == event)
12802 list_del(&event->migrate_entry);
12803 if (event->state >= PERF_EVENT_STATE_OFF)
12804 event->state = PERF_EVENT_STATE_INACTIVE;
12805 account_event_cpu(event, dst_cpu);
12806 perf_install_in_context(dst_ctx, event, dst_cpu);
12811 * Once all the siblings are setup properly, install the group leaders
12814 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12815 list_del(&event->migrate_entry);
12816 if (event->state >= PERF_EVENT_STATE_OFF)
12817 event->state = PERF_EVENT_STATE_INACTIVE;
12818 account_event_cpu(event, dst_cpu);
12819 perf_install_in_context(dst_ctx, event, dst_cpu);
12822 mutex_unlock(&dst_ctx->mutex);
12823 mutex_unlock(&src_ctx->mutex);
12825 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12827 static void sync_child_event(struct perf_event *child_event)
12829 struct perf_event *parent_event = child_event->parent;
12832 if (child_event->attr.inherit_stat) {
12833 struct task_struct *task = child_event->ctx->task;
12835 if (task && task != TASK_TOMBSTONE)
12836 perf_event_read_event(child_event, task);
12839 child_val = perf_event_count(child_event);
12842 * Add back the child's count to the parent's count:
12844 atomic64_add(child_val, &parent_event->child_count);
12845 atomic64_add(child_event->total_time_enabled,
12846 &parent_event->child_total_time_enabled);
12847 atomic64_add(child_event->total_time_running,
12848 &parent_event->child_total_time_running);
12852 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
12854 struct perf_event *parent_event = event->parent;
12855 unsigned long detach_flags = 0;
12857 if (parent_event) {
12859 * Do not destroy the 'original' grouping; because of the
12860 * context switch optimization the original events could've
12861 * ended up in a random child task.
12863 * If we were to destroy the original group, all group related
12864 * operations would cease to function properly after this
12865 * random child dies.
12867 * Do destroy all inherited groups, we don't care about those
12868 * and being thorough is better.
12870 detach_flags = DETACH_GROUP | DETACH_CHILD;
12871 mutex_lock(&parent_event->child_mutex);
12874 perf_remove_from_context(event, detach_flags);
12876 raw_spin_lock_irq(&ctx->lock);
12877 if (event->state > PERF_EVENT_STATE_EXIT)
12878 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
12879 raw_spin_unlock_irq(&ctx->lock);
12882 * Child events can be freed.
12884 if (parent_event) {
12885 mutex_unlock(&parent_event->child_mutex);
12887 * Kick perf_poll() for is_event_hup();
12889 perf_event_wakeup(parent_event);
12891 put_event(parent_event);
12896 * Parent events are governed by their filedesc, retain them.
12898 perf_event_wakeup(event);
12901 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12903 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12904 struct perf_event *child_event, *next;
12906 WARN_ON_ONCE(child != current);
12908 child_ctx = perf_pin_task_context(child, ctxn);
12913 * In order to reduce the amount of tricky in ctx tear-down, we hold
12914 * ctx::mutex over the entire thing. This serializes against almost
12915 * everything that wants to access the ctx.
12917 * The exception is sys_perf_event_open() /
12918 * perf_event_create_kernel_count() which does find_get_context()
12919 * without ctx::mutex (it cannot because of the move_group double mutex
12920 * lock thing). See the comments in perf_install_in_context().
12922 mutex_lock(&child_ctx->mutex);
12925 * In a single ctx::lock section, de-schedule the events and detach the
12926 * context from the task such that we cannot ever get it scheduled back
12929 raw_spin_lock_irq(&child_ctx->lock);
12930 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12933 * Now that the context is inactive, destroy the task <-> ctx relation
12934 * and mark the context dead.
12936 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12937 put_ctx(child_ctx); /* cannot be last */
12938 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12939 put_task_struct(current); /* cannot be last */
12941 clone_ctx = unclone_ctx(child_ctx);
12942 raw_spin_unlock_irq(&child_ctx->lock);
12945 put_ctx(clone_ctx);
12948 * Report the task dead after unscheduling the events so that we
12949 * won't get any samples after PERF_RECORD_EXIT. We can however still
12950 * get a few PERF_RECORD_READ events.
12952 perf_event_task(child, child_ctx, 0);
12954 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12955 perf_event_exit_event(child_event, child_ctx);
12957 mutex_unlock(&child_ctx->mutex);
12959 put_ctx(child_ctx);
12963 * When a child task exits, feed back event values to parent events.
12965 * Can be called with exec_update_lock held when called from
12966 * setup_new_exec().
12968 void perf_event_exit_task(struct task_struct *child)
12970 struct perf_event *event, *tmp;
12973 mutex_lock(&child->perf_event_mutex);
12974 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12976 list_del_init(&event->owner_entry);
12979 * Ensure the list deletion is visible before we clear
12980 * the owner, closes a race against perf_release() where
12981 * we need to serialize on the owner->perf_event_mutex.
12983 smp_store_release(&event->owner, NULL);
12985 mutex_unlock(&child->perf_event_mutex);
12987 for_each_task_context_nr(ctxn)
12988 perf_event_exit_task_context(child, ctxn);
12991 * The perf_event_exit_task_context calls perf_event_task
12992 * with child's task_ctx, which generates EXIT events for
12993 * child contexts and sets child->perf_event_ctxp[] to NULL.
12994 * At this point we need to send EXIT events to cpu contexts.
12996 perf_event_task(child, NULL, 0);
12999 static void perf_free_event(struct perf_event *event,
13000 struct perf_event_context *ctx)
13002 struct perf_event *parent = event->parent;
13004 if (WARN_ON_ONCE(!parent))
13007 mutex_lock(&parent->child_mutex);
13008 list_del_init(&event->child_list);
13009 mutex_unlock(&parent->child_mutex);
13013 raw_spin_lock_irq(&ctx->lock);
13014 perf_group_detach(event);
13015 list_del_event(event, ctx);
13016 raw_spin_unlock_irq(&ctx->lock);
13021 * Free a context as created by inheritance by perf_event_init_task() below,
13022 * used by fork() in case of fail.
13024 * Even though the task has never lived, the context and events have been
13025 * exposed through the child_list, so we must take care tearing it all down.
13027 void perf_event_free_task(struct task_struct *task)
13029 struct perf_event_context *ctx;
13030 struct perf_event *event, *tmp;
13033 for_each_task_context_nr(ctxn) {
13034 ctx = task->perf_event_ctxp[ctxn];
13038 mutex_lock(&ctx->mutex);
13039 raw_spin_lock_irq(&ctx->lock);
13041 * Destroy the task <-> ctx relation and mark the context dead.
13043 * This is important because even though the task hasn't been
13044 * exposed yet the context has been (through child_list).
13046 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
13047 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13048 put_task_struct(task); /* cannot be last */
13049 raw_spin_unlock_irq(&ctx->lock);
13051 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13052 perf_free_event(event, ctx);
13054 mutex_unlock(&ctx->mutex);
13057 * perf_event_release_kernel() could've stolen some of our
13058 * child events and still have them on its free_list. In that
13059 * case we must wait for these events to have been freed (in
13060 * particular all their references to this task must've been
13063 * Without this copy_process() will unconditionally free this
13064 * task (irrespective of its reference count) and
13065 * _free_event()'s put_task_struct(event->hw.target) will be a
13068 * Wait for all events to drop their context reference.
13070 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13071 put_ctx(ctx); /* must be last */
13075 void perf_event_delayed_put(struct task_struct *task)
13079 for_each_task_context_nr(ctxn)
13080 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
13083 struct file *perf_event_get(unsigned int fd)
13085 struct file *file = fget(fd);
13087 return ERR_PTR(-EBADF);
13089 if (file->f_op != &perf_fops) {
13091 return ERR_PTR(-EBADF);
13097 const struct perf_event *perf_get_event(struct file *file)
13099 if (file->f_op != &perf_fops)
13100 return ERR_PTR(-EINVAL);
13102 return file->private_data;
13105 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13108 return ERR_PTR(-EINVAL);
13110 return &event->attr;
13114 * Inherit an event from parent task to child task.
13117 * - valid pointer on success
13118 * - NULL for orphaned events
13119 * - IS_ERR() on error
13121 static struct perf_event *
13122 inherit_event(struct perf_event *parent_event,
13123 struct task_struct *parent,
13124 struct perf_event_context *parent_ctx,
13125 struct task_struct *child,
13126 struct perf_event *group_leader,
13127 struct perf_event_context *child_ctx)
13129 enum perf_event_state parent_state = parent_event->state;
13130 struct perf_event *child_event;
13131 unsigned long flags;
13134 * Instead of creating recursive hierarchies of events,
13135 * we link inherited events back to the original parent,
13136 * which has a filp for sure, which we use as the reference
13139 if (parent_event->parent)
13140 parent_event = parent_event->parent;
13142 child_event = perf_event_alloc(&parent_event->attr,
13145 group_leader, parent_event,
13147 if (IS_ERR(child_event))
13148 return child_event;
13151 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
13152 !child_ctx->task_ctx_data) {
13153 struct pmu *pmu = child_event->pmu;
13155 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
13156 if (!child_ctx->task_ctx_data) {
13157 free_event(child_event);
13158 return ERR_PTR(-ENOMEM);
13163 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13164 * must be under the same lock in order to serialize against
13165 * perf_event_release_kernel(), such that either we must observe
13166 * is_orphaned_event() or they will observe us on the child_list.
13168 mutex_lock(&parent_event->child_mutex);
13169 if (is_orphaned_event(parent_event) ||
13170 !atomic_long_inc_not_zero(&parent_event->refcount)) {
13171 mutex_unlock(&parent_event->child_mutex);
13172 /* task_ctx_data is freed with child_ctx */
13173 free_event(child_event);
13177 get_ctx(child_ctx);
13180 * Make the child state follow the state of the parent event,
13181 * not its attr.disabled bit. We hold the parent's mutex,
13182 * so we won't race with perf_event_{en, dis}able_family.
13184 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13185 child_event->state = PERF_EVENT_STATE_INACTIVE;
13187 child_event->state = PERF_EVENT_STATE_OFF;
13189 if (parent_event->attr.freq) {
13190 u64 sample_period = parent_event->hw.sample_period;
13191 struct hw_perf_event *hwc = &child_event->hw;
13193 hwc->sample_period = sample_period;
13194 hwc->last_period = sample_period;
13196 local64_set(&hwc->period_left, sample_period);
13199 child_event->ctx = child_ctx;
13200 child_event->overflow_handler = parent_event->overflow_handler;
13201 child_event->overflow_handler_context
13202 = parent_event->overflow_handler_context;
13205 * Precalculate sample_data sizes
13207 perf_event__header_size(child_event);
13208 perf_event__id_header_size(child_event);
13211 * Link it up in the child's context:
13213 raw_spin_lock_irqsave(&child_ctx->lock, flags);
13214 add_event_to_ctx(child_event, child_ctx);
13215 child_event->attach_state |= PERF_ATTACH_CHILD;
13216 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13219 * Link this into the parent event's child list
13221 list_add_tail(&child_event->child_list, &parent_event->child_list);
13222 mutex_unlock(&parent_event->child_mutex);
13224 return child_event;
13228 * Inherits an event group.
13230 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13231 * This matches with perf_event_release_kernel() removing all child events.
13237 static int inherit_group(struct perf_event *parent_event,
13238 struct task_struct *parent,
13239 struct perf_event_context *parent_ctx,
13240 struct task_struct *child,
13241 struct perf_event_context *child_ctx)
13243 struct perf_event *leader;
13244 struct perf_event *sub;
13245 struct perf_event *child_ctr;
13247 leader = inherit_event(parent_event, parent, parent_ctx,
13248 child, NULL, child_ctx);
13249 if (IS_ERR(leader))
13250 return PTR_ERR(leader);
13252 * @leader can be NULL here because of is_orphaned_event(). In this
13253 * case inherit_event() will create individual events, similar to what
13254 * perf_group_detach() would do anyway.
13256 for_each_sibling_event(sub, parent_event) {
13257 child_ctr = inherit_event(sub, parent, parent_ctx,
13258 child, leader, child_ctx);
13259 if (IS_ERR(child_ctr))
13260 return PTR_ERR(child_ctr);
13262 if (sub->aux_event == parent_event && child_ctr &&
13263 !perf_get_aux_event(child_ctr, leader))
13270 * Creates the child task context and tries to inherit the event-group.
13272 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13273 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13274 * consistent with perf_event_release_kernel() removing all child events.
13281 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13282 struct perf_event_context *parent_ctx,
13283 struct task_struct *child, int ctxn,
13284 u64 clone_flags, int *inherited_all)
13287 struct perf_event_context *child_ctx;
13289 if (!event->attr.inherit ||
13290 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13291 /* Do not inherit if sigtrap and signal handlers were cleared. */
13292 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13293 *inherited_all = 0;
13297 child_ctx = child->perf_event_ctxp[ctxn];
13300 * This is executed from the parent task context, so
13301 * inherit events that have been marked for cloning.
13302 * First allocate and initialize a context for the
13305 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
13309 child->perf_event_ctxp[ctxn] = child_ctx;
13312 ret = inherit_group(event, parent, parent_ctx,
13316 *inherited_all = 0;
13322 * Initialize the perf_event context in task_struct
13324 static int perf_event_init_context(struct task_struct *child, int ctxn,
13327 struct perf_event_context *child_ctx, *parent_ctx;
13328 struct perf_event_context *cloned_ctx;
13329 struct perf_event *event;
13330 struct task_struct *parent = current;
13331 int inherited_all = 1;
13332 unsigned long flags;
13335 if (likely(!parent->perf_event_ctxp[ctxn]))
13339 * If the parent's context is a clone, pin it so it won't get
13340 * swapped under us.
13342 parent_ctx = perf_pin_task_context(parent, ctxn);
13347 * No need to check if parent_ctx != NULL here; since we saw
13348 * it non-NULL earlier, the only reason for it to become NULL
13349 * is if we exit, and since we're currently in the middle of
13350 * a fork we can't be exiting at the same time.
13354 * Lock the parent list. No need to lock the child - not PID
13355 * hashed yet and not running, so nobody can access it.
13357 mutex_lock(&parent_ctx->mutex);
13360 * We dont have to disable NMIs - we are only looking at
13361 * the list, not manipulating it:
13363 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13364 ret = inherit_task_group(event, parent, parent_ctx,
13365 child, ctxn, clone_flags,
13372 * We can't hold ctx->lock when iterating the ->flexible_group list due
13373 * to allocations, but we need to prevent rotation because
13374 * rotate_ctx() will change the list from interrupt context.
13376 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13377 parent_ctx->rotate_disable = 1;
13378 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13380 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13381 ret = inherit_task_group(event, parent, parent_ctx,
13382 child, ctxn, clone_flags,
13388 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13389 parent_ctx->rotate_disable = 0;
13391 child_ctx = child->perf_event_ctxp[ctxn];
13393 if (child_ctx && inherited_all) {
13395 * Mark the child context as a clone of the parent
13396 * context, or of whatever the parent is a clone of.
13398 * Note that if the parent is a clone, the holding of
13399 * parent_ctx->lock avoids it from being uncloned.
13401 cloned_ctx = parent_ctx->parent_ctx;
13403 child_ctx->parent_ctx = cloned_ctx;
13404 child_ctx->parent_gen = parent_ctx->parent_gen;
13406 child_ctx->parent_ctx = parent_ctx;
13407 child_ctx->parent_gen = parent_ctx->generation;
13409 get_ctx(child_ctx->parent_ctx);
13412 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13414 mutex_unlock(&parent_ctx->mutex);
13416 perf_unpin_context(parent_ctx);
13417 put_ctx(parent_ctx);
13423 * Initialize the perf_event context in task_struct
13425 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
13429 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
13430 mutex_init(&child->perf_event_mutex);
13431 INIT_LIST_HEAD(&child->perf_event_list);
13433 for_each_task_context_nr(ctxn) {
13434 ret = perf_event_init_context(child, ctxn, clone_flags);
13436 perf_event_free_task(child);
13444 static void __init perf_event_init_all_cpus(void)
13446 struct swevent_htable *swhash;
13449 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13451 for_each_possible_cpu(cpu) {
13452 swhash = &per_cpu(swevent_htable, cpu);
13453 mutex_init(&swhash->hlist_mutex);
13454 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
13456 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13457 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13459 #ifdef CONFIG_CGROUP_PERF
13460 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13462 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13466 static void perf_swevent_init_cpu(unsigned int cpu)
13468 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13470 mutex_lock(&swhash->hlist_mutex);
13471 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13472 struct swevent_hlist *hlist;
13474 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13476 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13478 mutex_unlock(&swhash->hlist_mutex);
13481 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13482 static void __perf_event_exit_context(void *__info)
13484 struct perf_event_context *ctx = __info;
13485 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13486 struct perf_event *event;
13488 raw_spin_lock(&ctx->lock);
13489 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13490 list_for_each_entry(event, &ctx->event_list, event_entry)
13491 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13492 raw_spin_unlock(&ctx->lock);
13495 static void perf_event_exit_cpu_context(int cpu)
13497 struct perf_cpu_context *cpuctx;
13498 struct perf_event_context *ctx;
13501 mutex_lock(&pmus_lock);
13502 list_for_each_entry(pmu, &pmus, entry) {
13503 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13504 ctx = &cpuctx->ctx;
13506 mutex_lock(&ctx->mutex);
13507 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13508 cpuctx->online = 0;
13509 mutex_unlock(&ctx->mutex);
13511 cpumask_clear_cpu(cpu, perf_online_mask);
13512 mutex_unlock(&pmus_lock);
13516 static void perf_event_exit_cpu_context(int cpu) { }
13520 int perf_event_init_cpu(unsigned int cpu)
13522 struct perf_cpu_context *cpuctx;
13523 struct perf_event_context *ctx;
13526 perf_swevent_init_cpu(cpu);
13528 mutex_lock(&pmus_lock);
13529 cpumask_set_cpu(cpu, perf_online_mask);
13530 list_for_each_entry(pmu, &pmus, entry) {
13531 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13532 ctx = &cpuctx->ctx;
13534 mutex_lock(&ctx->mutex);
13535 cpuctx->online = 1;
13536 mutex_unlock(&ctx->mutex);
13538 mutex_unlock(&pmus_lock);
13543 int perf_event_exit_cpu(unsigned int cpu)
13545 perf_event_exit_cpu_context(cpu);
13550 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13554 for_each_online_cpu(cpu)
13555 perf_event_exit_cpu(cpu);
13561 * Run the perf reboot notifier at the very last possible moment so that
13562 * the generic watchdog code runs as long as possible.
13564 static struct notifier_block perf_reboot_notifier = {
13565 .notifier_call = perf_reboot,
13566 .priority = INT_MIN,
13569 void __init perf_event_init(void)
13573 idr_init(&pmu_idr);
13575 perf_event_init_all_cpus();
13576 init_srcu_struct(&pmus_srcu);
13577 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13578 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13579 perf_pmu_register(&perf_task_clock, NULL, -1);
13580 perf_tp_register();
13581 perf_event_init_cpu(smp_processor_id());
13582 register_reboot_notifier(&perf_reboot_notifier);
13584 ret = init_hw_breakpoint();
13585 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13587 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13590 * Build time assertion that we keep the data_head at the intended
13591 * location. IOW, validation we got the __reserved[] size right.
13593 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13597 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13600 struct perf_pmu_events_attr *pmu_attr =
13601 container_of(attr, struct perf_pmu_events_attr, attr);
13603 if (pmu_attr->event_str)
13604 return sprintf(page, "%s\n", pmu_attr->event_str);
13608 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13610 static int __init perf_event_sysfs_init(void)
13615 mutex_lock(&pmus_lock);
13617 ret = bus_register(&pmu_bus);
13621 list_for_each_entry(pmu, &pmus, entry) {
13622 if (!pmu->name || pmu->type < 0)
13625 ret = pmu_dev_alloc(pmu);
13626 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13628 pmu_bus_running = 1;
13632 mutex_unlock(&pmus_lock);
13636 device_initcall(perf_event_sysfs_init);
13638 #ifdef CONFIG_CGROUP_PERF
13639 static struct cgroup_subsys_state *
13640 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13642 struct perf_cgroup *jc;
13644 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13646 return ERR_PTR(-ENOMEM);
13648 jc->info = alloc_percpu(struct perf_cgroup_info);
13651 return ERR_PTR(-ENOMEM);
13657 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13659 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13661 free_percpu(jc->info);
13665 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13667 perf_event_cgroup(css->cgroup);
13671 static int __perf_cgroup_move(void *info)
13673 struct task_struct *task = info;
13675 perf_cgroup_switch(task);
13680 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13682 struct task_struct *task;
13683 struct cgroup_subsys_state *css;
13685 cgroup_taskset_for_each(task, css, tset)
13686 task_function_call(task, __perf_cgroup_move, task);
13689 struct cgroup_subsys perf_event_cgrp_subsys = {
13690 .css_alloc = perf_cgroup_css_alloc,
13691 .css_free = perf_cgroup_css_free,
13692 .css_online = perf_cgroup_css_online,
13693 .attach = perf_cgroup_attach,
13695 * Implicitly enable on dfl hierarchy so that perf events can
13696 * always be filtered by cgroup2 path as long as perf_event
13697 * controller is not mounted on a legacy hierarchy.
13699 .implicit_on_dfl = true,
13702 #endif /* CONFIG_CGROUP_PERF */
13704 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);