1 // SPDX-License-Identifier: GPL-2.0
3 * Performance events core code:
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
61 #include <asm/irq_regs.h>
63 typedef int (*remote_function_f)(void *);
65 struct remote_function_call {
66 struct task_struct *p;
67 remote_function_f func;
72 static void remote_function(void *data)
74 struct remote_function_call *tfc = data;
75 struct task_struct *p = tfc->p;
79 if (task_cpu(p) != smp_processor_id())
83 * Now that we're on right CPU with IRQs disabled, we can test
84 * if we hit the right task without races.
87 tfc->ret = -ESRCH; /* No such (running) process */
92 tfc->ret = tfc->func(tfc->info);
96 * task_function_call - call a function on the cpu on which a task runs
97 * @p: the task to evaluate
98 * @func: the function to be called
99 * @info: the function call argument
101 * Calls the function @func when the task is currently running. This might
102 * be on the current CPU, which just calls the function directly. This will
103 * retry due to any failures in smp_call_function_single(), such as if the
104 * task_cpu() goes offline concurrently.
106 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
109 task_function_call(struct task_struct *p, remote_function_f func, void *info)
111 struct remote_function_call data = {
120 ret = smp_call_function_single(task_cpu(p), remote_function,
135 * cpu_function_call - call a function on the cpu
136 * @cpu: target cpu to queue this function
137 * @func: the function to be called
138 * @info: the function call argument
140 * Calls the function @func on the remote cpu.
142 * returns: @func return value or -ENXIO when the cpu is offline
144 static int cpu_function_call(int cpu, remote_function_f func, void *info)
146 struct remote_function_call data = {
150 .ret = -ENXIO, /* No such CPU */
153 smp_call_function_single(cpu, remote_function, &data, 1);
158 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
159 struct perf_event_context *ctx)
161 raw_spin_lock(&cpuctx->ctx.lock);
163 raw_spin_lock(&ctx->lock);
166 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
167 struct perf_event_context *ctx)
170 raw_spin_unlock(&ctx->lock);
171 raw_spin_unlock(&cpuctx->ctx.lock);
174 #define TASK_TOMBSTONE ((void *)-1L)
176 static bool is_kernel_event(struct perf_event *event)
178 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
181 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
183 struct perf_event_context *perf_cpu_task_ctx(void)
185 lockdep_assert_irqs_disabled();
186 return this_cpu_ptr(&perf_cpu_context)->task_ctx;
190 * On task ctx scheduling...
192 * When !ctx->nr_events a task context will not be scheduled. This means
193 * we can disable the scheduler hooks (for performance) without leaving
194 * pending task ctx state.
196 * This however results in two special cases:
198 * - removing the last event from a task ctx; this is relatively straight
199 * forward and is done in __perf_remove_from_context.
201 * - adding the first event to a task ctx; this is tricky because we cannot
202 * rely on ctx->is_active and therefore cannot use event_function_call().
203 * See perf_install_in_context().
205 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
208 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
209 struct perf_event_context *, void *);
211 struct event_function_struct {
212 struct perf_event *event;
217 static int event_function(void *info)
219 struct event_function_struct *efs = info;
220 struct perf_event *event = efs->event;
221 struct perf_event_context *ctx = event->ctx;
222 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
223 struct perf_event_context *task_ctx = cpuctx->task_ctx;
226 lockdep_assert_irqs_disabled();
228 perf_ctx_lock(cpuctx, task_ctx);
230 * Since we do the IPI call without holding ctx->lock things can have
231 * changed, double check we hit the task we set out to hit.
234 if (ctx->task != current) {
240 * We only use event_function_call() on established contexts,
241 * and event_function() is only ever called when active (or
242 * rather, we'll have bailed in task_function_call() or the
243 * above ctx->task != current test), therefore we must have
244 * ctx->is_active here.
246 WARN_ON_ONCE(!ctx->is_active);
248 * And since we have ctx->is_active, cpuctx->task_ctx must
251 WARN_ON_ONCE(task_ctx != ctx);
253 WARN_ON_ONCE(&cpuctx->ctx != ctx);
256 efs->func(event, cpuctx, ctx, efs->data);
258 perf_ctx_unlock(cpuctx, task_ctx);
263 static void event_function_call(struct perf_event *event, event_f func, void *data)
265 struct perf_event_context *ctx = event->ctx;
266 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
267 struct event_function_struct efs = {
273 if (!event->parent) {
275 * If this is a !child event, we must hold ctx::mutex to
276 * stabilize the event->ctx relation. See
277 * perf_event_ctx_lock().
279 lockdep_assert_held(&ctx->mutex);
283 cpu_function_call(event->cpu, event_function, &efs);
287 if (task == TASK_TOMBSTONE)
291 if (!task_function_call(task, event_function, &efs))
294 raw_spin_lock_irq(&ctx->lock);
296 * Reload the task pointer, it might have been changed by
297 * a concurrent perf_event_context_sched_out().
300 if (task == TASK_TOMBSTONE) {
301 raw_spin_unlock_irq(&ctx->lock);
304 if (ctx->is_active) {
305 raw_spin_unlock_irq(&ctx->lock);
308 func(event, NULL, ctx, data);
309 raw_spin_unlock_irq(&ctx->lock);
313 * Similar to event_function_call() + event_function(), but hard assumes IRQs
314 * are already disabled and we're on the right CPU.
316 static void event_function_local(struct perf_event *event, event_f func, void *data)
318 struct perf_event_context *ctx = event->ctx;
319 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
320 struct task_struct *task = READ_ONCE(ctx->task);
321 struct perf_event_context *task_ctx = NULL;
323 lockdep_assert_irqs_disabled();
326 if (task == TASK_TOMBSTONE)
332 perf_ctx_lock(cpuctx, task_ctx);
335 if (task == TASK_TOMBSTONE)
340 * We must be either inactive or active and the right task,
341 * otherwise we're screwed, since we cannot IPI to somewhere
344 if (ctx->is_active) {
345 if (WARN_ON_ONCE(task != current))
348 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
352 WARN_ON_ONCE(&cpuctx->ctx != ctx);
355 func(event, cpuctx, ctx, data);
357 perf_ctx_unlock(cpuctx, task_ctx);
360 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
361 PERF_FLAG_FD_OUTPUT |\
362 PERF_FLAG_PID_CGROUP |\
363 PERF_FLAG_FD_CLOEXEC)
366 * branch priv levels that need permission checks
368 #define PERF_SAMPLE_BRANCH_PERM_PLM \
369 (PERF_SAMPLE_BRANCH_KERNEL |\
370 PERF_SAMPLE_BRANCH_HV)
373 EVENT_FLEXIBLE = 0x1,
376 /* see ctx_resched() for details */
379 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
383 * perf_sched_events : >0 events exist
386 static void perf_sched_delayed(struct work_struct *work);
387 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
388 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
389 static DEFINE_MUTEX(perf_sched_mutex);
390 static atomic_t perf_sched_count;
392 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
394 static atomic_t nr_mmap_events __read_mostly;
395 static atomic_t nr_comm_events __read_mostly;
396 static atomic_t nr_namespaces_events __read_mostly;
397 static atomic_t nr_task_events __read_mostly;
398 static atomic_t nr_freq_events __read_mostly;
399 static atomic_t nr_switch_events __read_mostly;
400 static atomic_t nr_ksymbol_events __read_mostly;
401 static atomic_t nr_bpf_events __read_mostly;
402 static atomic_t nr_cgroup_events __read_mostly;
403 static atomic_t nr_text_poke_events __read_mostly;
404 static atomic_t nr_build_id_events __read_mostly;
406 static LIST_HEAD(pmus);
407 static DEFINE_MUTEX(pmus_lock);
408 static struct srcu_struct pmus_srcu;
409 static cpumask_var_t perf_online_mask;
410 static struct kmem_cache *perf_event_cache;
413 * perf event paranoia level:
414 * -1 - not paranoid at all
415 * 0 - disallow raw tracepoint access for unpriv
416 * 1 - disallow cpu events for unpriv
417 * 2 - disallow kernel profiling for unpriv
419 int sysctl_perf_event_paranoid __read_mostly = 2;
421 /* Minimum for 512 kiB + 1 user control page */
422 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
425 * max perf event sample rate
427 #define DEFAULT_MAX_SAMPLE_RATE 100000
428 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
429 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
431 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
433 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
434 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
436 static int perf_sample_allowed_ns __read_mostly =
437 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
439 static void update_perf_cpu_limits(void)
441 u64 tmp = perf_sample_period_ns;
443 tmp *= sysctl_perf_cpu_time_max_percent;
444 tmp = div_u64(tmp, 100);
448 WRITE_ONCE(perf_sample_allowed_ns, tmp);
451 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
453 int perf_event_max_sample_rate_handler(struct ctl_table *table, int write,
454 void *buffer, size_t *lenp, loff_t *ppos)
457 int perf_cpu = sysctl_perf_cpu_time_max_percent;
459 * If throttling is disabled don't allow the write:
461 if (write && (perf_cpu == 100 || perf_cpu == 0))
464 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
468 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
469 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
470 update_perf_cpu_limits();
475 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
477 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
478 void *buffer, size_t *lenp, loff_t *ppos)
480 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
485 if (sysctl_perf_cpu_time_max_percent == 100 ||
486 sysctl_perf_cpu_time_max_percent == 0) {
488 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
489 WRITE_ONCE(perf_sample_allowed_ns, 0);
491 update_perf_cpu_limits();
498 * perf samples are done in some very critical code paths (NMIs).
499 * If they take too much CPU time, the system can lock up and not
500 * get any real work done. This will drop the sample rate when
501 * we detect that events are taking too long.
503 #define NR_ACCUMULATED_SAMPLES 128
504 static DEFINE_PER_CPU(u64, running_sample_length);
506 static u64 __report_avg;
507 static u64 __report_allowed;
509 static void perf_duration_warn(struct irq_work *w)
511 printk_ratelimited(KERN_INFO
512 "perf: interrupt took too long (%lld > %lld), lowering "
513 "kernel.perf_event_max_sample_rate to %d\n",
514 __report_avg, __report_allowed,
515 sysctl_perf_event_sample_rate);
518 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
520 void perf_sample_event_took(u64 sample_len_ns)
522 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
530 /* Decay the counter by 1 average sample. */
531 running_len = __this_cpu_read(running_sample_length);
532 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
533 running_len += sample_len_ns;
534 __this_cpu_write(running_sample_length, running_len);
537 * Note: this will be biased artifically low until we have
538 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
539 * from having to maintain a count.
541 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
542 if (avg_len <= max_len)
545 __report_avg = avg_len;
546 __report_allowed = max_len;
549 * Compute a throttle threshold 25% below the current duration.
551 avg_len += avg_len / 4;
552 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
558 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
559 WRITE_ONCE(max_samples_per_tick, max);
561 sysctl_perf_event_sample_rate = max * HZ;
562 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
564 if (!irq_work_queue(&perf_duration_work)) {
565 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
566 "kernel.perf_event_max_sample_rate to %d\n",
567 __report_avg, __report_allowed,
568 sysctl_perf_event_sample_rate);
572 static atomic64_t perf_event_id;
574 static void update_context_time(struct perf_event_context *ctx);
575 static u64 perf_event_time(struct perf_event *event);
577 void __weak perf_event_print_debug(void) { }
579 static inline u64 perf_clock(void)
581 return local_clock();
584 static inline u64 perf_event_clock(struct perf_event *event)
586 return event->clock();
590 * State based event timekeeping...
592 * The basic idea is to use event->state to determine which (if any) time
593 * fields to increment with the current delta. This means we only need to
594 * update timestamps when we change state or when they are explicitly requested
597 * Event groups make things a little more complicated, but not terribly so. The
598 * rules for a group are that if the group leader is OFF the entire group is
599 * OFF, irrespecive of what the group member states are. This results in
600 * __perf_effective_state().
602 * A futher ramification is that when a group leader flips between OFF and
603 * !OFF, we need to update all group member times.
606 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
607 * need to make sure the relevant context time is updated before we try and
608 * update our timestamps.
611 static __always_inline enum perf_event_state
612 __perf_effective_state(struct perf_event *event)
614 struct perf_event *leader = event->group_leader;
616 if (leader->state <= PERF_EVENT_STATE_OFF)
617 return leader->state;
622 static __always_inline void
623 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
625 enum perf_event_state state = __perf_effective_state(event);
626 u64 delta = now - event->tstamp;
628 *enabled = event->total_time_enabled;
629 if (state >= PERF_EVENT_STATE_INACTIVE)
632 *running = event->total_time_running;
633 if (state >= PERF_EVENT_STATE_ACTIVE)
637 static void perf_event_update_time(struct perf_event *event)
639 u64 now = perf_event_time(event);
641 __perf_update_times(event, now, &event->total_time_enabled,
642 &event->total_time_running);
646 static void perf_event_update_sibling_time(struct perf_event *leader)
648 struct perf_event *sibling;
650 for_each_sibling_event(sibling, leader)
651 perf_event_update_time(sibling);
655 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
657 if (event->state == state)
660 perf_event_update_time(event);
662 * If a group leader gets enabled/disabled all its siblings
665 if ((event->state < 0) ^ (state < 0))
666 perf_event_update_sibling_time(event);
668 WRITE_ONCE(event->state, state);
672 * UP store-release, load-acquire
675 #define __store_release(ptr, val) \
678 WRITE_ONCE(*(ptr), (val)); \
681 #define __load_acquire(ptr) \
683 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
688 static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
690 struct perf_event_pmu_context *pmu_ctx;
692 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
693 if (cgroup && !pmu_ctx->nr_cgroups)
695 perf_pmu_disable(pmu_ctx->pmu);
699 static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
701 struct perf_event_pmu_context *pmu_ctx;
703 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
704 if (cgroup && !pmu_ctx->nr_cgroups)
706 perf_pmu_enable(pmu_ctx->pmu);
710 static void ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type);
711 static void ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type);
713 #ifdef CONFIG_CGROUP_PERF
716 perf_cgroup_match(struct perf_event *event)
718 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
720 /* @event doesn't care about cgroup */
724 /* wants specific cgroup scope but @cpuctx isn't associated with any */
729 * Cgroup scoping is recursive. An event enabled for a cgroup is
730 * also enabled for all its descendant cgroups. If @cpuctx's
731 * cgroup is a descendant of @event's (the test covers identity
732 * case), it's a match.
734 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
735 event->cgrp->css.cgroup);
738 static inline void perf_detach_cgroup(struct perf_event *event)
740 css_put(&event->cgrp->css);
744 static inline int is_cgroup_event(struct perf_event *event)
746 return event->cgrp != NULL;
749 static inline u64 perf_cgroup_event_time(struct perf_event *event)
751 struct perf_cgroup_info *t;
753 t = per_cpu_ptr(event->cgrp->info, event->cpu);
757 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
759 struct perf_cgroup_info *t;
761 t = per_cpu_ptr(event->cgrp->info, event->cpu);
762 if (!__load_acquire(&t->active))
764 now += READ_ONCE(t->timeoffset);
768 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
771 info->time += now - info->timestamp;
772 info->timestamp = now;
774 * see update_context_time()
776 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
779 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
781 struct perf_cgroup *cgrp = cpuctx->cgrp;
782 struct cgroup_subsys_state *css;
783 struct perf_cgroup_info *info;
786 u64 now = perf_clock();
788 for (css = &cgrp->css; css; css = css->parent) {
789 cgrp = container_of(css, struct perf_cgroup, css);
790 info = this_cpu_ptr(cgrp->info);
792 __update_cgrp_time(info, now, true);
794 __store_release(&info->active, 0);
799 static inline void update_cgrp_time_from_event(struct perf_event *event)
801 struct perf_cgroup_info *info;
804 * ensure we access cgroup data only when needed and
805 * when we know the cgroup is pinned (css_get)
807 if (!is_cgroup_event(event))
810 info = this_cpu_ptr(event->cgrp->info);
812 * Do not update time when cgroup is not active
815 __update_cgrp_time(info, perf_clock(), true);
819 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
821 struct perf_event_context *ctx = &cpuctx->ctx;
822 struct perf_cgroup *cgrp = cpuctx->cgrp;
823 struct perf_cgroup_info *info;
824 struct cgroup_subsys_state *css;
827 * ctx->lock held by caller
828 * ensure we do not access cgroup data
829 * unless we have the cgroup pinned (css_get)
834 WARN_ON_ONCE(!ctx->nr_cgroups);
836 for (css = &cgrp->css; css; css = css->parent) {
837 cgrp = container_of(css, struct perf_cgroup, css);
838 info = this_cpu_ptr(cgrp->info);
839 __update_cgrp_time(info, ctx->timestamp, false);
840 __store_release(&info->active, 1);
845 * reschedule events based on the cgroup constraint of task.
847 static void perf_cgroup_switch(struct task_struct *task)
849 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
850 struct perf_cgroup *cgrp;
853 * cpuctx->cgrp is set when the first cgroup event enabled,
854 * and is cleared when the last cgroup event disabled.
856 if (READ_ONCE(cpuctx->cgrp) == NULL)
859 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
861 cgrp = perf_cgroup_from_task(task, NULL);
862 if (READ_ONCE(cpuctx->cgrp) == cgrp)
865 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
866 perf_ctx_disable(&cpuctx->ctx, true);
868 ctx_sched_out(&cpuctx->ctx, EVENT_ALL|EVENT_CGROUP);
870 * must not be done before ctxswout due
871 * to update_cgrp_time_from_cpuctx() in
876 * set cgrp before ctxsw in to allow
877 * perf_cgroup_set_timestamp() in ctx_sched_in()
878 * to not have to pass task around
880 ctx_sched_in(&cpuctx->ctx, EVENT_ALL|EVENT_CGROUP);
882 perf_ctx_enable(&cpuctx->ctx, true);
883 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
886 static int perf_cgroup_ensure_storage(struct perf_event *event,
887 struct cgroup_subsys_state *css)
889 struct perf_cpu_context *cpuctx;
890 struct perf_event **storage;
891 int cpu, heap_size, ret = 0;
894 * Allow storage to have sufficent space for an iterator for each
895 * possibly nested cgroup plus an iterator for events with no cgroup.
897 for (heap_size = 1; css; css = css->parent)
900 for_each_possible_cpu(cpu) {
901 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
902 if (heap_size <= cpuctx->heap_size)
905 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
906 GFP_KERNEL, cpu_to_node(cpu));
912 raw_spin_lock_irq(&cpuctx->ctx.lock);
913 if (cpuctx->heap_size < heap_size) {
914 swap(cpuctx->heap, storage);
915 if (storage == cpuctx->heap_default)
917 cpuctx->heap_size = heap_size;
919 raw_spin_unlock_irq(&cpuctx->ctx.lock);
927 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
928 struct perf_event_attr *attr,
929 struct perf_event *group_leader)
931 struct perf_cgroup *cgrp;
932 struct cgroup_subsys_state *css;
933 struct fd f = fdget(fd);
939 css = css_tryget_online_from_dir(f.file->f_path.dentry,
940 &perf_event_cgrp_subsys);
946 ret = perf_cgroup_ensure_storage(event, css);
950 cgrp = container_of(css, struct perf_cgroup, css);
954 * all events in a group must monitor
955 * the same cgroup because a task belongs
956 * to only one perf cgroup at a time
958 if (group_leader && group_leader->cgrp != cgrp) {
959 perf_detach_cgroup(event);
968 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
970 struct perf_cpu_context *cpuctx;
972 if (!is_cgroup_event(event))
975 event->pmu_ctx->nr_cgroups++;
978 * Because cgroup events are always per-cpu events,
979 * @ctx == &cpuctx->ctx.
981 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
983 if (ctx->nr_cgroups++)
986 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
990 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
992 struct perf_cpu_context *cpuctx;
994 if (!is_cgroup_event(event))
997 event->pmu_ctx->nr_cgroups--;
1000 * Because cgroup events are always per-cpu events,
1001 * @ctx == &cpuctx->ctx.
1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1005 if (--ctx->nr_cgroups)
1008 cpuctx->cgrp = NULL;
1011 #else /* !CONFIG_CGROUP_PERF */
1014 perf_cgroup_match(struct perf_event *event)
1019 static inline void perf_detach_cgroup(struct perf_event *event)
1022 static inline int is_cgroup_event(struct perf_event *event)
1027 static inline void update_cgrp_time_from_event(struct perf_event *event)
1031 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1036 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1037 struct perf_event_attr *attr,
1038 struct perf_event *group_leader)
1044 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1048 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1053 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1059 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1064 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1068 static void perf_cgroup_switch(struct task_struct *task)
1074 * set default to be dependent on timer tick just
1075 * like original code
1077 #define PERF_CPU_HRTIMER (1000 / HZ)
1079 * function must be called with interrupts disabled
1081 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1083 struct perf_cpu_pmu_context *cpc;
1086 lockdep_assert_irqs_disabled();
1088 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1089 rotations = perf_rotate_context(cpc);
1091 raw_spin_lock(&cpc->hrtimer_lock);
1093 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1095 cpc->hrtimer_active = 0;
1096 raw_spin_unlock(&cpc->hrtimer_lock);
1098 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1101 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1103 struct hrtimer *timer = &cpc->hrtimer;
1104 struct pmu *pmu = cpc->epc.pmu;
1108 * check default is sane, if not set then force to
1109 * default interval (1/tick)
1111 interval = pmu->hrtimer_interval_ms;
1113 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1115 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1117 raw_spin_lock_init(&cpc->hrtimer_lock);
1118 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1119 timer->function = perf_mux_hrtimer_handler;
1122 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1124 struct hrtimer *timer = &cpc->hrtimer;
1125 unsigned long flags;
1127 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1128 if (!cpc->hrtimer_active) {
1129 cpc->hrtimer_active = 1;
1130 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1131 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1133 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1138 static int perf_mux_hrtimer_restart_ipi(void *arg)
1140 return perf_mux_hrtimer_restart(arg);
1143 void perf_pmu_disable(struct pmu *pmu)
1145 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1147 pmu->pmu_disable(pmu);
1150 void perf_pmu_enable(struct pmu *pmu)
1152 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1154 pmu->pmu_enable(pmu);
1157 static void perf_assert_pmu_disabled(struct pmu *pmu)
1159 WARN_ON_ONCE(*this_cpu_ptr(pmu->pmu_disable_count) == 0);
1162 static void get_ctx(struct perf_event_context *ctx)
1164 refcount_inc(&ctx->refcount);
1167 static void *alloc_task_ctx_data(struct pmu *pmu)
1169 if (pmu->task_ctx_cache)
1170 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1175 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1177 if (pmu->task_ctx_cache && task_ctx_data)
1178 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1181 static void free_ctx(struct rcu_head *head)
1183 struct perf_event_context *ctx;
1185 ctx = container_of(head, struct perf_event_context, rcu_head);
1189 static void put_ctx(struct perf_event_context *ctx)
1191 if (refcount_dec_and_test(&ctx->refcount)) {
1192 if (ctx->parent_ctx)
1193 put_ctx(ctx->parent_ctx);
1194 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1195 put_task_struct(ctx->task);
1196 call_rcu(&ctx->rcu_head, free_ctx);
1201 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1202 * perf_pmu_migrate_context() we need some magic.
1204 * Those places that change perf_event::ctx will hold both
1205 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1207 * Lock ordering is by mutex address. There are two other sites where
1208 * perf_event_context::mutex nests and those are:
1210 * - perf_event_exit_task_context() [ child , 0 ]
1211 * perf_event_exit_event()
1212 * put_event() [ parent, 1 ]
1214 * - perf_event_init_context() [ parent, 0 ]
1215 * inherit_task_group()
1218 * perf_event_alloc()
1220 * perf_try_init_event() [ child , 1 ]
1222 * While it appears there is an obvious deadlock here -- the parent and child
1223 * nesting levels are inverted between the two. This is in fact safe because
1224 * life-time rules separate them. That is an exiting task cannot fork, and a
1225 * spawning task cannot (yet) exit.
1227 * But remember that these are parent<->child context relations, and
1228 * migration does not affect children, therefore these two orderings should not
1231 * The change in perf_event::ctx does not affect children (as claimed above)
1232 * because the sys_perf_event_open() case will install a new event and break
1233 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1234 * concerned with cpuctx and that doesn't have children.
1236 * The places that change perf_event::ctx will issue:
1238 * perf_remove_from_context();
1239 * synchronize_rcu();
1240 * perf_install_in_context();
1242 * to affect the change. The remove_from_context() + synchronize_rcu() should
1243 * quiesce the event, after which we can install it in the new location. This
1244 * means that only external vectors (perf_fops, prctl) can perturb the event
1245 * while in transit. Therefore all such accessors should also acquire
1246 * perf_event_context::mutex to serialize against this.
1248 * However; because event->ctx can change while we're waiting to acquire
1249 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1254 * task_struct::perf_event_mutex
1255 * perf_event_context::mutex
1256 * perf_event::child_mutex;
1257 * perf_event_context::lock
1258 * perf_event::mmap_mutex
1260 * perf_addr_filters_head::lock
1264 * cpuctx->mutex / perf_event_context::mutex
1266 static struct perf_event_context *
1267 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1269 struct perf_event_context *ctx;
1273 ctx = READ_ONCE(event->ctx);
1274 if (!refcount_inc_not_zero(&ctx->refcount)) {
1280 mutex_lock_nested(&ctx->mutex, nesting);
1281 if (event->ctx != ctx) {
1282 mutex_unlock(&ctx->mutex);
1290 static inline struct perf_event_context *
1291 perf_event_ctx_lock(struct perf_event *event)
1293 return perf_event_ctx_lock_nested(event, 0);
1296 static void perf_event_ctx_unlock(struct perf_event *event,
1297 struct perf_event_context *ctx)
1299 mutex_unlock(&ctx->mutex);
1304 * This must be done under the ctx->lock, such as to serialize against
1305 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1306 * calling scheduler related locks and ctx->lock nests inside those.
1308 static __must_check struct perf_event_context *
1309 unclone_ctx(struct perf_event_context *ctx)
1311 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1313 lockdep_assert_held(&ctx->lock);
1316 ctx->parent_ctx = NULL;
1322 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1327 * only top level events have the pid namespace they were created in
1330 event = event->parent;
1332 nr = __task_pid_nr_ns(p, type, event->ns);
1333 /* avoid -1 if it is idle thread or runs in another ns */
1334 if (!nr && !pid_alive(p))
1339 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1341 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1344 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1346 return perf_event_pid_type(event, p, PIDTYPE_PID);
1350 * If we inherit events we want to return the parent event id
1353 static u64 primary_event_id(struct perf_event *event)
1358 id = event->parent->id;
1364 * Get the perf_event_context for a task and lock it.
1366 * This has to cope with the fact that until it is locked,
1367 * the context could get moved to another task.
1369 static struct perf_event_context *
1370 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1372 struct perf_event_context *ctx;
1376 * One of the few rules of preemptible RCU is that one cannot do
1377 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1378 * part of the read side critical section was irqs-enabled -- see
1379 * rcu_read_unlock_special().
1381 * Since ctx->lock nests under rq->lock we must ensure the entire read
1382 * side critical section has interrupts disabled.
1384 local_irq_save(*flags);
1386 ctx = rcu_dereference(task->perf_event_ctxp);
1389 * If this context is a clone of another, it might
1390 * get swapped for another underneath us by
1391 * perf_event_task_sched_out, though the
1392 * rcu_read_lock() protects us from any context
1393 * getting freed. Lock the context and check if it
1394 * got swapped before we could get the lock, and retry
1395 * if so. If we locked the right context, then it
1396 * can't get swapped on us any more.
1398 raw_spin_lock(&ctx->lock);
1399 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1400 raw_spin_unlock(&ctx->lock);
1402 local_irq_restore(*flags);
1406 if (ctx->task == TASK_TOMBSTONE ||
1407 !refcount_inc_not_zero(&ctx->refcount)) {
1408 raw_spin_unlock(&ctx->lock);
1411 WARN_ON_ONCE(ctx->task != task);
1416 local_irq_restore(*flags);
1421 * Get the context for a task and increment its pin_count so it
1422 * can't get swapped to another task. This also increments its
1423 * reference count so that the context can't get freed.
1425 static struct perf_event_context *
1426 perf_pin_task_context(struct task_struct *task)
1428 struct perf_event_context *ctx;
1429 unsigned long flags;
1431 ctx = perf_lock_task_context(task, &flags);
1434 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1439 static void perf_unpin_context(struct perf_event_context *ctx)
1441 unsigned long flags;
1443 raw_spin_lock_irqsave(&ctx->lock, flags);
1445 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1449 * Update the record of the current time in a context.
1451 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1453 u64 now = perf_clock();
1455 lockdep_assert_held(&ctx->lock);
1458 ctx->time += now - ctx->timestamp;
1459 ctx->timestamp = now;
1462 * The above: time' = time + (now - timestamp), can be re-arranged
1463 * into: time` = now + (time - timestamp), which gives a single value
1464 * offset to compute future time without locks on.
1466 * See perf_event_time_now(), which can be used from NMI context where
1467 * it's (obviously) not possible to acquire ctx->lock in order to read
1468 * both the above values in a consistent manner.
1470 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1473 static void update_context_time(struct perf_event_context *ctx)
1475 __update_context_time(ctx, true);
1478 static u64 perf_event_time(struct perf_event *event)
1480 struct perf_event_context *ctx = event->ctx;
1485 if (is_cgroup_event(event))
1486 return perf_cgroup_event_time(event);
1491 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1493 struct perf_event_context *ctx = event->ctx;
1498 if (is_cgroup_event(event))
1499 return perf_cgroup_event_time_now(event, now);
1501 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1504 now += READ_ONCE(ctx->timeoffset);
1508 static enum event_type_t get_event_type(struct perf_event *event)
1510 struct perf_event_context *ctx = event->ctx;
1511 enum event_type_t event_type;
1513 lockdep_assert_held(&ctx->lock);
1516 * It's 'group type', really, because if our group leader is
1517 * pinned, so are we.
1519 if (event->group_leader != event)
1520 event = event->group_leader;
1522 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1524 event_type |= EVENT_CPU;
1530 * Helper function to initialize event group nodes.
1532 static void init_event_group(struct perf_event *event)
1534 RB_CLEAR_NODE(&event->group_node);
1535 event->group_index = 0;
1539 * Extract pinned or flexible groups from the context
1540 * based on event attrs bits.
1542 static struct perf_event_groups *
1543 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1545 if (event->attr.pinned)
1546 return &ctx->pinned_groups;
1548 return &ctx->flexible_groups;
1552 * Helper function to initializes perf_event_group trees.
1554 static void perf_event_groups_init(struct perf_event_groups *groups)
1556 groups->tree = RB_ROOT;
1560 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1562 struct cgroup *cgroup = NULL;
1564 #ifdef CONFIG_CGROUP_PERF
1566 cgroup = event->cgrp->css.cgroup;
1573 * Compare function for event groups;
1575 * Implements complex key that first sorts by CPU and then by virtual index
1576 * which provides ordering when rotating groups for the same CPU.
1578 static __always_inline int
1579 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1580 const struct cgroup *left_cgroup, const u64 left_group_index,
1581 const struct perf_event *right)
1583 if (left_cpu < right->cpu)
1585 if (left_cpu > right->cpu)
1589 if (left_pmu < right->pmu_ctx->pmu)
1591 if (left_pmu > right->pmu_ctx->pmu)
1595 #ifdef CONFIG_CGROUP_PERF
1597 const struct cgroup *right_cgroup = event_cgroup(right);
1599 if (left_cgroup != right_cgroup) {
1602 * Left has no cgroup but right does, no
1603 * cgroups come first.
1607 if (!right_cgroup) {
1609 * Right has no cgroup but left does, no
1610 * cgroups come first.
1614 /* Two dissimilar cgroups, order by id. */
1615 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1623 if (left_group_index < right->group_index)
1625 if (left_group_index > right->group_index)
1631 #define __node_2_pe(node) \
1632 rb_entry((node), struct perf_event, group_node)
1634 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1636 struct perf_event *e = __node_2_pe(a);
1637 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1638 e->group_index, __node_2_pe(b)) < 0;
1641 struct __group_key {
1644 struct cgroup *cgroup;
1647 static inline int __group_cmp(const void *key, const struct rb_node *node)
1649 const struct __group_key *a = key;
1650 const struct perf_event *b = __node_2_pe(node);
1652 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1653 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1657 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1659 const struct __group_key *a = key;
1660 const struct perf_event *b = __node_2_pe(node);
1662 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1663 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1668 * Insert @event into @groups' tree; using
1669 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1670 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1673 perf_event_groups_insert(struct perf_event_groups *groups,
1674 struct perf_event *event)
1676 event->group_index = ++groups->index;
1678 rb_add(&event->group_node, &groups->tree, __group_less);
1682 * Helper function to insert event into the pinned or flexible groups.
1685 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1687 struct perf_event_groups *groups;
1689 groups = get_event_groups(event, ctx);
1690 perf_event_groups_insert(groups, event);
1694 * Delete a group from a tree.
1697 perf_event_groups_delete(struct perf_event_groups *groups,
1698 struct perf_event *event)
1700 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1701 RB_EMPTY_ROOT(&groups->tree));
1703 rb_erase(&event->group_node, &groups->tree);
1704 init_event_group(event);
1708 * Helper function to delete event from its groups.
1711 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1713 struct perf_event_groups *groups;
1715 groups = get_event_groups(event, ctx);
1716 perf_event_groups_delete(groups, event);
1720 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1722 static struct perf_event *
1723 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1724 struct pmu *pmu, struct cgroup *cgrp)
1726 struct __group_key key = {
1731 struct rb_node *node;
1733 node = rb_find_first(&key, &groups->tree, __group_cmp);
1735 return __node_2_pe(node);
1740 static struct perf_event *
1741 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1743 struct __group_key key = {
1746 .cgroup = event_cgroup(event),
1748 struct rb_node *next;
1750 next = rb_next_match(&key, &event->group_node, __group_cmp);
1752 return __node_2_pe(next);
1757 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1758 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1759 event; event = perf_event_groups_next(event, pmu))
1762 * Iterate through the whole groups tree.
1764 #define perf_event_groups_for_each(event, groups) \
1765 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1766 typeof(*event), group_node); event; \
1767 event = rb_entry_safe(rb_next(&event->group_node), \
1768 typeof(*event), group_node))
1771 * Add an event from the lists for its context.
1772 * Must be called with ctx->mutex and ctx->lock held.
1775 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1777 lockdep_assert_held(&ctx->lock);
1779 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1780 event->attach_state |= PERF_ATTACH_CONTEXT;
1782 event->tstamp = perf_event_time(event);
1785 * If we're a stand alone event or group leader, we go to the context
1786 * list, group events are kept attached to the group so that
1787 * perf_group_detach can, at all times, locate all siblings.
1789 if (event->group_leader == event) {
1790 event->group_caps = event->event_caps;
1791 add_event_to_groups(event, ctx);
1794 list_add_rcu(&event->event_entry, &ctx->event_list);
1796 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1798 if (event->attr.inherit_stat)
1801 if (event->state > PERF_EVENT_STATE_OFF)
1802 perf_cgroup_event_enable(event, ctx);
1805 event->pmu_ctx->nr_events++;
1809 * Initialize event state based on the perf_event_attr::disabled.
1811 static inline void perf_event__state_init(struct perf_event *event)
1813 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1814 PERF_EVENT_STATE_INACTIVE;
1817 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1819 int entry = sizeof(u64); /* value */
1823 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1824 size += sizeof(u64);
1826 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1827 size += sizeof(u64);
1829 if (read_format & PERF_FORMAT_ID)
1830 entry += sizeof(u64);
1832 if (read_format & PERF_FORMAT_LOST)
1833 entry += sizeof(u64);
1835 if (read_format & PERF_FORMAT_GROUP) {
1837 size += sizeof(u64);
1841 * Since perf_event_validate_size() limits this to 16k and inhibits
1842 * adding more siblings, this will never overflow.
1844 return size + nr * entry;
1847 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1849 struct perf_sample_data *data;
1852 if (sample_type & PERF_SAMPLE_IP)
1853 size += sizeof(data->ip);
1855 if (sample_type & PERF_SAMPLE_ADDR)
1856 size += sizeof(data->addr);
1858 if (sample_type & PERF_SAMPLE_PERIOD)
1859 size += sizeof(data->period);
1861 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1862 size += sizeof(data->weight.full);
1864 if (sample_type & PERF_SAMPLE_READ)
1865 size += event->read_size;
1867 if (sample_type & PERF_SAMPLE_DATA_SRC)
1868 size += sizeof(data->data_src.val);
1870 if (sample_type & PERF_SAMPLE_TRANSACTION)
1871 size += sizeof(data->txn);
1873 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1874 size += sizeof(data->phys_addr);
1876 if (sample_type & PERF_SAMPLE_CGROUP)
1877 size += sizeof(data->cgroup);
1879 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1880 size += sizeof(data->data_page_size);
1882 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1883 size += sizeof(data->code_page_size);
1885 event->header_size = size;
1889 * Called at perf_event creation and when events are attached/detached from a
1892 static void perf_event__header_size(struct perf_event *event)
1895 __perf_event_read_size(event->attr.read_format,
1896 event->group_leader->nr_siblings);
1897 __perf_event_header_size(event, event->attr.sample_type);
1900 static void perf_event__id_header_size(struct perf_event *event)
1902 struct perf_sample_data *data;
1903 u64 sample_type = event->attr.sample_type;
1906 if (sample_type & PERF_SAMPLE_TID)
1907 size += sizeof(data->tid_entry);
1909 if (sample_type & PERF_SAMPLE_TIME)
1910 size += sizeof(data->time);
1912 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1913 size += sizeof(data->id);
1915 if (sample_type & PERF_SAMPLE_ID)
1916 size += sizeof(data->id);
1918 if (sample_type & PERF_SAMPLE_STREAM_ID)
1919 size += sizeof(data->stream_id);
1921 if (sample_type & PERF_SAMPLE_CPU)
1922 size += sizeof(data->cpu_entry);
1924 event->id_header_size = size;
1928 * Check that adding an event to the group does not result in anybody
1929 * overflowing the 64k event limit imposed by the output buffer.
1931 * Specifically, check that the read_size for the event does not exceed 16k,
1932 * read_size being the one term that grows with groups size. Since read_size
1933 * depends on per-event read_format, also (re)check the existing events.
1935 * This leaves 48k for the constant size fields and things like callchains,
1936 * branch stacks and register sets.
1938 static bool perf_event_validate_size(struct perf_event *event)
1940 struct perf_event *sibling, *group_leader = event->group_leader;
1942 if (__perf_event_read_size(event->attr.read_format,
1943 group_leader->nr_siblings + 1) > 16*1024)
1946 if (__perf_event_read_size(group_leader->attr.read_format,
1947 group_leader->nr_siblings + 1) > 16*1024)
1951 * When creating a new group leader, group_leader->ctx is initialized
1952 * after the size has been validated, but we cannot safely use
1953 * for_each_sibling_event() until group_leader->ctx is set. A new group
1954 * leader cannot have any siblings yet, so we can safely skip checking
1955 * the non-existent siblings.
1957 if (event == group_leader)
1960 for_each_sibling_event(sibling, group_leader) {
1961 if (__perf_event_read_size(sibling->attr.read_format,
1962 group_leader->nr_siblings + 1) > 16*1024)
1969 static void perf_group_attach(struct perf_event *event)
1971 struct perf_event *group_leader = event->group_leader, *pos;
1973 lockdep_assert_held(&event->ctx->lock);
1976 * We can have double attach due to group movement (move_group) in
1977 * perf_event_open().
1979 if (event->attach_state & PERF_ATTACH_GROUP)
1982 event->attach_state |= PERF_ATTACH_GROUP;
1984 if (group_leader == event)
1987 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1989 group_leader->group_caps &= event->event_caps;
1991 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1992 group_leader->nr_siblings++;
1993 group_leader->group_generation++;
1995 perf_event__header_size(group_leader);
1997 for_each_sibling_event(pos, group_leader)
1998 perf_event__header_size(pos);
2002 * Remove an event from the lists for its context.
2003 * Must be called with ctx->mutex and ctx->lock held.
2006 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2008 WARN_ON_ONCE(event->ctx != ctx);
2009 lockdep_assert_held(&ctx->lock);
2012 * We can have double detach due to exit/hot-unplug + close.
2014 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2017 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2020 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2022 if (event->attr.inherit_stat)
2025 list_del_rcu(&event->event_entry);
2027 if (event->group_leader == event)
2028 del_event_from_groups(event, ctx);
2031 * If event was in error state, then keep it
2032 * that way, otherwise bogus counts will be
2033 * returned on read(). The only way to get out
2034 * of error state is by explicit re-enabling
2037 if (event->state > PERF_EVENT_STATE_OFF) {
2038 perf_cgroup_event_disable(event, ctx);
2039 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2043 event->pmu_ctx->nr_events--;
2047 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2049 if (!has_aux(aux_event))
2052 if (!event->pmu->aux_output_match)
2055 return event->pmu->aux_output_match(aux_event);
2058 static void put_event(struct perf_event *event);
2059 static void event_sched_out(struct perf_event *event,
2060 struct perf_event_context *ctx);
2062 static void perf_put_aux_event(struct perf_event *event)
2064 struct perf_event_context *ctx = event->ctx;
2065 struct perf_event *iter;
2068 * If event uses aux_event tear down the link
2070 if (event->aux_event) {
2071 iter = event->aux_event;
2072 event->aux_event = NULL;
2078 * If the event is an aux_event, tear down all links to
2079 * it from other events.
2081 for_each_sibling_event(iter, event->group_leader) {
2082 if (iter->aux_event != event)
2085 iter->aux_event = NULL;
2089 * If it's ACTIVE, schedule it out and put it into ERROR
2090 * state so that we don't try to schedule it again. Note
2091 * that perf_event_enable() will clear the ERROR status.
2093 event_sched_out(iter, ctx);
2094 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2098 static bool perf_need_aux_event(struct perf_event *event)
2100 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2103 static int perf_get_aux_event(struct perf_event *event,
2104 struct perf_event *group_leader)
2107 * Our group leader must be an aux event if we want to be
2108 * an aux_output. This way, the aux event will precede its
2109 * aux_output events in the group, and therefore will always
2116 * aux_output and aux_sample_size are mutually exclusive.
2118 if (event->attr.aux_output && event->attr.aux_sample_size)
2121 if (event->attr.aux_output &&
2122 !perf_aux_output_match(event, group_leader))
2125 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2128 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2132 * Link aux_outputs to their aux event; this is undone in
2133 * perf_group_detach() by perf_put_aux_event(). When the
2134 * group in torn down, the aux_output events loose their
2135 * link to the aux_event and can't schedule any more.
2137 event->aux_event = group_leader;
2142 static inline struct list_head *get_event_list(struct perf_event *event)
2144 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2145 &event->pmu_ctx->flexible_active;
2149 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2150 * cannot exist on their own, schedule them out and move them into the ERROR
2151 * state. Also see _perf_event_enable(), it will not be able to recover
2154 static inline void perf_remove_sibling_event(struct perf_event *event)
2156 event_sched_out(event, event->ctx);
2157 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2160 static void perf_group_detach(struct perf_event *event)
2162 struct perf_event *leader = event->group_leader;
2163 struct perf_event *sibling, *tmp;
2164 struct perf_event_context *ctx = event->ctx;
2166 lockdep_assert_held(&ctx->lock);
2169 * We can have double detach due to exit/hot-unplug + close.
2171 if (!(event->attach_state & PERF_ATTACH_GROUP))
2174 event->attach_state &= ~PERF_ATTACH_GROUP;
2176 perf_put_aux_event(event);
2179 * If this is a sibling, remove it from its group.
2181 if (leader != event) {
2182 list_del_init(&event->sibling_list);
2183 event->group_leader->nr_siblings--;
2184 event->group_leader->group_generation++;
2189 * If this was a group event with sibling events then
2190 * upgrade the siblings to singleton events by adding them
2191 * to whatever list we are on.
2193 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2195 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2196 perf_remove_sibling_event(sibling);
2198 sibling->group_leader = sibling;
2199 list_del_init(&sibling->sibling_list);
2201 /* Inherit group flags from the previous leader */
2202 sibling->group_caps = event->group_caps;
2204 if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2205 add_event_to_groups(sibling, event->ctx);
2207 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2208 list_add_tail(&sibling->active_list, get_event_list(sibling));
2211 WARN_ON_ONCE(sibling->ctx != event->ctx);
2215 for_each_sibling_event(tmp, leader)
2216 perf_event__header_size(tmp);
2218 perf_event__header_size(leader);
2221 static void sync_child_event(struct perf_event *child_event);
2223 static void perf_child_detach(struct perf_event *event)
2225 struct perf_event *parent_event = event->parent;
2227 if (!(event->attach_state & PERF_ATTACH_CHILD))
2230 event->attach_state &= ~PERF_ATTACH_CHILD;
2232 if (WARN_ON_ONCE(!parent_event))
2235 lockdep_assert_held(&parent_event->child_mutex);
2237 sync_child_event(event);
2238 list_del_init(&event->child_list);
2241 static bool is_orphaned_event(struct perf_event *event)
2243 return event->state == PERF_EVENT_STATE_DEAD;
2247 event_filter_match(struct perf_event *event)
2249 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2250 perf_cgroup_match(event);
2254 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2256 struct perf_event_pmu_context *epc = event->pmu_ctx;
2257 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2258 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2260 // XXX cpc serialization, probably per-cpu IRQ disabled
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 cpc->active_oncpu--;
2305 if (event->attr.freq && event->attr.sample_freq) {
2309 if (event->attr.exclusive || !cpc->active_oncpu)
2312 perf_pmu_enable(event->pmu);
2316 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2318 struct perf_event *event;
2320 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2323 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2325 event_sched_out(group_event, ctx);
2328 * Schedule out siblings (if any):
2330 for_each_sibling_event(event, group_event)
2331 event_sched_out(event, ctx);
2334 #define DETACH_GROUP 0x01UL
2335 #define DETACH_CHILD 0x02UL
2336 #define DETACH_DEAD 0x04UL
2339 * Cross CPU call to remove a performance event
2341 * We disable the event on the hardware level first. After that we
2342 * remove it from the context list.
2345 __perf_remove_from_context(struct perf_event *event,
2346 struct perf_cpu_context *cpuctx,
2347 struct perf_event_context *ctx,
2350 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2351 unsigned long flags = (unsigned long)info;
2353 if (ctx->is_active & EVENT_TIME) {
2354 update_context_time(ctx);
2355 update_cgrp_time_from_cpuctx(cpuctx, false);
2359 * Ensure event_sched_out() switches to OFF, at the very least
2360 * this avoids raising perf_pending_task() at this time.
2362 if (flags & DETACH_DEAD)
2363 event->pending_disable = 1;
2364 event_sched_out(event, ctx);
2365 if (flags & DETACH_GROUP)
2366 perf_group_detach(event);
2367 if (flags & DETACH_CHILD)
2368 perf_child_detach(event);
2369 list_del_event(event, ctx);
2370 if (flags & DETACH_DEAD)
2371 event->state = PERF_EVENT_STATE_DEAD;
2373 if (!pmu_ctx->nr_events) {
2374 pmu_ctx->rotate_necessary = 0;
2376 if (ctx->task && ctx->is_active) {
2377 struct perf_cpu_pmu_context *cpc;
2379 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
2380 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2381 cpc->task_epc = NULL;
2385 if (!ctx->nr_events && ctx->is_active) {
2386 if (ctx == &cpuctx->ctx)
2387 update_cgrp_time_from_cpuctx(cpuctx, true);
2391 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2392 cpuctx->task_ctx = NULL;
2398 * Remove the event from a task's (or a CPU's) list of events.
2400 * If event->ctx is a cloned context, callers must make sure that
2401 * every task struct that event->ctx->task could possibly point to
2402 * remains valid. This is OK when called from perf_release since
2403 * that only calls us on the top-level context, which can't be a clone.
2404 * When called from perf_event_exit_task, it's OK because the
2405 * context has been detached from its task.
2407 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2409 struct perf_event_context *ctx = event->ctx;
2411 lockdep_assert_held(&ctx->mutex);
2414 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2415 * to work in the face of TASK_TOMBSTONE, unlike every other
2416 * event_function_call() user.
2418 raw_spin_lock_irq(&ctx->lock);
2419 if (!ctx->is_active) {
2420 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2421 ctx, (void *)flags);
2422 raw_spin_unlock_irq(&ctx->lock);
2425 raw_spin_unlock_irq(&ctx->lock);
2427 event_function_call(event, __perf_remove_from_context, (void *)flags);
2431 * Cross CPU call to disable a performance event
2433 static void __perf_event_disable(struct perf_event *event,
2434 struct perf_cpu_context *cpuctx,
2435 struct perf_event_context *ctx,
2438 if (event->state < PERF_EVENT_STATE_INACTIVE)
2441 if (ctx->is_active & EVENT_TIME) {
2442 update_context_time(ctx);
2443 update_cgrp_time_from_event(event);
2446 perf_pmu_disable(event->pmu_ctx->pmu);
2448 if (event == event->group_leader)
2449 group_sched_out(event, ctx);
2451 event_sched_out(event, ctx);
2453 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2454 perf_cgroup_event_disable(event, ctx);
2456 perf_pmu_enable(event->pmu_ctx->pmu);
2462 * If event->ctx is a cloned context, callers must make sure that
2463 * every task struct that event->ctx->task could possibly point to
2464 * remains valid. This condition is satisfied when called through
2465 * perf_event_for_each_child or perf_event_for_each because they
2466 * hold the top-level event's child_mutex, so any descendant that
2467 * goes to exit will block in perf_event_exit_event().
2469 * When called from perf_pending_irq it's OK because event->ctx
2470 * is the current context on this CPU and preemption is disabled,
2471 * hence we can't get into perf_event_task_sched_out for this context.
2473 static void _perf_event_disable(struct perf_event *event)
2475 struct perf_event_context *ctx = event->ctx;
2477 raw_spin_lock_irq(&ctx->lock);
2478 if (event->state <= PERF_EVENT_STATE_OFF) {
2479 raw_spin_unlock_irq(&ctx->lock);
2482 raw_spin_unlock_irq(&ctx->lock);
2484 event_function_call(event, __perf_event_disable, NULL);
2487 void perf_event_disable_local(struct perf_event *event)
2489 event_function_local(event, __perf_event_disable, NULL);
2493 * Strictly speaking kernel users cannot create groups and therefore this
2494 * interface does not need the perf_event_ctx_lock() magic.
2496 void perf_event_disable(struct perf_event *event)
2498 struct perf_event_context *ctx;
2500 ctx = perf_event_ctx_lock(event);
2501 _perf_event_disable(event);
2502 perf_event_ctx_unlock(event, ctx);
2504 EXPORT_SYMBOL_GPL(perf_event_disable);
2506 void perf_event_disable_inatomic(struct perf_event *event)
2508 event->pending_disable = 1;
2509 irq_work_queue(&event->pending_irq);
2512 #define MAX_INTERRUPTS (~0ULL)
2514 static void perf_log_throttle(struct perf_event *event, int enable);
2515 static void perf_log_itrace_start(struct perf_event *event);
2518 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2520 struct perf_event_pmu_context *epc = event->pmu_ctx;
2521 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2524 WARN_ON_ONCE(event->ctx != ctx);
2526 lockdep_assert_held(&ctx->lock);
2528 if (event->state <= PERF_EVENT_STATE_OFF)
2531 WRITE_ONCE(event->oncpu, smp_processor_id());
2533 * Order event::oncpu write to happen before the ACTIVE state is
2534 * visible. This allows perf_event_{stop,read}() to observe the correct
2535 * ->oncpu if it sees ACTIVE.
2538 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2541 * Unthrottle events, since we scheduled we might have missed several
2542 * ticks already, also for a heavily scheduling task there is little
2543 * guarantee it'll get a tick in a timely manner.
2545 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2546 perf_log_throttle(event, 1);
2547 event->hw.interrupts = 0;
2550 perf_pmu_disable(event->pmu);
2552 perf_log_itrace_start(event);
2554 if (event->pmu->add(event, PERF_EF_START)) {
2555 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2561 if (!is_software_event(event))
2562 cpc->active_oncpu++;
2563 if (event->attr.freq && event->attr.sample_freq) {
2567 if (event->attr.exclusive)
2571 perf_pmu_enable(event->pmu);
2577 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2579 struct perf_event *event, *partial_group = NULL;
2580 struct pmu *pmu = group_event->pmu_ctx->pmu;
2582 if (group_event->state == PERF_EVENT_STATE_OFF)
2585 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2587 if (event_sched_in(group_event, ctx))
2591 * Schedule in siblings as one group (if any):
2593 for_each_sibling_event(event, group_event) {
2594 if (event_sched_in(event, ctx)) {
2595 partial_group = event;
2600 if (!pmu->commit_txn(pmu))
2605 * Groups can be scheduled in as one unit only, so undo any
2606 * partial group before returning:
2607 * The events up to the failed event are scheduled out normally.
2609 for_each_sibling_event(event, group_event) {
2610 if (event == partial_group)
2613 event_sched_out(event, ctx);
2615 event_sched_out(group_event, ctx);
2618 pmu->cancel_txn(pmu);
2623 * Work out whether we can put this event group on the CPU now.
2625 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2627 struct perf_event_pmu_context *epc = event->pmu_ctx;
2628 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2631 * Groups consisting entirely of software events can always go on.
2633 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2636 * If an exclusive group is already on, no other hardware
2642 * If this group is exclusive and there are already
2643 * events on the CPU, it can't go on.
2645 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2648 * Otherwise, try to add it if all previous groups were able
2654 static void add_event_to_ctx(struct perf_event *event,
2655 struct perf_event_context *ctx)
2657 list_add_event(event, ctx);
2658 perf_group_attach(event);
2661 static void task_ctx_sched_out(struct perf_event_context *ctx,
2662 enum event_type_t event_type)
2664 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2666 if (!cpuctx->task_ctx)
2669 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2672 ctx_sched_out(ctx, event_type);
2675 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2676 struct perf_event_context *ctx)
2678 ctx_sched_in(&cpuctx->ctx, EVENT_PINNED);
2680 ctx_sched_in(ctx, EVENT_PINNED);
2681 ctx_sched_in(&cpuctx->ctx, EVENT_FLEXIBLE);
2683 ctx_sched_in(ctx, EVENT_FLEXIBLE);
2687 * We want to maintain the following priority of scheduling:
2688 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2689 * - task pinned (EVENT_PINNED)
2690 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2691 * - task flexible (EVENT_FLEXIBLE).
2693 * In order to avoid unscheduling and scheduling back in everything every
2694 * time an event is added, only do it for the groups of equal priority and
2697 * This can be called after a batch operation on task events, in which case
2698 * event_type is a bit mask of the types of events involved. For CPU events,
2699 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2702 * XXX: ctx_resched() reschedule entire perf_event_context while adding new
2703 * event to the context or enabling existing event in the context. We can
2704 * probably optimize it by rescheduling only affected pmu_ctx.
2706 static void ctx_resched(struct perf_cpu_context *cpuctx,
2707 struct perf_event_context *task_ctx,
2708 enum event_type_t event_type)
2710 bool cpu_event = !!(event_type & EVENT_CPU);
2713 * If pinned groups are involved, flexible groups also need to be
2716 if (event_type & EVENT_PINNED)
2717 event_type |= EVENT_FLEXIBLE;
2719 event_type &= EVENT_ALL;
2721 perf_ctx_disable(&cpuctx->ctx, false);
2723 perf_ctx_disable(task_ctx, false);
2724 task_ctx_sched_out(task_ctx, event_type);
2728 * Decide which cpu ctx groups to schedule out based on the types
2729 * of events that caused rescheduling:
2730 * - EVENT_CPU: schedule out corresponding groups;
2731 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2732 * - otherwise, do nothing more.
2735 ctx_sched_out(&cpuctx->ctx, event_type);
2736 else if (event_type & EVENT_PINNED)
2737 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
2739 perf_event_sched_in(cpuctx, task_ctx);
2741 perf_ctx_enable(&cpuctx->ctx, false);
2743 perf_ctx_enable(task_ctx, false);
2746 void perf_pmu_resched(struct pmu *pmu)
2748 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2749 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2751 perf_ctx_lock(cpuctx, task_ctx);
2752 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2753 perf_ctx_unlock(cpuctx, task_ctx);
2757 * Cross CPU call to install and enable a performance event
2759 * Very similar to remote_function() + event_function() but cannot assume that
2760 * things like ctx->is_active and cpuctx->task_ctx are set.
2762 static int __perf_install_in_context(void *info)
2764 struct perf_event *event = info;
2765 struct perf_event_context *ctx = event->ctx;
2766 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2767 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2768 bool reprogram = true;
2771 raw_spin_lock(&cpuctx->ctx.lock);
2773 raw_spin_lock(&ctx->lock);
2776 reprogram = (ctx->task == current);
2779 * If the task is running, it must be running on this CPU,
2780 * otherwise we cannot reprogram things.
2782 * If its not running, we don't care, ctx->lock will
2783 * serialize against it becoming runnable.
2785 if (task_curr(ctx->task) && !reprogram) {
2790 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2791 } else if (task_ctx) {
2792 raw_spin_lock(&task_ctx->lock);
2795 #ifdef CONFIG_CGROUP_PERF
2796 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2798 * If the current cgroup doesn't match the event's
2799 * cgroup, we should not try to schedule it.
2801 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2802 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2803 event->cgrp->css.cgroup);
2808 ctx_sched_out(ctx, EVENT_TIME);
2809 add_event_to_ctx(event, ctx);
2810 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2812 add_event_to_ctx(event, ctx);
2816 perf_ctx_unlock(cpuctx, task_ctx);
2821 static bool exclusive_event_installable(struct perf_event *event,
2822 struct perf_event_context *ctx);
2825 * Attach a performance event to a context.
2827 * Very similar to event_function_call, see comment there.
2830 perf_install_in_context(struct perf_event_context *ctx,
2831 struct perf_event *event,
2834 struct task_struct *task = READ_ONCE(ctx->task);
2836 lockdep_assert_held(&ctx->mutex);
2838 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2840 if (event->cpu != -1)
2841 WARN_ON_ONCE(event->cpu != cpu);
2844 * Ensures that if we can observe event->ctx, both the event and ctx
2845 * will be 'complete'. See perf_iterate_sb_cpu().
2847 smp_store_release(&event->ctx, ctx);
2850 * perf_event_attr::disabled events will not run and can be initialized
2851 * without IPI. Except when this is the first event for the context, in
2852 * that case we need the magic of the IPI to set ctx->is_active.
2854 * The IOC_ENABLE that is sure to follow the creation of a disabled
2855 * event will issue the IPI and reprogram the hardware.
2857 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2858 ctx->nr_events && !is_cgroup_event(event)) {
2859 raw_spin_lock_irq(&ctx->lock);
2860 if (ctx->task == TASK_TOMBSTONE) {
2861 raw_spin_unlock_irq(&ctx->lock);
2864 add_event_to_ctx(event, ctx);
2865 raw_spin_unlock_irq(&ctx->lock);
2870 cpu_function_call(cpu, __perf_install_in_context, event);
2875 * Should not happen, we validate the ctx is still alive before calling.
2877 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2881 * Installing events is tricky because we cannot rely on ctx->is_active
2882 * to be set in case this is the nr_events 0 -> 1 transition.
2884 * Instead we use task_curr(), which tells us if the task is running.
2885 * However, since we use task_curr() outside of rq::lock, we can race
2886 * against the actual state. This means the result can be wrong.
2888 * If we get a false positive, we retry, this is harmless.
2890 * If we get a false negative, things are complicated. If we are after
2891 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2892 * value must be correct. If we're before, it doesn't matter since
2893 * perf_event_context_sched_in() will program the counter.
2895 * However, this hinges on the remote context switch having observed
2896 * our task->perf_event_ctxp[] store, such that it will in fact take
2897 * ctx::lock in perf_event_context_sched_in().
2899 * We do this by task_function_call(), if the IPI fails to hit the task
2900 * we know any future context switch of task must see the
2901 * perf_event_ctpx[] store.
2905 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2906 * task_cpu() load, such that if the IPI then does not find the task
2907 * running, a future context switch of that task must observe the
2912 if (!task_function_call(task, __perf_install_in_context, event))
2915 raw_spin_lock_irq(&ctx->lock);
2917 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2919 * Cannot happen because we already checked above (which also
2920 * cannot happen), and we hold ctx->mutex, which serializes us
2921 * against perf_event_exit_task_context().
2923 raw_spin_unlock_irq(&ctx->lock);
2927 * If the task is not running, ctx->lock will avoid it becoming so,
2928 * thus we can safely install the event.
2930 if (task_curr(task)) {
2931 raw_spin_unlock_irq(&ctx->lock);
2934 add_event_to_ctx(event, ctx);
2935 raw_spin_unlock_irq(&ctx->lock);
2939 * Cross CPU call to enable a performance event
2941 static void __perf_event_enable(struct perf_event *event,
2942 struct perf_cpu_context *cpuctx,
2943 struct perf_event_context *ctx,
2946 struct perf_event *leader = event->group_leader;
2947 struct perf_event_context *task_ctx;
2949 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2950 event->state <= PERF_EVENT_STATE_ERROR)
2954 ctx_sched_out(ctx, EVENT_TIME);
2956 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2957 perf_cgroup_event_enable(event, ctx);
2959 if (!ctx->is_active)
2962 if (!event_filter_match(event)) {
2963 ctx_sched_in(ctx, EVENT_TIME);
2968 * If the event is in a group and isn't the group leader,
2969 * then don't put it on unless the group is on.
2971 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2972 ctx_sched_in(ctx, EVENT_TIME);
2976 task_ctx = cpuctx->task_ctx;
2978 WARN_ON_ONCE(task_ctx != ctx);
2980 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2986 * If event->ctx is a cloned context, callers must make sure that
2987 * every task struct that event->ctx->task could possibly point to
2988 * remains valid. This condition is satisfied when called through
2989 * perf_event_for_each_child or perf_event_for_each as described
2990 * for perf_event_disable.
2992 static void _perf_event_enable(struct perf_event *event)
2994 struct perf_event_context *ctx = event->ctx;
2996 raw_spin_lock_irq(&ctx->lock);
2997 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2998 event->state < PERF_EVENT_STATE_ERROR) {
3000 raw_spin_unlock_irq(&ctx->lock);
3005 * If the event is in error state, clear that first.
3007 * That way, if we see the event in error state below, we know that it
3008 * has gone back into error state, as distinct from the task having
3009 * been scheduled away before the cross-call arrived.
3011 if (event->state == PERF_EVENT_STATE_ERROR) {
3013 * Detached SIBLING events cannot leave ERROR state.
3015 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3016 event->group_leader == event)
3019 event->state = PERF_EVENT_STATE_OFF;
3021 raw_spin_unlock_irq(&ctx->lock);
3023 event_function_call(event, __perf_event_enable, NULL);
3027 * See perf_event_disable();
3029 void perf_event_enable(struct perf_event *event)
3031 struct perf_event_context *ctx;
3033 ctx = perf_event_ctx_lock(event);
3034 _perf_event_enable(event);
3035 perf_event_ctx_unlock(event, ctx);
3037 EXPORT_SYMBOL_GPL(perf_event_enable);
3039 struct stop_event_data {
3040 struct perf_event *event;
3041 unsigned int restart;
3044 static int __perf_event_stop(void *info)
3046 struct stop_event_data *sd = info;
3047 struct perf_event *event = sd->event;
3049 /* if it's already INACTIVE, do nothing */
3050 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3053 /* matches smp_wmb() in event_sched_in() */
3057 * There is a window with interrupts enabled before we get here,
3058 * so we need to check again lest we try to stop another CPU's event.
3060 if (READ_ONCE(event->oncpu) != smp_processor_id())
3063 event->pmu->stop(event, PERF_EF_UPDATE);
3066 * May race with the actual stop (through perf_pmu_output_stop()),
3067 * but it is only used for events with AUX ring buffer, and such
3068 * events will refuse to restart because of rb::aux_mmap_count==0,
3069 * see comments in perf_aux_output_begin().
3071 * Since this is happening on an event-local CPU, no trace is lost
3075 event->pmu->start(event, 0);
3080 static int perf_event_stop(struct perf_event *event, int restart)
3082 struct stop_event_data sd = {
3089 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3092 /* matches smp_wmb() in event_sched_in() */
3096 * We only want to restart ACTIVE events, so if the event goes
3097 * inactive here (event->oncpu==-1), there's nothing more to do;
3098 * fall through with ret==-ENXIO.
3100 ret = cpu_function_call(READ_ONCE(event->oncpu),
3101 __perf_event_stop, &sd);
3102 } while (ret == -EAGAIN);
3108 * In order to contain the amount of racy and tricky in the address filter
3109 * configuration management, it is a two part process:
3111 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3112 * we update the addresses of corresponding vmas in
3113 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3114 * (p2) when an event is scheduled in (pmu::add), it calls
3115 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3116 * if the generation has changed since the previous call.
3118 * If (p1) happens while the event is active, we restart it to force (p2).
3120 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3121 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3123 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3124 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3126 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3129 void perf_event_addr_filters_sync(struct perf_event *event)
3131 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3133 if (!has_addr_filter(event))
3136 raw_spin_lock(&ifh->lock);
3137 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3138 event->pmu->addr_filters_sync(event);
3139 event->hw.addr_filters_gen = event->addr_filters_gen;
3141 raw_spin_unlock(&ifh->lock);
3143 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3145 static int _perf_event_refresh(struct perf_event *event, int refresh)
3148 * not supported on inherited events
3150 if (event->attr.inherit || !is_sampling_event(event))
3153 atomic_add(refresh, &event->event_limit);
3154 _perf_event_enable(event);
3160 * See perf_event_disable()
3162 int perf_event_refresh(struct perf_event *event, int refresh)
3164 struct perf_event_context *ctx;
3167 ctx = perf_event_ctx_lock(event);
3168 ret = _perf_event_refresh(event, refresh);
3169 perf_event_ctx_unlock(event, ctx);
3173 EXPORT_SYMBOL_GPL(perf_event_refresh);
3175 static int perf_event_modify_breakpoint(struct perf_event *bp,
3176 struct perf_event_attr *attr)
3180 _perf_event_disable(bp);
3182 err = modify_user_hw_breakpoint_check(bp, attr, true);
3184 if (!bp->attr.disabled)
3185 _perf_event_enable(bp);
3191 * Copy event-type-independent attributes that may be modified.
3193 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3194 const struct perf_event_attr *from)
3196 to->sig_data = from->sig_data;
3199 static int perf_event_modify_attr(struct perf_event *event,
3200 struct perf_event_attr *attr)
3202 int (*func)(struct perf_event *, struct perf_event_attr *);
3203 struct perf_event *child;
3206 if (event->attr.type != attr->type)
3209 switch (event->attr.type) {
3210 case PERF_TYPE_BREAKPOINT:
3211 func = perf_event_modify_breakpoint;
3214 /* Place holder for future additions. */
3218 WARN_ON_ONCE(event->ctx->parent_ctx);
3220 mutex_lock(&event->child_mutex);
3222 * Event-type-independent attributes must be copied before event-type
3223 * modification, which will validate that final attributes match the
3224 * source attributes after all relevant attributes have been copied.
3226 perf_event_modify_copy_attr(&event->attr, attr);
3227 err = func(event, attr);
3230 list_for_each_entry(child, &event->child_list, child_list) {
3231 perf_event_modify_copy_attr(&child->attr, attr);
3232 err = func(child, attr);
3237 mutex_unlock(&event->child_mutex);
3241 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3242 enum event_type_t event_type)
3244 struct perf_event_context *ctx = pmu_ctx->ctx;
3245 struct perf_event *event, *tmp;
3246 struct pmu *pmu = pmu_ctx->pmu;
3248 if (ctx->task && !ctx->is_active) {
3249 struct perf_cpu_pmu_context *cpc;
3251 cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3252 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3253 cpc->task_epc = NULL;
3259 perf_pmu_disable(pmu);
3260 if (event_type & EVENT_PINNED) {
3261 list_for_each_entry_safe(event, tmp,
3262 &pmu_ctx->pinned_active,
3264 group_sched_out(event, ctx);
3267 if (event_type & EVENT_FLEXIBLE) {
3268 list_for_each_entry_safe(event, tmp,
3269 &pmu_ctx->flexible_active,
3271 group_sched_out(event, ctx);
3273 * Since we cleared EVENT_FLEXIBLE, also clear
3274 * rotate_necessary, is will be reset by
3275 * ctx_flexible_sched_in() when needed.
3277 pmu_ctx->rotate_necessary = 0;
3279 perf_pmu_enable(pmu);
3283 ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type)
3285 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3286 struct perf_event_pmu_context *pmu_ctx;
3287 int is_active = ctx->is_active;
3288 bool cgroup = event_type & EVENT_CGROUP;
3290 event_type &= ~EVENT_CGROUP;
3292 lockdep_assert_held(&ctx->lock);
3294 if (likely(!ctx->nr_events)) {
3296 * See __perf_remove_from_context().
3298 WARN_ON_ONCE(ctx->is_active);
3300 WARN_ON_ONCE(cpuctx->task_ctx);
3305 * Always update time if it was set; not only when it changes.
3306 * Otherwise we can 'forget' to update time for any but the last
3307 * context we sched out. For example:
3309 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3310 * ctx_sched_out(.event_type = EVENT_PINNED)
3312 * would only update time for the pinned events.
3314 if (is_active & EVENT_TIME) {
3315 /* update (and stop) ctx time */
3316 update_context_time(ctx);
3317 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3319 * CPU-release for the below ->is_active store,
3320 * see __load_acquire() in perf_event_time_now()
3325 ctx->is_active &= ~event_type;
3326 if (!(ctx->is_active & EVENT_ALL))
3330 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3331 if (!ctx->is_active)
3332 cpuctx->task_ctx = NULL;
3335 is_active ^= ctx->is_active; /* changed bits */
3337 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3338 if (cgroup && !pmu_ctx->nr_cgroups)
3340 __pmu_ctx_sched_out(pmu_ctx, is_active);
3345 * Test whether two contexts are equivalent, i.e. whether they have both been
3346 * cloned from the same version of the same context.
3348 * Equivalence is measured using a generation number in the context that is
3349 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3350 * and list_del_event().
3352 static int context_equiv(struct perf_event_context *ctx1,
3353 struct perf_event_context *ctx2)
3355 lockdep_assert_held(&ctx1->lock);
3356 lockdep_assert_held(&ctx2->lock);
3358 /* Pinning disables the swap optimization */
3359 if (ctx1->pin_count || ctx2->pin_count)
3362 /* If ctx1 is the parent of ctx2 */
3363 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3366 /* If ctx2 is the parent of ctx1 */
3367 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3371 * If ctx1 and ctx2 have the same parent; we flatten the parent
3372 * hierarchy, see perf_event_init_context().
3374 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3375 ctx1->parent_gen == ctx2->parent_gen)
3382 static void __perf_event_sync_stat(struct perf_event *event,
3383 struct perf_event *next_event)
3387 if (!event->attr.inherit_stat)
3391 * Update the event value, we cannot use perf_event_read()
3392 * because we're in the middle of a context switch and have IRQs
3393 * disabled, which upsets smp_call_function_single(), however
3394 * we know the event must be on the current CPU, therefore we
3395 * don't need to use it.
3397 if (event->state == PERF_EVENT_STATE_ACTIVE)
3398 event->pmu->read(event);
3400 perf_event_update_time(event);
3403 * In order to keep per-task stats reliable we need to flip the event
3404 * values when we flip the contexts.
3406 value = local64_read(&next_event->count);
3407 value = local64_xchg(&event->count, value);
3408 local64_set(&next_event->count, value);
3410 swap(event->total_time_enabled, next_event->total_time_enabled);
3411 swap(event->total_time_running, next_event->total_time_running);
3414 * Since we swizzled the values, update the user visible data too.
3416 perf_event_update_userpage(event);
3417 perf_event_update_userpage(next_event);
3420 static void perf_event_sync_stat(struct perf_event_context *ctx,
3421 struct perf_event_context *next_ctx)
3423 struct perf_event *event, *next_event;
3428 update_context_time(ctx);
3430 event = list_first_entry(&ctx->event_list,
3431 struct perf_event, event_entry);
3433 next_event = list_first_entry(&next_ctx->event_list,
3434 struct perf_event, event_entry);
3436 while (&event->event_entry != &ctx->event_list &&
3437 &next_event->event_entry != &next_ctx->event_list) {
3439 __perf_event_sync_stat(event, next_event);
3441 event = list_next_entry(event, event_entry);
3442 next_event = list_next_entry(next_event, event_entry);
3446 #define double_list_for_each_entry(pos1, pos2, head1, head2, member) \
3447 for (pos1 = list_first_entry(head1, typeof(*pos1), member), \
3448 pos2 = list_first_entry(head2, typeof(*pos2), member); \
3449 !list_entry_is_head(pos1, head1, member) && \
3450 !list_entry_is_head(pos2, head2, member); \
3451 pos1 = list_next_entry(pos1, member), \
3452 pos2 = list_next_entry(pos2, member))
3454 static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx,
3455 struct perf_event_context *next_ctx)
3457 struct perf_event_pmu_context *prev_epc, *next_epc;
3459 if (!prev_ctx->nr_task_data)
3462 double_list_for_each_entry(prev_epc, next_epc,
3463 &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list,
3466 if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu))
3470 * PMU specific parts of task perf context can require
3471 * additional synchronization. As an example of such
3472 * synchronization see implementation details of Intel
3473 * LBR call stack data profiling;
3475 if (prev_epc->pmu->swap_task_ctx)
3476 prev_epc->pmu->swap_task_ctx(prev_epc, next_epc);
3478 swap(prev_epc->task_ctx_data, next_epc->task_ctx_data);
3482 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in)
3484 struct perf_event_pmu_context *pmu_ctx;
3485 struct perf_cpu_pmu_context *cpc;
3487 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3488 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3490 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3491 pmu_ctx->pmu->sched_task(pmu_ctx, sched_in);
3496 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3498 struct perf_event_context *ctx = task->perf_event_ctxp;
3499 struct perf_event_context *next_ctx;
3500 struct perf_event_context *parent, *next_parent;
3507 next_ctx = rcu_dereference(next->perf_event_ctxp);
3511 parent = rcu_dereference(ctx->parent_ctx);
3512 next_parent = rcu_dereference(next_ctx->parent_ctx);
3514 /* If neither context have a parent context; they cannot be clones. */
3515 if (!parent && !next_parent)
3518 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3520 * Looks like the two contexts are clones, so we might be
3521 * able to optimize the context switch. We lock both
3522 * contexts and check that they are clones under the
3523 * lock (including re-checking that neither has been
3524 * uncloned in the meantime). It doesn't matter which
3525 * order we take the locks because no other cpu could
3526 * be trying to lock both of these tasks.
3528 raw_spin_lock(&ctx->lock);
3529 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3530 if (context_equiv(ctx, next_ctx)) {
3532 perf_ctx_disable(ctx, false);
3534 /* PMIs are disabled; ctx->nr_pending is stable. */
3535 if (local_read(&ctx->nr_pending) ||
3536 local_read(&next_ctx->nr_pending)) {
3538 * Must not swap out ctx when there's pending
3539 * events that rely on the ctx->task relation.
3541 raw_spin_unlock(&next_ctx->lock);
3546 WRITE_ONCE(ctx->task, next);
3547 WRITE_ONCE(next_ctx->task, task);
3549 perf_ctx_sched_task_cb(ctx, false);
3550 perf_event_swap_task_ctx_data(ctx, next_ctx);
3552 perf_ctx_enable(ctx, false);
3555 * RCU_INIT_POINTER here is safe because we've not
3556 * modified the ctx and the above modification of
3557 * ctx->task and ctx->task_ctx_data are immaterial
3558 * since those values are always verified under
3559 * ctx->lock which we're now holding.
3561 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3562 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3566 perf_event_sync_stat(ctx, next_ctx);
3568 raw_spin_unlock(&next_ctx->lock);
3569 raw_spin_unlock(&ctx->lock);
3575 raw_spin_lock(&ctx->lock);
3576 perf_ctx_disable(ctx, false);
3579 perf_ctx_sched_task_cb(ctx, false);
3580 task_ctx_sched_out(ctx, EVENT_ALL);
3582 perf_ctx_enable(ctx, false);
3583 raw_spin_unlock(&ctx->lock);
3587 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3588 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3590 void perf_sched_cb_dec(struct pmu *pmu)
3592 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3594 this_cpu_dec(perf_sched_cb_usages);
3597 if (!--cpc->sched_cb_usage)
3598 list_del(&cpc->sched_cb_entry);
3602 void perf_sched_cb_inc(struct pmu *pmu)
3604 struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3606 if (!cpc->sched_cb_usage++)
3607 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3610 this_cpu_inc(perf_sched_cb_usages);
3614 * This function provides the context switch callback to the lower code
3615 * layer. It is invoked ONLY when the context switch callback is enabled.
3617 * This callback is relevant even to per-cpu events; for example multi event
3618 * PEBS requires this to provide PID/TID information. This requires we flush
3619 * all queued PEBS records before we context switch to a new task.
3621 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in)
3623 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3628 /* software PMUs will not have sched_task */
3629 if (WARN_ON_ONCE(!pmu->sched_task))
3632 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3633 perf_pmu_disable(pmu);
3635 pmu->sched_task(cpc->task_epc, sched_in);
3637 perf_pmu_enable(pmu);
3638 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3641 static void perf_pmu_sched_task(struct task_struct *prev,
3642 struct task_struct *next,
3645 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3646 struct perf_cpu_pmu_context *cpc;
3648 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3649 if (prev == next || cpuctx->task_ctx)
3652 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3653 __perf_pmu_sched_task(cpc, sched_in);
3656 static void perf_event_switch(struct task_struct *task,
3657 struct task_struct *next_prev, bool sched_in);
3660 * Called from scheduler to remove the events of the current task,
3661 * with interrupts disabled.
3663 * We stop each event and update the event value in event->count.
3665 * This does not protect us against NMI, but disable()
3666 * sets the disabled bit in the control field of event _before_
3667 * accessing the event control register. If a NMI hits, then it will
3668 * not restart the event.
3670 void __perf_event_task_sched_out(struct task_struct *task,
3671 struct task_struct *next)
3673 if (__this_cpu_read(perf_sched_cb_usages))
3674 perf_pmu_sched_task(task, next, false);
3676 if (atomic_read(&nr_switch_events))
3677 perf_event_switch(task, next, false);
3679 perf_event_context_sched_out(task, next);
3682 * if cgroup events exist on this CPU, then we need
3683 * to check if we have to switch out PMU state.
3684 * cgroup event are system-wide mode only
3686 perf_cgroup_switch(next);
3689 static bool perf_less_group_idx(const void *l, const void *r)
3691 const struct perf_event *le = *(const struct perf_event **)l;
3692 const struct perf_event *re = *(const struct perf_event **)r;
3694 return le->group_index < re->group_index;
3697 static void swap_ptr(void *l, void *r)
3699 void **lp = l, **rp = r;
3704 static const struct min_heap_callbacks perf_min_heap = {
3705 .elem_size = sizeof(struct perf_event *),
3706 .less = perf_less_group_idx,
3710 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3712 struct perf_event **itrs = heap->data;
3715 itrs[heap->nr] = event;
3720 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3722 struct perf_cpu_pmu_context *cpc;
3724 if (!pmu_ctx->ctx->task)
3727 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3728 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3729 cpc->task_epc = pmu_ctx;
3732 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3733 struct perf_event_groups *groups, int cpu,
3735 int (*func)(struct perf_event *, void *),
3738 #ifdef CONFIG_CGROUP_PERF
3739 struct cgroup_subsys_state *css = NULL;
3741 struct perf_cpu_context *cpuctx = NULL;
3742 /* Space for per CPU and/or any CPU event iterators. */
3743 struct perf_event *itrs[2];
3744 struct min_heap event_heap;
3745 struct perf_event **evt;
3748 if (pmu->filter && pmu->filter(pmu, cpu))
3752 cpuctx = this_cpu_ptr(&perf_cpu_context);
3753 event_heap = (struct min_heap){
3754 .data = cpuctx->heap,
3756 .size = cpuctx->heap_size,
3759 lockdep_assert_held(&cpuctx->ctx.lock);
3761 #ifdef CONFIG_CGROUP_PERF
3763 css = &cpuctx->cgrp->css;
3766 event_heap = (struct min_heap){
3769 .size = ARRAY_SIZE(itrs),
3771 /* Events not within a CPU context may be on any CPU. */
3772 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3774 evt = event_heap.data;
3776 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3778 #ifdef CONFIG_CGROUP_PERF
3779 for (; css; css = css->parent)
3780 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3783 if (event_heap.nr) {
3784 __link_epc((*evt)->pmu_ctx);
3785 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3788 min_heapify_all(&event_heap, &perf_min_heap);
3790 while (event_heap.nr) {
3791 ret = func(*evt, data);
3795 *evt = perf_event_groups_next(*evt, pmu);
3797 min_heapify(&event_heap, 0, &perf_min_heap);
3799 min_heap_pop(&event_heap, &perf_min_heap);
3806 * Because the userpage is strictly per-event (there is no concept of context,
3807 * so there cannot be a context indirection), every userpage must be updated
3808 * when context time starts :-(
3810 * IOW, we must not miss EVENT_TIME edges.
3812 static inline bool event_update_userpage(struct perf_event *event)
3814 if (likely(!atomic_read(&event->mmap_count)))
3817 perf_event_update_time(event);
3818 perf_event_update_userpage(event);
3823 static inline void group_update_userpage(struct perf_event *group_event)
3825 struct perf_event *event;
3827 if (!event_update_userpage(group_event))
3830 for_each_sibling_event(event, group_event)
3831 event_update_userpage(event);
3834 static int merge_sched_in(struct perf_event *event, void *data)
3836 struct perf_event_context *ctx = event->ctx;
3837 int *can_add_hw = data;
3839 if (event->state <= PERF_EVENT_STATE_OFF)
3842 if (!event_filter_match(event))
3845 if (group_can_go_on(event, *can_add_hw)) {
3846 if (!group_sched_in(event, ctx))
3847 list_add_tail(&event->active_list, get_event_list(event));
3850 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3852 if (event->attr.pinned) {
3853 perf_cgroup_event_disable(event, ctx);
3854 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3856 struct perf_cpu_pmu_context *cpc;
3858 event->pmu_ctx->rotate_necessary = 1;
3859 cpc = this_cpu_ptr(event->pmu_ctx->pmu->cpu_pmu_context);
3860 perf_mux_hrtimer_restart(cpc);
3861 group_update_userpage(event);
3868 static void pmu_groups_sched_in(struct perf_event_context *ctx,
3869 struct perf_event_groups *groups,
3873 visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
3874 merge_sched_in, &can_add_hw);
3877 static void ctx_groups_sched_in(struct perf_event_context *ctx,
3878 struct perf_event_groups *groups,
3881 struct perf_event_pmu_context *pmu_ctx;
3883 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3884 if (cgroup && !pmu_ctx->nr_cgroups)
3886 pmu_groups_sched_in(ctx, groups, pmu_ctx->pmu);
3890 static void __pmu_ctx_sched_in(struct perf_event_context *ctx,
3893 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu);
3897 ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type)
3899 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3900 int is_active = ctx->is_active;
3901 bool cgroup = event_type & EVENT_CGROUP;
3903 event_type &= ~EVENT_CGROUP;
3905 lockdep_assert_held(&ctx->lock);
3907 if (likely(!ctx->nr_events))
3910 if (!(is_active & EVENT_TIME)) {
3911 /* start ctx time */
3912 __update_context_time(ctx, false);
3913 perf_cgroup_set_timestamp(cpuctx);
3915 * CPU-release for the below ->is_active store,
3916 * see __load_acquire() in perf_event_time_now()
3921 ctx->is_active |= (event_type | EVENT_TIME);
3924 cpuctx->task_ctx = ctx;
3926 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3929 is_active ^= ctx->is_active; /* changed bits */
3932 * First go through the list and put on any pinned groups
3933 * in order to give them the best chance of going on.
3935 if (is_active & EVENT_PINNED)
3936 ctx_groups_sched_in(ctx, &ctx->pinned_groups, cgroup);
3938 /* Then walk through the lower prio flexible groups */
3939 if (is_active & EVENT_FLEXIBLE)
3940 ctx_groups_sched_in(ctx, &ctx->flexible_groups, cgroup);
3943 static void perf_event_context_sched_in(struct task_struct *task)
3945 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3946 struct perf_event_context *ctx;
3949 ctx = rcu_dereference(task->perf_event_ctxp);
3953 if (cpuctx->task_ctx == ctx) {
3954 perf_ctx_lock(cpuctx, ctx);
3955 perf_ctx_disable(ctx, false);
3957 perf_ctx_sched_task_cb(ctx, true);
3959 perf_ctx_enable(ctx, false);
3960 perf_ctx_unlock(cpuctx, ctx);
3964 perf_ctx_lock(cpuctx, ctx);
3966 * We must check ctx->nr_events while holding ctx->lock, such
3967 * that we serialize against perf_install_in_context().
3969 if (!ctx->nr_events)
3972 perf_ctx_disable(ctx, false);
3974 * We want to keep the following priority order:
3975 * cpu pinned (that don't need to move), task pinned,
3976 * cpu flexible, task flexible.
3978 * However, if task's ctx is not carrying any pinned
3979 * events, no need to flip the cpuctx's events around.
3981 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
3982 perf_ctx_disable(&cpuctx->ctx, false);
3983 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
3986 perf_event_sched_in(cpuctx, ctx);
3988 perf_ctx_sched_task_cb(cpuctx->task_ctx, true);
3990 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3991 perf_ctx_enable(&cpuctx->ctx, false);
3993 perf_ctx_enable(ctx, false);
3996 perf_ctx_unlock(cpuctx, ctx);
4002 * Called from scheduler to add the events of the current task
4003 * with interrupts disabled.
4005 * We restore the event value and then enable it.
4007 * This does not protect us against NMI, but enable()
4008 * sets the enabled bit in the control field of event _before_
4009 * accessing the event control register. If a NMI hits, then it will
4010 * keep the event running.
4012 void __perf_event_task_sched_in(struct task_struct *prev,
4013 struct task_struct *task)
4015 perf_event_context_sched_in(task);
4017 if (atomic_read(&nr_switch_events))
4018 perf_event_switch(task, prev, true);
4020 if (__this_cpu_read(perf_sched_cb_usages))
4021 perf_pmu_sched_task(prev, task, true);
4024 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4026 u64 frequency = event->attr.sample_freq;
4027 u64 sec = NSEC_PER_SEC;
4028 u64 divisor, dividend;
4030 int count_fls, nsec_fls, frequency_fls, sec_fls;
4032 count_fls = fls64(count);
4033 nsec_fls = fls64(nsec);
4034 frequency_fls = fls64(frequency);
4038 * We got @count in @nsec, with a target of sample_freq HZ
4039 * the target period becomes:
4042 * period = -------------------
4043 * @nsec * sample_freq
4048 * Reduce accuracy by one bit such that @a and @b converge
4049 * to a similar magnitude.
4051 #define REDUCE_FLS(a, b) \
4053 if (a##_fls > b##_fls) { \
4063 * Reduce accuracy until either term fits in a u64, then proceed with
4064 * the other, so that finally we can do a u64/u64 division.
4066 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4067 REDUCE_FLS(nsec, frequency);
4068 REDUCE_FLS(sec, count);
4071 if (count_fls + sec_fls > 64) {
4072 divisor = nsec * frequency;
4074 while (count_fls + sec_fls > 64) {
4075 REDUCE_FLS(count, sec);
4079 dividend = count * sec;
4081 dividend = count * sec;
4083 while (nsec_fls + frequency_fls > 64) {
4084 REDUCE_FLS(nsec, frequency);
4088 divisor = nsec * frequency;
4094 return div64_u64(dividend, divisor);
4097 static DEFINE_PER_CPU(int, perf_throttled_count);
4098 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4100 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4102 struct hw_perf_event *hwc = &event->hw;
4103 s64 period, sample_period;
4106 period = perf_calculate_period(event, nsec, count);
4108 delta = (s64)(period - hwc->sample_period);
4109 delta = (delta + 7) / 8; /* low pass filter */
4111 sample_period = hwc->sample_period + delta;
4116 hwc->sample_period = sample_period;
4118 if (local64_read(&hwc->period_left) > 8*sample_period) {
4120 event->pmu->stop(event, PERF_EF_UPDATE);
4122 local64_set(&hwc->period_left, 0);
4125 event->pmu->start(event, PERF_EF_RELOAD);
4129 static void perf_adjust_freq_unthr_events(struct list_head *event_list)
4131 struct perf_event *event;
4132 struct hw_perf_event *hwc;
4133 u64 now, period = TICK_NSEC;
4136 list_for_each_entry(event, event_list, active_list) {
4137 if (event->state != PERF_EVENT_STATE_ACTIVE)
4140 // XXX use visit thingy to avoid the -1,cpu match
4141 if (!event_filter_match(event))
4146 if (hwc->interrupts == MAX_INTERRUPTS) {
4147 hwc->interrupts = 0;
4148 perf_log_throttle(event, 1);
4149 if (!event->attr.freq || !event->attr.sample_freq)
4150 event->pmu->start(event, 0);
4153 if (!event->attr.freq || !event->attr.sample_freq)
4157 * stop the event and update event->count
4159 event->pmu->stop(event, PERF_EF_UPDATE);
4161 now = local64_read(&event->count);
4162 delta = now - hwc->freq_count_stamp;
4163 hwc->freq_count_stamp = now;
4167 * reload only if value has changed
4168 * we have stopped the event so tell that
4169 * to perf_adjust_period() to avoid stopping it
4173 perf_adjust_period(event, period, delta, false);
4175 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4180 * combine freq adjustment with unthrottling to avoid two passes over the
4181 * events. At the same time, make sure, having freq events does not change
4182 * the rate of unthrottling as that would introduce bias.
4185 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4187 struct perf_event_pmu_context *pmu_ctx;
4190 * only need to iterate over all events iff:
4191 * - context have events in frequency mode (needs freq adjust)
4192 * - there are events to unthrottle on this cpu
4194 if (!(ctx->nr_freq || unthrottle))
4197 raw_spin_lock(&ctx->lock);
4199 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4200 if (!(pmu_ctx->nr_freq || unthrottle))
4202 if (!perf_pmu_ctx_is_active(pmu_ctx))
4204 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4207 perf_pmu_disable(pmu_ctx->pmu);
4208 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4209 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4210 perf_pmu_enable(pmu_ctx->pmu);
4213 raw_spin_unlock(&ctx->lock);
4217 * Move @event to the tail of the @ctx's elegible events.
4219 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4222 * Rotate the first entry last of non-pinned groups. Rotation might be
4223 * disabled by the inheritance code.
4225 if (ctx->rotate_disable)
4228 perf_event_groups_delete(&ctx->flexible_groups, event);
4229 perf_event_groups_insert(&ctx->flexible_groups, event);
4232 /* pick an event from the flexible_groups to rotate */
4233 static inline struct perf_event *
4234 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4236 struct perf_event *event;
4237 struct rb_node *node;
4238 struct rb_root *tree;
4239 struct __group_key key = {
4240 .pmu = pmu_ctx->pmu,
4243 /* pick the first active flexible event */
4244 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4245 struct perf_event, active_list);
4249 /* if no active flexible event, pick the first event */
4250 tree = &pmu_ctx->ctx->flexible_groups.tree;
4252 if (!pmu_ctx->ctx->task) {
4253 key.cpu = smp_processor_id();
4255 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4257 event = __node_2_pe(node);
4262 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4264 event = __node_2_pe(node);
4268 key.cpu = smp_processor_id();
4269 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4271 event = __node_2_pe(node);
4275 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4276 * finds there are unschedulable events, it will set it again.
4278 pmu_ctx->rotate_necessary = 0;
4283 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4285 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4286 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4287 struct perf_event *cpu_event = NULL, *task_event = NULL;
4288 int cpu_rotate, task_rotate;
4292 * Since we run this from IRQ context, nobody can install new
4293 * events, thus the event count values are stable.
4296 cpu_epc = &cpc->epc;
4298 task_epc = cpc->task_epc;
4300 cpu_rotate = cpu_epc->rotate_necessary;
4301 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4303 if (!(cpu_rotate || task_rotate))
4306 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4307 perf_pmu_disable(pmu);
4310 task_event = ctx_event_to_rotate(task_epc);
4312 cpu_event = ctx_event_to_rotate(cpu_epc);
4315 * As per the order given at ctx_resched() first 'pop' task flexible
4316 * and then, if needed CPU flexible.
4318 if (task_event || (task_epc && cpu_event)) {
4319 update_context_time(task_epc->ctx);
4320 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4324 update_context_time(&cpuctx->ctx);
4325 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4326 rotate_ctx(&cpuctx->ctx, cpu_event);
4327 __pmu_ctx_sched_in(&cpuctx->ctx, pmu);
4331 rotate_ctx(task_epc->ctx, task_event);
4333 if (task_event || (task_epc && cpu_event))
4334 __pmu_ctx_sched_in(task_epc->ctx, pmu);
4336 perf_pmu_enable(pmu);
4337 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4342 void perf_event_task_tick(void)
4344 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4345 struct perf_event_context *ctx;
4348 lockdep_assert_irqs_disabled();
4350 __this_cpu_inc(perf_throttled_seq);
4351 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4352 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4354 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4357 ctx = rcu_dereference(current->perf_event_ctxp);
4359 perf_adjust_freq_unthr_context(ctx, !!throttled);
4363 static int event_enable_on_exec(struct perf_event *event,
4364 struct perf_event_context *ctx)
4366 if (!event->attr.enable_on_exec)
4369 event->attr.enable_on_exec = 0;
4370 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4373 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4379 * Enable all of a task's events that have been marked enable-on-exec.
4380 * This expects task == current.
4382 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4384 struct perf_event_context *clone_ctx = NULL;
4385 enum event_type_t event_type = 0;
4386 struct perf_cpu_context *cpuctx;
4387 struct perf_event *event;
4388 unsigned long flags;
4391 local_irq_save(flags);
4392 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4395 if (!ctx->nr_events)
4398 cpuctx = this_cpu_ptr(&perf_cpu_context);
4399 perf_ctx_lock(cpuctx, ctx);
4400 ctx_sched_out(ctx, EVENT_TIME);
4402 list_for_each_entry(event, &ctx->event_list, event_entry) {
4403 enabled |= event_enable_on_exec(event, ctx);
4404 event_type |= get_event_type(event);
4408 * Unclone and reschedule this context if we enabled any event.
4411 clone_ctx = unclone_ctx(ctx);
4412 ctx_resched(cpuctx, ctx, event_type);
4414 ctx_sched_in(ctx, EVENT_TIME);
4416 perf_ctx_unlock(cpuctx, ctx);
4419 local_irq_restore(flags);
4425 static void perf_remove_from_owner(struct perf_event *event);
4426 static void perf_event_exit_event(struct perf_event *event,
4427 struct perf_event_context *ctx);
4430 * Removes all events from the current task that have been marked
4431 * remove-on-exec, and feeds their values back to parent events.
4433 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4435 struct perf_event_context *clone_ctx = NULL;
4436 struct perf_event *event, *next;
4437 unsigned long flags;
4438 bool modified = false;
4440 mutex_lock(&ctx->mutex);
4442 if (WARN_ON_ONCE(ctx->task != current))
4445 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4446 if (!event->attr.remove_on_exec)
4449 if (!is_kernel_event(event))
4450 perf_remove_from_owner(event);
4454 perf_event_exit_event(event, ctx);
4457 raw_spin_lock_irqsave(&ctx->lock, flags);
4459 clone_ctx = unclone_ctx(ctx);
4460 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4463 mutex_unlock(&ctx->mutex);
4469 struct perf_read_data {
4470 struct perf_event *event;
4475 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4477 u16 local_pkg, event_pkg;
4479 if ((unsigned)event_cpu >= nr_cpu_ids)
4482 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4483 int local_cpu = smp_processor_id();
4485 event_pkg = topology_physical_package_id(event_cpu);
4486 local_pkg = topology_physical_package_id(local_cpu);
4488 if (event_pkg == local_pkg)
4496 * Cross CPU call to read the hardware event
4498 static void __perf_event_read(void *info)
4500 struct perf_read_data *data = info;
4501 struct perf_event *sub, *event = data->event;
4502 struct perf_event_context *ctx = event->ctx;
4503 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4504 struct pmu *pmu = event->pmu;
4507 * If this is a task context, we need to check whether it is
4508 * the current task context of this cpu. If not it has been
4509 * scheduled out before the smp call arrived. In that case
4510 * event->count would have been updated to a recent sample
4511 * when the event was scheduled out.
4513 if (ctx->task && cpuctx->task_ctx != ctx)
4516 raw_spin_lock(&ctx->lock);
4517 if (ctx->is_active & EVENT_TIME) {
4518 update_context_time(ctx);
4519 update_cgrp_time_from_event(event);
4522 perf_event_update_time(event);
4524 perf_event_update_sibling_time(event);
4526 if (event->state != PERF_EVENT_STATE_ACTIVE)
4535 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4539 for_each_sibling_event(sub, event) {
4540 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4542 * Use sibling's PMU rather than @event's since
4543 * sibling could be on different (eg: software) PMU.
4545 sub->pmu->read(sub);
4549 data->ret = pmu->commit_txn(pmu);
4552 raw_spin_unlock(&ctx->lock);
4555 static inline u64 perf_event_count(struct perf_event *event)
4557 return local64_read(&event->count) + atomic64_read(&event->child_count);
4560 static void calc_timer_values(struct perf_event *event,
4567 *now = perf_clock();
4568 ctx_time = perf_event_time_now(event, *now);
4569 __perf_update_times(event, ctx_time, enabled, running);
4573 * NMI-safe method to read a local event, that is an event that
4575 * - either for the current task, or for this CPU
4576 * - does not have inherit set, for inherited task events
4577 * will not be local and we cannot read them atomically
4578 * - must not have a pmu::count method
4580 int perf_event_read_local(struct perf_event *event, u64 *value,
4581 u64 *enabled, u64 *running)
4583 unsigned long flags;
4589 * Disabling interrupts avoids all counter scheduling (context
4590 * switches, timer based rotation and IPIs).
4592 local_irq_save(flags);
4595 * It must not be an event with inherit set, we cannot read
4596 * all child counters from atomic context.
4598 if (event->attr.inherit) {
4603 /* If this is a per-task event, it must be for current */
4604 if ((event->attach_state & PERF_ATTACH_TASK) &&
4605 event->hw.target != current) {
4611 * Get the event CPU numbers, and adjust them to local if the event is
4612 * a per-package event that can be read locally
4614 event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4615 event_cpu = __perf_event_read_cpu(event, event->cpu);
4617 /* If this is a per-CPU event, it must be for this CPU */
4618 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4619 event_cpu != smp_processor_id()) {
4624 /* If this is a pinned event it must be running on this CPU */
4625 if (event->attr.pinned && event_oncpu != smp_processor_id()) {
4631 * If the event is currently on this CPU, its either a per-task event,
4632 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4635 if (event_oncpu == smp_processor_id())
4636 event->pmu->read(event);
4638 *value = local64_read(&event->count);
4639 if (enabled || running) {
4640 u64 __enabled, __running, __now;
4642 calc_timer_values(event, &__now, &__enabled, &__running);
4644 *enabled = __enabled;
4646 *running = __running;
4649 local_irq_restore(flags);
4654 static int perf_event_read(struct perf_event *event, bool group)
4656 enum perf_event_state state = READ_ONCE(event->state);
4657 int event_cpu, ret = 0;
4660 * If event is enabled and currently active on a CPU, update the
4661 * value in the event structure:
4664 if (state == PERF_EVENT_STATE_ACTIVE) {
4665 struct perf_read_data data;
4668 * Orders the ->state and ->oncpu loads such that if we see
4669 * ACTIVE we must also see the right ->oncpu.
4671 * Matches the smp_wmb() from event_sched_in().
4675 event_cpu = READ_ONCE(event->oncpu);
4676 if ((unsigned)event_cpu >= nr_cpu_ids)
4679 data = (struct perf_read_data){
4686 event_cpu = __perf_event_read_cpu(event, event_cpu);
4689 * Purposely ignore the smp_call_function_single() return
4692 * If event_cpu isn't a valid CPU it means the event got
4693 * scheduled out and that will have updated the event count.
4695 * Therefore, either way, we'll have an up-to-date event count
4698 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4702 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4703 struct perf_event_context *ctx = event->ctx;
4704 unsigned long flags;
4706 raw_spin_lock_irqsave(&ctx->lock, flags);
4707 state = event->state;
4708 if (state != PERF_EVENT_STATE_INACTIVE) {
4709 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4714 * May read while context is not active (e.g., thread is
4715 * blocked), in that case we cannot update context time
4717 if (ctx->is_active & EVENT_TIME) {
4718 update_context_time(ctx);
4719 update_cgrp_time_from_event(event);
4722 perf_event_update_time(event);
4724 perf_event_update_sibling_time(event);
4725 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4732 * Initialize the perf_event context in a task_struct:
4734 static void __perf_event_init_context(struct perf_event_context *ctx)
4736 raw_spin_lock_init(&ctx->lock);
4737 mutex_init(&ctx->mutex);
4738 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4739 perf_event_groups_init(&ctx->pinned_groups);
4740 perf_event_groups_init(&ctx->flexible_groups);
4741 INIT_LIST_HEAD(&ctx->event_list);
4742 refcount_set(&ctx->refcount, 1);
4746 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4749 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4750 INIT_LIST_HEAD(&epc->pinned_active);
4751 INIT_LIST_HEAD(&epc->flexible_active);
4752 atomic_set(&epc->refcount, 1);
4755 static struct perf_event_context *
4756 alloc_perf_context(struct task_struct *task)
4758 struct perf_event_context *ctx;
4760 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4764 __perf_event_init_context(ctx);
4766 ctx->task = get_task_struct(task);
4771 static struct task_struct *
4772 find_lively_task_by_vpid(pid_t vpid)
4774 struct task_struct *task;
4780 task = find_task_by_vpid(vpid);
4782 get_task_struct(task);
4786 return ERR_PTR(-ESRCH);
4792 * Returns a matching context with refcount and pincount.
4794 static struct perf_event_context *
4795 find_get_context(struct task_struct *task, struct perf_event *event)
4797 struct perf_event_context *ctx, *clone_ctx = NULL;
4798 struct perf_cpu_context *cpuctx;
4799 unsigned long flags;
4803 /* Must be root to operate on a CPU event: */
4804 err = perf_allow_cpu(&event->attr);
4806 return ERR_PTR(err);
4808 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4811 raw_spin_lock_irqsave(&ctx->lock, flags);
4813 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4820 ctx = perf_lock_task_context(task, &flags);
4822 clone_ctx = unclone_ctx(ctx);
4825 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4830 ctx = alloc_perf_context(task);
4836 mutex_lock(&task->perf_event_mutex);
4838 * If it has already passed perf_event_exit_task().
4839 * we must see PF_EXITING, it takes this mutex too.
4841 if (task->flags & PF_EXITING)
4843 else if (task->perf_event_ctxp)
4848 rcu_assign_pointer(task->perf_event_ctxp, ctx);
4850 mutex_unlock(&task->perf_event_mutex);
4852 if (unlikely(err)) {
4864 return ERR_PTR(err);
4867 static struct perf_event_pmu_context *
4868 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
4869 struct perf_event *event)
4871 struct perf_event_pmu_context *new = NULL, *epc;
4872 void *task_ctx_data = NULL;
4876 * perf_pmu_migrate_context() / __perf_pmu_install_event()
4877 * relies on the fact that find_get_pmu_context() cannot fail
4880 struct perf_cpu_pmu_context *cpc;
4882 cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
4884 raw_spin_lock_irq(&ctx->lock);
4886 atomic_set(&epc->refcount, 1);
4888 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4891 WARN_ON_ONCE(epc->ctx != ctx);
4892 atomic_inc(&epc->refcount);
4894 raw_spin_unlock_irq(&ctx->lock);
4898 new = kzalloc(sizeof(*epc), GFP_KERNEL);
4900 return ERR_PTR(-ENOMEM);
4902 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4903 task_ctx_data = alloc_task_ctx_data(pmu);
4904 if (!task_ctx_data) {
4906 return ERR_PTR(-ENOMEM);
4910 __perf_init_event_pmu_context(new, pmu);
4915 * lockdep_assert_held(&ctx->mutex);
4917 * can't because perf_event_init_task() doesn't actually hold the
4921 raw_spin_lock_irq(&ctx->lock);
4922 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4923 if (epc->pmu == pmu) {
4924 WARN_ON_ONCE(epc->ctx != ctx);
4925 atomic_inc(&epc->refcount);
4933 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4937 if (task_ctx_data && !epc->task_ctx_data) {
4938 epc->task_ctx_data = task_ctx_data;
4939 task_ctx_data = NULL;
4940 ctx->nr_task_data++;
4942 raw_spin_unlock_irq(&ctx->lock);
4944 free_task_ctx_data(pmu, task_ctx_data);
4950 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
4952 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
4955 static void free_epc_rcu(struct rcu_head *head)
4957 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
4959 kfree(epc->task_ctx_data);
4963 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
4965 struct perf_event_context *ctx = epc->ctx;
4966 unsigned long flags;
4971 * lockdep_assert_held(&ctx->mutex);
4973 * can't because of the call-site in _free_event()/put_event()
4974 * which isn't always called under ctx->mutex.
4976 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
4979 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
4981 list_del_init(&epc->pmu_ctx_entry);
4984 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
4985 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
4987 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4992 call_rcu(&epc->rcu_head, free_epc_rcu);
4995 static void perf_event_free_filter(struct perf_event *event);
4997 static void free_event_rcu(struct rcu_head *head)
4999 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
5002 put_pid_ns(event->ns);
5003 perf_event_free_filter(event);
5004 kmem_cache_free(perf_event_cache, event);
5007 static void ring_buffer_attach(struct perf_event *event,
5008 struct perf_buffer *rb);
5010 static void detach_sb_event(struct perf_event *event)
5012 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5014 raw_spin_lock(&pel->lock);
5015 list_del_rcu(&event->sb_list);
5016 raw_spin_unlock(&pel->lock);
5019 static bool is_sb_event(struct perf_event *event)
5021 struct perf_event_attr *attr = &event->attr;
5026 if (event->attach_state & PERF_ATTACH_TASK)
5029 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5030 attr->comm || attr->comm_exec ||
5031 attr->task || attr->ksymbol ||
5032 attr->context_switch || attr->text_poke ||
5038 static void unaccount_pmu_sb_event(struct perf_event *event)
5040 if (is_sb_event(event))
5041 detach_sb_event(event);
5044 #ifdef CONFIG_NO_HZ_FULL
5045 static DEFINE_SPINLOCK(nr_freq_lock);
5048 static void unaccount_freq_event_nohz(void)
5050 #ifdef CONFIG_NO_HZ_FULL
5051 spin_lock(&nr_freq_lock);
5052 if (atomic_dec_and_test(&nr_freq_events))
5053 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5054 spin_unlock(&nr_freq_lock);
5058 static void unaccount_freq_event(void)
5060 if (tick_nohz_full_enabled())
5061 unaccount_freq_event_nohz();
5063 atomic_dec(&nr_freq_events);
5066 static void unaccount_event(struct perf_event *event)
5073 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5075 if (event->attr.mmap || event->attr.mmap_data)
5076 atomic_dec(&nr_mmap_events);
5077 if (event->attr.build_id)
5078 atomic_dec(&nr_build_id_events);
5079 if (event->attr.comm)
5080 atomic_dec(&nr_comm_events);
5081 if (event->attr.namespaces)
5082 atomic_dec(&nr_namespaces_events);
5083 if (event->attr.cgroup)
5084 atomic_dec(&nr_cgroup_events);
5085 if (event->attr.task)
5086 atomic_dec(&nr_task_events);
5087 if (event->attr.freq)
5088 unaccount_freq_event();
5089 if (event->attr.context_switch) {
5091 atomic_dec(&nr_switch_events);
5093 if (is_cgroup_event(event))
5095 if (has_branch_stack(event))
5097 if (event->attr.ksymbol)
5098 atomic_dec(&nr_ksymbol_events);
5099 if (event->attr.bpf_event)
5100 atomic_dec(&nr_bpf_events);
5101 if (event->attr.text_poke)
5102 atomic_dec(&nr_text_poke_events);
5105 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5106 schedule_delayed_work(&perf_sched_work, HZ);
5109 unaccount_pmu_sb_event(event);
5112 static void perf_sched_delayed(struct work_struct *work)
5114 mutex_lock(&perf_sched_mutex);
5115 if (atomic_dec_and_test(&perf_sched_count))
5116 static_branch_disable(&perf_sched_events);
5117 mutex_unlock(&perf_sched_mutex);
5121 * The following implement mutual exclusion of events on "exclusive" pmus
5122 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5123 * at a time, so we disallow creating events that might conflict, namely:
5125 * 1) cpu-wide events in the presence of per-task events,
5126 * 2) per-task events in the presence of cpu-wide events,
5127 * 3) two matching events on the same perf_event_context.
5129 * The former two cases are handled in the allocation path (perf_event_alloc(),
5130 * _free_event()), the latter -- before the first perf_install_in_context().
5132 static int exclusive_event_init(struct perf_event *event)
5134 struct pmu *pmu = event->pmu;
5136 if (!is_exclusive_pmu(pmu))
5140 * Prevent co-existence of per-task and cpu-wide events on the
5141 * same exclusive pmu.
5143 * Negative pmu::exclusive_cnt means there are cpu-wide
5144 * events on this "exclusive" pmu, positive means there are
5147 * Since this is called in perf_event_alloc() path, event::ctx
5148 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5149 * to mean "per-task event", because unlike other attach states it
5150 * never gets cleared.
5152 if (event->attach_state & PERF_ATTACH_TASK) {
5153 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5156 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5163 static void exclusive_event_destroy(struct perf_event *event)
5165 struct pmu *pmu = event->pmu;
5167 if (!is_exclusive_pmu(pmu))
5170 /* see comment in exclusive_event_init() */
5171 if (event->attach_state & PERF_ATTACH_TASK)
5172 atomic_dec(&pmu->exclusive_cnt);
5174 atomic_inc(&pmu->exclusive_cnt);
5177 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5179 if ((e1->pmu == e2->pmu) &&
5180 (e1->cpu == e2->cpu ||
5187 static bool exclusive_event_installable(struct perf_event *event,
5188 struct perf_event_context *ctx)
5190 struct perf_event *iter_event;
5191 struct pmu *pmu = event->pmu;
5193 lockdep_assert_held(&ctx->mutex);
5195 if (!is_exclusive_pmu(pmu))
5198 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5199 if (exclusive_event_match(iter_event, event))
5206 static void perf_addr_filters_splice(struct perf_event *event,
5207 struct list_head *head);
5209 static void _free_event(struct perf_event *event)
5211 irq_work_sync(&event->pending_irq);
5213 unaccount_event(event);
5215 security_perf_event_free(event);
5219 * Can happen when we close an event with re-directed output.
5221 * Since we have a 0 refcount, perf_mmap_close() will skip
5222 * over us; possibly making our ring_buffer_put() the last.
5224 mutex_lock(&event->mmap_mutex);
5225 ring_buffer_attach(event, NULL);
5226 mutex_unlock(&event->mmap_mutex);
5229 if (is_cgroup_event(event))
5230 perf_detach_cgroup(event);
5232 if (!event->parent) {
5233 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
5234 put_callchain_buffers();
5237 perf_event_free_bpf_prog(event);
5238 perf_addr_filters_splice(event, NULL);
5239 kfree(event->addr_filter_ranges);
5242 event->destroy(event);
5245 * Must be after ->destroy(), due to uprobe_perf_close() using
5248 if (event->hw.target)
5249 put_task_struct(event->hw.target);
5252 put_pmu_ctx(event->pmu_ctx);
5255 * perf_event_free_task() relies on put_ctx() being 'last', in particular
5256 * all task references must be cleaned up.
5259 put_ctx(event->ctx);
5261 exclusive_event_destroy(event);
5262 module_put(event->pmu->module);
5264 call_rcu(&event->rcu_head, free_event_rcu);
5268 * Used to free events which have a known refcount of 1, such as in error paths
5269 * where the event isn't exposed yet and inherited events.
5271 static void free_event(struct perf_event *event)
5273 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5274 "unexpected event refcount: %ld; ptr=%p\n",
5275 atomic_long_read(&event->refcount), event)) {
5276 /* leak to avoid use-after-free */
5284 * Remove user event from the owner task.
5286 static void perf_remove_from_owner(struct perf_event *event)
5288 struct task_struct *owner;
5292 * Matches the smp_store_release() in perf_event_exit_task(). If we
5293 * observe !owner it means the list deletion is complete and we can
5294 * indeed free this event, otherwise we need to serialize on
5295 * owner->perf_event_mutex.
5297 owner = READ_ONCE(event->owner);
5300 * Since delayed_put_task_struct() also drops the last
5301 * task reference we can safely take a new reference
5302 * while holding the rcu_read_lock().
5304 get_task_struct(owner);
5310 * If we're here through perf_event_exit_task() we're already
5311 * holding ctx->mutex which would be an inversion wrt. the
5312 * normal lock order.
5314 * However we can safely take this lock because its the child
5317 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5320 * We have to re-check the event->owner field, if it is cleared
5321 * we raced with perf_event_exit_task(), acquiring the mutex
5322 * ensured they're done, and we can proceed with freeing the
5326 list_del_init(&event->owner_entry);
5327 smp_store_release(&event->owner, NULL);
5329 mutex_unlock(&owner->perf_event_mutex);
5330 put_task_struct(owner);
5334 static void put_event(struct perf_event *event)
5336 if (!atomic_long_dec_and_test(&event->refcount))
5343 * Kill an event dead; while event:refcount will preserve the event
5344 * object, it will not preserve its functionality. Once the last 'user'
5345 * gives up the object, we'll destroy the thing.
5347 int perf_event_release_kernel(struct perf_event *event)
5349 struct perf_event_context *ctx = event->ctx;
5350 struct perf_event *child, *tmp;
5351 LIST_HEAD(free_list);
5354 * If we got here through err_alloc: free_event(event); we will not
5355 * have attached to a context yet.
5358 WARN_ON_ONCE(event->attach_state &
5359 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5363 if (!is_kernel_event(event))
5364 perf_remove_from_owner(event);
5366 ctx = perf_event_ctx_lock(event);
5367 WARN_ON_ONCE(ctx->parent_ctx);
5370 * Mark this event as STATE_DEAD, there is no external reference to it
5373 * Anybody acquiring event->child_mutex after the below loop _must_
5374 * also see this, most importantly inherit_event() which will avoid
5375 * placing more children on the list.
5377 * Thus this guarantees that we will in fact observe and kill _ALL_
5380 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5382 perf_event_ctx_unlock(event, ctx);
5385 mutex_lock(&event->child_mutex);
5386 list_for_each_entry(child, &event->child_list, child_list) {
5389 * Cannot change, child events are not migrated, see the
5390 * comment with perf_event_ctx_lock_nested().
5392 ctx = READ_ONCE(child->ctx);
5394 * Since child_mutex nests inside ctx::mutex, we must jump
5395 * through hoops. We start by grabbing a reference on the ctx.
5397 * Since the event cannot get freed while we hold the
5398 * child_mutex, the context must also exist and have a !0
5404 * Now that we have a ctx ref, we can drop child_mutex, and
5405 * acquire ctx::mutex without fear of it going away. Then we
5406 * can re-acquire child_mutex.
5408 mutex_unlock(&event->child_mutex);
5409 mutex_lock(&ctx->mutex);
5410 mutex_lock(&event->child_mutex);
5413 * Now that we hold ctx::mutex and child_mutex, revalidate our
5414 * state, if child is still the first entry, it didn't get freed
5415 * and we can continue doing so.
5417 tmp = list_first_entry_or_null(&event->child_list,
5418 struct perf_event, child_list);
5420 perf_remove_from_context(child, DETACH_GROUP);
5421 list_move(&child->child_list, &free_list);
5423 * This matches the refcount bump in inherit_event();
5424 * this can't be the last reference.
5429 mutex_unlock(&event->child_mutex);
5430 mutex_unlock(&ctx->mutex);
5434 mutex_unlock(&event->child_mutex);
5436 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5437 void *var = &child->ctx->refcount;
5439 list_del(&child->child_list);
5443 * Wake any perf_event_free_task() waiting for this event to be
5446 smp_mb(); /* pairs with wait_var_event() */
5451 put_event(event); /* Must be the 'last' reference */
5454 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5457 * Called when the last reference to the file is gone.
5459 static int perf_release(struct inode *inode, struct file *file)
5461 perf_event_release_kernel(file->private_data);
5465 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5467 struct perf_event *child;
5473 mutex_lock(&event->child_mutex);
5475 (void)perf_event_read(event, false);
5476 total += perf_event_count(event);
5478 *enabled += event->total_time_enabled +
5479 atomic64_read(&event->child_total_time_enabled);
5480 *running += event->total_time_running +
5481 atomic64_read(&event->child_total_time_running);
5483 list_for_each_entry(child, &event->child_list, child_list) {
5484 (void)perf_event_read(child, false);
5485 total += perf_event_count(child);
5486 *enabled += child->total_time_enabled;
5487 *running += child->total_time_running;
5489 mutex_unlock(&event->child_mutex);
5494 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5496 struct perf_event_context *ctx;
5499 ctx = perf_event_ctx_lock(event);
5500 count = __perf_event_read_value(event, enabled, running);
5501 perf_event_ctx_unlock(event, ctx);
5505 EXPORT_SYMBOL_GPL(perf_event_read_value);
5507 static int __perf_read_group_add(struct perf_event *leader,
5508 u64 read_format, u64 *values)
5510 struct perf_event_context *ctx = leader->ctx;
5511 struct perf_event *sub, *parent;
5512 unsigned long flags;
5513 int n = 1; /* skip @nr */
5516 ret = perf_event_read(leader, true);
5520 raw_spin_lock_irqsave(&ctx->lock, flags);
5522 * Verify the grouping between the parent and child (inherited)
5523 * events is still in tact.
5526 * - leader->ctx->lock pins leader->sibling_list
5527 * - parent->child_mutex pins parent->child_list
5528 * - parent->ctx->mutex pins parent->sibling_list
5530 * Because parent->ctx != leader->ctx (and child_list nests inside
5531 * ctx->mutex), group destruction is not atomic between children, also
5532 * see perf_event_release_kernel(). Additionally, parent can grow the
5535 * Therefore it is possible to have parent and child groups in a
5536 * different configuration and summing over such a beast makes no sense
5541 parent = leader->parent;
5543 (parent->group_generation != leader->group_generation ||
5544 parent->nr_siblings != leader->nr_siblings)) {
5550 * Since we co-schedule groups, {enabled,running} times of siblings
5551 * will be identical to those of the leader, so we only publish one
5554 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5555 values[n++] += leader->total_time_enabled +
5556 atomic64_read(&leader->child_total_time_enabled);
5559 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5560 values[n++] += leader->total_time_running +
5561 atomic64_read(&leader->child_total_time_running);
5565 * Write {count,id} tuples for every sibling.
5567 values[n++] += perf_event_count(leader);
5568 if (read_format & PERF_FORMAT_ID)
5569 values[n++] = primary_event_id(leader);
5570 if (read_format & PERF_FORMAT_LOST)
5571 values[n++] = atomic64_read(&leader->lost_samples);
5573 for_each_sibling_event(sub, leader) {
5574 values[n++] += perf_event_count(sub);
5575 if (read_format & PERF_FORMAT_ID)
5576 values[n++] = primary_event_id(sub);
5577 if (read_format & PERF_FORMAT_LOST)
5578 values[n++] = atomic64_read(&sub->lost_samples);
5582 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5586 static int perf_read_group(struct perf_event *event,
5587 u64 read_format, char __user *buf)
5589 struct perf_event *leader = event->group_leader, *child;
5590 struct perf_event_context *ctx = leader->ctx;
5594 lockdep_assert_held(&ctx->mutex);
5596 values = kzalloc(event->read_size, GFP_KERNEL);
5600 values[0] = 1 + leader->nr_siblings;
5602 mutex_lock(&leader->child_mutex);
5604 ret = __perf_read_group_add(leader, read_format, values);
5608 list_for_each_entry(child, &leader->child_list, child_list) {
5609 ret = __perf_read_group_add(child, read_format, values);
5614 mutex_unlock(&leader->child_mutex);
5616 ret = event->read_size;
5617 if (copy_to_user(buf, values, event->read_size))
5622 mutex_unlock(&leader->child_mutex);
5628 static int perf_read_one(struct perf_event *event,
5629 u64 read_format, char __user *buf)
5631 u64 enabled, running;
5635 values[n++] = __perf_event_read_value(event, &enabled, &running);
5636 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5637 values[n++] = enabled;
5638 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5639 values[n++] = running;
5640 if (read_format & PERF_FORMAT_ID)
5641 values[n++] = primary_event_id(event);
5642 if (read_format & PERF_FORMAT_LOST)
5643 values[n++] = atomic64_read(&event->lost_samples);
5645 if (copy_to_user(buf, values, n * sizeof(u64)))
5648 return n * sizeof(u64);
5651 static bool is_event_hup(struct perf_event *event)
5655 if (event->state > PERF_EVENT_STATE_EXIT)
5658 mutex_lock(&event->child_mutex);
5659 no_children = list_empty(&event->child_list);
5660 mutex_unlock(&event->child_mutex);
5665 * Read the performance event - simple non blocking version for now
5668 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5670 u64 read_format = event->attr.read_format;
5674 * Return end-of-file for a read on an event that is in
5675 * error state (i.e. because it was pinned but it couldn't be
5676 * scheduled on to the CPU at some point).
5678 if (event->state == PERF_EVENT_STATE_ERROR)
5681 if (count < event->read_size)
5684 WARN_ON_ONCE(event->ctx->parent_ctx);
5685 if (read_format & PERF_FORMAT_GROUP)
5686 ret = perf_read_group(event, read_format, buf);
5688 ret = perf_read_one(event, read_format, buf);
5694 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5696 struct perf_event *event = file->private_data;
5697 struct perf_event_context *ctx;
5700 ret = security_perf_event_read(event);
5704 ctx = perf_event_ctx_lock(event);
5705 ret = __perf_read(event, buf, count);
5706 perf_event_ctx_unlock(event, ctx);
5711 static __poll_t perf_poll(struct file *file, poll_table *wait)
5713 struct perf_event *event = file->private_data;
5714 struct perf_buffer *rb;
5715 __poll_t events = EPOLLHUP;
5717 poll_wait(file, &event->waitq, wait);
5719 if (is_event_hup(event))
5723 * Pin the event->rb by taking event->mmap_mutex; otherwise
5724 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5726 mutex_lock(&event->mmap_mutex);
5729 events = atomic_xchg(&rb->poll, 0);
5730 mutex_unlock(&event->mmap_mutex);
5734 static void _perf_event_reset(struct perf_event *event)
5736 (void)perf_event_read(event, false);
5737 local64_set(&event->count, 0);
5738 perf_event_update_userpage(event);
5741 /* Assume it's not an event with inherit set. */
5742 u64 perf_event_pause(struct perf_event *event, bool reset)
5744 struct perf_event_context *ctx;
5747 ctx = perf_event_ctx_lock(event);
5748 WARN_ON_ONCE(event->attr.inherit);
5749 _perf_event_disable(event);
5750 count = local64_read(&event->count);
5752 local64_set(&event->count, 0);
5753 perf_event_ctx_unlock(event, ctx);
5757 EXPORT_SYMBOL_GPL(perf_event_pause);
5760 * Holding the top-level event's child_mutex means that any
5761 * descendant process that has inherited this event will block
5762 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5763 * task existence requirements of perf_event_enable/disable.
5765 static void perf_event_for_each_child(struct perf_event *event,
5766 void (*func)(struct perf_event *))
5768 struct perf_event *child;
5770 WARN_ON_ONCE(event->ctx->parent_ctx);
5772 mutex_lock(&event->child_mutex);
5774 list_for_each_entry(child, &event->child_list, child_list)
5776 mutex_unlock(&event->child_mutex);
5779 static void perf_event_for_each(struct perf_event *event,
5780 void (*func)(struct perf_event *))
5782 struct perf_event_context *ctx = event->ctx;
5783 struct perf_event *sibling;
5785 lockdep_assert_held(&ctx->mutex);
5787 event = event->group_leader;
5789 perf_event_for_each_child(event, func);
5790 for_each_sibling_event(sibling, event)
5791 perf_event_for_each_child(sibling, func);
5794 static void __perf_event_period(struct perf_event *event,
5795 struct perf_cpu_context *cpuctx,
5796 struct perf_event_context *ctx,
5799 u64 value = *((u64 *)info);
5802 if (event->attr.freq) {
5803 event->attr.sample_freq = value;
5805 event->attr.sample_period = value;
5806 event->hw.sample_period = value;
5809 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5811 perf_pmu_disable(event->pmu);
5813 * We could be throttled; unthrottle now to avoid the tick
5814 * trying to unthrottle while we already re-started the event.
5816 if (event->hw.interrupts == MAX_INTERRUPTS) {
5817 event->hw.interrupts = 0;
5818 perf_log_throttle(event, 1);
5820 event->pmu->stop(event, PERF_EF_UPDATE);
5823 local64_set(&event->hw.period_left, 0);
5826 event->pmu->start(event, PERF_EF_RELOAD);
5827 perf_pmu_enable(event->pmu);
5831 static int perf_event_check_period(struct perf_event *event, u64 value)
5833 return event->pmu->check_period(event, value);
5836 static int _perf_event_period(struct perf_event *event, u64 value)
5838 if (!is_sampling_event(event))
5844 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5847 if (perf_event_check_period(event, value))
5850 if (!event->attr.freq && (value & (1ULL << 63)))
5853 event_function_call(event, __perf_event_period, &value);
5858 int perf_event_period(struct perf_event *event, u64 value)
5860 struct perf_event_context *ctx;
5863 ctx = perf_event_ctx_lock(event);
5864 ret = _perf_event_period(event, value);
5865 perf_event_ctx_unlock(event, ctx);
5869 EXPORT_SYMBOL_GPL(perf_event_period);
5871 static const struct file_operations perf_fops;
5873 static inline int perf_fget_light(int fd, struct fd *p)
5875 struct fd f = fdget(fd);
5879 if (f.file->f_op != &perf_fops) {
5887 static int perf_event_set_output(struct perf_event *event,
5888 struct perf_event *output_event);
5889 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5890 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5891 struct perf_event_attr *attr);
5893 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5895 void (*func)(struct perf_event *);
5899 case PERF_EVENT_IOC_ENABLE:
5900 func = _perf_event_enable;
5902 case PERF_EVENT_IOC_DISABLE:
5903 func = _perf_event_disable;
5905 case PERF_EVENT_IOC_RESET:
5906 func = _perf_event_reset;
5909 case PERF_EVENT_IOC_REFRESH:
5910 return _perf_event_refresh(event, arg);
5912 case PERF_EVENT_IOC_PERIOD:
5916 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5919 return _perf_event_period(event, value);
5921 case PERF_EVENT_IOC_ID:
5923 u64 id = primary_event_id(event);
5925 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5930 case PERF_EVENT_IOC_SET_OUTPUT:
5934 struct perf_event *output_event;
5936 ret = perf_fget_light(arg, &output);
5939 output_event = output.file->private_data;
5940 ret = perf_event_set_output(event, output_event);
5943 ret = perf_event_set_output(event, NULL);
5948 case PERF_EVENT_IOC_SET_FILTER:
5949 return perf_event_set_filter(event, (void __user *)arg);
5951 case PERF_EVENT_IOC_SET_BPF:
5953 struct bpf_prog *prog;
5956 prog = bpf_prog_get(arg);
5958 return PTR_ERR(prog);
5960 err = perf_event_set_bpf_prog(event, prog, 0);
5969 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5970 struct perf_buffer *rb;
5973 rb = rcu_dereference(event->rb);
5974 if (!rb || !rb->nr_pages) {
5978 rb_toggle_paused(rb, !!arg);
5983 case PERF_EVENT_IOC_QUERY_BPF:
5984 return perf_event_query_prog_array(event, (void __user *)arg);
5986 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5987 struct perf_event_attr new_attr;
5988 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5994 return perf_event_modify_attr(event, &new_attr);
6000 if (flags & PERF_IOC_FLAG_GROUP)
6001 perf_event_for_each(event, func);
6003 perf_event_for_each_child(event, func);
6008 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6010 struct perf_event *event = file->private_data;
6011 struct perf_event_context *ctx;
6014 /* Treat ioctl like writes as it is likely a mutating operation. */
6015 ret = security_perf_event_write(event);
6019 ctx = perf_event_ctx_lock(event);
6020 ret = _perf_ioctl(event, cmd, arg);
6021 perf_event_ctx_unlock(event, ctx);
6026 #ifdef CONFIG_COMPAT
6027 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6030 switch (_IOC_NR(cmd)) {
6031 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6032 case _IOC_NR(PERF_EVENT_IOC_ID):
6033 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6034 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
6035 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6036 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6037 cmd &= ~IOCSIZE_MASK;
6038 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6042 return perf_ioctl(file, cmd, arg);
6045 # define perf_compat_ioctl NULL
6048 int perf_event_task_enable(void)
6050 struct perf_event_context *ctx;
6051 struct perf_event *event;
6053 mutex_lock(¤t->perf_event_mutex);
6054 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6055 ctx = perf_event_ctx_lock(event);
6056 perf_event_for_each_child(event, _perf_event_enable);
6057 perf_event_ctx_unlock(event, ctx);
6059 mutex_unlock(¤t->perf_event_mutex);
6064 int perf_event_task_disable(void)
6066 struct perf_event_context *ctx;
6067 struct perf_event *event;
6069 mutex_lock(¤t->perf_event_mutex);
6070 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6071 ctx = perf_event_ctx_lock(event);
6072 perf_event_for_each_child(event, _perf_event_disable);
6073 perf_event_ctx_unlock(event, ctx);
6075 mutex_unlock(¤t->perf_event_mutex);
6080 static int perf_event_index(struct perf_event *event)
6082 if (event->hw.state & PERF_HES_STOPPED)
6085 if (event->state != PERF_EVENT_STATE_ACTIVE)
6088 return event->pmu->event_idx(event);
6091 static void perf_event_init_userpage(struct perf_event *event)
6093 struct perf_event_mmap_page *userpg;
6094 struct perf_buffer *rb;
6097 rb = rcu_dereference(event->rb);
6101 userpg = rb->user_page;
6103 /* Allow new userspace to detect that bit 0 is deprecated */
6104 userpg->cap_bit0_is_deprecated = 1;
6105 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6106 userpg->data_offset = PAGE_SIZE;
6107 userpg->data_size = perf_data_size(rb);
6113 void __weak arch_perf_update_userpage(
6114 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6119 * Callers need to ensure there can be no nesting of this function, otherwise
6120 * the seqlock logic goes bad. We can not serialize this because the arch
6121 * code calls this from NMI context.
6123 void perf_event_update_userpage(struct perf_event *event)
6125 struct perf_event_mmap_page *userpg;
6126 struct perf_buffer *rb;
6127 u64 enabled, running, now;
6130 rb = rcu_dereference(event->rb);
6135 * compute total_time_enabled, total_time_running
6136 * based on snapshot values taken when the event
6137 * was last scheduled in.
6139 * we cannot simply called update_context_time()
6140 * because of locking issue as we can be called in
6143 calc_timer_values(event, &now, &enabled, &running);
6145 userpg = rb->user_page;
6147 * Disable preemption to guarantee consistent time stamps are stored to
6153 userpg->index = perf_event_index(event);
6154 userpg->offset = perf_event_count(event);
6156 userpg->offset -= local64_read(&event->hw.prev_count);
6158 userpg->time_enabled = enabled +
6159 atomic64_read(&event->child_total_time_enabled);
6161 userpg->time_running = running +
6162 atomic64_read(&event->child_total_time_running);
6164 arch_perf_update_userpage(event, userpg, now);
6172 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6174 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
6176 struct perf_event *event = vmf->vma->vm_file->private_data;
6177 struct perf_buffer *rb;
6178 vm_fault_t ret = VM_FAULT_SIGBUS;
6180 if (vmf->flags & FAULT_FLAG_MKWRITE) {
6181 if (vmf->pgoff == 0)
6187 rb = rcu_dereference(event->rb);
6191 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
6194 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
6198 get_page(vmf->page);
6199 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
6200 vmf->page->index = vmf->pgoff;
6209 static void ring_buffer_attach(struct perf_event *event,
6210 struct perf_buffer *rb)
6212 struct perf_buffer *old_rb = NULL;
6213 unsigned long flags;
6215 WARN_ON_ONCE(event->parent);
6219 * Should be impossible, we set this when removing
6220 * event->rb_entry and wait/clear when adding event->rb_entry.
6222 WARN_ON_ONCE(event->rcu_pending);
6225 spin_lock_irqsave(&old_rb->event_lock, flags);
6226 list_del_rcu(&event->rb_entry);
6227 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6229 event->rcu_batches = get_state_synchronize_rcu();
6230 event->rcu_pending = 1;
6234 if (event->rcu_pending) {
6235 cond_synchronize_rcu(event->rcu_batches);
6236 event->rcu_pending = 0;
6239 spin_lock_irqsave(&rb->event_lock, flags);
6240 list_add_rcu(&event->rb_entry, &rb->event_list);
6241 spin_unlock_irqrestore(&rb->event_lock, flags);
6245 * Avoid racing with perf_mmap_close(AUX): stop the event
6246 * before swizzling the event::rb pointer; if it's getting
6247 * unmapped, its aux_mmap_count will be 0 and it won't
6248 * restart. See the comment in __perf_pmu_output_stop().
6250 * Data will inevitably be lost when set_output is done in
6251 * mid-air, but then again, whoever does it like this is
6252 * not in for the data anyway.
6255 perf_event_stop(event, 0);
6257 rcu_assign_pointer(event->rb, rb);
6260 ring_buffer_put(old_rb);
6262 * Since we detached before setting the new rb, so that we
6263 * could attach the new rb, we could have missed a wakeup.
6266 wake_up_all(&event->waitq);
6270 static void ring_buffer_wakeup(struct perf_event *event)
6272 struct perf_buffer *rb;
6275 event = event->parent;
6278 rb = rcu_dereference(event->rb);
6280 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6281 wake_up_all(&event->waitq);
6286 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6288 struct perf_buffer *rb;
6291 event = event->parent;
6294 rb = rcu_dereference(event->rb);
6296 if (!refcount_inc_not_zero(&rb->refcount))
6304 void ring_buffer_put(struct perf_buffer *rb)
6306 if (!refcount_dec_and_test(&rb->refcount))
6309 WARN_ON_ONCE(!list_empty(&rb->event_list));
6311 call_rcu(&rb->rcu_head, rb_free_rcu);
6314 static void perf_mmap_open(struct vm_area_struct *vma)
6316 struct perf_event *event = vma->vm_file->private_data;
6318 atomic_inc(&event->mmap_count);
6319 atomic_inc(&event->rb->mmap_count);
6322 atomic_inc(&event->rb->aux_mmap_count);
6324 if (event->pmu->event_mapped)
6325 event->pmu->event_mapped(event, vma->vm_mm);
6328 static void perf_pmu_output_stop(struct perf_event *event);
6331 * A buffer can be mmap()ed multiple times; either directly through the same
6332 * event, or through other events by use of perf_event_set_output().
6334 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6335 * the buffer here, where we still have a VM context. This means we need
6336 * to detach all events redirecting to us.
6338 static void perf_mmap_close(struct vm_area_struct *vma)
6340 struct perf_event *event = vma->vm_file->private_data;
6341 struct perf_buffer *rb = ring_buffer_get(event);
6342 struct user_struct *mmap_user = rb->mmap_user;
6343 int mmap_locked = rb->mmap_locked;
6344 unsigned long size = perf_data_size(rb);
6345 bool detach_rest = false;
6347 if (event->pmu->event_unmapped)
6348 event->pmu->event_unmapped(event, vma->vm_mm);
6351 * rb->aux_mmap_count will always drop before rb->mmap_count and
6352 * event->mmap_count, so it is ok to use event->mmap_mutex to
6353 * serialize with perf_mmap here.
6355 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6356 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6358 * Stop all AUX events that are writing to this buffer,
6359 * so that we can free its AUX pages and corresponding PMU
6360 * data. Note that after rb::aux_mmap_count dropped to zero,
6361 * they won't start any more (see perf_aux_output_begin()).
6363 perf_pmu_output_stop(event);
6365 /* now it's safe to free the pages */
6366 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6367 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6369 /* this has to be the last one */
6371 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6373 mutex_unlock(&event->mmap_mutex);
6376 if (atomic_dec_and_test(&rb->mmap_count))
6379 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6382 ring_buffer_attach(event, NULL);
6383 mutex_unlock(&event->mmap_mutex);
6385 /* If there's still other mmap()s of this buffer, we're done. */
6390 * No other mmap()s, detach from all other events that might redirect
6391 * into the now unreachable buffer. Somewhat complicated by the
6392 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6396 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6397 if (!atomic_long_inc_not_zero(&event->refcount)) {
6399 * This event is en-route to free_event() which will
6400 * detach it and remove it from the list.
6406 mutex_lock(&event->mmap_mutex);
6408 * Check we didn't race with perf_event_set_output() which can
6409 * swizzle the rb from under us while we were waiting to
6410 * acquire mmap_mutex.
6412 * If we find a different rb; ignore this event, a next
6413 * iteration will no longer find it on the list. We have to
6414 * still restart the iteration to make sure we're not now
6415 * iterating the wrong list.
6417 if (event->rb == rb)
6418 ring_buffer_attach(event, NULL);
6420 mutex_unlock(&event->mmap_mutex);
6424 * Restart the iteration; either we're on the wrong list or
6425 * destroyed its integrity by doing a deletion.
6432 * It could be there's still a few 0-ref events on the list; they'll
6433 * get cleaned up by free_event() -- they'll also still have their
6434 * ref on the rb and will free it whenever they are done with it.
6436 * Aside from that, this buffer is 'fully' detached and unmapped,
6437 * undo the VM accounting.
6440 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6441 &mmap_user->locked_vm);
6442 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6443 free_uid(mmap_user);
6446 ring_buffer_put(rb); /* could be last */
6449 static const struct vm_operations_struct perf_mmap_vmops = {
6450 .open = perf_mmap_open,
6451 .close = perf_mmap_close, /* non mergeable */
6452 .fault = perf_mmap_fault,
6453 .page_mkwrite = perf_mmap_fault,
6456 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6458 struct perf_event *event = file->private_data;
6459 unsigned long user_locked, user_lock_limit;
6460 struct user_struct *user = current_user();
6461 struct perf_buffer *rb = NULL;
6462 unsigned long locked, lock_limit;
6463 unsigned long vma_size;
6464 unsigned long nr_pages;
6465 long user_extra = 0, extra = 0;
6466 int ret = 0, flags = 0;
6469 * Don't allow mmap() of inherited per-task counters. This would
6470 * create a performance issue due to all children writing to the
6473 if (event->cpu == -1 && event->attr.inherit)
6476 if (!(vma->vm_flags & VM_SHARED))
6479 ret = security_perf_event_read(event);
6483 vma_size = vma->vm_end - vma->vm_start;
6485 if (vma->vm_pgoff == 0) {
6486 nr_pages = (vma_size / PAGE_SIZE) - 1;
6489 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6490 * mapped, all subsequent mappings should have the same size
6491 * and offset. Must be above the normal perf buffer.
6493 u64 aux_offset, aux_size;
6498 nr_pages = vma_size / PAGE_SIZE;
6500 mutex_lock(&event->mmap_mutex);
6507 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6508 aux_size = READ_ONCE(rb->user_page->aux_size);
6510 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6513 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6516 /* already mapped with a different offset */
6517 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6520 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6523 /* already mapped with a different size */
6524 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6527 if (!is_power_of_2(nr_pages))
6530 if (!atomic_inc_not_zero(&rb->mmap_count))
6533 if (rb_has_aux(rb)) {
6534 atomic_inc(&rb->aux_mmap_count);
6539 atomic_set(&rb->aux_mmap_count, 1);
6540 user_extra = nr_pages;
6546 * If we have rb pages ensure they're a power-of-two number, so we
6547 * can do bitmasks instead of modulo.
6549 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6552 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6555 WARN_ON_ONCE(event->ctx->parent_ctx);
6557 mutex_lock(&event->mmap_mutex);
6559 if (data_page_nr(event->rb) != nr_pages) {
6564 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6566 * Raced against perf_mmap_close(); remove the
6567 * event and try again.
6569 ring_buffer_attach(event, NULL);
6570 mutex_unlock(&event->mmap_mutex);
6577 user_extra = nr_pages + 1;
6580 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6583 * Increase the limit linearly with more CPUs:
6585 user_lock_limit *= num_online_cpus();
6587 user_locked = atomic_long_read(&user->locked_vm);
6590 * sysctl_perf_event_mlock may have changed, so that
6591 * user->locked_vm > user_lock_limit
6593 if (user_locked > user_lock_limit)
6594 user_locked = user_lock_limit;
6595 user_locked += user_extra;
6597 if (user_locked > user_lock_limit) {
6599 * charge locked_vm until it hits user_lock_limit;
6600 * charge the rest from pinned_vm
6602 extra = user_locked - user_lock_limit;
6603 user_extra -= extra;
6606 lock_limit = rlimit(RLIMIT_MEMLOCK);
6607 lock_limit >>= PAGE_SHIFT;
6608 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6610 if ((locked > lock_limit) && perf_is_paranoid() &&
6611 !capable(CAP_IPC_LOCK)) {
6616 WARN_ON(!rb && event->rb);
6618 if (vma->vm_flags & VM_WRITE)
6619 flags |= RING_BUFFER_WRITABLE;
6622 rb = rb_alloc(nr_pages,
6623 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6631 atomic_set(&rb->mmap_count, 1);
6632 rb->mmap_user = get_current_user();
6633 rb->mmap_locked = extra;
6635 ring_buffer_attach(event, rb);
6637 perf_event_update_time(event);
6638 perf_event_init_userpage(event);
6639 perf_event_update_userpage(event);
6641 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6642 event->attr.aux_watermark, flags);
6644 rb->aux_mmap_locked = extra;
6649 atomic_long_add(user_extra, &user->locked_vm);
6650 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6652 atomic_inc(&event->mmap_count);
6654 atomic_dec(&rb->mmap_count);
6657 mutex_unlock(&event->mmap_mutex);
6660 * Since pinned accounting is per vm we cannot allow fork() to copy our
6663 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
6664 vma->vm_ops = &perf_mmap_vmops;
6666 if (event->pmu->event_mapped)
6667 event->pmu->event_mapped(event, vma->vm_mm);
6672 static int perf_fasync(int fd, struct file *filp, int on)
6674 struct inode *inode = file_inode(filp);
6675 struct perf_event *event = filp->private_data;
6679 retval = fasync_helper(fd, filp, on, &event->fasync);
6680 inode_unlock(inode);
6688 static const struct file_operations perf_fops = {
6689 .llseek = no_llseek,
6690 .release = perf_release,
6693 .unlocked_ioctl = perf_ioctl,
6694 .compat_ioctl = perf_compat_ioctl,
6696 .fasync = perf_fasync,
6702 * If there's data, ensure we set the poll() state and publish everything
6703 * to user-space before waking everybody up.
6706 void perf_event_wakeup(struct perf_event *event)
6708 ring_buffer_wakeup(event);
6710 if (event->pending_kill) {
6711 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6712 event->pending_kill = 0;
6716 static void perf_sigtrap(struct perf_event *event)
6719 * We'd expect this to only occur if the irq_work is delayed and either
6720 * ctx->task or current has changed in the meantime. This can be the
6721 * case on architectures that do not implement arch_irq_work_raise().
6723 if (WARN_ON_ONCE(event->ctx->task != current))
6727 * Both perf_pending_task() and perf_pending_irq() can race with the
6730 if (current->flags & PF_EXITING)
6733 send_sig_perf((void __user *)event->pending_addr,
6734 event->orig_type, event->attr.sig_data);
6738 * Deliver the pending work in-event-context or follow the context.
6740 static void __perf_pending_irq(struct perf_event *event)
6742 int cpu = READ_ONCE(event->oncpu);
6745 * If the event isn't running; we done. event_sched_out() will have
6746 * taken care of things.
6752 * Yay, we hit home and are in the context of the event.
6754 if (cpu == smp_processor_id()) {
6755 if (event->pending_sigtrap) {
6756 event->pending_sigtrap = 0;
6757 perf_sigtrap(event);
6758 local_dec(&event->ctx->nr_pending);
6760 if (event->pending_disable) {
6761 event->pending_disable = 0;
6762 perf_event_disable_local(event);
6770 * perf_event_disable_inatomic()
6771 * @pending_disable = CPU-A;
6775 * @pending_disable = -1;
6778 * perf_event_disable_inatomic()
6779 * @pending_disable = CPU-B;
6780 * irq_work_queue(); // FAILS
6783 * perf_pending_irq()
6785 * But the event runs on CPU-B and wants disabling there.
6787 irq_work_queue_on(&event->pending_irq, cpu);
6790 static void perf_pending_irq(struct irq_work *entry)
6792 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6796 * If we 'fail' here, that's OK, it means recursion is already disabled
6797 * and we won't recurse 'further'.
6799 rctx = perf_swevent_get_recursion_context();
6802 * The wakeup isn't bound to the context of the event -- it can happen
6803 * irrespective of where the event is.
6805 if (event->pending_wakeup) {
6806 event->pending_wakeup = 0;
6807 perf_event_wakeup(event);
6810 __perf_pending_irq(event);
6813 perf_swevent_put_recursion_context(rctx);
6816 static void perf_pending_task(struct callback_head *head)
6818 struct perf_event *event = container_of(head, struct perf_event, pending_task);
6822 * If we 'fail' here, that's OK, it means recursion is already disabled
6823 * and we won't recurse 'further'.
6825 preempt_disable_notrace();
6826 rctx = perf_swevent_get_recursion_context();
6828 if (event->pending_work) {
6829 event->pending_work = 0;
6830 perf_sigtrap(event);
6831 local_dec(&event->ctx->nr_pending);
6835 perf_swevent_put_recursion_context(rctx);
6836 preempt_enable_notrace();
6841 #ifdef CONFIG_GUEST_PERF_EVENTS
6842 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6844 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
6845 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
6846 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
6848 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6850 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6853 rcu_assign_pointer(perf_guest_cbs, cbs);
6854 static_call_update(__perf_guest_state, cbs->state);
6855 static_call_update(__perf_guest_get_ip, cbs->get_ip);
6857 /* Implementing ->handle_intel_pt_intr is optional. */
6858 if (cbs->handle_intel_pt_intr)
6859 static_call_update(__perf_guest_handle_intel_pt_intr,
6860 cbs->handle_intel_pt_intr);
6862 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6864 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6866 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6869 rcu_assign_pointer(perf_guest_cbs, NULL);
6870 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
6871 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
6872 static_call_update(__perf_guest_handle_intel_pt_intr,
6873 (void *)&__static_call_return0);
6876 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6880 perf_output_sample_regs(struct perf_output_handle *handle,
6881 struct pt_regs *regs, u64 mask)
6884 DECLARE_BITMAP(_mask, 64);
6886 bitmap_from_u64(_mask, mask);
6887 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6890 val = perf_reg_value(regs, bit);
6891 perf_output_put(handle, val);
6895 static void perf_sample_regs_user(struct perf_regs *regs_user,
6896 struct pt_regs *regs)
6898 if (user_mode(regs)) {
6899 regs_user->abi = perf_reg_abi(current);
6900 regs_user->regs = regs;
6901 } else if (!(current->flags & PF_KTHREAD)) {
6902 perf_get_regs_user(regs_user, regs);
6904 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6905 regs_user->regs = NULL;
6909 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6910 struct pt_regs *regs)
6912 regs_intr->regs = regs;
6913 regs_intr->abi = perf_reg_abi(current);
6918 * Get remaining task size from user stack pointer.
6920 * It'd be better to take stack vma map and limit this more
6921 * precisely, but there's no way to get it safely under interrupt,
6922 * so using TASK_SIZE as limit.
6924 static u64 perf_ustack_task_size(struct pt_regs *regs)
6926 unsigned long addr = perf_user_stack_pointer(regs);
6928 if (!addr || addr >= TASK_SIZE)
6931 return TASK_SIZE - addr;
6935 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6936 struct pt_regs *regs)
6940 /* No regs, no stack pointer, no dump. */
6945 * Check if we fit in with the requested stack size into the:
6947 * If we don't, we limit the size to the TASK_SIZE.
6949 * - remaining sample size
6950 * If we don't, we customize the stack size to
6951 * fit in to the remaining sample size.
6954 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6955 stack_size = min(stack_size, (u16) task_size);
6957 /* Current header size plus static size and dynamic size. */
6958 header_size += 2 * sizeof(u64);
6960 /* Do we fit in with the current stack dump size? */
6961 if ((u16) (header_size + stack_size) < header_size) {
6963 * If we overflow the maximum size for the sample,
6964 * we customize the stack dump size to fit in.
6966 stack_size = USHRT_MAX - header_size - sizeof(u64);
6967 stack_size = round_up(stack_size, sizeof(u64));
6974 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6975 struct pt_regs *regs)
6977 /* Case of a kernel thread, nothing to dump */
6980 perf_output_put(handle, size);
6989 * - the size requested by user or the best one we can fit
6990 * in to the sample max size
6992 * - user stack dump data
6994 * - the actual dumped size
6998 perf_output_put(handle, dump_size);
7001 sp = perf_user_stack_pointer(regs);
7002 rem = __output_copy_user(handle, (void *) sp, dump_size);
7003 dyn_size = dump_size - rem;
7005 perf_output_skip(handle, rem);
7008 perf_output_put(handle, dyn_size);
7012 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7013 struct perf_sample_data *data,
7016 struct perf_event *sampler = event->aux_event;
7017 struct perf_buffer *rb;
7024 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7027 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7030 rb = ring_buffer_get(sampler);
7035 * If this is an NMI hit inside sampling code, don't take
7036 * the sample. See also perf_aux_sample_output().
7038 if (READ_ONCE(rb->aux_in_sampling)) {
7041 size = min_t(size_t, size, perf_aux_size(rb));
7042 data->aux_size = ALIGN(size, sizeof(u64));
7044 ring_buffer_put(rb);
7047 return data->aux_size;
7050 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
7051 struct perf_event *event,
7052 struct perf_output_handle *handle,
7055 unsigned long flags;
7059 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7060 * paths. If we start calling them in NMI context, they may race with
7061 * the IRQ ones, that is, for example, re-starting an event that's just
7062 * been stopped, which is why we're using a separate callback that
7063 * doesn't change the event state.
7065 * IRQs need to be disabled to prevent IPIs from racing with us.
7067 local_irq_save(flags);
7069 * Guard against NMI hits inside the critical section;
7070 * see also perf_prepare_sample_aux().
7072 WRITE_ONCE(rb->aux_in_sampling, 1);
7075 ret = event->pmu->snapshot_aux(event, handle, size);
7078 WRITE_ONCE(rb->aux_in_sampling, 0);
7079 local_irq_restore(flags);
7084 static void perf_aux_sample_output(struct perf_event *event,
7085 struct perf_output_handle *handle,
7086 struct perf_sample_data *data)
7088 struct perf_event *sampler = event->aux_event;
7089 struct perf_buffer *rb;
7093 if (WARN_ON_ONCE(!sampler || !data->aux_size))
7096 rb = ring_buffer_get(sampler);
7100 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7103 * An error here means that perf_output_copy() failed (returned a
7104 * non-zero surplus that it didn't copy), which in its current
7105 * enlightened implementation is not possible. If that changes, we'd
7108 if (WARN_ON_ONCE(size < 0))
7112 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7113 * perf_prepare_sample_aux(), so should not be more than that.
7115 pad = data->aux_size - size;
7116 if (WARN_ON_ONCE(pad >= sizeof(u64)))
7121 perf_output_copy(handle, &zero, pad);
7125 ring_buffer_put(rb);
7129 * A set of common sample data types saved even for non-sample records
7130 * when event->attr.sample_id_all is set.
7132 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7133 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7134 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7136 static void __perf_event_header__init_id(struct perf_sample_data *data,
7137 struct perf_event *event,
7140 data->type = event->attr.sample_type;
7141 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
7143 if (sample_type & PERF_SAMPLE_TID) {
7144 /* namespace issues */
7145 data->tid_entry.pid = perf_event_pid(event, current);
7146 data->tid_entry.tid = perf_event_tid(event, current);
7149 if (sample_type & PERF_SAMPLE_TIME)
7150 data->time = perf_event_clock(event);
7152 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7153 data->id = primary_event_id(event);
7155 if (sample_type & PERF_SAMPLE_STREAM_ID)
7156 data->stream_id = event->id;
7158 if (sample_type & PERF_SAMPLE_CPU) {
7159 data->cpu_entry.cpu = raw_smp_processor_id();
7160 data->cpu_entry.reserved = 0;
7164 void perf_event_header__init_id(struct perf_event_header *header,
7165 struct perf_sample_data *data,
7166 struct perf_event *event)
7168 if (event->attr.sample_id_all) {
7169 header->size += event->id_header_size;
7170 __perf_event_header__init_id(data, event, event->attr.sample_type);
7174 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7175 struct perf_sample_data *data)
7177 u64 sample_type = data->type;
7179 if (sample_type & PERF_SAMPLE_TID)
7180 perf_output_put(handle, data->tid_entry);
7182 if (sample_type & PERF_SAMPLE_TIME)
7183 perf_output_put(handle, data->time);
7185 if (sample_type & PERF_SAMPLE_ID)
7186 perf_output_put(handle, data->id);
7188 if (sample_type & PERF_SAMPLE_STREAM_ID)
7189 perf_output_put(handle, data->stream_id);
7191 if (sample_type & PERF_SAMPLE_CPU)
7192 perf_output_put(handle, data->cpu_entry);
7194 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7195 perf_output_put(handle, data->id);
7198 void perf_event__output_id_sample(struct perf_event *event,
7199 struct perf_output_handle *handle,
7200 struct perf_sample_data *sample)
7202 if (event->attr.sample_id_all)
7203 __perf_event__output_id_sample(handle, sample);
7206 static void perf_output_read_one(struct perf_output_handle *handle,
7207 struct perf_event *event,
7208 u64 enabled, u64 running)
7210 u64 read_format = event->attr.read_format;
7214 values[n++] = perf_event_count(event);
7215 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7216 values[n++] = enabled +
7217 atomic64_read(&event->child_total_time_enabled);
7219 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7220 values[n++] = running +
7221 atomic64_read(&event->child_total_time_running);
7223 if (read_format & PERF_FORMAT_ID)
7224 values[n++] = primary_event_id(event);
7225 if (read_format & PERF_FORMAT_LOST)
7226 values[n++] = atomic64_read(&event->lost_samples);
7228 __output_copy(handle, values, n * sizeof(u64));
7231 static void perf_output_read_group(struct perf_output_handle *handle,
7232 struct perf_event *event,
7233 u64 enabled, u64 running)
7235 struct perf_event *leader = event->group_leader, *sub;
7236 u64 read_format = event->attr.read_format;
7237 unsigned long flags;
7242 * Disabling interrupts avoids all counter scheduling
7243 * (context switches, timer based rotation and IPIs).
7245 local_irq_save(flags);
7247 values[n++] = 1 + leader->nr_siblings;
7249 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7250 values[n++] = enabled;
7252 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7253 values[n++] = running;
7255 if ((leader != event) &&
7256 (leader->state == PERF_EVENT_STATE_ACTIVE))
7257 leader->pmu->read(leader);
7259 values[n++] = perf_event_count(leader);
7260 if (read_format & PERF_FORMAT_ID)
7261 values[n++] = primary_event_id(leader);
7262 if (read_format & PERF_FORMAT_LOST)
7263 values[n++] = atomic64_read(&leader->lost_samples);
7265 __output_copy(handle, values, n * sizeof(u64));
7267 for_each_sibling_event(sub, leader) {
7270 if ((sub != event) &&
7271 (sub->state == PERF_EVENT_STATE_ACTIVE))
7272 sub->pmu->read(sub);
7274 values[n++] = perf_event_count(sub);
7275 if (read_format & PERF_FORMAT_ID)
7276 values[n++] = primary_event_id(sub);
7277 if (read_format & PERF_FORMAT_LOST)
7278 values[n++] = atomic64_read(&sub->lost_samples);
7280 __output_copy(handle, values, n * sizeof(u64));
7283 local_irq_restore(flags);
7286 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7287 PERF_FORMAT_TOTAL_TIME_RUNNING)
7290 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7292 * The problem is that its both hard and excessively expensive to iterate the
7293 * child list, not to mention that its impossible to IPI the children running
7294 * on another CPU, from interrupt/NMI context.
7296 static void perf_output_read(struct perf_output_handle *handle,
7297 struct perf_event *event)
7299 u64 enabled = 0, running = 0, now;
7300 u64 read_format = event->attr.read_format;
7303 * compute total_time_enabled, total_time_running
7304 * based on snapshot values taken when the event
7305 * was last scheduled in.
7307 * we cannot simply called update_context_time()
7308 * because of locking issue as we are called in
7311 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7312 calc_timer_values(event, &now, &enabled, &running);
7314 if (event->attr.read_format & PERF_FORMAT_GROUP)
7315 perf_output_read_group(handle, event, enabled, running);
7317 perf_output_read_one(handle, event, enabled, running);
7320 void perf_output_sample(struct perf_output_handle *handle,
7321 struct perf_event_header *header,
7322 struct perf_sample_data *data,
7323 struct perf_event *event)
7325 u64 sample_type = data->type;
7327 perf_output_put(handle, *header);
7329 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7330 perf_output_put(handle, data->id);
7332 if (sample_type & PERF_SAMPLE_IP)
7333 perf_output_put(handle, data->ip);
7335 if (sample_type & PERF_SAMPLE_TID)
7336 perf_output_put(handle, data->tid_entry);
7338 if (sample_type & PERF_SAMPLE_TIME)
7339 perf_output_put(handle, data->time);
7341 if (sample_type & PERF_SAMPLE_ADDR)
7342 perf_output_put(handle, data->addr);
7344 if (sample_type & PERF_SAMPLE_ID)
7345 perf_output_put(handle, data->id);
7347 if (sample_type & PERF_SAMPLE_STREAM_ID)
7348 perf_output_put(handle, data->stream_id);
7350 if (sample_type & PERF_SAMPLE_CPU)
7351 perf_output_put(handle, data->cpu_entry);
7353 if (sample_type & PERF_SAMPLE_PERIOD)
7354 perf_output_put(handle, data->period);
7356 if (sample_type & PERF_SAMPLE_READ)
7357 perf_output_read(handle, event);
7359 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7362 size += data->callchain->nr;
7363 size *= sizeof(u64);
7364 __output_copy(handle, data->callchain, size);
7367 if (sample_type & PERF_SAMPLE_RAW) {
7368 struct perf_raw_record *raw = data->raw;
7371 struct perf_raw_frag *frag = &raw->frag;
7373 perf_output_put(handle, raw->size);
7376 __output_custom(handle, frag->copy,
7377 frag->data, frag->size);
7379 __output_copy(handle, frag->data,
7382 if (perf_raw_frag_last(frag))
7387 __output_skip(handle, NULL, frag->pad);
7393 .size = sizeof(u32),
7396 perf_output_put(handle, raw);
7400 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7401 if (data->br_stack) {
7404 size = data->br_stack->nr
7405 * sizeof(struct perf_branch_entry);
7407 perf_output_put(handle, data->br_stack->nr);
7408 if (branch_sample_hw_index(event))
7409 perf_output_put(handle, data->br_stack->hw_idx);
7410 perf_output_copy(handle, data->br_stack->entries, size);
7412 * Add the extension space which is appended
7413 * right after the struct perf_branch_stack.
7415 if (data->br_stack_cntr) {
7416 size = data->br_stack->nr * sizeof(u64);
7417 perf_output_copy(handle, data->br_stack_cntr, size);
7421 * we always store at least the value of nr
7424 perf_output_put(handle, nr);
7428 if (sample_type & PERF_SAMPLE_REGS_USER) {
7429 u64 abi = data->regs_user.abi;
7432 * If there are no regs to dump, notice it through
7433 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7435 perf_output_put(handle, abi);
7438 u64 mask = event->attr.sample_regs_user;
7439 perf_output_sample_regs(handle,
7440 data->regs_user.regs,
7445 if (sample_type & PERF_SAMPLE_STACK_USER) {
7446 perf_output_sample_ustack(handle,
7447 data->stack_user_size,
7448 data->regs_user.regs);
7451 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7452 perf_output_put(handle, data->weight.full);
7454 if (sample_type & PERF_SAMPLE_DATA_SRC)
7455 perf_output_put(handle, data->data_src.val);
7457 if (sample_type & PERF_SAMPLE_TRANSACTION)
7458 perf_output_put(handle, data->txn);
7460 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7461 u64 abi = data->regs_intr.abi;
7463 * If there are no regs to dump, notice it through
7464 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7466 perf_output_put(handle, abi);
7469 u64 mask = event->attr.sample_regs_intr;
7471 perf_output_sample_regs(handle,
7472 data->regs_intr.regs,
7477 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7478 perf_output_put(handle, data->phys_addr);
7480 if (sample_type & PERF_SAMPLE_CGROUP)
7481 perf_output_put(handle, data->cgroup);
7483 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7484 perf_output_put(handle, data->data_page_size);
7486 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7487 perf_output_put(handle, data->code_page_size);
7489 if (sample_type & PERF_SAMPLE_AUX) {
7490 perf_output_put(handle, data->aux_size);
7493 perf_aux_sample_output(event, handle, data);
7496 if (!event->attr.watermark) {
7497 int wakeup_events = event->attr.wakeup_events;
7499 if (wakeup_events) {
7500 struct perf_buffer *rb = handle->rb;
7501 int events = local_inc_return(&rb->events);
7503 if (events >= wakeup_events) {
7504 local_sub(wakeup_events, &rb->events);
7505 local_inc(&rb->wakeup);
7511 static u64 perf_virt_to_phys(u64 virt)
7518 if (virt >= TASK_SIZE) {
7519 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7520 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7521 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7522 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7525 * Walking the pages tables for user address.
7526 * Interrupts are disabled, so it prevents any tear down
7527 * of the page tables.
7528 * Try IRQ-safe get_user_page_fast_only first.
7529 * If failed, leave phys_addr as 0.
7531 if (current->mm != NULL) {
7534 pagefault_disable();
7535 if (get_user_page_fast_only(virt, 0, &p)) {
7536 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7547 * Return the pagetable size of a given virtual address.
7549 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7553 #ifdef CONFIG_HAVE_FAST_GUP
7560 pgdp = pgd_offset(mm, addr);
7561 pgd = READ_ONCE(*pgdp);
7566 return pgd_leaf_size(pgd);
7568 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7569 p4d = READ_ONCE(*p4dp);
7570 if (!p4d_present(p4d))
7574 return p4d_leaf_size(p4d);
7576 pudp = pud_offset_lockless(p4dp, p4d, addr);
7577 pud = READ_ONCE(*pudp);
7578 if (!pud_present(pud))
7582 return pud_leaf_size(pud);
7584 pmdp = pmd_offset_lockless(pudp, pud, addr);
7586 pmd = pmdp_get_lockless(pmdp);
7587 if (!pmd_present(pmd))
7591 return pmd_leaf_size(pmd);
7593 ptep = pte_offset_map(&pmd, addr);
7597 pte = ptep_get_lockless(ptep);
7598 if (pte_present(pte))
7599 size = pte_leaf_size(pte);
7601 #endif /* CONFIG_HAVE_FAST_GUP */
7606 static u64 perf_get_page_size(unsigned long addr)
7608 struct mm_struct *mm;
7609 unsigned long flags;
7616 * Software page-table walkers must disable IRQs,
7617 * which prevents any tear down of the page tables.
7619 local_irq_save(flags);
7624 * For kernel threads and the like, use init_mm so that
7625 * we can find kernel memory.
7630 size = perf_get_pgtable_size(mm, addr);
7632 local_irq_restore(flags);
7637 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7639 struct perf_callchain_entry *
7640 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7642 bool kernel = !event->attr.exclude_callchain_kernel;
7643 bool user = !event->attr.exclude_callchain_user;
7644 /* Disallow cross-task user callchains. */
7645 bool crosstask = event->ctx->task && event->ctx->task != current;
7646 const u32 max_stack = event->attr.sample_max_stack;
7647 struct perf_callchain_entry *callchain;
7649 if (!kernel && !user)
7650 return &__empty_callchain;
7652 callchain = get_perf_callchain(regs, 0, kernel, user,
7653 max_stack, crosstask, true);
7654 return callchain ?: &__empty_callchain;
7657 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
7659 return d * !!(flags & s);
7662 void perf_prepare_sample(struct perf_sample_data *data,
7663 struct perf_event *event,
7664 struct pt_regs *regs)
7666 u64 sample_type = event->attr.sample_type;
7667 u64 filtered_sample_type;
7670 * Add the sample flags that are dependent to others. And clear the
7671 * sample flags that have already been done by the PMU driver.
7673 filtered_sample_type = sample_type;
7674 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
7676 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
7677 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
7678 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
7679 PERF_SAMPLE_REGS_USER);
7680 filtered_sample_type &= ~data->sample_flags;
7682 if (filtered_sample_type == 0) {
7683 /* Make sure it has the correct data->type for output */
7684 data->type = event->attr.sample_type;
7688 __perf_event_header__init_id(data, event, filtered_sample_type);
7690 if (filtered_sample_type & PERF_SAMPLE_IP) {
7691 data->ip = perf_instruction_pointer(regs);
7692 data->sample_flags |= PERF_SAMPLE_IP;
7695 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7696 perf_sample_save_callchain(data, event, regs);
7698 if (filtered_sample_type & PERF_SAMPLE_RAW) {
7700 data->dyn_size += sizeof(u64);
7701 data->sample_flags |= PERF_SAMPLE_RAW;
7704 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
7705 data->br_stack = NULL;
7706 data->dyn_size += sizeof(u64);
7707 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
7710 if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
7711 perf_sample_regs_user(&data->regs_user, regs);
7714 * It cannot use the filtered_sample_type here as REGS_USER can be set
7715 * by STACK_USER (using __cond_set() above) and we don't want to update
7716 * the dyn_size if it's not requested by users.
7718 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
7719 /* regs dump ABI info */
7720 int size = sizeof(u64);
7722 if (data->regs_user.regs) {
7723 u64 mask = event->attr.sample_regs_user;
7724 size += hweight64(mask) * sizeof(u64);
7727 data->dyn_size += size;
7728 data->sample_flags |= PERF_SAMPLE_REGS_USER;
7731 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
7733 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7734 * processed as the last one or have additional check added
7735 * in case new sample type is added, because we could eat
7736 * up the rest of the sample size.
7738 u16 stack_size = event->attr.sample_stack_user;
7739 u16 header_size = perf_sample_data_size(data, event);
7740 u16 size = sizeof(u64);
7742 stack_size = perf_sample_ustack_size(stack_size, header_size,
7743 data->regs_user.regs);
7746 * If there is something to dump, add space for the dump
7747 * itself and for the field that tells the dynamic size,
7748 * which is how many have been actually dumped.
7751 size += sizeof(u64) + stack_size;
7753 data->stack_user_size = stack_size;
7754 data->dyn_size += size;
7755 data->sample_flags |= PERF_SAMPLE_STACK_USER;
7758 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
7759 data->weight.full = 0;
7760 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
7763 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
7764 data->data_src.val = PERF_MEM_NA;
7765 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
7768 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
7770 data->sample_flags |= PERF_SAMPLE_TRANSACTION;
7773 if (filtered_sample_type & PERF_SAMPLE_ADDR) {
7775 data->sample_flags |= PERF_SAMPLE_ADDR;
7778 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
7779 /* regs dump ABI info */
7780 int size = sizeof(u64);
7782 perf_sample_regs_intr(&data->regs_intr, regs);
7784 if (data->regs_intr.regs) {
7785 u64 mask = event->attr.sample_regs_intr;
7787 size += hweight64(mask) * sizeof(u64);
7790 data->dyn_size += size;
7791 data->sample_flags |= PERF_SAMPLE_REGS_INTR;
7794 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
7795 data->phys_addr = perf_virt_to_phys(data->addr);
7796 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
7799 #ifdef CONFIG_CGROUP_PERF
7800 if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
7801 struct cgroup *cgrp;
7803 /* protected by RCU */
7804 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7805 data->cgroup = cgroup_id(cgrp);
7806 data->sample_flags |= PERF_SAMPLE_CGROUP;
7811 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7812 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7813 * but the value will not dump to the userspace.
7815 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
7816 data->data_page_size = perf_get_page_size(data->addr);
7817 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
7820 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
7821 data->code_page_size = perf_get_page_size(data->ip);
7822 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
7825 if (filtered_sample_type & PERF_SAMPLE_AUX) {
7827 u16 header_size = perf_sample_data_size(data, event);
7829 header_size += sizeof(u64); /* size */
7832 * Given the 16bit nature of header::size, an AUX sample can
7833 * easily overflow it, what with all the preceding sample bits.
7834 * Make sure this doesn't happen by using up to U16_MAX bytes
7835 * per sample in total (rounded down to 8 byte boundary).
7837 size = min_t(size_t, U16_MAX - header_size,
7838 event->attr.aux_sample_size);
7839 size = rounddown(size, 8);
7840 size = perf_prepare_sample_aux(event, data, size);
7842 WARN_ON_ONCE(size + header_size > U16_MAX);
7843 data->dyn_size += size + sizeof(u64); /* size above */
7844 data->sample_flags |= PERF_SAMPLE_AUX;
7848 void perf_prepare_header(struct perf_event_header *header,
7849 struct perf_sample_data *data,
7850 struct perf_event *event,
7851 struct pt_regs *regs)
7853 header->type = PERF_RECORD_SAMPLE;
7854 header->size = perf_sample_data_size(data, event);
7855 header->misc = perf_misc_flags(regs);
7858 * If you're adding more sample types here, you likely need to do
7859 * something about the overflowing header::size, like repurpose the
7860 * lowest 3 bits of size, which should be always zero at the moment.
7861 * This raises a more important question, do we really need 512k sized
7862 * samples and why, so good argumentation is in order for whatever you
7865 WARN_ON_ONCE(header->size & 7);
7868 static __always_inline int
7869 __perf_event_output(struct perf_event *event,
7870 struct perf_sample_data *data,
7871 struct pt_regs *regs,
7872 int (*output_begin)(struct perf_output_handle *,
7873 struct perf_sample_data *,
7874 struct perf_event *,
7877 struct perf_output_handle handle;
7878 struct perf_event_header header;
7881 /* protect the callchain buffers */
7884 perf_prepare_sample(data, event, regs);
7885 perf_prepare_header(&header, data, event, regs);
7887 err = output_begin(&handle, data, event, header.size);
7891 perf_output_sample(&handle, &header, data, event);
7893 perf_output_end(&handle);
7901 perf_event_output_forward(struct perf_event *event,
7902 struct perf_sample_data *data,
7903 struct pt_regs *regs)
7905 __perf_event_output(event, data, regs, perf_output_begin_forward);
7909 perf_event_output_backward(struct perf_event *event,
7910 struct perf_sample_data *data,
7911 struct pt_regs *regs)
7913 __perf_event_output(event, data, regs, perf_output_begin_backward);
7917 perf_event_output(struct perf_event *event,
7918 struct perf_sample_data *data,
7919 struct pt_regs *regs)
7921 return __perf_event_output(event, data, regs, perf_output_begin);
7928 struct perf_read_event {
7929 struct perf_event_header header;
7936 perf_event_read_event(struct perf_event *event,
7937 struct task_struct *task)
7939 struct perf_output_handle handle;
7940 struct perf_sample_data sample;
7941 struct perf_read_event read_event = {
7943 .type = PERF_RECORD_READ,
7945 .size = sizeof(read_event) + event->read_size,
7947 .pid = perf_event_pid(event, task),
7948 .tid = perf_event_tid(event, task),
7952 perf_event_header__init_id(&read_event.header, &sample, event);
7953 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7957 perf_output_put(&handle, read_event);
7958 perf_output_read(&handle, event);
7959 perf_event__output_id_sample(event, &handle, &sample);
7961 perf_output_end(&handle);
7964 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7967 perf_iterate_ctx(struct perf_event_context *ctx,
7968 perf_iterate_f output,
7969 void *data, bool all)
7971 struct perf_event *event;
7973 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7975 if (event->state < PERF_EVENT_STATE_INACTIVE)
7977 if (!event_filter_match(event))
7981 output(event, data);
7985 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7987 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7988 struct perf_event *event;
7990 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7992 * Skip events that are not fully formed yet; ensure that
7993 * if we observe event->ctx, both event and ctx will be
7994 * complete enough. See perf_install_in_context().
7996 if (!smp_load_acquire(&event->ctx))
7999 if (event->state < PERF_EVENT_STATE_INACTIVE)
8001 if (!event_filter_match(event))
8003 output(event, data);
8008 * Iterate all events that need to receive side-band events.
8010 * For new callers; ensure that account_pmu_sb_event() includes
8011 * your event, otherwise it might not get delivered.
8014 perf_iterate_sb(perf_iterate_f output, void *data,
8015 struct perf_event_context *task_ctx)
8017 struct perf_event_context *ctx;
8023 * If we have task_ctx != NULL we only notify the task context itself.
8024 * The task_ctx is set only for EXIT events before releasing task
8028 perf_iterate_ctx(task_ctx, output, data, false);
8032 perf_iterate_sb_cpu(output, data);
8034 ctx = rcu_dereference(current->perf_event_ctxp);
8036 perf_iterate_ctx(ctx, output, data, false);
8043 * Clear all file-based filters at exec, they'll have to be
8044 * re-instated when/if these objects are mmapped again.
8046 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
8048 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8049 struct perf_addr_filter *filter;
8050 unsigned int restart = 0, count = 0;
8051 unsigned long flags;
8053 if (!has_addr_filter(event))
8056 raw_spin_lock_irqsave(&ifh->lock, flags);
8057 list_for_each_entry(filter, &ifh->list, entry) {
8058 if (filter->path.dentry) {
8059 event->addr_filter_ranges[count].start = 0;
8060 event->addr_filter_ranges[count].size = 0;
8068 event->addr_filters_gen++;
8069 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8072 perf_event_stop(event, 1);
8075 void perf_event_exec(void)
8077 struct perf_event_context *ctx;
8079 ctx = perf_pin_task_context(current);
8083 perf_event_enable_on_exec(ctx);
8084 perf_event_remove_on_exec(ctx);
8085 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
8087 perf_unpin_context(ctx);
8091 struct remote_output {
8092 struct perf_buffer *rb;
8096 static void __perf_event_output_stop(struct perf_event *event, void *data)
8098 struct perf_event *parent = event->parent;
8099 struct remote_output *ro = data;
8100 struct perf_buffer *rb = ro->rb;
8101 struct stop_event_data sd = {
8105 if (!has_aux(event))
8112 * In case of inheritance, it will be the parent that links to the
8113 * ring-buffer, but it will be the child that's actually using it.
8115 * We are using event::rb to determine if the event should be stopped,
8116 * however this may race with ring_buffer_attach() (through set_output),
8117 * which will make us skip the event that actually needs to be stopped.
8118 * So ring_buffer_attach() has to stop an aux event before re-assigning
8121 if (rcu_dereference(parent->rb) == rb)
8122 ro->err = __perf_event_stop(&sd);
8125 static int __perf_pmu_output_stop(void *info)
8127 struct perf_event *event = info;
8128 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
8129 struct remote_output ro = {
8134 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
8135 if (cpuctx->task_ctx)
8136 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
8143 static void perf_pmu_output_stop(struct perf_event *event)
8145 struct perf_event *iter;
8150 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8152 * For per-CPU events, we need to make sure that neither they
8153 * nor their children are running; for cpu==-1 events it's
8154 * sufficient to stop the event itself if it's active, since
8155 * it can't have children.
8159 cpu = READ_ONCE(iter->oncpu);
8164 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8165 if (err == -EAGAIN) {
8174 * task tracking -- fork/exit
8176 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8179 struct perf_task_event {
8180 struct task_struct *task;
8181 struct perf_event_context *task_ctx;
8184 struct perf_event_header header;
8194 static int perf_event_task_match(struct perf_event *event)
8196 return event->attr.comm || event->attr.mmap ||
8197 event->attr.mmap2 || event->attr.mmap_data ||
8201 static void perf_event_task_output(struct perf_event *event,
8204 struct perf_task_event *task_event = data;
8205 struct perf_output_handle handle;
8206 struct perf_sample_data sample;
8207 struct task_struct *task = task_event->task;
8208 int ret, size = task_event->event_id.header.size;
8210 if (!perf_event_task_match(event))
8213 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8215 ret = perf_output_begin(&handle, &sample, event,
8216 task_event->event_id.header.size);
8220 task_event->event_id.pid = perf_event_pid(event, task);
8221 task_event->event_id.tid = perf_event_tid(event, task);
8223 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8224 task_event->event_id.ppid = perf_event_pid(event,
8226 task_event->event_id.ptid = perf_event_pid(event,
8228 } else { /* PERF_RECORD_FORK */
8229 task_event->event_id.ppid = perf_event_pid(event, current);
8230 task_event->event_id.ptid = perf_event_tid(event, current);
8233 task_event->event_id.time = perf_event_clock(event);
8235 perf_output_put(&handle, task_event->event_id);
8237 perf_event__output_id_sample(event, &handle, &sample);
8239 perf_output_end(&handle);
8241 task_event->event_id.header.size = size;
8244 static void perf_event_task(struct task_struct *task,
8245 struct perf_event_context *task_ctx,
8248 struct perf_task_event task_event;
8250 if (!atomic_read(&nr_comm_events) &&
8251 !atomic_read(&nr_mmap_events) &&
8252 !atomic_read(&nr_task_events))
8255 task_event = (struct perf_task_event){
8257 .task_ctx = task_ctx,
8260 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8262 .size = sizeof(task_event.event_id),
8272 perf_iterate_sb(perf_event_task_output,
8277 void perf_event_fork(struct task_struct *task)
8279 perf_event_task(task, NULL, 1);
8280 perf_event_namespaces(task);
8287 struct perf_comm_event {
8288 struct task_struct *task;
8293 struct perf_event_header header;
8300 static int perf_event_comm_match(struct perf_event *event)
8302 return event->attr.comm;
8305 static void perf_event_comm_output(struct perf_event *event,
8308 struct perf_comm_event *comm_event = data;
8309 struct perf_output_handle handle;
8310 struct perf_sample_data sample;
8311 int size = comm_event->event_id.header.size;
8314 if (!perf_event_comm_match(event))
8317 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8318 ret = perf_output_begin(&handle, &sample, event,
8319 comm_event->event_id.header.size);
8324 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8325 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8327 perf_output_put(&handle, comm_event->event_id);
8328 __output_copy(&handle, comm_event->comm,
8329 comm_event->comm_size);
8331 perf_event__output_id_sample(event, &handle, &sample);
8333 perf_output_end(&handle);
8335 comm_event->event_id.header.size = size;
8338 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8340 char comm[TASK_COMM_LEN];
8343 memset(comm, 0, sizeof(comm));
8344 strscpy(comm, comm_event->task->comm, sizeof(comm));
8345 size = ALIGN(strlen(comm)+1, sizeof(u64));
8347 comm_event->comm = comm;
8348 comm_event->comm_size = size;
8350 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8352 perf_iterate_sb(perf_event_comm_output,
8357 void perf_event_comm(struct task_struct *task, bool exec)
8359 struct perf_comm_event comm_event;
8361 if (!atomic_read(&nr_comm_events))
8364 comm_event = (struct perf_comm_event){
8370 .type = PERF_RECORD_COMM,
8371 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8379 perf_event_comm_event(&comm_event);
8383 * namespaces tracking
8386 struct perf_namespaces_event {
8387 struct task_struct *task;
8390 struct perf_event_header header;
8395 struct perf_ns_link_info link_info[NR_NAMESPACES];
8399 static int perf_event_namespaces_match(struct perf_event *event)
8401 return event->attr.namespaces;
8404 static void perf_event_namespaces_output(struct perf_event *event,
8407 struct perf_namespaces_event *namespaces_event = data;
8408 struct perf_output_handle handle;
8409 struct perf_sample_data sample;
8410 u16 header_size = namespaces_event->event_id.header.size;
8413 if (!perf_event_namespaces_match(event))
8416 perf_event_header__init_id(&namespaces_event->event_id.header,
8418 ret = perf_output_begin(&handle, &sample, event,
8419 namespaces_event->event_id.header.size);
8423 namespaces_event->event_id.pid = perf_event_pid(event,
8424 namespaces_event->task);
8425 namespaces_event->event_id.tid = perf_event_tid(event,
8426 namespaces_event->task);
8428 perf_output_put(&handle, namespaces_event->event_id);
8430 perf_event__output_id_sample(event, &handle, &sample);
8432 perf_output_end(&handle);
8434 namespaces_event->event_id.header.size = header_size;
8437 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8438 struct task_struct *task,
8439 const struct proc_ns_operations *ns_ops)
8441 struct path ns_path;
8442 struct inode *ns_inode;
8445 error = ns_get_path(&ns_path, task, ns_ops);
8447 ns_inode = ns_path.dentry->d_inode;
8448 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8449 ns_link_info->ino = ns_inode->i_ino;
8454 void perf_event_namespaces(struct task_struct *task)
8456 struct perf_namespaces_event namespaces_event;
8457 struct perf_ns_link_info *ns_link_info;
8459 if (!atomic_read(&nr_namespaces_events))
8462 namespaces_event = (struct perf_namespaces_event){
8466 .type = PERF_RECORD_NAMESPACES,
8468 .size = sizeof(namespaces_event.event_id),
8472 .nr_namespaces = NR_NAMESPACES,
8473 /* .link_info[NR_NAMESPACES] */
8477 ns_link_info = namespaces_event.event_id.link_info;
8479 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8480 task, &mntns_operations);
8482 #ifdef CONFIG_USER_NS
8483 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8484 task, &userns_operations);
8486 #ifdef CONFIG_NET_NS
8487 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8488 task, &netns_operations);
8490 #ifdef CONFIG_UTS_NS
8491 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8492 task, &utsns_operations);
8494 #ifdef CONFIG_IPC_NS
8495 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8496 task, &ipcns_operations);
8498 #ifdef CONFIG_PID_NS
8499 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8500 task, &pidns_operations);
8502 #ifdef CONFIG_CGROUPS
8503 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8504 task, &cgroupns_operations);
8507 perf_iterate_sb(perf_event_namespaces_output,
8515 #ifdef CONFIG_CGROUP_PERF
8517 struct perf_cgroup_event {
8521 struct perf_event_header header;
8527 static int perf_event_cgroup_match(struct perf_event *event)
8529 return event->attr.cgroup;
8532 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8534 struct perf_cgroup_event *cgroup_event = data;
8535 struct perf_output_handle handle;
8536 struct perf_sample_data sample;
8537 u16 header_size = cgroup_event->event_id.header.size;
8540 if (!perf_event_cgroup_match(event))
8543 perf_event_header__init_id(&cgroup_event->event_id.header,
8545 ret = perf_output_begin(&handle, &sample, event,
8546 cgroup_event->event_id.header.size);
8550 perf_output_put(&handle, cgroup_event->event_id);
8551 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8553 perf_event__output_id_sample(event, &handle, &sample);
8555 perf_output_end(&handle);
8557 cgroup_event->event_id.header.size = header_size;
8560 static void perf_event_cgroup(struct cgroup *cgrp)
8562 struct perf_cgroup_event cgroup_event;
8563 char path_enomem[16] = "//enomem";
8567 if (!atomic_read(&nr_cgroup_events))
8570 cgroup_event = (struct perf_cgroup_event){
8573 .type = PERF_RECORD_CGROUP,
8575 .size = sizeof(cgroup_event.event_id),
8577 .id = cgroup_id(cgrp),
8581 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8582 if (pathname == NULL) {
8583 cgroup_event.path = path_enomem;
8585 /* just to be sure to have enough space for alignment */
8586 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8587 cgroup_event.path = pathname;
8591 * Since our buffer works in 8 byte units we need to align our string
8592 * size to a multiple of 8. However, we must guarantee the tail end is
8593 * zero'd out to avoid leaking random bits to userspace.
8595 size = strlen(cgroup_event.path) + 1;
8596 while (!IS_ALIGNED(size, sizeof(u64)))
8597 cgroup_event.path[size++] = '\0';
8599 cgroup_event.event_id.header.size += size;
8600 cgroup_event.path_size = size;
8602 perf_iterate_sb(perf_event_cgroup_output,
8615 struct perf_mmap_event {
8616 struct vm_area_struct *vma;
8618 const char *file_name;
8624 u8 build_id[BUILD_ID_SIZE_MAX];
8628 struct perf_event_header header;
8638 static int perf_event_mmap_match(struct perf_event *event,
8641 struct perf_mmap_event *mmap_event = data;
8642 struct vm_area_struct *vma = mmap_event->vma;
8643 int executable = vma->vm_flags & VM_EXEC;
8645 return (!executable && event->attr.mmap_data) ||
8646 (executable && (event->attr.mmap || event->attr.mmap2));
8649 static void perf_event_mmap_output(struct perf_event *event,
8652 struct perf_mmap_event *mmap_event = data;
8653 struct perf_output_handle handle;
8654 struct perf_sample_data sample;
8655 int size = mmap_event->event_id.header.size;
8656 u32 type = mmap_event->event_id.header.type;
8660 if (!perf_event_mmap_match(event, data))
8663 if (event->attr.mmap2) {
8664 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8665 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8666 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8667 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8668 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8669 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8670 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8673 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8674 ret = perf_output_begin(&handle, &sample, event,
8675 mmap_event->event_id.header.size);
8679 mmap_event->event_id.pid = perf_event_pid(event, current);
8680 mmap_event->event_id.tid = perf_event_tid(event, current);
8682 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8684 if (event->attr.mmap2 && use_build_id)
8685 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8687 perf_output_put(&handle, mmap_event->event_id);
8689 if (event->attr.mmap2) {
8691 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8693 __output_copy(&handle, size, 4);
8694 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8696 perf_output_put(&handle, mmap_event->maj);
8697 perf_output_put(&handle, mmap_event->min);
8698 perf_output_put(&handle, mmap_event->ino);
8699 perf_output_put(&handle, mmap_event->ino_generation);
8701 perf_output_put(&handle, mmap_event->prot);
8702 perf_output_put(&handle, mmap_event->flags);
8705 __output_copy(&handle, mmap_event->file_name,
8706 mmap_event->file_size);
8708 perf_event__output_id_sample(event, &handle, &sample);
8710 perf_output_end(&handle);
8712 mmap_event->event_id.header.size = size;
8713 mmap_event->event_id.header.type = type;
8716 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8718 struct vm_area_struct *vma = mmap_event->vma;
8719 struct file *file = vma->vm_file;
8720 int maj = 0, min = 0;
8721 u64 ino = 0, gen = 0;
8722 u32 prot = 0, flags = 0;
8728 if (vma->vm_flags & VM_READ)
8730 if (vma->vm_flags & VM_WRITE)
8732 if (vma->vm_flags & VM_EXEC)
8735 if (vma->vm_flags & VM_MAYSHARE)
8738 flags = MAP_PRIVATE;
8740 if (vma->vm_flags & VM_LOCKED)
8741 flags |= MAP_LOCKED;
8742 if (is_vm_hugetlb_page(vma))
8743 flags |= MAP_HUGETLB;
8746 struct inode *inode;
8749 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8755 * d_path() works from the end of the rb backwards, so we
8756 * need to add enough zero bytes after the string to handle
8757 * the 64bit alignment we do later.
8759 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8764 inode = file_inode(vma->vm_file);
8765 dev = inode->i_sb->s_dev;
8767 gen = inode->i_generation;
8773 if (vma->vm_ops && vma->vm_ops->name)
8774 name = (char *) vma->vm_ops->name(vma);
8776 name = (char *)arch_vma_name(vma);
8778 if (vma_is_initial_heap(vma))
8780 else if (vma_is_initial_stack(vma))
8788 strscpy(tmp, name, sizeof(tmp));
8792 * Since our buffer works in 8 byte units we need to align our string
8793 * size to a multiple of 8. However, we must guarantee the tail end is
8794 * zero'd out to avoid leaking random bits to userspace.
8796 size = strlen(name)+1;
8797 while (!IS_ALIGNED(size, sizeof(u64)))
8798 name[size++] = '\0';
8800 mmap_event->file_name = name;
8801 mmap_event->file_size = size;
8802 mmap_event->maj = maj;
8803 mmap_event->min = min;
8804 mmap_event->ino = ino;
8805 mmap_event->ino_generation = gen;
8806 mmap_event->prot = prot;
8807 mmap_event->flags = flags;
8809 if (!(vma->vm_flags & VM_EXEC))
8810 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8812 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8814 if (atomic_read(&nr_build_id_events))
8815 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8817 perf_iterate_sb(perf_event_mmap_output,
8825 * Check whether inode and address range match filter criteria.
8827 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8828 struct file *file, unsigned long offset,
8831 /* d_inode(NULL) won't be equal to any mapped user-space file */
8832 if (!filter->path.dentry)
8835 if (d_inode(filter->path.dentry) != file_inode(file))
8838 if (filter->offset > offset + size)
8841 if (filter->offset + filter->size < offset)
8847 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8848 struct vm_area_struct *vma,
8849 struct perf_addr_filter_range *fr)
8851 unsigned long vma_size = vma->vm_end - vma->vm_start;
8852 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8853 struct file *file = vma->vm_file;
8855 if (!perf_addr_filter_match(filter, file, off, vma_size))
8858 if (filter->offset < off) {
8859 fr->start = vma->vm_start;
8860 fr->size = min(vma_size, filter->size - (off - filter->offset));
8862 fr->start = vma->vm_start + filter->offset - off;
8863 fr->size = min(vma->vm_end - fr->start, filter->size);
8869 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8871 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8872 struct vm_area_struct *vma = data;
8873 struct perf_addr_filter *filter;
8874 unsigned int restart = 0, count = 0;
8875 unsigned long flags;
8877 if (!has_addr_filter(event))
8883 raw_spin_lock_irqsave(&ifh->lock, flags);
8884 list_for_each_entry(filter, &ifh->list, entry) {
8885 if (perf_addr_filter_vma_adjust(filter, vma,
8886 &event->addr_filter_ranges[count]))
8893 event->addr_filters_gen++;
8894 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8897 perf_event_stop(event, 1);
8901 * Adjust all task's events' filters to the new vma
8903 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8905 struct perf_event_context *ctx;
8908 * Data tracing isn't supported yet and as such there is no need
8909 * to keep track of anything that isn't related to executable code:
8911 if (!(vma->vm_flags & VM_EXEC))
8915 ctx = rcu_dereference(current->perf_event_ctxp);
8917 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8921 void perf_event_mmap(struct vm_area_struct *vma)
8923 struct perf_mmap_event mmap_event;
8925 if (!atomic_read(&nr_mmap_events))
8928 mmap_event = (struct perf_mmap_event){
8934 .type = PERF_RECORD_MMAP,
8935 .misc = PERF_RECORD_MISC_USER,
8940 .start = vma->vm_start,
8941 .len = vma->vm_end - vma->vm_start,
8942 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8944 /* .maj (attr_mmap2 only) */
8945 /* .min (attr_mmap2 only) */
8946 /* .ino (attr_mmap2 only) */
8947 /* .ino_generation (attr_mmap2 only) */
8948 /* .prot (attr_mmap2 only) */
8949 /* .flags (attr_mmap2 only) */
8952 perf_addr_filters_adjust(vma);
8953 perf_event_mmap_event(&mmap_event);
8956 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8957 unsigned long size, u64 flags)
8959 struct perf_output_handle handle;
8960 struct perf_sample_data sample;
8961 struct perf_aux_event {
8962 struct perf_event_header header;
8968 .type = PERF_RECORD_AUX,
8970 .size = sizeof(rec),
8978 perf_event_header__init_id(&rec.header, &sample, event);
8979 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8984 perf_output_put(&handle, rec);
8985 perf_event__output_id_sample(event, &handle, &sample);
8987 perf_output_end(&handle);
8991 * Lost/dropped samples logging
8993 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8995 struct perf_output_handle handle;
8996 struct perf_sample_data sample;
9000 struct perf_event_header header;
9002 } lost_samples_event = {
9004 .type = PERF_RECORD_LOST_SAMPLES,
9006 .size = sizeof(lost_samples_event),
9011 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
9013 ret = perf_output_begin(&handle, &sample, event,
9014 lost_samples_event.header.size);
9018 perf_output_put(&handle, lost_samples_event);
9019 perf_event__output_id_sample(event, &handle, &sample);
9020 perf_output_end(&handle);
9024 * context_switch tracking
9027 struct perf_switch_event {
9028 struct task_struct *task;
9029 struct task_struct *next_prev;
9032 struct perf_event_header header;
9038 static int perf_event_switch_match(struct perf_event *event)
9040 return event->attr.context_switch;
9043 static void perf_event_switch_output(struct perf_event *event, void *data)
9045 struct perf_switch_event *se = data;
9046 struct perf_output_handle handle;
9047 struct perf_sample_data sample;
9050 if (!perf_event_switch_match(event))
9053 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9054 if (event->ctx->task) {
9055 se->event_id.header.type = PERF_RECORD_SWITCH;
9056 se->event_id.header.size = sizeof(se->event_id.header);
9058 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
9059 se->event_id.header.size = sizeof(se->event_id);
9060 se->event_id.next_prev_pid =
9061 perf_event_pid(event, se->next_prev);
9062 se->event_id.next_prev_tid =
9063 perf_event_tid(event, se->next_prev);
9066 perf_event_header__init_id(&se->event_id.header, &sample, event);
9068 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
9072 if (event->ctx->task)
9073 perf_output_put(&handle, se->event_id.header);
9075 perf_output_put(&handle, se->event_id);
9077 perf_event__output_id_sample(event, &handle, &sample);
9079 perf_output_end(&handle);
9082 static void perf_event_switch(struct task_struct *task,
9083 struct task_struct *next_prev, bool sched_in)
9085 struct perf_switch_event switch_event;
9087 /* N.B. caller checks nr_switch_events != 0 */
9089 switch_event = (struct perf_switch_event){
9091 .next_prev = next_prev,
9095 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
9098 /* .next_prev_pid */
9099 /* .next_prev_tid */
9103 if (!sched_in && task->on_rq) {
9104 switch_event.event_id.header.misc |=
9105 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
9108 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
9112 * IRQ throttle logging
9115 static void perf_log_throttle(struct perf_event *event, int enable)
9117 struct perf_output_handle handle;
9118 struct perf_sample_data sample;
9122 struct perf_event_header header;
9126 } throttle_event = {
9128 .type = PERF_RECORD_THROTTLE,
9130 .size = sizeof(throttle_event),
9132 .time = perf_event_clock(event),
9133 .id = primary_event_id(event),
9134 .stream_id = event->id,
9138 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9140 perf_event_header__init_id(&throttle_event.header, &sample, event);
9142 ret = perf_output_begin(&handle, &sample, event,
9143 throttle_event.header.size);
9147 perf_output_put(&handle, throttle_event);
9148 perf_event__output_id_sample(event, &handle, &sample);
9149 perf_output_end(&handle);
9153 * ksymbol register/unregister tracking
9156 struct perf_ksymbol_event {
9160 struct perf_event_header header;
9168 static int perf_event_ksymbol_match(struct perf_event *event)
9170 return event->attr.ksymbol;
9173 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9175 struct perf_ksymbol_event *ksymbol_event = data;
9176 struct perf_output_handle handle;
9177 struct perf_sample_data sample;
9180 if (!perf_event_ksymbol_match(event))
9183 perf_event_header__init_id(&ksymbol_event->event_id.header,
9185 ret = perf_output_begin(&handle, &sample, event,
9186 ksymbol_event->event_id.header.size);
9190 perf_output_put(&handle, ksymbol_event->event_id);
9191 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9192 perf_event__output_id_sample(event, &handle, &sample);
9194 perf_output_end(&handle);
9197 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9200 struct perf_ksymbol_event ksymbol_event;
9201 char name[KSYM_NAME_LEN];
9205 if (!atomic_read(&nr_ksymbol_events))
9208 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9209 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9212 strscpy(name, sym, KSYM_NAME_LEN);
9213 name_len = strlen(name) + 1;
9214 while (!IS_ALIGNED(name_len, sizeof(u64)))
9215 name[name_len++] = '\0';
9216 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9219 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9221 ksymbol_event = (struct perf_ksymbol_event){
9223 .name_len = name_len,
9226 .type = PERF_RECORD_KSYMBOL,
9227 .size = sizeof(ksymbol_event.event_id) +
9232 .ksym_type = ksym_type,
9237 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9240 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9244 * bpf program load/unload tracking
9247 struct perf_bpf_event {
9248 struct bpf_prog *prog;
9250 struct perf_event_header header;
9254 u8 tag[BPF_TAG_SIZE];
9258 static int perf_event_bpf_match(struct perf_event *event)
9260 return event->attr.bpf_event;
9263 static void perf_event_bpf_output(struct perf_event *event, void *data)
9265 struct perf_bpf_event *bpf_event = data;
9266 struct perf_output_handle handle;
9267 struct perf_sample_data sample;
9270 if (!perf_event_bpf_match(event))
9273 perf_event_header__init_id(&bpf_event->event_id.header,
9275 ret = perf_output_begin(&handle, &sample, event,
9276 bpf_event->event_id.header.size);
9280 perf_output_put(&handle, bpf_event->event_id);
9281 perf_event__output_id_sample(event, &handle, &sample);
9283 perf_output_end(&handle);
9286 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9287 enum perf_bpf_event_type type)
9289 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9292 if (prog->aux->func_cnt == 0) {
9293 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9294 (u64)(unsigned long)prog->bpf_func,
9295 prog->jited_len, unregister,
9296 prog->aux->ksym.name);
9298 for (i = 0; i < prog->aux->func_cnt; i++) {
9299 struct bpf_prog *subprog = prog->aux->func[i];
9302 PERF_RECORD_KSYMBOL_TYPE_BPF,
9303 (u64)(unsigned long)subprog->bpf_func,
9304 subprog->jited_len, unregister,
9305 subprog->aux->ksym.name);
9310 void perf_event_bpf_event(struct bpf_prog *prog,
9311 enum perf_bpf_event_type type,
9314 struct perf_bpf_event bpf_event;
9317 case PERF_BPF_EVENT_PROG_LOAD:
9318 case PERF_BPF_EVENT_PROG_UNLOAD:
9319 if (atomic_read(&nr_ksymbol_events))
9320 perf_event_bpf_emit_ksymbols(prog, type);
9326 if (!atomic_read(&nr_bpf_events))
9329 bpf_event = (struct perf_bpf_event){
9333 .type = PERF_RECORD_BPF_EVENT,
9334 .size = sizeof(bpf_event.event_id),
9338 .id = prog->aux->id,
9342 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9344 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9345 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9348 struct perf_text_poke_event {
9349 const void *old_bytes;
9350 const void *new_bytes;
9356 struct perf_event_header header;
9362 static int perf_event_text_poke_match(struct perf_event *event)
9364 return event->attr.text_poke;
9367 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9369 struct perf_text_poke_event *text_poke_event = data;
9370 struct perf_output_handle handle;
9371 struct perf_sample_data sample;
9375 if (!perf_event_text_poke_match(event))
9378 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9380 ret = perf_output_begin(&handle, &sample, event,
9381 text_poke_event->event_id.header.size);
9385 perf_output_put(&handle, text_poke_event->event_id);
9386 perf_output_put(&handle, text_poke_event->old_len);
9387 perf_output_put(&handle, text_poke_event->new_len);
9389 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9390 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9392 if (text_poke_event->pad)
9393 __output_copy(&handle, &padding, text_poke_event->pad);
9395 perf_event__output_id_sample(event, &handle, &sample);
9397 perf_output_end(&handle);
9400 void perf_event_text_poke(const void *addr, const void *old_bytes,
9401 size_t old_len, const void *new_bytes, size_t new_len)
9403 struct perf_text_poke_event text_poke_event;
9406 if (!atomic_read(&nr_text_poke_events))
9409 tot = sizeof(text_poke_event.old_len) + old_len;
9410 tot += sizeof(text_poke_event.new_len) + new_len;
9411 pad = ALIGN(tot, sizeof(u64)) - tot;
9413 text_poke_event = (struct perf_text_poke_event){
9414 .old_bytes = old_bytes,
9415 .new_bytes = new_bytes,
9421 .type = PERF_RECORD_TEXT_POKE,
9422 .misc = PERF_RECORD_MISC_KERNEL,
9423 .size = sizeof(text_poke_event.event_id) + tot + pad,
9425 .addr = (unsigned long)addr,
9429 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9432 void perf_event_itrace_started(struct perf_event *event)
9434 event->attach_state |= PERF_ATTACH_ITRACE;
9437 static void perf_log_itrace_start(struct perf_event *event)
9439 struct perf_output_handle handle;
9440 struct perf_sample_data sample;
9441 struct perf_aux_event {
9442 struct perf_event_header header;
9449 event = event->parent;
9451 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9452 event->attach_state & PERF_ATTACH_ITRACE)
9455 rec.header.type = PERF_RECORD_ITRACE_START;
9456 rec.header.misc = 0;
9457 rec.header.size = sizeof(rec);
9458 rec.pid = perf_event_pid(event, current);
9459 rec.tid = perf_event_tid(event, current);
9461 perf_event_header__init_id(&rec.header, &sample, event);
9462 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9467 perf_output_put(&handle, rec);
9468 perf_event__output_id_sample(event, &handle, &sample);
9470 perf_output_end(&handle);
9473 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9475 struct perf_output_handle handle;
9476 struct perf_sample_data sample;
9477 struct perf_aux_event {
9478 struct perf_event_header header;
9484 event = event->parent;
9486 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9487 rec.header.misc = 0;
9488 rec.header.size = sizeof(rec);
9491 perf_event_header__init_id(&rec.header, &sample, event);
9492 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9497 perf_output_put(&handle, rec);
9498 perf_event__output_id_sample(event, &handle, &sample);
9500 perf_output_end(&handle);
9502 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
9505 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9507 struct hw_perf_event *hwc = &event->hw;
9511 seq = __this_cpu_read(perf_throttled_seq);
9512 if (seq != hwc->interrupts_seq) {
9513 hwc->interrupts_seq = seq;
9514 hwc->interrupts = 1;
9517 if (unlikely(throttle &&
9518 hwc->interrupts > max_samples_per_tick)) {
9519 __this_cpu_inc(perf_throttled_count);
9520 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9521 hwc->interrupts = MAX_INTERRUPTS;
9522 perf_log_throttle(event, 0);
9527 if (event->attr.freq) {
9528 u64 now = perf_clock();
9529 s64 delta = now - hwc->freq_time_stamp;
9531 hwc->freq_time_stamp = now;
9533 if (delta > 0 && delta < 2*TICK_NSEC)
9534 perf_adjust_period(event, delta, hwc->last_period, true);
9540 int perf_event_account_interrupt(struct perf_event *event)
9542 return __perf_event_account_interrupt(event, 1);
9545 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
9548 * Due to interrupt latency (AKA "skid"), we may enter the
9549 * kernel before taking an overflow, even if the PMU is only
9550 * counting user events.
9552 if (event->attr.exclude_kernel && !user_mode(regs))
9558 #ifdef CONFIG_BPF_SYSCALL
9559 static int bpf_overflow_handler(struct perf_event *event,
9560 struct perf_sample_data *data,
9561 struct pt_regs *regs)
9563 struct bpf_perf_event_data_kern ctx = {
9567 struct bpf_prog *prog;
9570 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9571 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9574 prog = READ_ONCE(event->prog);
9576 perf_prepare_sample(data, event, regs);
9577 ret = bpf_prog_run(prog, &ctx);
9581 __this_cpu_dec(bpf_prog_active);
9586 static inline int perf_event_set_bpf_handler(struct perf_event *event,
9587 struct bpf_prog *prog,
9590 if (event->overflow_handler_context)
9591 /* hw breakpoint or kernel counter */
9597 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
9600 if (event->attr.precise_ip &&
9601 prog->call_get_stack &&
9602 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
9603 event->attr.exclude_callchain_kernel ||
9604 event->attr.exclude_callchain_user)) {
9606 * On perf_event with precise_ip, calling bpf_get_stack()
9607 * may trigger unwinder warnings and occasional crashes.
9608 * bpf_get_[stack|stackid] works around this issue by using
9609 * callchain attached to perf_sample_data. If the
9610 * perf_event does not full (kernel and user) callchain
9611 * attached to perf_sample_data, do not allow attaching BPF
9612 * program that calls bpf_get_[stack|stackid].
9618 event->bpf_cookie = bpf_cookie;
9622 static inline void perf_event_free_bpf_handler(struct perf_event *event)
9624 struct bpf_prog *prog = event->prog;
9633 static inline int bpf_overflow_handler(struct perf_event *event,
9634 struct perf_sample_data *data,
9635 struct pt_regs *regs)
9640 static inline int perf_event_set_bpf_handler(struct perf_event *event,
9641 struct bpf_prog *prog,
9647 static inline void perf_event_free_bpf_handler(struct perf_event *event)
9653 * Generic event overflow handling, sampling.
9656 static int __perf_event_overflow(struct perf_event *event,
9657 int throttle, struct perf_sample_data *data,
9658 struct pt_regs *regs)
9660 int events = atomic_read(&event->event_limit);
9664 * Non-sampling counters might still use the PMI to fold short
9665 * hardware counters, ignore those.
9667 if (unlikely(!is_sampling_event(event)))
9670 ret = __perf_event_account_interrupt(event, throttle);
9672 if (event->prog && !bpf_overflow_handler(event, data, regs))
9676 * XXX event_limit might not quite work as expected on inherited
9680 event->pending_kill = POLL_IN;
9681 if (events && atomic_dec_and_test(&event->event_limit)) {
9683 event->pending_kill = POLL_HUP;
9684 perf_event_disable_inatomic(event);
9687 if (event->attr.sigtrap) {
9689 * The desired behaviour of sigtrap vs invalid samples is a bit
9690 * tricky; on the one hand, one should not loose the SIGTRAP if
9691 * it is the first event, on the other hand, we should also not
9692 * trigger the WARN or override the data address.
9694 bool valid_sample = sample_is_allowed(event, regs);
9695 unsigned int pending_id = 1;
9698 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
9699 if (!event->pending_sigtrap) {
9700 event->pending_sigtrap = pending_id;
9701 local_inc(&event->ctx->nr_pending);
9702 } else if (event->attr.exclude_kernel && valid_sample) {
9704 * Should not be able to return to user space without
9705 * consuming pending_sigtrap; with exceptions:
9707 * 1. Where !exclude_kernel, events can overflow again
9708 * in the kernel without returning to user space.
9710 * 2. Events that can overflow again before the IRQ-
9711 * work without user space progress (e.g. hrtimer).
9712 * To approximate progress (with false negatives),
9713 * check 32-bit hash of the current IP.
9715 WARN_ON_ONCE(event->pending_sigtrap != pending_id);
9718 event->pending_addr = 0;
9719 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
9720 event->pending_addr = data->addr;
9721 irq_work_queue(&event->pending_irq);
9724 READ_ONCE(event->overflow_handler)(event, data, regs);
9726 if (*perf_event_fasync(event) && event->pending_kill) {
9727 event->pending_wakeup = 1;
9728 irq_work_queue(&event->pending_irq);
9734 int perf_event_overflow(struct perf_event *event,
9735 struct perf_sample_data *data,
9736 struct pt_regs *regs)
9738 return __perf_event_overflow(event, 1, data, regs);
9742 * Generic software event infrastructure
9745 struct swevent_htable {
9746 struct swevent_hlist *swevent_hlist;
9747 struct mutex hlist_mutex;
9750 /* Recursion avoidance in each contexts */
9751 int recursion[PERF_NR_CONTEXTS];
9754 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9757 * We directly increment event->count and keep a second value in
9758 * event->hw.period_left to count intervals. This period event
9759 * is kept in the range [-sample_period, 0] so that we can use the
9763 u64 perf_swevent_set_period(struct perf_event *event)
9765 struct hw_perf_event *hwc = &event->hw;
9766 u64 period = hwc->last_period;
9770 hwc->last_period = hwc->sample_period;
9772 old = local64_read(&hwc->period_left);
9778 nr = div64_u64(period + val, period);
9779 offset = nr * period;
9781 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
9786 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9787 struct perf_sample_data *data,
9788 struct pt_regs *regs)
9790 struct hw_perf_event *hwc = &event->hw;
9794 overflow = perf_swevent_set_period(event);
9796 if (hwc->interrupts == MAX_INTERRUPTS)
9799 for (; overflow; overflow--) {
9800 if (__perf_event_overflow(event, throttle,
9803 * We inhibit the overflow from happening when
9804 * hwc->interrupts == MAX_INTERRUPTS.
9812 static void perf_swevent_event(struct perf_event *event, u64 nr,
9813 struct perf_sample_data *data,
9814 struct pt_regs *regs)
9816 struct hw_perf_event *hwc = &event->hw;
9818 local64_add(nr, &event->count);
9823 if (!is_sampling_event(event))
9826 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9828 return perf_swevent_overflow(event, 1, data, regs);
9830 data->period = event->hw.last_period;
9832 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9833 return perf_swevent_overflow(event, 1, data, regs);
9835 if (local64_add_negative(nr, &hwc->period_left))
9838 perf_swevent_overflow(event, 0, data, regs);
9841 static int perf_exclude_event(struct perf_event *event,
9842 struct pt_regs *regs)
9844 if (event->hw.state & PERF_HES_STOPPED)
9848 if (event->attr.exclude_user && user_mode(regs))
9851 if (event->attr.exclude_kernel && !user_mode(regs))
9858 static int perf_swevent_match(struct perf_event *event,
9859 enum perf_type_id type,
9861 struct perf_sample_data *data,
9862 struct pt_regs *regs)
9864 if (event->attr.type != type)
9867 if (event->attr.config != event_id)
9870 if (perf_exclude_event(event, regs))
9876 static inline u64 swevent_hash(u64 type, u32 event_id)
9878 u64 val = event_id | (type << 32);
9880 return hash_64(val, SWEVENT_HLIST_BITS);
9883 static inline struct hlist_head *
9884 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9886 u64 hash = swevent_hash(type, event_id);
9888 return &hlist->heads[hash];
9891 /* For the read side: events when they trigger */
9892 static inline struct hlist_head *
9893 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9895 struct swevent_hlist *hlist;
9897 hlist = rcu_dereference(swhash->swevent_hlist);
9901 return __find_swevent_head(hlist, type, event_id);
9904 /* For the event head insertion and removal in the hlist */
9905 static inline struct hlist_head *
9906 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9908 struct swevent_hlist *hlist;
9909 u32 event_id = event->attr.config;
9910 u64 type = event->attr.type;
9913 * Event scheduling is always serialized against hlist allocation
9914 * and release. Which makes the protected version suitable here.
9915 * The context lock guarantees that.
9917 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9918 lockdep_is_held(&event->ctx->lock));
9922 return __find_swevent_head(hlist, type, event_id);
9925 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9927 struct perf_sample_data *data,
9928 struct pt_regs *regs)
9930 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9931 struct perf_event *event;
9932 struct hlist_head *head;
9935 head = find_swevent_head_rcu(swhash, type, event_id);
9939 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9940 if (perf_swevent_match(event, type, event_id, data, regs))
9941 perf_swevent_event(event, nr, data, regs);
9947 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9949 int perf_swevent_get_recursion_context(void)
9951 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9953 return get_recursion_context(swhash->recursion);
9955 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9957 void perf_swevent_put_recursion_context(int rctx)
9959 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9961 put_recursion_context(swhash->recursion, rctx);
9964 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9966 struct perf_sample_data data;
9968 if (WARN_ON_ONCE(!regs))
9971 perf_sample_data_init(&data, addr, 0);
9972 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9975 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9979 preempt_disable_notrace();
9980 rctx = perf_swevent_get_recursion_context();
9981 if (unlikely(rctx < 0))
9984 ___perf_sw_event(event_id, nr, regs, addr);
9986 perf_swevent_put_recursion_context(rctx);
9988 preempt_enable_notrace();
9991 static void perf_swevent_read(struct perf_event *event)
9995 static int perf_swevent_add(struct perf_event *event, int flags)
9997 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9998 struct hw_perf_event *hwc = &event->hw;
9999 struct hlist_head *head;
10001 if (is_sampling_event(event)) {
10002 hwc->last_period = hwc->sample_period;
10003 perf_swevent_set_period(event);
10006 hwc->state = !(flags & PERF_EF_START);
10008 head = find_swevent_head(swhash, event);
10009 if (WARN_ON_ONCE(!head))
10012 hlist_add_head_rcu(&event->hlist_entry, head);
10013 perf_event_update_userpage(event);
10018 static void perf_swevent_del(struct perf_event *event, int flags)
10020 hlist_del_rcu(&event->hlist_entry);
10023 static void perf_swevent_start(struct perf_event *event, int flags)
10025 event->hw.state = 0;
10028 static void perf_swevent_stop(struct perf_event *event, int flags)
10030 event->hw.state = PERF_HES_STOPPED;
10033 /* Deref the hlist from the update side */
10034 static inline struct swevent_hlist *
10035 swevent_hlist_deref(struct swevent_htable *swhash)
10037 return rcu_dereference_protected(swhash->swevent_hlist,
10038 lockdep_is_held(&swhash->hlist_mutex));
10041 static void swevent_hlist_release(struct swevent_htable *swhash)
10043 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
10048 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
10049 kfree_rcu(hlist, rcu_head);
10052 static void swevent_hlist_put_cpu(int cpu)
10054 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10056 mutex_lock(&swhash->hlist_mutex);
10058 if (!--swhash->hlist_refcount)
10059 swevent_hlist_release(swhash);
10061 mutex_unlock(&swhash->hlist_mutex);
10064 static void swevent_hlist_put(void)
10068 for_each_possible_cpu(cpu)
10069 swevent_hlist_put_cpu(cpu);
10072 static int swevent_hlist_get_cpu(int cpu)
10074 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10077 mutex_lock(&swhash->hlist_mutex);
10078 if (!swevent_hlist_deref(swhash) &&
10079 cpumask_test_cpu(cpu, perf_online_mask)) {
10080 struct swevent_hlist *hlist;
10082 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
10087 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10089 swhash->hlist_refcount++;
10091 mutex_unlock(&swhash->hlist_mutex);
10096 static int swevent_hlist_get(void)
10098 int err, cpu, failed_cpu;
10100 mutex_lock(&pmus_lock);
10101 for_each_possible_cpu(cpu) {
10102 err = swevent_hlist_get_cpu(cpu);
10108 mutex_unlock(&pmus_lock);
10111 for_each_possible_cpu(cpu) {
10112 if (cpu == failed_cpu)
10114 swevent_hlist_put_cpu(cpu);
10116 mutex_unlock(&pmus_lock);
10120 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
10122 static void sw_perf_event_destroy(struct perf_event *event)
10124 u64 event_id = event->attr.config;
10126 WARN_ON(event->parent);
10128 static_key_slow_dec(&perf_swevent_enabled[event_id]);
10129 swevent_hlist_put();
10132 static struct pmu perf_cpu_clock; /* fwd declaration */
10133 static struct pmu perf_task_clock;
10135 static int perf_swevent_init(struct perf_event *event)
10137 u64 event_id = event->attr.config;
10139 if (event->attr.type != PERF_TYPE_SOFTWARE)
10143 * no branch sampling for software events
10145 if (has_branch_stack(event))
10146 return -EOPNOTSUPP;
10148 switch (event_id) {
10149 case PERF_COUNT_SW_CPU_CLOCK:
10150 event->attr.type = perf_cpu_clock.type;
10152 case PERF_COUNT_SW_TASK_CLOCK:
10153 event->attr.type = perf_task_clock.type;
10160 if (event_id >= PERF_COUNT_SW_MAX)
10163 if (!event->parent) {
10166 err = swevent_hlist_get();
10170 static_key_slow_inc(&perf_swevent_enabled[event_id]);
10171 event->destroy = sw_perf_event_destroy;
10177 static struct pmu perf_swevent = {
10178 .task_ctx_nr = perf_sw_context,
10180 .capabilities = PERF_PMU_CAP_NO_NMI,
10182 .event_init = perf_swevent_init,
10183 .add = perf_swevent_add,
10184 .del = perf_swevent_del,
10185 .start = perf_swevent_start,
10186 .stop = perf_swevent_stop,
10187 .read = perf_swevent_read,
10190 #ifdef CONFIG_EVENT_TRACING
10192 static void tp_perf_event_destroy(struct perf_event *event)
10194 perf_trace_destroy(event);
10197 static int perf_tp_event_init(struct perf_event *event)
10201 if (event->attr.type != PERF_TYPE_TRACEPOINT)
10205 * no branch sampling for tracepoint events
10207 if (has_branch_stack(event))
10208 return -EOPNOTSUPP;
10210 err = perf_trace_init(event);
10214 event->destroy = tp_perf_event_destroy;
10219 static struct pmu perf_tracepoint = {
10220 .task_ctx_nr = perf_sw_context,
10222 .event_init = perf_tp_event_init,
10223 .add = perf_trace_add,
10224 .del = perf_trace_del,
10225 .start = perf_swevent_start,
10226 .stop = perf_swevent_stop,
10227 .read = perf_swevent_read,
10230 static int perf_tp_filter_match(struct perf_event *event,
10231 struct perf_sample_data *data)
10233 void *record = data->raw->frag.data;
10235 /* only top level events have filters set */
10237 event = event->parent;
10239 if (likely(!event->filter) || filter_match_preds(event->filter, record))
10244 static int perf_tp_event_match(struct perf_event *event,
10245 struct perf_sample_data *data,
10246 struct pt_regs *regs)
10248 if (event->hw.state & PERF_HES_STOPPED)
10251 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10253 if (event->attr.exclude_kernel && !user_mode(regs))
10256 if (!perf_tp_filter_match(event, data))
10262 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10263 struct trace_event_call *call, u64 count,
10264 struct pt_regs *regs, struct hlist_head *head,
10265 struct task_struct *task)
10267 if (bpf_prog_array_valid(call)) {
10268 *(struct pt_regs **)raw_data = regs;
10269 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10270 perf_swevent_put_recursion_context(rctx);
10274 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10277 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10279 static void __perf_tp_event_target_task(u64 count, void *record,
10280 struct pt_regs *regs,
10281 struct perf_sample_data *data,
10282 struct perf_event *event)
10284 struct trace_entry *entry = record;
10286 if (event->attr.config != entry->type)
10288 /* Cannot deliver synchronous signal to other task. */
10289 if (event->attr.sigtrap)
10291 if (perf_tp_event_match(event, data, regs))
10292 perf_swevent_event(event, count, data, regs);
10295 static void perf_tp_event_target_task(u64 count, void *record,
10296 struct pt_regs *regs,
10297 struct perf_sample_data *data,
10298 struct perf_event_context *ctx)
10300 unsigned int cpu = smp_processor_id();
10301 struct pmu *pmu = &perf_tracepoint;
10302 struct perf_event *event, *sibling;
10304 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10305 __perf_tp_event_target_task(count, record, regs, data, event);
10306 for_each_sibling_event(sibling, event)
10307 __perf_tp_event_target_task(count, record, regs, data, sibling);
10310 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10311 __perf_tp_event_target_task(count, record, regs, data, event);
10312 for_each_sibling_event(sibling, event)
10313 __perf_tp_event_target_task(count, record, regs, data, sibling);
10317 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10318 struct pt_regs *regs, struct hlist_head *head, int rctx,
10319 struct task_struct *task)
10321 struct perf_sample_data data;
10322 struct perf_event *event;
10324 struct perf_raw_record raw = {
10326 .size = entry_size,
10331 perf_sample_data_init(&data, 0, 0);
10332 perf_sample_save_raw_data(&data, &raw);
10334 perf_trace_buf_update(record, event_type);
10336 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10337 if (perf_tp_event_match(event, &data, regs)) {
10338 perf_swevent_event(event, count, &data, regs);
10341 * Here use the same on-stack perf_sample_data,
10342 * some members in data are event-specific and
10343 * need to be re-computed for different sweveents.
10344 * Re-initialize data->sample_flags safely to avoid
10345 * the problem that next event skips preparing data
10346 * because data->sample_flags is set.
10348 perf_sample_data_init(&data, 0, 0);
10349 perf_sample_save_raw_data(&data, &raw);
10354 * If we got specified a target task, also iterate its context and
10355 * deliver this event there too.
10357 if (task && task != current) {
10358 struct perf_event_context *ctx;
10361 ctx = rcu_dereference(task->perf_event_ctxp);
10365 raw_spin_lock(&ctx->lock);
10366 perf_tp_event_target_task(count, record, regs, &data, ctx);
10367 raw_spin_unlock(&ctx->lock);
10372 perf_swevent_put_recursion_context(rctx);
10374 EXPORT_SYMBOL_GPL(perf_tp_event);
10376 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10378 * Flags in config, used by dynamic PMU kprobe and uprobe
10379 * The flags should match following PMU_FORMAT_ATTR().
10381 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10382 * if not set, create kprobe/uprobe
10384 * The following values specify a reference counter (or semaphore in the
10385 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10386 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10388 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
10389 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
10391 enum perf_probe_config {
10392 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
10393 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
10394 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
10397 PMU_FORMAT_ATTR(retprobe, "config:0");
10400 #ifdef CONFIG_KPROBE_EVENTS
10401 static struct attribute *kprobe_attrs[] = {
10402 &format_attr_retprobe.attr,
10406 static struct attribute_group kprobe_format_group = {
10408 .attrs = kprobe_attrs,
10411 static const struct attribute_group *kprobe_attr_groups[] = {
10412 &kprobe_format_group,
10416 static int perf_kprobe_event_init(struct perf_event *event);
10417 static struct pmu perf_kprobe = {
10418 .task_ctx_nr = perf_sw_context,
10419 .event_init = perf_kprobe_event_init,
10420 .add = perf_trace_add,
10421 .del = perf_trace_del,
10422 .start = perf_swevent_start,
10423 .stop = perf_swevent_stop,
10424 .read = perf_swevent_read,
10425 .attr_groups = kprobe_attr_groups,
10428 static int perf_kprobe_event_init(struct perf_event *event)
10433 if (event->attr.type != perf_kprobe.type)
10436 if (!perfmon_capable())
10440 * no branch sampling for probe events
10442 if (has_branch_stack(event))
10443 return -EOPNOTSUPP;
10445 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10446 err = perf_kprobe_init(event, is_retprobe);
10450 event->destroy = perf_kprobe_destroy;
10454 #endif /* CONFIG_KPROBE_EVENTS */
10456 #ifdef CONFIG_UPROBE_EVENTS
10457 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10459 static struct attribute *uprobe_attrs[] = {
10460 &format_attr_retprobe.attr,
10461 &format_attr_ref_ctr_offset.attr,
10465 static struct attribute_group uprobe_format_group = {
10467 .attrs = uprobe_attrs,
10470 static const struct attribute_group *uprobe_attr_groups[] = {
10471 &uprobe_format_group,
10475 static int perf_uprobe_event_init(struct perf_event *event);
10476 static struct pmu perf_uprobe = {
10477 .task_ctx_nr = perf_sw_context,
10478 .event_init = perf_uprobe_event_init,
10479 .add = perf_trace_add,
10480 .del = perf_trace_del,
10481 .start = perf_swevent_start,
10482 .stop = perf_swevent_stop,
10483 .read = perf_swevent_read,
10484 .attr_groups = uprobe_attr_groups,
10487 static int perf_uprobe_event_init(struct perf_event *event)
10490 unsigned long ref_ctr_offset;
10493 if (event->attr.type != perf_uprobe.type)
10496 if (!perfmon_capable())
10500 * no branch sampling for probe events
10502 if (has_branch_stack(event))
10503 return -EOPNOTSUPP;
10505 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10506 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10507 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10511 event->destroy = perf_uprobe_destroy;
10515 #endif /* CONFIG_UPROBE_EVENTS */
10517 static inline void perf_tp_register(void)
10519 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10520 #ifdef CONFIG_KPROBE_EVENTS
10521 perf_pmu_register(&perf_kprobe, "kprobe", -1);
10523 #ifdef CONFIG_UPROBE_EVENTS
10524 perf_pmu_register(&perf_uprobe, "uprobe", -1);
10528 static void perf_event_free_filter(struct perf_event *event)
10530 ftrace_profile_free_filter(event);
10534 * returns true if the event is a tracepoint, or a kprobe/upprobe created
10535 * with perf_event_open()
10537 static inline bool perf_event_is_tracing(struct perf_event *event)
10539 if (event->pmu == &perf_tracepoint)
10541 #ifdef CONFIG_KPROBE_EVENTS
10542 if (event->pmu == &perf_kprobe)
10545 #ifdef CONFIG_UPROBE_EVENTS
10546 if (event->pmu == &perf_uprobe)
10552 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10555 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10557 if (!perf_event_is_tracing(event))
10558 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10560 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10561 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10562 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10563 is_syscall_tp = is_syscall_trace_event(event->tp_event);
10564 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10565 /* bpf programs can only be attached to u/kprobe or tracepoint */
10568 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10569 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10570 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10573 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
10574 /* only uprobe programs are allowed to be sleepable */
10577 /* Kprobe override only works for kprobes, not uprobes. */
10578 if (prog->kprobe_override && !is_kprobe)
10581 if (is_tracepoint || is_syscall_tp) {
10582 int off = trace_event_get_offsets(event->tp_event);
10584 if (prog->aux->max_ctx_offset > off)
10588 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10591 void perf_event_free_bpf_prog(struct perf_event *event)
10593 if (!perf_event_is_tracing(event)) {
10594 perf_event_free_bpf_handler(event);
10597 perf_event_detach_bpf_prog(event);
10602 static inline void perf_tp_register(void)
10606 static void perf_event_free_filter(struct perf_event *event)
10610 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10616 void perf_event_free_bpf_prog(struct perf_event *event)
10619 #endif /* CONFIG_EVENT_TRACING */
10621 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10622 void perf_bp_event(struct perf_event *bp, void *data)
10624 struct perf_sample_data sample;
10625 struct pt_regs *regs = data;
10627 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10629 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10630 perf_swevent_event(bp, 1, &sample, regs);
10635 * Allocate a new address filter
10637 static struct perf_addr_filter *
10638 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10640 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10641 struct perf_addr_filter *filter;
10643 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10647 INIT_LIST_HEAD(&filter->entry);
10648 list_add_tail(&filter->entry, filters);
10653 static void free_filters_list(struct list_head *filters)
10655 struct perf_addr_filter *filter, *iter;
10657 list_for_each_entry_safe(filter, iter, filters, entry) {
10658 path_put(&filter->path);
10659 list_del(&filter->entry);
10665 * Free existing address filters and optionally install new ones
10667 static void perf_addr_filters_splice(struct perf_event *event,
10668 struct list_head *head)
10670 unsigned long flags;
10673 if (!has_addr_filter(event))
10676 /* don't bother with children, they don't have their own filters */
10680 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10682 list_splice_init(&event->addr_filters.list, &list);
10684 list_splice(head, &event->addr_filters.list);
10686 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10688 free_filters_list(&list);
10692 * Scan through mm's vmas and see if one of them matches the
10693 * @filter; if so, adjust filter's address range.
10694 * Called with mm::mmap_lock down for reading.
10696 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10697 struct mm_struct *mm,
10698 struct perf_addr_filter_range *fr)
10700 struct vm_area_struct *vma;
10701 VMA_ITERATOR(vmi, mm, 0);
10703 for_each_vma(vmi, vma) {
10707 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10713 * Update event's address range filters based on the
10714 * task's existing mappings, if any.
10716 static void perf_event_addr_filters_apply(struct perf_event *event)
10718 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10719 struct task_struct *task = READ_ONCE(event->ctx->task);
10720 struct perf_addr_filter *filter;
10721 struct mm_struct *mm = NULL;
10722 unsigned int count = 0;
10723 unsigned long flags;
10726 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10727 * will stop on the parent's child_mutex that our caller is also holding
10729 if (task == TASK_TOMBSTONE)
10732 if (ifh->nr_file_filters) {
10733 mm = get_task_mm(task);
10737 mmap_read_lock(mm);
10740 raw_spin_lock_irqsave(&ifh->lock, flags);
10741 list_for_each_entry(filter, &ifh->list, entry) {
10742 if (filter->path.dentry) {
10744 * Adjust base offset if the filter is associated to a
10745 * binary that needs to be mapped:
10747 event->addr_filter_ranges[count].start = 0;
10748 event->addr_filter_ranges[count].size = 0;
10750 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10752 event->addr_filter_ranges[count].start = filter->offset;
10753 event->addr_filter_ranges[count].size = filter->size;
10759 event->addr_filters_gen++;
10760 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10762 if (ifh->nr_file_filters) {
10763 mmap_read_unlock(mm);
10769 perf_event_stop(event, 1);
10773 * Address range filtering: limiting the data to certain
10774 * instruction address ranges. Filters are ioctl()ed to us from
10775 * userspace as ascii strings.
10777 * Filter string format:
10779 * ACTION RANGE_SPEC
10780 * where ACTION is one of the
10781 * * "filter": limit the trace to this region
10782 * * "start": start tracing from this address
10783 * * "stop": stop tracing at this address/region;
10785 * * for kernel addresses: <start address>[/<size>]
10786 * * for object files: <start address>[/<size>]@</path/to/object/file>
10788 * if <size> is not specified or is zero, the range is treated as a single
10789 * address; not valid for ACTION=="filter".
10803 IF_STATE_ACTION = 0,
10808 static const match_table_t if_tokens = {
10809 { IF_ACT_FILTER, "filter" },
10810 { IF_ACT_START, "start" },
10811 { IF_ACT_STOP, "stop" },
10812 { IF_SRC_FILE, "%u/%u@%s" },
10813 { IF_SRC_KERNEL, "%u/%u" },
10814 { IF_SRC_FILEADDR, "%u@%s" },
10815 { IF_SRC_KERNELADDR, "%u" },
10816 { IF_ACT_NONE, NULL },
10820 * Address filter string parser
10823 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10824 struct list_head *filters)
10826 struct perf_addr_filter *filter = NULL;
10827 char *start, *orig, *filename = NULL;
10828 substring_t args[MAX_OPT_ARGS];
10829 int state = IF_STATE_ACTION, token;
10830 unsigned int kernel = 0;
10833 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10837 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10838 static const enum perf_addr_filter_action_t actions[] = {
10839 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10840 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10841 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10848 /* filter definition begins */
10849 if (state == IF_STATE_ACTION) {
10850 filter = perf_addr_filter_new(event, filters);
10855 token = match_token(start, if_tokens, args);
10857 case IF_ACT_FILTER:
10860 if (state != IF_STATE_ACTION)
10863 filter->action = actions[token];
10864 state = IF_STATE_SOURCE;
10867 case IF_SRC_KERNELADDR:
10868 case IF_SRC_KERNEL:
10872 case IF_SRC_FILEADDR:
10874 if (state != IF_STATE_SOURCE)
10878 ret = kstrtoul(args[0].from, 0, &filter->offset);
10882 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10884 ret = kstrtoul(args[1].from, 0, &filter->size);
10889 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10890 int fpos = token == IF_SRC_FILE ? 2 : 1;
10893 filename = match_strdup(&args[fpos]);
10900 state = IF_STATE_END;
10908 * Filter definition is fully parsed, validate and install it.
10909 * Make sure that it doesn't contradict itself or the event's
10912 if (state == IF_STATE_END) {
10916 * ACTION "filter" must have a non-zero length region
10919 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10928 * For now, we only support file-based filters
10929 * in per-task events; doing so for CPU-wide
10930 * events requires additional context switching
10931 * trickery, since same object code will be
10932 * mapped at different virtual addresses in
10933 * different processes.
10936 if (!event->ctx->task)
10939 /* look up the path and grab its inode */
10940 ret = kern_path(filename, LOOKUP_FOLLOW,
10946 if (!filter->path.dentry ||
10947 !S_ISREG(d_inode(filter->path.dentry)
10951 event->addr_filters.nr_file_filters++;
10954 /* ready to consume more filters */
10957 state = IF_STATE_ACTION;
10963 if (state != IF_STATE_ACTION)
10973 free_filters_list(filters);
10980 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10982 LIST_HEAD(filters);
10986 * Since this is called in perf_ioctl() path, we're already holding
10989 lockdep_assert_held(&event->ctx->mutex);
10991 if (WARN_ON_ONCE(event->parent))
10994 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10996 goto fail_clear_files;
10998 ret = event->pmu->addr_filters_validate(&filters);
11000 goto fail_free_filters;
11002 /* remove existing filters, if any */
11003 perf_addr_filters_splice(event, &filters);
11005 /* install new filters */
11006 perf_event_for_each_child(event, perf_event_addr_filters_apply);
11011 free_filters_list(&filters);
11014 event->addr_filters.nr_file_filters = 0;
11019 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
11024 filter_str = strndup_user(arg, PAGE_SIZE);
11025 if (IS_ERR(filter_str))
11026 return PTR_ERR(filter_str);
11028 #ifdef CONFIG_EVENT_TRACING
11029 if (perf_event_is_tracing(event)) {
11030 struct perf_event_context *ctx = event->ctx;
11033 * Beware, here be dragons!!
11035 * the tracepoint muck will deadlock against ctx->mutex, but
11036 * the tracepoint stuff does not actually need it. So
11037 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11038 * already have a reference on ctx.
11040 * This can result in event getting moved to a different ctx,
11041 * but that does not affect the tracepoint state.
11043 mutex_unlock(&ctx->mutex);
11044 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
11045 mutex_lock(&ctx->mutex);
11048 if (has_addr_filter(event))
11049 ret = perf_event_set_addr_filter(event, filter_str);
11056 * hrtimer based swevent callback
11059 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
11061 enum hrtimer_restart ret = HRTIMER_RESTART;
11062 struct perf_sample_data data;
11063 struct pt_regs *regs;
11064 struct perf_event *event;
11067 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
11069 if (event->state != PERF_EVENT_STATE_ACTIVE)
11070 return HRTIMER_NORESTART;
11072 event->pmu->read(event);
11074 perf_sample_data_init(&data, 0, event->hw.last_period);
11075 regs = get_irq_regs();
11077 if (regs && !perf_exclude_event(event, regs)) {
11078 if (!(event->attr.exclude_idle && is_idle_task(current)))
11079 if (__perf_event_overflow(event, 1, &data, regs))
11080 ret = HRTIMER_NORESTART;
11083 period = max_t(u64, 10000, event->hw.sample_period);
11084 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
11089 static void perf_swevent_start_hrtimer(struct perf_event *event)
11091 struct hw_perf_event *hwc = &event->hw;
11094 if (!is_sampling_event(event))
11097 period = local64_read(&hwc->period_left);
11102 local64_set(&hwc->period_left, 0);
11104 period = max_t(u64, 10000, hwc->sample_period);
11106 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
11107 HRTIMER_MODE_REL_PINNED_HARD);
11110 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
11112 struct hw_perf_event *hwc = &event->hw;
11114 if (is_sampling_event(event)) {
11115 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
11116 local64_set(&hwc->period_left, ktime_to_ns(remaining));
11118 hrtimer_cancel(&hwc->hrtimer);
11122 static void perf_swevent_init_hrtimer(struct perf_event *event)
11124 struct hw_perf_event *hwc = &event->hw;
11126 if (!is_sampling_event(event))
11129 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
11130 hwc->hrtimer.function = perf_swevent_hrtimer;
11133 * Since hrtimers have a fixed rate, we can do a static freq->period
11134 * mapping and avoid the whole period adjust feedback stuff.
11136 if (event->attr.freq) {
11137 long freq = event->attr.sample_freq;
11139 event->attr.sample_period = NSEC_PER_SEC / freq;
11140 hwc->sample_period = event->attr.sample_period;
11141 local64_set(&hwc->period_left, hwc->sample_period);
11142 hwc->last_period = hwc->sample_period;
11143 event->attr.freq = 0;
11148 * Software event: cpu wall time clock
11151 static void cpu_clock_event_update(struct perf_event *event)
11156 now = local_clock();
11157 prev = local64_xchg(&event->hw.prev_count, now);
11158 local64_add(now - prev, &event->count);
11161 static void cpu_clock_event_start(struct perf_event *event, int flags)
11163 local64_set(&event->hw.prev_count, local_clock());
11164 perf_swevent_start_hrtimer(event);
11167 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11169 perf_swevent_cancel_hrtimer(event);
11170 cpu_clock_event_update(event);
11173 static int cpu_clock_event_add(struct perf_event *event, int flags)
11175 if (flags & PERF_EF_START)
11176 cpu_clock_event_start(event, flags);
11177 perf_event_update_userpage(event);
11182 static void cpu_clock_event_del(struct perf_event *event, int flags)
11184 cpu_clock_event_stop(event, flags);
11187 static void cpu_clock_event_read(struct perf_event *event)
11189 cpu_clock_event_update(event);
11192 static int cpu_clock_event_init(struct perf_event *event)
11194 if (event->attr.type != perf_cpu_clock.type)
11197 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11201 * no branch sampling for software events
11203 if (has_branch_stack(event))
11204 return -EOPNOTSUPP;
11206 perf_swevent_init_hrtimer(event);
11211 static struct pmu perf_cpu_clock = {
11212 .task_ctx_nr = perf_sw_context,
11214 .capabilities = PERF_PMU_CAP_NO_NMI,
11215 .dev = PMU_NULL_DEV,
11217 .event_init = cpu_clock_event_init,
11218 .add = cpu_clock_event_add,
11219 .del = cpu_clock_event_del,
11220 .start = cpu_clock_event_start,
11221 .stop = cpu_clock_event_stop,
11222 .read = cpu_clock_event_read,
11226 * Software event: task time clock
11229 static void task_clock_event_update(struct perf_event *event, u64 now)
11234 prev = local64_xchg(&event->hw.prev_count, now);
11235 delta = now - prev;
11236 local64_add(delta, &event->count);
11239 static void task_clock_event_start(struct perf_event *event, int flags)
11241 local64_set(&event->hw.prev_count, event->ctx->time);
11242 perf_swevent_start_hrtimer(event);
11245 static void task_clock_event_stop(struct perf_event *event, int flags)
11247 perf_swevent_cancel_hrtimer(event);
11248 task_clock_event_update(event, event->ctx->time);
11251 static int task_clock_event_add(struct perf_event *event, int flags)
11253 if (flags & PERF_EF_START)
11254 task_clock_event_start(event, flags);
11255 perf_event_update_userpage(event);
11260 static void task_clock_event_del(struct perf_event *event, int flags)
11262 task_clock_event_stop(event, PERF_EF_UPDATE);
11265 static void task_clock_event_read(struct perf_event *event)
11267 u64 now = perf_clock();
11268 u64 delta = now - event->ctx->timestamp;
11269 u64 time = event->ctx->time + delta;
11271 task_clock_event_update(event, time);
11274 static int task_clock_event_init(struct perf_event *event)
11276 if (event->attr.type != perf_task_clock.type)
11279 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11283 * no branch sampling for software events
11285 if (has_branch_stack(event))
11286 return -EOPNOTSUPP;
11288 perf_swevent_init_hrtimer(event);
11293 static struct pmu perf_task_clock = {
11294 .task_ctx_nr = perf_sw_context,
11296 .capabilities = PERF_PMU_CAP_NO_NMI,
11297 .dev = PMU_NULL_DEV,
11299 .event_init = task_clock_event_init,
11300 .add = task_clock_event_add,
11301 .del = task_clock_event_del,
11302 .start = task_clock_event_start,
11303 .stop = task_clock_event_stop,
11304 .read = task_clock_event_read,
11307 static void perf_pmu_nop_void(struct pmu *pmu)
11311 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11315 static int perf_pmu_nop_int(struct pmu *pmu)
11320 static int perf_event_nop_int(struct perf_event *event, u64 value)
11325 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11327 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11329 __this_cpu_write(nop_txn_flags, flags);
11331 if (flags & ~PERF_PMU_TXN_ADD)
11334 perf_pmu_disable(pmu);
11337 static int perf_pmu_commit_txn(struct pmu *pmu)
11339 unsigned int flags = __this_cpu_read(nop_txn_flags);
11341 __this_cpu_write(nop_txn_flags, 0);
11343 if (flags & ~PERF_PMU_TXN_ADD)
11346 perf_pmu_enable(pmu);
11350 static void perf_pmu_cancel_txn(struct pmu *pmu)
11352 unsigned int flags = __this_cpu_read(nop_txn_flags);
11354 __this_cpu_write(nop_txn_flags, 0);
11356 if (flags & ~PERF_PMU_TXN_ADD)
11359 perf_pmu_enable(pmu);
11362 static int perf_event_idx_default(struct perf_event *event)
11367 static void free_pmu_context(struct pmu *pmu)
11369 free_percpu(pmu->cpu_pmu_context);
11373 * Let userspace know that this PMU supports address range filtering:
11375 static ssize_t nr_addr_filters_show(struct device *dev,
11376 struct device_attribute *attr,
11379 struct pmu *pmu = dev_get_drvdata(dev);
11381 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11383 DEVICE_ATTR_RO(nr_addr_filters);
11385 static struct idr pmu_idr;
11388 type_show(struct device *dev, struct device_attribute *attr, char *page)
11390 struct pmu *pmu = dev_get_drvdata(dev);
11392 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11394 static DEVICE_ATTR_RO(type);
11397 perf_event_mux_interval_ms_show(struct device *dev,
11398 struct device_attribute *attr,
11401 struct pmu *pmu = dev_get_drvdata(dev);
11403 return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11406 static DEFINE_MUTEX(mux_interval_mutex);
11409 perf_event_mux_interval_ms_store(struct device *dev,
11410 struct device_attribute *attr,
11411 const char *buf, size_t count)
11413 struct pmu *pmu = dev_get_drvdata(dev);
11414 int timer, cpu, ret;
11416 ret = kstrtoint(buf, 0, &timer);
11423 /* same value, noting to do */
11424 if (timer == pmu->hrtimer_interval_ms)
11427 mutex_lock(&mux_interval_mutex);
11428 pmu->hrtimer_interval_ms = timer;
11430 /* update all cpuctx for this PMU */
11432 for_each_online_cpu(cpu) {
11433 struct perf_cpu_pmu_context *cpc;
11434 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11435 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11437 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
11439 cpus_read_unlock();
11440 mutex_unlock(&mux_interval_mutex);
11444 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11446 static struct attribute *pmu_dev_attrs[] = {
11447 &dev_attr_type.attr,
11448 &dev_attr_perf_event_mux_interval_ms.attr,
11449 &dev_attr_nr_addr_filters.attr,
11453 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
11455 struct device *dev = kobj_to_dev(kobj);
11456 struct pmu *pmu = dev_get_drvdata(dev);
11458 if (n == 2 && !pmu->nr_addr_filters)
11464 static struct attribute_group pmu_dev_attr_group = {
11465 .is_visible = pmu_dev_is_visible,
11466 .attrs = pmu_dev_attrs,
11469 static const struct attribute_group *pmu_dev_groups[] = {
11470 &pmu_dev_attr_group,
11474 static int pmu_bus_running;
11475 static struct bus_type pmu_bus = {
11476 .name = "event_source",
11477 .dev_groups = pmu_dev_groups,
11480 static void pmu_dev_release(struct device *dev)
11485 static int pmu_dev_alloc(struct pmu *pmu)
11489 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11493 pmu->dev->groups = pmu->attr_groups;
11494 device_initialize(pmu->dev);
11496 dev_set_drvdata(pmu->dev, pmu);
11497 pmu->dev->bus = &pmu_bus;
11498 pmu->dev->parent = pmu->parent;
11499 pmu->dev->release = pmu_dev_release;
11501 ret = dev_set_name(pmu->dev, "%s", pmu->name);
11505 ret = device_add(pmu->dev);
11509 if (pmu->attr_update) {
11510 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11519 device_del(pmu->dev);
11522 put_device(pmu->dev);
11526 static struct lock_class_key cpuctx_mutex;
11527 static struct lock_class_key cpuctx_lock;
11529 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11531 int cpu, ret, max = PERF_TYPE_MAX;
11533 mutex_lock(&pmus_lock);
11535 pmu->pmu_disable_count = alloc_percpu(int);
11536 if (!pmu->pmu_disable_count)
11540 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) {
11550 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
11554 WARN_ON(type >= 0 && ret != type);
11559 if (pmu_bus_running && !pmu->dev) {
11560 ret = pmu_dev_alloc(pmu);
11566 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context);
11567 if (!pmu->cpu_pmu_context)
11570 for_each_possible_cpu(cpu) {
11571 struct perf_cpu_pmu_context *cpc;
11573 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11574 __perf_init_event_pmu_context(&cpc->epc, pmu);
11575 __perf_mux_hrtimer_init(cpc, cpu);
11578 if (!pmu->start_txn) {
11579 if (pmu->pmu_enable) {
11581 * If we have pmu_enable/pmu_disable calls, install
11582 * transaction stubs that use that to try and batch
11583 * hardware accesses.
11585 pmu->start_txn = perf_pmu_start_txn;
11586 pmu->commit_txn = perf_pmu_commit_txn;
11587 pmu->cancel_txn = perf_pmu_cancel_txn;
11589 pmu->start_txn = perf_pmu_nop_txn;
11590 pmu->commit_txn = perf_pmu_nop_int;
11591 pmu->cancel_txn = perf_pmu_nop_void;
11595 if (!pmu->pmu_enable) {
11596 pmu->pmu_enable = perf_pmu_nop_void;
11597 pmu->pmu_disable = perf_pmu_nop_void;
11600 if (!pmu->check_period)
11601 pmu->check_period = perf_event_nop_int;
11603 if (!pmu->event_idx)
11604 pmu->event_idx = perf_event_idx_default;
11606 list_add_rcu(&pmu->entry, &pmus);
11607 atomic_set(&pmu->exclusive_cnt, 0);
11610 mutex_unlock(&pmus_lock);
11615 if (pmu->dev && pmu->dev != PMU_NULL_DEV) {
11616 device_del(pmu->dev);
11617 put_device(pmu->dev);
11621 idr_remove(&pmu_idr, pmu->type);
11624 free_percpu(pmu->pmu_disable_count);
11627 EXPORT_SYMBOL_GPL(perf_pmu_register);
11629 void perf_pmu_unregister(struct pmu *pmu)
11631 mutex_lock(&pmus_lock);
11632 list_del_rcu(&pmu->entry);
11635 * We dereference the pmu list under both SRCU and regular RCU, so
11636 * synchronize against both of those.
11638 synchronize_srcu(&pmus_srcu);
11641 free_percpu(pmu->pmu_disable_count);
11642 idr_remove(&pmu_idr, pmu->type);
11643 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
11644 if (pmu->nr_addr_filters)
11645 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11646 device_del(pmu->dev);
11647 put_device(pmu->dev);
11649 free_pmu_context(pmu);
11650 mutex_unlock(&pmus_lock);
11652 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11654 static inline bool has_extended_regs(struct perf_event *event)
11656 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11657 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11660 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11662 struct perf_event_context *ctx = NULL;
11665 if (!try_module_get(pmu->module))
11669 * A number of pmu->event_init() methods iterate the sibling_list to,
11670 * for example, validate if the group fits on the PMU. Therefore,
11671 * if this is a sibling event, acquire the ctx->mutex to protect
11672 * the sibling_list.
11674 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11676 * This ctx->mutex can nest when we're called through
11677 * inheritance. See the perf_event_ctx_lock_nested() comment.
11679 ctx = perf_event_ctx_lock_nested(event->group_leader,
11680 SINGLE_DEPTH_NESTING);
11685 ret = pmu->event_init(event);
11688 perf_event_ctx_unlock(event->group_leader, ctx);
11691 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11692 has_extended_regs(event))
11695 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11696 event_has_any_exclude_flag(event))
11699 if (ret && event->destroy)
11700 event->destroy(event);
11704 module_put(pmu->module);
11709 static struct pmu *perf_init_event(struct perf_event *event)
11711 bool extended_type = false;
11712 int idx, type, ret;
11715 idx = srcu_read_lock(&pmus_srcu);
11718 * Save original type before calling pmu->event_init() since certain
11719 * pmus overwrites event->attr.type to forward event to another pmu.
11721 event->orig_type = event->attr.type;
11723 /* Try parent's PMU first: */
11724 if (event->parent && event->parent->pmu) {
11725 pmu = event->parent->pmu;
11726 ret = perf_try_init_event(pmu, event);
11732 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11733 * are often aliases for PERF_TYPE_RAW.
11735 type = event->attr.type;
11736 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
11737 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
11739 type = PERF_TYPE_RAW;
11741 extended_type = true;
11742 event->attr.config &= PERF_HW_EVENT_MASK;
11748 pmu = idr_find(&pmu_idr, type);
11751 if (event->attr.type != type && type != PERF_TYPE_RAW &&
11752 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
11755 ret = perf_try_init_event(pmu, event);
11756 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
11757 type = event->attr.type;
11762 pmu = ERR_PTR(ret);
11767 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11768 ret = perf_try_init_event(pmu, event);
11772 if (ret != -ENOENT) {
11773 pmu = ERR_PTR(ret);
11778 pmu = ERR_PTR(-ENOENT);
11780 srcu_read_unlock(&pmus_srcu, idx);
11785 static void attach_sb_event(struct perf_event *event)
11787 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11789 raw_spin_lock(&pel->lock);
11790 list_add_rcu(&event->sb_list, &pel->list);
11791 raw_spin_unlock(&pel->lock);
11795 * We keep a list of all !task (and therefore per-cpu) events
11796 * that need to receive side-band records.
11798 * This avoids having to scan all the various PMU per-cpu contexts
11799 * looking for them.
11801 static void account_pmu_sb_event(struct perf_event *event)
11803 if (is_sb_event(event))
11804 attach_sb_event(event);
11807 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11808 static void account_freq_event_nohz(void)
11810 #ifdef CONFIG_NO_HZ_FULL
11811 /* Lock so we don't race with concurrent unaccount */
11812 spin_lock(&nr_freq_lock);
11813 if (atomic_inc_return(&nr_freq_events) == 1)
11814 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11815 spin_unlock(&nr_freq_lock);
11819 static void account_freq_event(void)
11821 if (tick_nohz_full_enabled())
11822 account_freq_event_nohz();
11824 atomic_inc(&nr_freq_events);
11828 static void account_event(struct perf_event *event)
11835 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11837 if (event->attr.mmap || event->attr.mmap_data)
11838 atomic_inc(&nr_mmap_events);
11839 if (event->attr.build_id)
11840 atomic_inc(&nr_build_id_events);
11841 if (event->attr.comm)
11842 atomic_inc(&nr_comm_events);
11843 if (event->attr.namespaces)
11844 atomic_inc(&nr_namespaces_events);
11845 if (event->attr.cgroup)
11846 atomic_inc(&nr_cgroup_events);
11847 if (event->attr.task)
11848 atomic_inc(&nr_task_events);
11849 if (event->attr.freq)
11850 account_freq_event();
11851 if (event->attr.context_switch) {
11852 atomic_inc(&nr_switch_events);
11855 if (has_branch_stack(event))
11857 if (is_cgroup_event(event))
11859 if (event->attr.ksymbol)
11860 atomic_inc(&nr_ksymbol_events);
11861 if (event->attr.bpf_event)
11862 atomic_inc(&nr_bpf_events);
11863 if (event->attr.text_poke)
11864 atomic_inc(&nr_text_poke_events);
11868 * We need the mutex here because static_branch_enable()
11869 * must complete *before* the perf_sched_count increment
11872 if (atomic_inc_not_zero(&perf_sched_count))
11875 mutex_lock(&perf_sched_mutex);
11876 if (!atomic_read(&perf_sched_count)) {
11877 static_branch_enable(&perf_sched_events);
11879 * Guarantee that all CPUs observe they key change and
11880 * call the perf scheduling hooks before proceeding to
11881 * install events that need them.
11886 * Now that we have waited for the sync_sched(), allow further
11887 * increments to by-pass the mutex.
11889 atomic_inc(&perf_sched_count);
11890 mutex_unlock(&perf_sched_mutex);
11894 account_pmu_sb_event(event);
11898 * Allocate and initialize an event structure
11900 static struct perf_event *
11901 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11902 struct task_struct *task,
11903 struct perf_event *group_leader,
11904 struct perf_event *parent_event,
11905 perf_overflow_handler_t overflow_handler,
11906 void *context, int cgroup_fd)
11909 struct perf_event *event;
11910 struct hw_perf_event *hwc;
11911 long err = -EINVAL;
11914 if ((unsigned)cpu >= nr_cpu_ids) {
11915 if (!task || cpu != -1)
11916 return ERR_PTR(-EINVAL);
11918 if (attr->sigtrap && !task) {
11919 /* Requires a task: avoid signalling random tasks. */
11920 return ERR_PTR(-EINVAL);
11923 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11924 event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11927 return ERR_PTR(-ENOMEM);
11930 * Single events are their own group leaders, with an
11931 * empty sibling list:
11934 group_leader = event;
11936 mutex_init(&event->child_mutex);
11937 INIT_LIST_HEAD(&event->child_list);
11939 INIT_LIST_HEAD(&event->event_entry);
11940 INIT_LIST_HEAD(&event->sibling_list);
11941 INIT_LIST_HEAD(&event->active_list);
11942 init_event_group(event);
11943 INIT_LIST_HEAD(&event->rb_entry);
11944 INIT_LIST_HEAD(&event->active_entry);
11945 INIT_LIST_HEAD(&event->addr_filters.list);
11946 INIT_HLIST_NODE(&event->hlist_entry);
11949 init_waitqueue_head(&event->waitq);
11950 init_irq_work(&event->pending_irq, perf_pending_irq);
11951 init_task_work(&event->pending_task, perf_pending_task);
11953 mutex_init(&event->mmap_mutex);
11954 raw_spin_lock_init(&event->addr_filters.lock);
11956 atomic_long_set(&event->refcount, 1);
11958 event->attr = *attr;
11959 event->group_leader = group_leader;
11963 event->parent = parent_event;
11965 event->ns = get_pid_ns(task_active_pid_ns(current));
11966 event->id = atomic64_inc_return(&perf_event_id);
11968 event->state = PERF_EVENT_STATE_INACTIVE;
11971 event->event_caps = parent_event->event_caps;
11974 event->attach_state = PERF_ATTACH_TASK;
11976 * XXX pmu::event_init needs to know what task to account to
11977 * and we cannot use the ctx information because we need the
11978 * pmu before we get a ctx.
11980 event->hw.target = get_task_struct(task);
11983 event->clock = &local_clock;
11985 event->clock = parent_event->clock;
11987 if (!overflow_handler && parent_event) {
11988 overflow_handler = parent_event->overflow_handler;
11989 context = parent_event->overflow_handler_context;
11990 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11991 if (parent_event->prog) {
11992 struct bpf_prog *prog = parent_event->prog;
11994 bpf_prog_inc(prog);
11995 event->prog = prog;
12000 if (overflow_handler) {
12001 event->overflow_handler = overflow_handler;
12002 event->overflow_handler_context = context;
12003 } else if (is_write_backward(event)){
12004 event->overflow_handler = perf_event_output_backward;
12005 event->overflow_handler_context = NULL;
12007 event->overflow_handler = perf_event_output_forward;
12008 event->overflow_handler_context = NULL;
12011 perf_event__state_init(event);
12016 hwc->sample_period = attr->sample_period;
12017 if (attr->freq && attr->sample_freq)
12018 hwc->sample_period = 1;
12019 hwc->last_period = hwc->sample_period;
12021 local64_set(&hwc->period_left, hwc->sample_period);
12024 * We currently do not support PERF_SAMPLE_READ on inherited events.
12025 * See perf_output_read().
12027 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
12030 if (!has_branch_stack(event))
12031 event->attr.branch_sample_type = 0;
12033 pmu = perf_init_event(event);
12035 err = PTR_ERR(pmu);
12040 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12041 * events (they don't make sense as the cgroup will be different
12042 * on other CPUs in the uncore mask).
12044 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) {
12049 if (event->attr.aux_output &&
12050 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
12055 if (cgroup_fd != -1) {
12056 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
12061 err = exclusive_event_init(event);
12065 if (has_addr_filter(event)) {
12066 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
12067 sizeof(struct perf_addr_filter_range),
12069 if (!event->addr_filter_ranges) {
12075 * Clone the parent's vma offsets: they are valid until exec()
12076 * even if the mm is not shared with the parent.
12078 if (event->parent) {
12079 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
12081 raw_spin_lock_irq(&ifh->lock);
12082 memcpy(event->addr_filter_ranges,
12083 event->parent->addr_filter_ranges,
12084 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
12085 raw_spin_unlock_irq(&ifh->lock);
12088 /* force hw sync on the address filters */
12089 event->addr_filters_gen = 1;
12092 if (!event->parent) {
12093 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
12094 err = get_callchain_buffers(attr->sample_max_stack);
12096 goto err_addr_filters;
12100 err = security_perf_event_alloc(event);
12102 goto err_callchain_buffer;
12104 /* symmetric to unaccount_event() in _free_event() */
12105 account_event(event);
12109 err_callchain_buffer:
12110 if (!event->parent) {
12111 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
12112 put_callchain_buffers();
12115 kfree(event->addr_filter_ranges);
12118 exclusive_event_destroy(event);
12121 if (is_cgroup_event(event))
12122 perf_detach_cgroup(event);
12123 if (event->destroy)
12124 event->destroy(event);
12125 module_put(pmu->module);
12127 if (event->hw.target)
12128 put_task_struct(event->hw.target);
12129 call_rcu(&event->rcu_head, free_event_rcu);
12131 return ERR_PTR(err);
12134 static int perf_copy_attr(struct perf_event_attr __user *uattr,
12135 struct perf_event_attr *attr)
12140 /* Zero the full structure, so that a short copy will be nice. */
12141 memset(attr, 0, sizeof(*attr));
12143 ret = get_user(size, &uattr->size);
12147 /* ABI compatibility quirk: */
12149 size = PERF_ATTR_SIZE_VER0;
12150 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
12153 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
12162 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
12165 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
12168 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
12171 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
12172 u64 mask = attr->branch_sample_type;
12174 /* only using defined bits */
12175 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
12178 /* at least one branch bit must be set */
12179 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
12182 /* propagate priv level, when not set for branch */
12183 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
12185 /* exclude_kernel checked on syscall entry */
12186 if (!attr->exclude_kernel)
12187 mask |= PERF_SAMPLE_BRANCH_KERNEL;
12189 if (!attr->exclude_user)
12190 mask |= PERF_SAMPLE_BRANCH_USER;
12192 if (!attr->exclude_hv)
12193 mask |= PERF_SAMPLE_BRANCH_HV;
12195 * adjust user setting (for HW filter setup)
12197 attr->branch_sample_type = mask;
12199 /* privileged levels capture (kernel, hv): check permissions */
12200 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
12201 ret = perf_allow_kernel(attr);
12207 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
12208 ret = perf_reg_validate(attr->sample_regs_user);
12213 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
12214 if (!arch_perf_have_user_stack_dump())
12218 * We have __u32 type for the size, but so far
12219 * we can only use __u16 as maximum due to the
12220 * __u16 sample size limit.
12222 if (attr->sample_stack_user >= USHRT_MAX)
12224 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
12228 if (!attr->sample_max_stack)
12229 attr->sample_max_stack = sysctl_perf_event_max_stack;
12231 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
12232 ret = perf_reg_validate(attr->sample_regs_intr);
12234 #ifndef CONFIG_CGROUP_PERF
12235 if (attr->sample_type & PERF_SAMPLE_CGROUP)
12238 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
12239 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
12242 if (!attr->inherit && attr->inherit_thread)
12245 if (attr->remove_on_exec && attr->enable_on_exec)
12248 if (attr->sigtrap && !attr->remove_on_exec)
12255 put_user(sizeof(*attr), &uattr->size);
12260 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12266 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12270 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12272 struct perf_buffer *rb = NULL;
12275 if (!output_event) {
12276 mutex_lock(&event->mmap_mutex);
12280 /* don't allow circular references */
12281 if (event == output_event)
12285 * Don't allow cross-cpu buffers
12287 if (output_event->cpu != event->cpu)
12291 * If its not a per-cpu rb, it must be the same task.
12293 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
12297 * Mixing clocks in the same buffer is trouble you don't need.
12299 if (output_event->clock != event->clock)
12303 * Either writing ring buffer from beginning or from end.
12304 * Mixing is not allowed.
12306 if (is_write_backward(output_event) != is_write_backward(event))
12310 * If both events generate aux data, they must be on the same PMU
12312 if (has_aux(event) && has_aux(output_event) &&
12313 event->pmu != output_event->pmu)
12317 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12318 * output_event is already on rb->event_list, and the list iteration
12319 * restarts after every removal, it is guaranteed this new event is
12320 * observed *OR* if output_event is already removed, it's guaranteed we
12321 * observe !rb->mmap_count.
12323 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12325 /* Can't redirect output if we've got an active mmap() */
12326 if (atomic_read(&event->mmap_count))
12329 if (output_event) {
12330 /* get the rb we want to redirect to */
12331 rb = ring_buffer_get(output_event);
12335 /* did we race against perf_mmap_close() */
12336 if (!atomic_read(&rb->mmap_count)) {
12337 ring_buffer_put(rb);
12342 ring_buffer_attach(event, rb);
12346 mutex_unlock(&event->mmap_mutex);
12348 mutex_unlock(&output_event->mmap_mutex);
12354 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12356 bool nmi_safe = false;
12359 case CLOCK_MONOTONIC:
12360 event->clock = &ktime_get_mono_fast_ns;
12364 case CLOCK_MONOTONIC_RAW:
12365 event->clock = &ktime_get_raw_fast_ns;
12369 case CLOCK_REALTIME:
12370 event->clock = &ktime_get_real_ns;
12373 case CLOCK_BOOTTIME:
12374 event->clock = &ktime_get_boottime_ns;
12378 event->clock = &ktime_get_clocktai_ns;
12385 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12392 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12394 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12395 bool is_capable = perfmon_capable();
12397 if (attr->sigtrap) {
12399 * perf_event_attr::sigtrap sends signals to the other task.
12400 * Require the current task to also have CAP_KILL.
12403 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12407 * If the required capabilities aren't available, checks for
12408 * ptrace permissions: upgrade to ATTACH, since sending signals
12409 * can effectively change the target task.
12411 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12415 * Preserve ptrace permission check for backwards compatibility. The
12416 * ptrace check also includes checks that the current task and other
12417 * task have matching uids, and is therefore not done here explicitly.
12419 return is_capable || ptrace_may_access(task, ptrace_mode);
12423 * sys_perf_event_open - open a performance event, associate it to a task/cpu
12425 * @attr_uptr: event_id type attributes for monitoring/sampling
12428 * @group_fd: group leader event fd
12429 * @flags: perf event open flags
12431 SYSCALL_DEFINE5(perf_event_open,
12432 struct perf_event_attr __user *, attr_uptr,
12433 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12435 struct perf_event *group_leader = NULL, *output_event = NULL;
12436 struct perf_event_pmu_context *pmu_ctx;
12437 struct perf_event *event, *sibling;
12438 struct perf_event_attr attr;
12439 struct perf_event_context *ctx;
12440 struct file *event_file = NULL;
12441 struct fd group = {NULL, 0};
12442 struct task_struct *task = NULL;
12445 int move_group = 0;
12447 int f_flags = O_RDWR;
12448 int cgroup_fd = -1;
12450 /* for future expandability... */
12451 if (flags & ~PERF_FLAG_ALL)
12454 err = perf_copy_attr(attr_uptr, &attr);
12458 /* Do we allow access to perf_event_open(2) ? */
12459 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12463 if (!attr.exclude_kernel) {
12464 err = perf_allow_kernel(&attr);
12469 if (attr.namespaces) {
12470 if (!perfmon_capable())
12475 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12478 if (attr.sample_period & (1ULL << 63))
12482 /* Only privileged users can get physical addresses */
12483 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12484 err = perf_allow_kernel(&attr);
12489 /* REGS_INTR can leak data, lockdown must prevent this */
12490 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12491 err = security_locked_down(LOCKDOWN_PERF);
12497 * In cgroup mode, the pid argument is used to pass the fd
12498 * opened to the cgroup directory in cgroupfs. The cpu argument
12499 * designates the cpu on which to monitor threads from that
12502 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12505 if (flags & PERF_FLAG_FD_CLOEXEC)
12506 f_flags |= O_CLOEXEC;
12508 event_fd = get_unused_fd_flags(f_flags);
12512 if (group_fd != -1) {
12513 err = perf_fget_light(group_fd, &group);
12516 group_leader = group.file->private_data;
12517 if (flags & PERF_FLAG_FD_OUTPUT)
12518 output_event = group_leader;
12519 if (flags & PERF_FLAG_FD_NO_GROUP)
12520 group_leader = NULL;
12523 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12524 task = find_lively_task_by_vpid(pid);
12525 if (IS_ERR(task)) {
12526 err = PTR_ERR(task);
12531 if (task && group_leader &&
12532 group_leader->attr.inherit != attr.inherit) {
12537 if (flags & PERF_FLAG_PID_CGROUP)
12540 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12541 NULL, NULL, cgroup_fd);
12542 if (IS_ERR(event)) {
12543 err = PTR_ERR(event);
12547 if (is_sampling_event(event)) {
12548 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12555 * Special case software events and allow them to be part of
12556 * any hardware group.
12560 if (attr.use_clockid) {
12561 err = perf_event_set_clock(event, attr.clockid);
12566 if (pmu->task_ctx_nr == perf_sw_context)
12567 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12570 err = down_read_interruptible(&task->signal->exec_update_lock);
12575 * We must hold exec_update_lock across this and any potential
12576 * perf_install_in_context() call for this new event to
12577 * serialize against exec() altering our credentials (and the
12578 * perf_event_exit_task() that could imply).
12581 if (!perf_check_permission(&attr, task))
12586 * Get the target context (task or percpu):
12588 ctx = find_get_context(task, event);
12590 err = PTR_ERR(ctx);
12594 mutex_lock(&ctx->mutex);
12596 if (ctx->task == TASK_TOMBSTONE) {
12603 * Check if the @cpu we're creating an event for is online.
12605 * We use the perf_cpu_context::ctx::mutex to serialize against
12606 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12608 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
12610 if (!cpuctx->online) {
12616 if (group_leader) {
12620 * Do not allow a recursive hierarchy (this new sibling
12621 * becoming part of another group-sibling):
12623 if (group_leader->group_leader != group_leader)
12626 /* All events in a group should have the same clock */
12627 if (group_leader->clock != event->clock)
12631 * Make sure we're both events for the same CPU;
12632 * grouping events for different CPUs is broken; since
12633 * you can never concurrently schedule them anyhow.
12635 if (group_leader->cpu != event->cpu)
12639 * Make sure we're both on the same context; either task or cpu.
12641 if (group_leader->ctx != ctx)
12645 * Only a group leader can be exclusive or pinned
12647 if (attr.exclusive || attr.pinned)
12650 if (is_software_event(event) &&
12651 !in_software_context(group_leader)) {
12653 * If the event is a sw event, but the group_leader
12654 * is on hw context.
12656 * Allow the addition of software events to hw
12657 * groups, this is safe because software events
12658 * never fail to schedule.
12660 * Note the comment that goes with struct
12661 * perf_event_pmu_context.
12663 pmu = group_leader->pmu_ctx->pmu;
12664 } else if (!is_software_event(event)) {
12665 if (is_software_event(group_leader) &&
12666 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12668 * In case the group is a pure software group, and we
12669 * try to add a hardware event, move the whole group to
12670 * the hardware context.
12675 /* Don't allow group of multiple hw events from different pmus */
12676 if (!in_software_context(group_leader) &&
12677 group_leader->pmu_ctx->pmu != pmu)
12683 * Now that we're certain of the pmu; find the pmu_ctx.
12685 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12686 if (IS_ERR(pmu_ctx)) {
12687 err = PTR_ERR(pmu_ctx);
12690 event->pmu_ctx = pmu_ctx;
12692 if (output_event) {
12693 err = perf_event_set_output(event, output_event);
12698 if (!perf_event_validate_size(event)) {
12703 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12709 * Must be under the same ctx::mutex as perf_install_in_context(),
12710 * because we need to serialize with concurrent event creation.
12712 if (!exclusive_event_installable(event, ctx)) {
12717 WARN_ON_ONCE(ctx->parent_ctx);
12719 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
12720 if (IS_ERR(event_file)) {
12721 err = PTR_ERR(event_file);
12727 * This is the point on no return; we cannot fail hereafter. This is
12728 * where we start modifying current state.
12732 perf_remove_from_context(group_leader, 0);
12733 put_pmu_ctx(group_leader->pmu_ctx);
12735 for_each_sibling_event(sibling, group_leader) {
12736 perf_remove_from_context(sibling, 0);
12737 put_pmu_ctx(sibling->pmu_ctx);
12741 * Install the group siblings before the group leader.
12743 * Because a group leader will try and install the entire group
12744 * (through the sibling list, which is still in-tact), we can
12745 * end up with siblings installed in the wrong context.
12747 * By installing siblings first we NO-OP because they're not
12748 * reachable through the group lists.
12750 for_each_sibling_event(sibling, group_leader) {
12751 sibling->pmu_ctx = pmu_ctx;
12752 get_pmu_ctx(pmu_ctx);
12753 perf_event__state_init(sibling);
12754 perf_install_in_context(ctx, sibling, sibling->cpu);
12758 * Removing from the context ends up with disabled
12759 * event. What we want here is event in the initial
12760 * startup state, ready to be add into new context.
12762 group_leader->pmu_ctx = pmu_ctx;
12763 get_pmu_ctx(pmu_ctx);
12764 perf_event__state_init(group_leader);
12765 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12769 * Precalculate sample_data sizes; do while holding ctx::mutex such
12770 * that we're serialized against further additions and before
12771 * perf_install_in_context() which is the point the event is active and
12772 * can use these values.
12774 perf_event__header_size(event);
12775 perf_event__id_header_size(event);
12777 event->owner = current;
12779 perf_install_in_context(ctx, event, event->cpu);
12780 perf_unpin_context(ctx);
12782 mutex_unlock(&ctx->mutex);
12785 up_read(&task->signal->exec_update_lock);
12786 put_task_struct(task);
12789 mutex_lock(¤t->perf_event_mutex);
12790 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12791 mutex_unlock(¤t->perf_event_mutex);
12794 * Drop the reference on the group_event after placing the
12795 * new event on the sibling_list. This ensures destruction
12796 * of the group leader will find the pointer to itself in
12797 * perf_group_detach().
12800 fd_install(event_fd, event_file);
12804 put_pmu_ctx(event->pmu_ctx);
12805 event->pmu_ctx = NULL; /* _free_event() */
12807 mutex_unlock(&ctx->mutex);
12808 perf_unpin_context(ctx);
12812 up_read(&task->signal->exec_update_lock);
12817 put_task_struct(task);
12821 put_unused_fd(event_fd);
12826 * perf_event_create_kernel_counter
12828 * @attr: attributes of the counter to create
12829 * @cpu: cpu in which the counter is bound
12830 * @task: task to profile (NULL for percpu)
12831 * @overflow_handler: callback to trigger when we hit the event
12832 * @context: context data could be used in overflow_handler callback
12834 struct perf_event *
12835 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12836 struct task_struct *task,
12837 perf_overflow_handler_t overflow_handler,
12840 struct perf_event_pmu_context *pmu_ctx;
12841 struct perf_event_context *ctx;
12842 struct perf_event *event;
12847 * Grouping is not supported for kernel events, neither is 'AUX',
12848 * make sure the caller's intentions are adjusted.
12850 if (attr->aux_output)
12851 return ERR_PTR(-EINVAL);
12853 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12854 overflow_handler, context, -1);
12855 if (IS_ERR(event)) {
12856 err = PTR_ERR(event);
12860 /* Mark owner so we could distinguish it from user events. */
12861 event->owner = TASK_TOMBSTONE;
12864 if (pmu->task_ctx_nr == perf_sw_context)
12865 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12868 * Get the target context (task or percpu):
12870 ctx = find_get_context(task, event);
12872 err = PTR_ERR(ctx);
12876 WARN_ON_ONCE(ctx->parent_ctx);
12877 mutex_lock(&ctx->mutex);
12878 if (ctx->task == TASK_TOMBSTONE) {
12883 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12884 if (IS_ERR(pmu_ctx)) {
12885 err = PTR_ERR(pmu_ctx);
12888 event->pmu_ctx = pmu_ctx;
12892 * Check if the @cpu we're creating an event for is online.
12894 * We use the perf_cpu_context::ctx::mutex to serialize against
12895 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12897 struct perf_cpu_context *cpuctx =
12898 container_of(ctx, struct perf_cpu_context, ctx);
12899 if (!cpuctx->online) {
12905 if (!exclusive_event_installable(event, ctx)) {
12910 perf_install_in_context(ctx, event, event->cpu);
12911 perf_unpin_context(ctx);
12912 mutex_unlock(&ctx->mutex);
12917 put_pmu_ctx(pmu_ctx);
12918 event->pmu_ctx = NULL; /* _free_event() */
12920 mutex_unlock(&ctx->mutex);
12921 perf_unpin_context(ctx);
12926 return ERR_PTR(err);
12928 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12930 static void __perf_pmu_remove(struct perf_event_context *ctx,
12931 int cpu, struct pmu *pmu,
12932 struct perf_event_groups *groups,
12933 struct list_head *events)
12935 struct perf_event *event, *sibling;
12937 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
12938 perf_remove_from_context(event, 0);
12939 put_pmu_ctx(event->pmu_ctx);
12940 list_add(&event->migrate_entry, events);
12942 for_each_sibling_event(sibling, event) {
12943 perf_remove_from_context(sibling, 0);
12944 put_pmu_ctx(sibling->pmu_ctx);
12945 list_add(&sibling->migrate_entry, events);
12950 static void __perf_pmu_install_event(struct pmu *pmu,
12951 struct perf_event_context *ctx,
12952 int cpu, struct perf_event *event)
12954 struct perf_event_pmu_context *epc;
12955 struct perf_event_context *old_ctx = event->ctx;
12957 get_ctx(ctx); /* normally find_get_context() */
12960 epc = find_get_pmu_context(pmu, ctx, event);
12961 event->pmu_ctx = epc;
12963 if (event->state >= PERF_EVENT_STATE_OFF)
12964 event->state = PERF_EVENT_STATE_INACTIVE;
12965 perf_install_in_context(ctx, event, cpu);
12968 * Now that event->ctx is updated and visible, put the old ctx.
12973 static void __perf_pmu_install(struct perf_event_context *ctx,
12974 int cpu, struct pmu *pmu, struct list_head *events)
12976 struct perf_event *event, *tmp;
12979 * Re-instate events in 2 passes.
12981 * Skip over group leaders and only install siblings on this first
12982 * pass, siblings will not get enabled without a leader, however a
12983 * leader will enable its siblings, even if those are still on the old
12986 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12987 if (event->group_leader == event)
12990 list_del(&event->migrate_entry);
12991 __perf_pmu_install_event(pmu, ctx, cpu, event);
12995 * Once all the siblings are setup properly, install the group leaders
12998 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12999 list_del(&event->migrate_entry);
13000 __perf_pmu_install_event(pmu, ctx, cpu, event);
13004 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
13006 struct perf_event_context *src_ctx, *dst_ctx;
13010 * Since per-cpu context is persistent, no need to grab an extra
13013 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
13014 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
13017 * See perf_event_ctx_lock() for comments on the details
13018 * of swizzling perf_event::ctx.
13020 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
13022 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
13023 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
13025 if (!list_empty(&events)) {
13027 * Wait for the events to quiesce before re-instating them.
13031 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
13034 mutex_unlock(&dst_ctx->mutex);
13035 mutex_unlock(&src_ctx->mutex);
13037 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
13039 static void sync_child_event(struct perf_event *child_event)
13041 struct perf_event *parent_event = child_event->parent;
13044 if (child_event->attr.inherit_stat) {
13045 struct task_struct *task = child_event->ctx->task;
13047 if (task && task != TASK_TOMBSTONE)
13048 perf_event_read_event(child_event, task);
13051 child_val = perf_event_count(child_event);
13054 * Add back the child's count to the parent's count:
13056 atomic64_add(child_val, &parent_event->child_count);
13057 atomic64_add(child_event->total_time_enabled,
13058 &parent_event->child_total_time_enabled);
13059 atomic64_add(child_event->total_time_running,
13060 &parent_event->child_total_time_running);
13064 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
13066 struct perf_event *parent_event = event->parent;
13067 unsigned long detach_flags = 0;
13069 if (parent_event) {
13071 * Do not destroy the 'original' grouping; because of the
13072 * context switch optimization the original events could've
13073 * ended up in a random child task.
13075 * If we were to destroy the original group, all group related
13076 * operations would cease to function properly after this
13077 * random child dies.
13079 * Do destroy all inherited groups, we don't care about those
13080 * and being thorough is better.
13082 detach_flags = DETACH_GROUP | DETACH_CHILD;
13083 mutex_lock(&parent_event->child_mutex);
13086 perf_remove_from_context(event, detach_flags);
13088 raw_spin_lock_irq(&ctx->lock);
13089 if (event->state > PERF_EVENT_STATE_EXIT)
13090 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
13091 raw_spin_unlock_irq(&ctx->lock);
13094 * Child events can be freed.
13096 if (parent_event) {
13097 mutex_unlock(&parent_event->child_mutex);
13099 * Kick perf_poll() for is_event_hup();
13101 perf_event_wakeup(parent_event);
13103 put_event(parent_event);
13108 * Parent events are governed by their filedesc, retain them.
13110 perf_event_wakeup(event);
13113 static void perf_event_exit_task_context(struct task_struct *child)
13115 struct perf_event_context *child_ctx, *clone_ctx = NULL;
13116 struct perf_event *child_event, *next;
13118 WARN_ON_ONCE(child != current);
13120 child_ctx = perf_pin_task_context(child);
13125 * In order to reduce the amount of tricky in ctx tear-down, we hold
13126 * ctx::mutex over the entire thing. This serializes against almost
13127 * everything that wants to access the ctx.
13129 * The exception is sys_perf_event_open() /
13130 * perf_event_create_kernel_count() which does find_get_context()
13131 * without ctx::mutex (it cannot because of the move_group double mutex
13132 * lock thing). See the comments in perf_install_in_context().
13134 mutex_lock(&child_ctx->mutex);
13137 * In a single ctx::lock section, de-schedule the events and detach the
13138 * context from the task such that we cannot ever get it scheduled back
13141 raw_spin_lock_irq(&child_ctx->lock);
13142 task_ctx_sched_out(child_ctx, EVENT_ALL);
13145 * Now that the context is inactive, destroy the task <-> ctx relation
13146 * and mark the context dead.
13148 RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
13149 put_ctx(child_ctx); /* cannot be last */
13150 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
13151 put_task_struct(current); /* cannot be last */
13153 clone_ctx = unclone_ctx(child_ctx);
13154 raw_spin_unlock_irq(&child_ctx->lock);
13157 put_ctx(clone_ctx);
13160 * Report the task dead after unscheduling the events so that we
13161 * won't get any samples after PERF_RECORD_EXIT. We can however still
13162 * get a few PERF_RECORD_READ events.
13164 perf_event_task(child, child_ctx, 0);
13166 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
13167 perf_event_exit_event(child_event, child_ctx);
13169 mutex_unlock(&child_ctx->mutex);
13171 put_ctx(child_ctx);
13175 * When a child task exits, feed back event values to parent events.
13177 * Can be called with exec_update_lock held when called from
13178 * setup_new_exec().
13180 void perf_event_exit_task(struct task_struct *child)
13182 struct perf_event *event, *tmp;
13184 mutex_lock(&child->perf_event_mutex);
13185 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
13187 list_del_init(&event->owner_entry);
13190 * Ensure the list deletion is visible before we clear
13191 * the owner, closes a race against perf_release() where
13192 * we need to serialize on the owner->perf_event_mutex.
13194 smp_store_release(&event->owner, NULL);
13196 mutex_unlock(&child->perf_event_mutex);
13198 perf_event_exit_task_context(child);
13201 * The perf_event_exit_task_context calls perf_event_task
13202 * with child's task_ctx, which generates EXIT events for
13203 * child contexts and sets child->perf_event_ctxp[] to NULL.
13204 * At this point we need to send EXIT events to cpu contexts.
13206 perf_event_task(child, NULL, 0);
13209 static void perf_free_event(struct perf_event *event,
13210 struct perf_event_context *ctx)
13212 struct perf_event *parent = event->parent;
13214 if (WARN_ON_ONCE(!parent))
13217 mutex_lock(&parent->child_mutex);
13218 list_del_init(&event->child_list);
13219 mutex_unlock(&parent->child_mutex);
13223 raw_spin_lock_irq(&ctx->lock);
13224 perf_group_detach(event);
13225 list_del_event(event, ctx);
13226 raw_spin_unlock_irq(&ctx->lock);
13231 * Free a context as created by inheritance by perf_event_init_task() below,
13232 * used by fork() in case of fail.
13234 * Even though the task has never lived, the context and events have been
13235 * exposed through the child_list, so we must take care tearing it all down.
13237 void perf_event_free_task(struct task_struct *task)
13239 struct perf_event_context *ctx;
13240 struct perf_event *event, *tmp;
13242 ctx = rcu_access_pointer(task->perf_event_ctxp);
13246 mutex_lock(&ctx->mutex);
13247 raw_spin_lock_irq(&ctx->lock);
13249 * Destroy the task <-> ctx relation and mark the context dead.
13251 * This is important because even though the task hasn't been
13252 * exposed yet the context has been (through child_list).
13254 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
13255 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13256 put_task_struct(task); /* cannot be last */
13257 raw_spin_unlock_irq(&ctx->lock);
13260 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13261 perf_free_event(event, ctx);
13263 mutex_unlock(&ctx->mutex);
13266 * perf_event_release_kernel() could've stolen some of our
13267 * child events and still have them on its free_list. In that
13268 * case we must wait for these events to have been freed (in
13269 * particular all their references to this task must've been
13272 * Without this copy_process() will unconditionally free this
13273 * task (irrespective of its reference count) and
13274 * _free_event()'s put_task_struct(event->hw.target) will be a
13277 * Wait for all events to drop their context reference.
13279 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13280 put_ctx(ctx); /* must be last */
13283 void perf_event_delayed_put(struct task_struct *task)
13285 WARN_ON_ONCE(task->perf_event_ctxp);
13288 struct file *perf_event_get(unsigned int fd)
13290 struct file *file = fget(fd);
13292 return ERR_PTR(-EBADF);
13294 if (file->f_op != &perf_fops) {
13296 return ERR_PTR(-EBADF);
13302 const struct perf_event *perf_get_event(struct file *file)
13304 if (file->f_op != &perf_fops)
13305 return ERR_PTR(-EINVAL);
13307 return file->private_data;
13310 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13313 return ERR_PTR(-EINVAL);
13315 return &event->attr;
13319 * Inherit an event from parent task to child task.
13322 * - valid pointer on success
13323 * - NULL for orphaned events
13324 * - IS_ERR() on error
13326 static struct perf_event *
13327 inherit_event(struct perf_event *parent_event,
13328 struct task_struct *parent,
13329 struct perf_event_context *parent_ctx,
13330 struct task_struct *child,
13331 struct perf_event *group_leader,
13332 struct perf_event_context *child_ctx)
13334 enum perf_event_state parent_state = parent_event->state;
13335 struct perf_event_pmu_context *pmu_ctx;
13336 struct perf_event *child_event;
13337 unsigned long flags;
13340 * Instead of creating recursive hierarchies of events,
13341 * we link inherited events back to the original parent,
13342 * which has a filp for sure, which we use as the reference
13345 if (parent_event->parent)
13346 parent_event = parent_event->parent;
13348 child_event = perf_event_alloc(&parent_event->attr,
13351 group_leader, parent_event,
13353 if (IS_ERR(child_event))
13354 return child_event;
13356 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
13357 if (IS_ERR(pmu_ctx)) {
13358 free_event(child_event);
13359 return ERR_CAST(pmu_ctx);
13361 child_event->pmu_ctx = pmu_ctx;
13364 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13365 * must be under the same lock in order to serialize against
13366 * perf_event_release_kernel(), such that either we must observe
13367 * is_orphaned_event() or they will observe us on the child_list.
13369 mutex_lock(&parent_event->child_mutex);
13370 if (is_orphaned_event(parent_event) ||
13371 !atomic_long_inc_not_zero(&parent_event->refcount)) {
13372 mutex_unlock(&parent_event->child_mutex);
13373 /* task_ctx_data is freed with child_ctx */
13374 free_event(child_event);
13378 get_ctx(child_ctx);
13381 * Make the child state follow the state of the parent event,
13382 * not its attr.disabled bit. We hold the parent's mutex,
13383 * so we won't race with perf_event_{en, dis}able_family.
13385 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13386 child_event->state = PERF_EVENT_STATE_INACTIVE;
13388 child_event->state = PERF_EVENT_STATE_OFF;
13390 if (parent_event->attr.freq) {
13391 u64 sample_period = parent_event->hw.sample_period;
13392 struct hw_perf_event *hwc = &child_event->hw;
13394 hwc->sample_period = sample_period;
13395 hwc->last_period = sample_period;
13397 local64_set(&hwc->period_left, sample_period);
13400 child_event->ctx = child_ctx;
13401 child_event->overflow_handler = parent_event->overflow_handler;
13402 child_event->overflow_handler_context
13403 = parent_event->overflow_handler_context;
13406 * Precalculate sample_data sizes
13408 perf_event__header_size(child_event);
13409 perf_event__id_header_size(child_event);
13412 * Link it up in the child's context:
13414 raw_spin_lock_irqsave(&child_ctx->lock, flags);
13415 add_event_to_ctx(child_event, child_ctx);
13416 child_event->attach_state |= PERF_ATTACH_CHILD;
13417 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13420 * Link this into the parent event's child list
13422 list_add_tail(&child_event->child_list, &parent_event->child_list);
13423 mutex_unlock(&parent_event->child_mutex);
13425 return child_event;
13429 * Inherits an event group.
13431 * This will quietly suppress orphaned events; !inherit_event() is not an error.
13432 * This matches with perf_event_release_kernel() removing all child events.
13438 static int inherit_group(struct perf_event *parent_event,
13439 struct task_struct *parent,
13440 struct perf_event_context *parent_ctx,
13441 struct task_struct *child,
13442 struct perf_event_context *child_ctx)
13444 struct perf_event *leader;
13445 struct perf_event *sub;
13446 struct perf_event *child_ctr;
13448 leader = inherit_event(parent_event, parent, parent_ctx,
13449 child, NULL, child_ctx);
13450 if (IS_ERR(leader))
13451 return PTR_ERR(leader);
13453 * @leader can be NULL here because of is_orphaned_event(). In this
13454 * case inherit_event() will create individual events, similar to what
13455 * perf_group_detach() would do anyway.
13457 for_each_sibling_event(sub, parent_event) {
13458 child_ctr = inherit_event(sub, parent, parent_ctx,
13459 child, leader, child_ctx);
13460 if (IS_ERR(child_ctr))
13461 return PTR_ERR(child_ctr);
13463 if (sub->aux_event == parent_event && child_ctr &&
13464 !perf_get_aux_event(child_ctr, leader))
13468 leader->group_generation = parent_event->group_generation;
13473 * Creates the child task context and tries to inherit the event-group.
13475 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13476 * inherited_all set when we 'fail' to inherit an orphaned event; this is
13477 * consistent with perf_event_release_kernel() removing all child events.
13484 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13485 struct perf_event_context *parent_ctx,
13486 struct task_struct *child,
13487 u64 clone_flags, int *inherited_all)
13489 struct perf_event_context *child_ctx;
13492 if (!event->attr.inherit ||
13493 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13494 /* Do not inherit if sigtrap and signal handlers were cleared. */
13495 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13496 *inherited_all = 0;
13500 child_ctx = child->perf_event_ctxp;
13503 * This is executed from the parent task context, so
13504 * inherit events that have been marked for cloning.
13505 * First allocate and initialize a context for the
13508 child_ctx = alloc_perf_context(child);
13512 child->perf_event_ctxp = child_ctx;
13515 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
13517 *inherited_all = 0;
13523 * Initialize the perf_event context in task_struct
13525 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
13527 struct perf_event_context *child_ctx, *parent_ctx;
13528 struct perf_event_context *cloned_ctx;
13529 struct perf_event *event;
13530 struct task_struct *parent = current;
13531 int inherited_all = 1;
13532 unsigned long flags;
13535 if (likely(!parent->perf_event_ctxp))
13539 * If the parent's context is a clone, pin it so it won't get
13540 * swapped under us.
13542 parent_ctx = perf_pin_task_context(parent);
13547 * No need to check if parent_ctx != NULL here; since we saw
13548 * it non-NULL earlier, the only reason for it to become NULL
13549 * is if we exit, and since we're currently in the middle of
13550 * a fork we can't be exiting at the same time.
13554 * Lock the parent list. No need to lock the child - not PID
13555 * hashed yet and not running, so nobody can access it.
13557 mutex_lock(&parent_ctx->mutex);
13560 * We dont have to disable NMIs - we are only looking at
13561 * the list, not manipulating it:
13563 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13564 ret = inherit_task_group(event, parent, parent_ctx,
13565 child, clone_flags, &inherited_all);
13571 * We can't hold ctx->lock when iterating the ->flexible_group list due
13572 * to allocations, but we need to prevent rotation because
13573 * rotate_ctx() will change the list from interrupt context.
13575 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13576 parent_ctx->rotate_disable = 1;
13577 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13579 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13580 ret = inherit_task_group(event, parent, parent_ctx,
13581 child, clone_flags, &inherited_all);
13586 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13587 parent_ctx->rotate_disable = 0;
13589 child_ctx = child->perf_event_ctxp;
13591 if (child_ctx && inherited_all) {
13593 * Mark the child context as a clone of the parent
13594 * context, or of whatever the parent is a clone of.
13596 * Note that if the parent is a clone, the holding of
13597 * parent_ctx->lock avoids it from being uncloned.
13599 cloned_ctx = parent_ctx->parent_ctx;
13601 child_ctx->parent_ctx = cloned_ctx;
13602 child_ctx->parent_gen = parent_ctx->parent_gen;
13604 child_ctx->parent_ctx = parent_ctx;
13605 child_ctx->parent_gen = parent_ctx->generation;
13607 get_ctx(child_ctx->parent_ctx);
13610 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13612 mutex_unlock(&parent_ctx->mutex);
13614 perf_unpin_context(parent_ctx);
13615 put_ctx(parent_ctx);
13621 * Initialize the perf_event context in task_struct
13623 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
13627 child->perf_event_ctxp = NULL;
13628 mutex_init(&child->perf_event_mutex);
13629 INIT_LIST_HEAD(&child->perf_event_list);
13631 ret = perf_event_init_context(child, clone_flags);
13633 perf_event_free_task(child);
13640 static void __init perf_event_init_all_cpus(void)
13642 struct swevent_htable *swhash;
13643 struct perf_cpu_context *cpuctx;
13646 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13648 for_each_possible_cpu(cpu) {
13649 swhash = &per_cpu(swevent_htable, cpu);
13650 mutex_init(&swhash->hlist_mutex);
13652 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13653 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13655 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13657 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13658 __perf_event_init_context(&cpuctx->ctx);
13659 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
13660 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
13661 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
13662 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
13663 cpuctx->heap = cpuctx->heap_default;
13667 static void perf_swevent_init_cpu(unsigned int cpu)
13669 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13671 mutex_lock(&swhash->hlist_mutex);
13672 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13673 struct swevent_hlist *hlist;
13675 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13677 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13679 mutex_unlock(&swhash->hlist_mutex);
13682 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13683 static void __perf_event_exit_context(void *__info)
13685 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
13686 struct perf_event_context *ctx = __info;
13687 struct perf_event *event;
13689 raw_spin_lock(&ctx->lock);
13690 ctx_sched_out(ctx, EVENT_TIME);
13691 list_for_each_entry(event, &ctx->event_list, event_entry)
13692 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13693 raw_spin_unlock(&ctx->lock);
13696 static void perf_event_exit_cpu_context(int cpu)
13698 struct perf_cpu_context *cpuctx;
13699 struct perf_event_context *ctx;
13701 // XXX simplify cpuctx->online
13702 mutex_lock(&pmus_lock);
13703 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13704 ctx = &cpuctx->ctx;
13706 mutex_lock(&ctx->mutex);
13707 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13708 cpuctx->online = 0;
13709 mutex_unlock(&ctx->mutex);
13710 cpumask_clear_cpu(cpu, perf_online_mask);
13711 mutex_unlock(&pmus_lock);
13715 static void perf_event_exit_cpu_context(int cpu) { }
13719 int perf_event_init_cpu(unsigned int cpu)
13721 struct perf_cpu_context *cpuctx;
13722 struct perf_event_context *ctx;
13724 perf_swevent_init_cpu(cpu);
13726 mutex_lock(&pmus_lock);
13727 cpumask_set_cpu(cpu, perf_online_mask);
13728 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13729 ctx = &cpuctx->ctx;
13731 mutex_lock(&ctx->mutex);
13732 cpuctx->online = 1;
13733 mutex_unlock(&ctx->mutex);
13734 mutex_unlock(&pmus_lock);
13739 int perf_event_exit_cpu(unsigned int cpu)
13741 perf_event_exit_cpu_context(cpu);
13746 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13750 for_each_online_cpu(cpu)
13751 perf_event_exit_cpu(cpu);
13757 * Run the perf reboot notifier at the very last possible moment so that
13758 * the generic watchdog code runs as long as possible.
13760 static struct notifier_block perf_reboot_notifier = {
13761 .notifier_call = perf_reboot,
13762 .priority = INT_MIN,
13765 void __init perf_event_init(void)
13769 idr_init(&pmu_idr);
13771 perf_event_init_all_cpus();
13772 init_srcu_struct(&pmus_srcu);
13773 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13774 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
13775 perf_pmu_register(&perf_task_clock, "task_clock", -1);
13776 perf_tp_register();
13777 perf_event_init_cpu(smp_processor_id());
13778 register_reboot_notifier(&perf_reboot_notifier);
13780 ret = init_hw_breakpoint();
13781 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13783 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13786 * Build time assertion that we keep the data_head at the intended
13787 * location. IOW, validation we got the __reserved[] size right.
13789 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13793 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13796 struct perf_pmu_events_attr *pmu_attr =
13797 container_of(attr, struct perf_pmu_events_attr, attr);
13799 if (pmu_attr->event_str)
13800 return sprintf(page, "%s\n", pmu_attr->event_str);
13804 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13806 static int __init perf_event_sysfs_init(void)
13811 mutex_lock(&pmus_lock);
13813 ret = bus_register(&pmu_bus);
13817 list_for_each_entry(pmu, &pmus, entry) {
13821 ret = pmu_dev_alloc(pmu);
13822 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13824 pmu_bus_running = 1;
13828 mutex_unlock(&pmus_lock);
13832 device_initcall(perf_event_sysfs_init);
13834 #ifdef CONFIG_CGROUP_PERF
13835 static struct cgroup_subsys_state *
13836 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13838 struct perf_cgroup *jc;
13840 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13842 return ERR_PTR(-ENOMEM);
13844 jc->info = alloc_percpu(struct perf_cgroup_info);
13847 return ERR_PTR(-ENOMEM);
13853 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13855 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13857 free_percpu(jc->info);
13861 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13863 perf_event_cgroup(css->cgroup);
13867 static int __perf_cgroup_move(void *info)
13869 struct task_struct *task = info;
13872 perf_cgroup_switch(task);
13878 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13880 struct task_struct *task;
13881 struct cgroup_subsys_state *css;
13883 cgroup_taskset_for_each(task, css, tset)
13884 task_function_call(task, __perf_cgroup_move, task);
13887 struct cgroup_subsys perf_event_cgrp_subsys = {
13888 .css_alloc = perf_cgroup_css_alloc,
13889 .css_free = perf_cgroup_css_free,
13890 .css_online = perf_cgroup_css_online,
13891 .attach = perf_cgroup_attach,
13893 * Implicitly enable on dfl hierarchy so that perf events can
13894 * always be filtered by cgroup2 path as long as perf_event
13895 * controller is not mounted on a legacy hierarchy.
13897 .implicit_on_dfl = true,
13900 #endif /* CONFIG_CGROUP_PERF */
13902 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);