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>
60 #include <asm/irq_regs.h>
62 typedef int (*remote_function_f)(void *);
64 struct remote_function_call {
65 struct task_struct *p;
66 remote_function_f func;
71 static void remote_function(void *data)
73 struct remote_function_call *tfc = data;
74 struct task_struct *p = tfc->p;
78 if (task_cpu(p) != smp_processor_id())
82 * Now that we're on right CPU with IRQs disabled, we can test
83 * if we hit the right task without races.
86 tfc->ret = -ESRCH; /* No such (running) process */
91 tfc->ret = tfc->func(tfc->info);
95 * task_function_call - call a function on the cpu on which a task runs
96 * @p: the task to evaluate
97 * @func: the function to be called
98 * @info: the function call argument
100 * Calls the function @func when the task is currently running. This might
101 * be on the current CPU, which just calls the function directly. This will
102 * retry due to any failures in smp_call_function_single(), such as if the
103 * task_cpu() goes offline concurrently.
105 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
108 task_function_call(struct task_struct *p, remote_function_f func, void *info)
110 struct remote_function_call data = {
119 ret = smp_call_function_single(task_cpu(p), remote_function,
134 * cpu_function_call - call a function on the cpu
135 * @func: the function to be called
136 * @info: the function call argument
138 * Calls the function @func on the remote cpu.
140 * returns: @func return value or -ENXIO when the cpu is offline
142 static int cpu_function_call(int cpu, remote_function_f func, void *info)
144 struct remote_function_call data = {
148 .ret = -ENXIO, /* No such CPU */
151 smp_call_function_single(cpu, remote_function, &data, 1);
156 static inline struct perf_cpu_context *
157 __get_cpu_context(struct perf_event_context *ctx)
159 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
162 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
163 struct perf_event_context *ctx)
165 raw_spin_lock(&cpuctx->ctx.lock);
167 raw_spin_lock(&ctx->lock);
170 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
171 struct perf_event_context *ctx)
174 raw_spin_unlock(&ctx->lock);
175 raw_spin_unlock(&cpuctx->ctx.lock);
178 #define TASK_TOMBSTONE ((void *)-1L)
180 static bool is_kernel_event(struct perf_event *event)
182 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
186 * On task ctx scheduling...
188 * When !ctx->nr_events a task context will not be scheduled. This means
189 * we can disable the scheduler hooks (for performance) without leaving
190 * pending task ctx state.
192 * This however results in two special cases:
194 * - removing the last event from a task ctx; this is relatively straight
195 * forward and is done in __perf_remove_from_context.
197 * - adding the first event to a task ctx; this is tricky because we cannot
198 * rely on ctx->is_active and therefore cannot use event_function_call().
199 * See perf_install_in_context().
201 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
204 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
205 struct perf_event_context *, void *);
207 struct event_function_struct {
208 struct perf_event *event;
213 static int event_function(void *info)
215 struct event_function_struct *efs = info;
216 struct perf_event *event = efs->event;
217 struct perf_event_context *ctx = event->ctx;
218 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
219 struct perf_event_context *task_ctx = cpuctx->task_ctx;
222 lockdep_assert_irqs_disabled();
224 perf_ctx_lock(cpuctx, task_ctx);
226 * Since we do the IPI call without holding ctx->lock things can have
227 * changed, double check we hit the task we set out to hit.
230 if (ctx->task != current) {
236 * We only use event_function_call() on established contexts,
237 * and event_function() is only ever called when active (or
238 * rather, we'll have bailed in task_function_call() or the
239 * above ctx->task != current test), therefore we must have
240 * ctx->is_active here.
242 WARN_ON_ONCE(!ctx->is_active);
244 * And since we have ctx->is_active, cpuctx->task_ctx must
247 WARN_ON_ONCE(task_ctx != ctx);
249 WARN_ON_ONCE(&cpuctx->ctx != ctx);
252 efs->func(event, cpuctx, ctx, efs->data);
254 perf_ctx_unlock(cpuctx, task_ctx);
259 static void event_function_call(struct perf_event *event, event_f func, void *data)
261 struct perf_event_context *ctx = event->ctx;
262 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
263 struct event_function_struct efs = {
269 if (!event->parent) {
271 * If this is a !child event, we must hold ctx::mutex to
272 * stabilize the event->ctx relation. See
273 * perf_event_ctx_lock().
275 lockdep_assert_held(&ctx->mutex);
279 cpu_function_call(event->cpu, event_function, &efs);
283 if (task == TASK_TOMBSTONE)
287 if (!task_function_call(task, event_function, &efs))
290 raw_spin_lock_irq(&ctx->lock);
292 * Reload the task pointer, it might have been changed by
293 * a concurrent perf_event_context_sched_out().
296 if (task == TASK_TOMBSTONE) {
297 raw_spin_unlock_irq(&ctx->lock);
300 if (ctx->is_active) {
301 raw_spin_unlock_irq(&ctx->lock);
304 func(event, NULL, ctx, data);
305 raw_spin_unlock_irq(&ctx->lock);
309 * Similar to event_function_call() + event_function(), but hard assumes IRQs
310 * are already disabled and we're on the right CPU.
312 static void event_function_local(struct perf_event *event, event_f func, void *data)
314 struct perf_event_context *ctx = event->ctx;
315 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
316 struct task_struct *task = READ_ONCE(ctx->task);
317 struct perf_event_context *task_ctx = NULL;
319 lockdep_assert_irqs_disabled();
322 if (task == TASK_TOMBSTONE)
328 perf_ctx_lock(cpuctx, task_ctx);
331 if (task == TASK_TOMBSTONE)
336 * We must be either inactive or active and the right task,
337 * otherwise we're screwed, since we cannot IPI to somewhere
340 if (ctx->is_active) {
341 if (WARN_ON_ONCE(task != current))
344 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
348 WARN_ON_ONCE(&cpuctx->ctx != ctx);
351 func(event, cpuctx, ctx, data);
353 perf_ctx_unlock(cpuctx, task_ctx);
356 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
357 PERF_FLAG_FD_OUTPUT |\
358 PERF_FLAG_PID_CGROUP |\
359 PERF_FLAG_FD_CLOEXEC)
362 * branch priv levels that need permission checks
364 #define PERF_SAMPLE_BRANCH_PERM_PLM \
365 (PERF_SAMPLE_BRANCH_KERNEL |\
366 PERF_SAMPLE_BRANCH_HV)
369 EVENT_FLEXIBLE = 0x1,
372 /* see ctx_resched() for details */
374 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
378 * perf_sched_events : >0 events exist
379 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
382 static void perf_sched_delayed(struct work_struct *work);
383 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
384 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
385 static DEFINE_MUTEX(perf_sched_mutex);
386 static atomic_t perf_sched_count;
388 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
389 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
390 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
392 static atomic_t nr_mmap_events __read_mostly;
393 static atomic_t nr_comm_events __read_mostly;
394 static atomic_t nr_namespaces_events __read_mostly;
395 static atomic_t nr_task_events __read_mostly;
396 static atomic_t nr_freq_events __read_mostly;
397 static atomic_t nr_switch_events __read_mostly;
398 static atomic_t nr_ksymbol_events __read_mostly;
399 static atomic_t nr_bpf_events __read_mostly;
400 static atomic_t nr_cgroup_events __read_mostly;
401 static atomic_t nr_text_poke_events __read_mostly;
402 static atomic_t nr_build_id_events __read_mostly;
404 static LIST_HEAD(pmus);
405 static DEFINE_MUTEX(pmus_lock);
406 static struct srcu_struct pmus_srcu;
407 static cpumask_var_t perf_online_mask;
410 * perf event paranoia level:
411 * -1 - not paranoid at all
412 * 0 - disallow raw tracepoint access for unpriv
413 * 1 - disallow cpu events for unpriv
414 * 2 - disallow kernel profiling for unpriv
416 int sysctl_perf_event_paranoid __read_mostly = 2;
418 /* Minimum for 512 kiB + 1 user control page */
419 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
422 * max perf event sample rate
424 #define DEFAULT_MAX_SAMPLE_RATE 100000
425 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
426 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
428 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
430 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
431 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
433 static int perf_sample_allowed_ns __read_mostly =
434 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
436 static void update_perf_cpu_limits(void)
438 u64 tmp = perf_sample_period_ns;
440 tmp *= sysctl_perf_cpu_time_max_percent;
441 tmp = div_u64(tmp, 100);
445 WRITE_ONCE(perf_sample_allowed_ns, tmp);
448 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
450 int perf_proc_update_handler(struct ctl_table *table, int write,
451 void *buffer, size_t *lenp, loff_t *ppos)
454 int perf_cpu = sysctl_perf_cpu_time_max_percent;
456 * If throttling is disabled don't allow the write:
458 if (write && (perf_cpu == 100 || perf_cpu == 0))
461 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
465 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
466 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
467 update_perf_cpu_limits();
472 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
474 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
475 void *buffer, size_t *lenp, loff_t *ppos)
477 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
482 if (sysctl_perf_cpu_time_max_percent == 100 ||
483 sysctl_perf_cpu_time_max_percent == 0) {
485 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
486 WRITE_ONCE(perf_sample_allowed_ns, 0);
488 update_perf_cpu_limits();
495 * perf samples are done in some very critical code paths (NMIs).
496 * If they take too much CPU time, the system can lock up and not
497 * get any real work done. This will drop the sample rate when
498 * we detect that events are taking too long.
500 #define NR_ACCUMULATED_SAMPLES 128
501 static DEFINE_PER_CPU(u64, running_sample_length);
503 static u64 __report_avg;
504 static u64 __report_allowed;
506 static void perf_duration_warn(struct irq_work *w)
508 printk_ratelimited(KERN_INFO
509 "perf: interrupt took too long (%lld > %lld), lowering "
510 "kernel.perf_event_max_sample_rate to %d\n",
511 __report_avg, __report_allowed,
512 sysctl_perf_event_sample_rate);
515 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
517 void perf_sample_event_took(u64 sample_len_ns)
519 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
527 /* Decay the counter by 1 average sample. */
528 running_len = __this_cpu_read(running_sample_length);
529 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
530 running_len += sample_len_ns;
531 __this_cpu_write(running_sample_length, running_len);
534 * Note: this will be biased artifically low until we have
535 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
536 * from having to maintain a count.
538 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
539 if (avg_len <= max_len)
542 __report_avg = avg_len;
543 __report_allowed = max_len;
546 * Compute a throttle threshold 25% below the current duration.
548 avg_len += avg_len / 4;
549 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
555 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
556 WRITE_ONCE(max_samples_per_tick, max);
558 sysctl_perf_event_sample_rate = max * HZ;
559 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
561 if (!irq_work_queue(&perf_duration_work)) {
562 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
563 "kernel.perf_event_max_sample_rate to %d\n",
564 __report_avg, __report_allowed,
565 sysctl_perf_event_sample_rate);
569 static atomic64_t perf_event_id;
571 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
572 enum event_type_t event_type);
574 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
575 enum event_type_t event_type,
576 struct task_struct *task);
578 static void update_context_time(struct perf_event_context *ctx);
579 static u64 perf_event_time(struct perf_event *event);
581 void __weak perf_event_print_debug(void) { }
583 extern __weak const char *perf_pmu_name(void)
588 static inline u64 perf_clock(void)
590 return local_clock();
593 static inline u64 perf_event_clock(struct perf_event *event)
595 return event->clock();
599 * State based event timekeeping...
601 * The basic idea is to use event->state to determine which (if any) time
602 * fields to increment with the current delta. This means we only need to
603 * update timestamps when we change state or when they are explicitly requested
606 * Event groups make things a little more complicated, but not terribly so. The
607 * rules for a group are that if the group leader is OFF the entire group is
608 * OFF, irrespecive of what the group member states are. This results in
609 * __perf_effective_state().
611 * A futher ramification is that when a group leader flips between OFF and
612 * !OFF, we need to update all group member times.
615 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
616 * need to make sure the relevant context time is updated before we try and
617 * update our timestamps.
620 static __always_inline enum perf_event_state
621 __perf_effective_state(struct perf_event *event)
623 struct perf_event *leader = event->group_leader;
625 if (leader->state <= PERF_EVENT_STATE_OFF)
626 return leader->state;
631 static __always_inline void
632 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
634 enum perf_event_state state = __perf_effective_state(event);
635 u64 delta = now - event->tstamp;
637 *enabled = event->total_time_enabled;
638 if (state >= PERF_EVENT_STATE_INACTIVE)
641 *running = event->total_time_running;
642 if (state >= PERF_EVENT_STATE_ACTIVE)
646 static void perf_event_update_time(struct perf_event *event)
648 u64 now = perf_event_time(event);
650 __perf_update_times(event, now, &event->total_time_enabled,
651 &event->total_time_running);
655 static void perf_event_update_sibling_time(struct perf_event *leader)
657 struct perf_event *sibling;
659 for_each_sibling_event(sibling, leader)
660 perf_event_update_time(sibling);
664 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
666 if (event->state == state)
669 perf_event_update_time(event);
671 * If a group leader gets enabled/disabled all its siblings
674 if ((event->state < 0) ^ (state < 0))
675 perf_event_update_sibling_time(event);
677 WRITE_ONCE(event->state, state);
680 #ifdef CONFIG_CGROUP_PERF
683 perf_cgroup_match(struct perf_event *event)
685 struct perf_event_context *ctx = event->ctx;
686 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
688 /* @event doesn't care about cgroup */
692 /* wants specific cgroup scope but @cpuctx isn't associated with any */
697 * Cgroup scoping is recursive. An event enabled for a cgroup is
698 * also enabled for all its descendant cgroups. If @cpuctx's
699 * cgroup is a descendant of @event's (the test covers identity
700 * case), it's a match.
702 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
703 event->cgrp->css.cgroup);
706 static inline void perf_detach_cgroup(struct perf_event *event)
708 css_put(&event->cgrp->css);
712 static inline int is_cgroup_event(struct perf_event *event)
714 return event->cgrp != NULL;
717 static inline u64 perf_cgroup_event_time(struct perf_event *event)
719 struct perf_cgroup_info *t;
721 t = per_cpu_ptr(event->cgrp->info, event->cpu);
725 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
727 struct perf_cgroup_info *info;
732 info = this_cpu_ptr(cgrp->info);
734 info->time += now - info->timestamp;
735 info->timestamp = now;
738 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
740 struct perf_cgroup *cgrp = cpuctx->cgrp;
741 struct cgroup_subsys_state *css;
744 for (css = &cgrp->css; css; css = css->parent) {
745 cgrp = container_of(css, struct perf_cgroup, css);
746 __update_cgrp_time(cgrp);
751 static inline void update_cgrp_time_from_event(struct perf_event *event)
753 struct perf_cgroup *cgrp;
756 * ensure we access cgroup data only when needed and
757 * when we know the cgroup is pinned (css_get)
759 if (!is_cgroup_event(event))
762 cgrp = perf_cgroup_from_task(current, event->ctx);
764 * Do not update time when cgroup is not active
766 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
767 __update_cgrp_time(event->cgrp);
771 perf_cgroup_set_timestamp(struct task_struct *task,
772 struct perf_event_context *ctx)
774 struct perf_cgroup *cgrp;
775 struct perf_cgroup_info *info;
776 struct cgroup_subsys_state *css;
779 * ctx->lock held by caller
780 * ensure we do not access cgroup data
781 * unless we have the cgroup pinned (css_get)
783 if (!task || !ctx->nr_cgroups)
786 cgrp = perf_cgroup_from_task(task, ctx);
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);
791 info->timestamp = ctx->timestamp;
795 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
797 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
798 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
801 * reschedule events based on the cgroup constraint of task.
803 * mode SWOUT : schedule out everything
804 * mode SWIN : schedule in based on cgroup for next
806 static void perf_cgroup_switch(struct task_struct *task, int mode)
808 struct perf_cpu_context *cpuctx;
809 struct list_head *list;
813 * Disable interrupts and preemption to avoid this CPU's
814 * cgrp_cpuctx_entry to change under us.
816 local_irq_save(flags);
818 list = this_cpu_ptr(&cgrp_cpuctx_list);
819 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
820 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
822 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
823 perf_pmu_disable(cpuctx->ctx.pmu);
825 if (mode & PERF_CGROUP_SWOUT) {
826 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
828 * must not be done before ctxswout due
829 * to event_filter_match() in event_sched_out()
834 if (mode & PERF_CGROUP_SWIN) {
835 WARN_ON_ONCE(cpuctx->cgrp);
837 * set cgrp before ctxsw in to allow
838 * event_filter_match() to not have to pass
840 * we pass the cpuctx->ctx to perf_cgroup_from_task()
841 * because cgorup events are only per-cpu
843 cpuctx->cgrp = perf_cgroup_from_task(task,
845 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
847 perf_pmu_enable(cpuctx->ctx.pmu);
848 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
851 local_irq_restore(flags);
854 static inline void perf_cgroup_sched_out(struct task_struct *task,
855 struct task_struct *next)
857 struct perf_cgroup *cgrp1;
858 struct perf_cgroup *cgrp2 = NULL;
862 * we come here when we know perf_cgroup_events > 0
863 * we do not need to pass the ctx here because we know
864 * we are holding the rcu lock
866 cgrp1 = perf_cgroup_from_task(task, NULL);
867 cgrp2 = perf_cgroup_from_task(next, NULL);
870 * only schedule out current cgroup events if we know
871 * that we are switching to a different cgroup. Otherwise,
872 * do no touch the cgroup events.
875 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
880 static inline void perf_cgroup_sched_in(struct task_struct *prev,
881 struct task_struct *task)
883 struct perf_cgroup *cgrp1;
884 struct perf_cgroup *cgrp2 = NULL;
888 * we come here when we know perf_cgroup_events > 0
889 * we do not need to pass the ctx here because we know
890 * we are holding the rcu lock
892 cgrp1 = perf_cgroup_from_task(task, NULL);
893 cgrp2 = perf_cgroup_from_task(prev, NULL);
896 * only need to schedule in cgroup events if we are changing
897 * cgroup during ctxsw. Cgroup events were not scheduled
898 * out of ctxsw out if that was not the case.
901 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
906 static int perf_cgroup_ensure_storage(struct perf_event *event,
907 struct cgroup_subsys_state *css)
909 struct perf_cpu_context *cpuctx;
910 struct perf_event **storage;
911 int cpu, heap_size, ret = 0;
914 * Allow storage to have sufficent space for an iterator for each
915 * possibly nested cgroup plus an iterator for events with no cgroup.
917 for (heap_size = 1; css; css = css->parent)
920 for_each_possible_cpu(cpu) {
921 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
922 if (heap_size <= cpuctx->heap_size)
925 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
926 GFP_KERNEL, cpu_to_node(cpu));
932 raw_spin_lock_irq(&cpuctx->ctx.lock);
933 if (cpuctx->heap_size < heap_size) {
934 swap(cpuctx->heap, storage);
935 if (storage == cpuctx->heap_default)
937 cpuctx->heap_size = heap_size;
939 raw_spin_unlock_irq(&cpuctx->ctx.lock);
947 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
948 struct perf_event_attr *attr,
949 struct perf_event *group_leader)
951 struct perf_cgroup *cgrp;
952 struct cgroup_subsys_state *css;
953 struct fd f = fdget(fd);
959 css = css_tryget_online_from_dir(f.file->f_path.dentry,
960 &perf_event_cgrp_subsys);
966 ret = perf_cgroup_ensure_storage(event, css);
970 cgrp = container_of(css, struct perf_cgroup, css);
974 * all events in a group must monitor
975 * the same cgroup because a task belongs
976 * to only one perf cgroup at a time
978 if (group_leader && group_leader->cgrp != cgrp) {
979 perf_detach_cgroup(event);
988 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
990 struct perf_cgroup_info *t;
991 t = per_cpu_ptr(event->cgrp->info, event->cpu);
992 event->shadow_ctx_time = now - t->timestamp;
996 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
998 struct perf_cpu_context *cpuctx;
1000 if (!is_cgroup_event(event))
1004 * Because cgroup events are always per-cpu events,
1005 * @ctx == &cpuctx->ctx.
1007 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1010 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1011 * matching the event's cgroup, we must do this for every new event,
1012 * because if the first would mismatch, the second would not try again
1013 * and we would leave cpuctx->cgrp unset.
1015 if (ctx->is_active && !cpuctx->cgrp) {
1016 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1018 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1019 cpuctx->cgrp = cgrp;
1022 if (ctx->nr_cgroups++)
1025 list_add(&cpuctx->cgrp_cpuctx_entry,
1026 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1030 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1032 struct perf_cpu_context *cpuctx;
1034 if (!is_cgroup_event(event))
1038 * Because cgroup events are always per-cpu events,
1039 * @ctx == &cpuctx->ctx.
1041 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1043 if (--ctx->nr_cgroups)
1046 if (ctx->is_active && cpuctx->cgrp)
1047 cpuctx->cgrp = NULL;
1049 list_del(&cpuctx->cgrp_cpuctx_entry);
1052 #else /* !CONFIG_CGROUP_PERF */
1055 perf_cgroup_match(struct perf_event *event)
1060 static inline void perf_detach_cgroup(struct perf_event *event)
1063 static inline int is_cgroup_event(struct perf_event *event)
1068 static inline void update_cgrp_time_from_event(struct perf_event *event)
1072 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1076 static inline void perf_cgroup_sched_out(struct task_struct *task,
1077 struct task_struct *next)
1081 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1082 struct task_struct *task)
1086 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1087 struct perf_event_attr *attr,
1088 struct perf_event *group_leader)
1094 perf_cgroup_set_timestamp(struct task_struct *task,
1095 struct perf_event_context *ctx)
1100 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1105 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1109 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1115 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1120 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1126 * set default to be dependent on timer tick just
1127 * like original code
1129 #define PERF_CPU_HRTIMER (1000 / HZ)
1131 * function must be called with interrupts disabled
1133 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1135 struct perf_cpu_context *cpuctx;
1138 lockdep_assert_irqs_disabled();
1140 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1141 rotations = perf_rotate_context(cpuctx);
1143 raw_spin_lock(&cpuctx->hrtimer_lock);
1145 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1147 cpuctx->hrtimer_active = 0;
1148 raw_spin_unlock(&cpuctx->hrtimer_lock);
1150 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1153 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1155 struct hrtimer *timer = &cpuctx->hrtimer;
1156 struct pmu *pmu = cpuctx->ctx.pmu;
1159 /* no multiplexing needed for SW PMU */
1160 if (pmu->task_ctx_nr == perf_sw_context)
1164 * check default is sane, if not set then force to
1165 * default interval (1/tick)
1167 interval = pmu->hrtimer_interval_ms;
1169 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1171 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1173 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1174 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1175 timer->function = perf_mux_hrtimer_handler;
1178 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1180 struct hrtimer *timer = &cpuctx->hrtimer;
1181 struct pmu *pmu = cpuctx->ctx.pmu;
1182 unsigned long flags;
1184 /* not for SW PMU */
1185 if (pmu->task_ctx_nr == perf_sw_context)
1188 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1189 if (!cpuctx->hrtimer_active) {
1190 cpuctx->hrtimer_active = 1;
1191 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1192 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1194 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1199 void perf_pmu_disable(struct pmu *pmu)
1201 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1203 pmu->pmu_disable(pmu);
1206 void perf_pmu_enable(struct pmu *pmu)
1208 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1210 pmu->pmu_enable(pmu);
1213 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1216 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1217 * perf_event_task_tick() are fully serialized because they're strictly cpu
1218 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1219 * disabled, while perf_event_task_tick is called from IRQ context.
1221 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1223 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1225 lockdep_assert_irqs_disabled();
1227 WARN_ON(!list_empty(&ctx->active_ctx_list));
1229 list_add(&ctx->active_ctx_list, head);
1232 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1234 lockdep_assert_irqs_disabled();
1236 WARN_ON(list_empty(&ctx->active_ctx_list));
1238 list_del_init(&ctx->active_ctx_list);
1241 static void get_ctx(struct perf_event_context *ctx)
1243 refcount_inc(&ctx->refcount);
1246 static void *alloc_task_ctx_data(struct pmu *pmu)
1248 if (pmu->task_ctx_cache)
1249 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1254 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1256 if (pmu->task_ctx_cache && task_ctx_data)
1257 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1260 static void free_ctx(struct rcu_head *head)
1262 struct perf_event_context *ctx;
1264 ctx = container_of(head, struct perf_event_context, rcu_head);
1265 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1269 static void put_ctx(struct perf_event_context *ctx)
1271 if (refcount_dec_and_test(&ctx->refcount)) {
1272 if (ctx->parent_ctx)
1273 put_ctx(ctx->parent_ctx);
1274 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1275 put_task_struct(ctx->task);
1276 call_rcu(&ctx->rcu_head, free_ctx);
1281 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1282 * perf_pmu_migrate_context() we need some magic.
1284 * Those places that change perf_event::ctx will hold both
1285 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1287 * Lock ordering is by mutex address. There are two other sites where
1288 * perf_event_context::mutex nests and those are:
1290 * - perf_event_exit_task_context() [ child , 0 ]
1291 * perf_event_exit_event()
1292 * put_event() [ parent, 1 ]
1294 * - perf_event_init_context() [ parent, 0 ]
1295 * inherit_task_group()
1298 * perf_event_alloc()
1300 * perf_try_init_event() [ child , 1 ]
1302 * While it appears there is an obvious deadlock here -- the parent and child
1303 * nesting levels are inverted between the two. This is in fact safe because
1304 * life-time rules separate them. That is an exiting task cannot fork, and a
1305 * spawning task cannot (yet) exit.
1307 * But remember that these are parent<->child context relations, and
1308 * migration does not affect children, therefore these two orderings should not
1311 * The change in perf_event::ctx does not affect children (as claimed above)
1312 * because the sys_perf_event_open() case will install a new event and break
1313 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1314 * concerned with cpuctx and that doesn't have children.
1316 * The places that change perf_event::ctx will issue:
1318 * perf_remove_from_context();
1319 * synchronize_rcu();
1320 * perf_install_in_context();
1322 * to affect the change. The remove_from_context() + synchronize_rcu() should
1323 * quiesce the event, after which we can install it in the new location. This
1324 * means that only external vectors (perf_fops, prctl) can perturb the event
1325 * while in transit. Therefore all such accessors should also acquire
1326 * perf_event_context::mutex to serialize against this.
1328 * However; because event->ctx can change while we're waiting to acquire
1329 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1334 * task_struct::perf_event_mutex
1335 * perf_event_context::mutex
1336 * perf_event::child_mutex;
1337 * perf_event_context::lock
1338 * perf_event::mmap_mutex
1340 * perf_addr_filters_head::lock
1344 * cpuctx->mutex / perf_event_context::mutex
1346 static struct perf_event_context *
1347 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1349 struct perf_event_context *ctx;
1353 ctx = READ_ONCE(event->ctx);
1354 if (!refcount_inc_not_zero(&ctx->refcount)) {
1360 mutex_lock_nested(&ctx->mutex, nesting);
1361 if (event->ctx != ctx) {
1362 mutex_unlock(&ctx->mutex);
1370 static inline struct perf_event_context *
1371 perf_event_ctx_lock(struct perf_event *event)
1373 return perf_event_ctx_lock_nested(event, 0);
1376 static void perf_event_ctx_unlock(struct perf_event *event,
1377 struct perf_event_context *ctx)
1379 mutex_unlock(&ctx->mutex);
1384 * This must be done under the ctx->lock, such as to serialize against
1385 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1386 * calling scheduler related locks and ctx->lock nests inside those.
1388 static __must_check struct perf_event_context *
1389 unclone_ctx(struct perf_event_context *ctx)
1391 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1393 lockdep_assert_held(&ctx->lock);
1396 ctx->parent_ctx = NULL;
1402 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1407 * only top level events have the pid namespace they were created in
1410 event = event->parent;
1412 nr = __task_pid_nr_ns(p, type, event->ns);
1413 /* avoid -1 if it is idle thread or runs in another ns */
1414 if (!nr && !pid_alive(p))
1419 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1421 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1424 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1426 return perf_event_pid_type(event, p, PIDTYPE_PID);
1430 * If we inherit events we want to return the parent event id
1433 static u64 primary_event_id(struct perf_event *event)
1438 id = event->parent->id;
1444 * Get the perf_event_context for a task and lock it.
1446 * This has to cope with the fact that until it is locked,
1447 * the context could get moved to another task.
1449 static struct perf_event_context *
1450 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1452 struct perf_event_context *ctx;
1456 * One of the few rules of preemptible RCU is that one cannot do
1457 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1458 * part of the read side critical section was irqs-enabled -- see
1459 * rcu_read_unlock_special().
1461 * Since ctx->lock nests under rq->lock we must ensure the entire read
1462 * side critical section has interrupts disabled.
1464 local_irq_save(*flags);
1466 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1469 * If this context is a clone of another, it might
1470 * get swapped for another underneath us by
1471 * perf_event_task_sched_out, though the
1472 * rcu_read_lock() protects us from any context
1473 * getting freed. Lock the context and check if it
1474 * got swapped before we could get the lock, and retry
1475 * if so. If we locked the right context, then it
1476 * can't get swapped on us any more.
1478 raw_spin_lock(&ctx->lock);
1479 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1480 raw_spin_unlock(&ctx->lock);
1482 local_irq_restore(*flags);
1486 if (ctx->task == TASK_TOMBSTONE ||
1487 !refcount_inc_not_zero(&ctx->refcount)) {
1488 raw_spin_unlock(&ctx->lock);
1491 WARN_ON_ONCE(ctx->task != task);
1496 local_irq_restore(*flags);
1501 * Get the context for a task and increment its pin_count so it
1502 * can't get swapped to another task. This also increments its
1503 * reference count so that the context can't get freed.
1505 static struct perf_event_context *
1506 perf_pin_task_context(struct task_struct *task, int ctxn)
1508 struct perf_event_context *ctx;
1509 unsigned long flags;
1511 ctx = perf_lock_task_context(task, ctxn, &flags);
1514 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1519 static void perf_unpin_context(struct perf_event_context *ctx)
1521 unsigned long flags;
1523 raw_spin_lock_irqsave(&ctx->lock, flags);
1525 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1529 * Update the record of the current time in a context.
1531 static void update_context_time(struct perf_event_context *ctx)
1533 u64 now = perf_clock();
1535 ctx->time += now - ctx->timestamp;
1536 ctx->timestamp = now;
1539 static u64 perf_event_time(struct perf_event *event)
1541 struct perf_event_context *ctx = event->ctx;
1543 if (is_cgroup_event(event))
1544 return perf_cgroup_event_time(event);
1546 return ctx ? ctx->time : 0;
1549 static enum event_type_t get_event_type(struct perf_event *event)
1551 struct perf_event_context *ctx = event->ctx;
1552 enum event_type_t event_type;
1554 lockdep_assert_held(&ctx->lock);
1557 * It's 'group type', really, because if our group leader is
1558 * pinned, so are we.
1560 if (event->group_leader != event)
1561 event = event->group_leader;
1563 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1565 event_type |= EVENT_CPU;
1571 * Helper function to initialize event group nodes.
1573 static void init_event_group(struct perf_event *event)
1575 RB_CLEAR_NODE(&event->group_node);
1576 event->group_index = 0;
1580 * Extract pinned or flexible groups from the context
1581 * based on event attrs bits.
1583 static struct perf_event_groups *
1584 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1586 if (event->attr.pinned)
1587 return &ctx->pinned_groups;
1589 return &ctx->flexible_groups;
1593 * Helper function to initializes perf_event_group trees.
1595 static void perf_event_groups_init(struct perf_event_groups *groups)
1597 groups->tree = RB_ROOT;
1601 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1603 struct cgroup *cgroup = NULL;
1605 #ifdef CONFIG_CGROUP_PERF
1607 cgroup = event->cgrp->css.cgroup;
1614 * Compare function for event groups;
1616 * Implements complex key that first sorts by CPU and then by virtual index
1617 * which provides ordering when rotating groups for the same CPU.
1619 static __always_inline int
1620 perf_event_groups_cmp(const int left_cpu, const struct cgroup *left_cgroup,
1621 const u64 left_group_index, const struct perf_event *right)
1623 if (left_cpu < right->cpu)
1625 if (left_cpu > right->cpu)
1628 #ifdef CONFIG_CGROUP_PERF
1630 const struct cgroup *right_cgroup = event_cgroup(right);
1632 if (left_cgroup != right_cgroup) {
1635 * Left has no cgroup but right does, no
1636 * cgroups come first.
1640 if (!right_cgroup) {
1642 * Right has no cgroup but left does, no
1643 * cgroups come first.
1647 /* Two dissimilar cgroups, order by id. */
1648 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1656 if (left_group_index < right->group_index)
1658 if (left_group_index > right->group_index)
1664 #define __node_2_pe(node) \
1665 rb_entry((node), struct perf_event, group_node)
1667 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1669 struct perf_event *e = __node_2_pe(a);
1670 return perf_event_groups_cmp(e->cpu, event_cgroup(e), e->group_index,
1671 __node_2_pe(b)) < 0;
1674 struct __group_key {
1676 struct cgroup *cgroup;
1679 static inline int __group_cmp(const void *key, const struct rb_node *node)
1681 const struct __group_key *a = key;
1682 const struct perf_event *b = __node_2_pe(node);
1684 /* partial/subtree match: @cpu, @cgroup; ignore: @group_index */
1685 return perf_event_groups_cmp(a->cpu, a->cgroup, b->group_index, b);
1689 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1690 * key (see perf_event_groups_less). This places it last inside the CPU
1694 perf_event_groups_insert(struct perf_event_groups *groups,
1695 struct perf_event *event)
1697 event->group_index = ++groups->index;
1699 rb_add(&event->group_node, &groups->tree, __group_less);
1703 * Helper function to insert event into the pinned or flexible groups.
1706 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1708 struct perf_event_groups *groups;
1710 groups = get_event_groups(event, ctx);
1711 perf_event_groups_insert(groups, event);
1715 * Delete a group from a tree.
1718 perf_event_groups_delete(struct perf_event_groups *groups,
1719 struct perf_event *event)
1721 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1722 RB_EMPTY_ROOT(&groups->tree));
1724 rb_erase(&event->group_node, &groups->tree);
1725 init_event_group(event);
1729 * Helper function to delete event from its groups.
1732 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1734 struct perf_event_groups *groups;
1736 groups = get_event_groups(event, ctx);
1737 perf_event_groups_delete(groups, event);
1741 * Get the leftmost event in the cpu/cgroup subtree.
1743 static struct perf_event *
1744 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1745 struct cgroup *cgrp)
1747 struct __group_key key = {
1751 struct rb_node *node;
1753 node = rb_find_first(&key, &groups->tree, __group_cmp);
1755 return __node_2_pe(node);
1761 * Like rb_entry_next_safe() for the @cpu subtree.
1763 static struct perf_event *
1764 perf_event_groups_next(struct perf_event *event)
1766 struct __group_key key = {
1768 .cgroup = event_cgroup(event),
1770 struct rb_node *next;
1772 next = rb_next_match(&key, &event->group_node, __group_cmp);
1774 return __node_2_pe(next);
1780 * Iterate through the whole groups tree.
1782 #define perf_event_groups_for_each(event, groups) \
1783 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1784 typeof(*event), group_node); event; \
1785 event = rb_entry_safe(rb_next(&event->group_node), \
1786 typeof(*event), group_node))
1789 * Add an event from the lists for its context.
1790 * Must be called with ctx->mutex and ctx->lock held.
1793 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1795 lockdep_assert_held(&ctx->lock);
1797 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1798 event->attach_state |= PERF_ATTACH_CONTEXT;
1800 event->tstamp = perf_event_time(event);
1803 * If we're a stand alone event or group leader, we go to the context
1804 * list, group events are kept attached to the group so that
1805 * perf_group_detach can, at all times, locate all siblings.
1807 if (event->group_leader == event) {
1808 event->group_caps = event->event_caps;
1809 add_event_to_groups(event, ctx);
1812 list_add_rcu(&event->event_entry, &ctx->event_list);
1814 if (event->attr.inherit_stat)
1817 if (event->state > PERF_EVENT_STATE_OFF)
1818 perf_cgroup_event_enable(event, ctx);
1824 * Initialize event state based on the perf_event_attr::disabled.
1826 static inline void perf_event__state_init(struct perf_event *event)
1828 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1829 PERF_EVENT_STATE_INACTIVE;
1832 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1834 int entry = sizeof(u64); /* value */
1838 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1839 size += sizeof(u64);
1841 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1842 size += sizeof(u64);
1844 if (event->attr.read_format & PERF_FORMAT_ID)
1845 entry += sizeof(u64);
1847 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1849 size += sizeof(u64);
1853 event->read_size = size;
1856 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1858 struct perf_sample_data *data;
1861 if (sample_type & PERF_SAMPLE_IP)
1862 size += sizeof(data->ip);
1864 if (sample_type & PERF_SAMPLE_ADDR)
1865 size += sizeof(data->addr);
1867 if (sample_type & PERF_SAMPLE_PERIOD)
1868 size += sizeof(data->period);
1870 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1871 size += sizeof(data->weight.full);
1873 if (sample_type & PERF_SAMPLE_READ)
1874 size += event->read_size;
1876 if (sample_type & PERF_SAMPLE_DATA_SRC)
1877 size += sizeof(data->data_src.val);
1879 if (sample_type & PERF_SAMPLE_TRANSACTION)
1880 size += sizeof(data->txn);
1882 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1883 size += sizeof(data->phys_addr);
1885 if (sample_type & PERF_SAMPLE_CGROUP)
1886 size += sizeof(data->cgroup);
1888 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1889 size += sizeof(data->data_page_size);
1891 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1892 size += sizeof(data->code_page_size);
1894 event->header_size = size;
1898 * Called at perf_event creation and when events are attached/detached from a
1901 static void perf_event__header_size(struct perf_event *event)
1903 __perf_event_read_size(event,
1904 event->group_leader->nr_siblings);
1905 __perf_event_header_size(event, event->attr.sample_type);
1908 static void perf_event__id_header_size(struct perf_event *event)
1910 struct perf_sample_data *data;
1911 u64 sample_type = event->attr.sample_type;
1914 if (sample_type & PERF_SAMPLE_TID)
1915 size += sizeof(data->tid_entry);
1917 if (sample_type & PERF_SAMPLE_TIME)
1918 size += sizeof(data->time);
1920 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1921 size += sizeof(data->id);
1923 if (sample_type & PERF_SAMPLE_ID)
1924 size += sizeof(data->id);
1926 if (sample_type & PERF_SAMPLE_STREAM_ID)
1927 size += sizeof(data->stream_id);
1929 if (sample_type & PERF_SAMPLE_CPU)
1930 size += sizeof(data->cpu_entry);
1932 event->id_header_size = size;
1935 static bool perf_event_validate_size(struct perf_event *event)
1938 * The values computed here will be over-written when we actually
1941 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1942 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1943 perf_event__id_header_size(event);
1946 * Sum the lot; should not exceed the 64k limit we have on records.
1947 * Conservative limit to allow for callchains and other variable fields.
1949 if (event->read_size + event->header_size +
1950 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1956 static void perf_group_attach(struct perf_event *event)
1958 struct perf_event *group_leader = event->group_leader, *pos;
1960 lockdep_assert_held(&event->ctx->lock);
1963 * We can have double attach due to group movement in perf_event_open.
1965 if (event->attach_state & PERF_ATTACH_GROUP)
1968 event->attach_state |= PERF_ATTACH_GROUP;
1970 if (group_leader == event)
1973 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1975 group_leader->group_caps &= event->event_caps;
1977 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1978 group_leader->nr_siblings++;
1980 perf_event__header_size(group_leader);
1982 for_each_sibling_event(pos, group_leader)
1983 perf_event__header_size(pos);
1987 * Remove an event from the lists for its context.
1988 * Must be called with ctx->mutex and ctx->lock held.
1991 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1993 WARN_ON_ONCE(event->ctx != ctx);
1994 lockdep_assert_held(&ctx->lock);
1997 * We can have double detach due to exit/hot-unplug + close.
1999 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2002 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2005 if (event->attr.inherit_stat)
2008 list_del_rcu(&event->event_entry);
2010 if (event->group_leader == event)
2011 del_event_from_groups(event, ctx);
2014 * If event was in error state, then keep it
2015 * that way, otherwise bogus counts will be
2016 * returned on read(). The only way to get out
2017 * of error state is by explicit re-enabling
2020 if (event->state > PERF_EVENT_STATE_OFF) {
2021 perf_cgroup_event_disable(event, ctx);
2022 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2029 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2031 if (!has_aux(aux_event))
2034 if (!event->pmu->aux_output_match)
2037 return event->pmu->aux_output_match(aux_event);
2040 static void put_event(struct perf_event *event);
2041 static void event_sched_out(struct perf_event *event,
2042 struct perf_cpu_context *cpuctx,
2043 struct perf_event_context *ctx);
2045 static void perf_put_aux_event(struct perf_event *event)
2047 struct perf_event_context *ctx = event->ctx;
2048 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2049 struct perf_event *iter;
2052 * If event uses aux_event tear down the link
2054 if (event->aux_event) {
2055 iter = event->aux_event;
2056 event->aux_event = NULL;
2062 * If the event is an aux_event, tear down all links to
2063 * it from other events.
2065 for_each_sibling_event(iter, event->group_leader) {
2066 if (iter->aux_event != event)
2069 iter->aux_event = NULL;
2073 * If it's ACTIVE, schedule it out and put it into ERROR
2074 * state so that we don't try to schedule it again. Note
2075 * that perf_event_enable() will clear the ERROR status.
2077 event_sched_out(iter, cpuctx, ctx);
2078 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2082 static bool perf_need_aux_event(struct perf_event *event)
2084 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2087 static int perf_get_aux_event(struct perf_event *event,
2088 struct perf_event *group_leader)
2091 * Our group leader must be an aux event if we want to be
2092 * an aux_output. This way, the aux event will precede its
2093 * aux_output events in the group, and therefore will always
2100 * aux_output and aux_sample_size are mutually exclusive.
2102 if (event->attr.aux_output && event->attr.aux_sample_size)
2105 if (event->attr.aux_output &&
2106 !perf_aux_output_match(event, group_leader))
2109 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2112 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2116 * Link aux_outputs to their aux event; this is undone in
2117 * perf_group_detach() by perf_put_aux_event(). When the
2118 * group in torn down, the aux_output events loose their
2119 * link to the aux_event and can't schedule any more.
2121 event->aux_event = group_leader;
2126 static inline struct list_head *get_event_list(struct perf_event *event)
2128 struct perf_event_context *ctx = event->ctx;
2129 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2133 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2134 * cannot exist on their own, schedule them out and move them into the ERROR
2135 * state. Also see _perf_event_enable(), it will not be able to recover
2138 static inline void perf_remove_sibling_event(struct perf_event *event)
2140 struct perf_event_context *ctx = event->ctx;
2141 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2143 event_sched_out(event, cpuctx, ctx);
2144 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2147 static void perf_group_detach(struct perf_event *event)
2149 struct perf_event *leader = event->group_leader;
2150 struct perf_event *sibling, *tmp;
2151 struct perf_event_context *ctx = event->ctx;
2153 lockdep_assert_held(&ctx->lock);
2156 * We can have double detach due to exit/hot-unplug + close.
2158 if (!(event->attach_state & PERF_ATTACH_GROUP))
2161 event->attach_state &= ~PERF_ATTACH_GROUP;
2163 perf_put_aux_event(event);
2166 * If this is a sibling, remove it from its group.
2168 if (leader != event) {
2169 list_del_init(&event->sibling_list);
2170 event->group_leader->nr_siblings--;
2175 * If this was a group event with sibling events then
2176 * upgrade the siblings to singleton events by adding them
2177 * to whatever list we are on.
2179 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2181 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2182 perf_remove_sibling_event(sibling);
2184 sibling->group_leader = sibling;
2185 list_del_init(&sibling->sibling_list);
2187 /* Inherit group flags from the previous leader */
2188 sibling->group_caps = event->group_caps;
2190 if (!RB_EMPTY_NODE(&event->group_node)) {
2191 add_event_to_groups(sibling, event->ctx);
2193 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2194 list_add_tail(&sibling->active_list, get_event_list(sibling));
2197 WARN_ON_ONCE(sibling->ctx != event->ctx);
2201 for_each_sibling_event(tmp, leader)
2202 perf_event__header_size(tmp);
2204 perf_event__header_size(leader);
2207 static bool is_orphaned_event(struct perf_event *event)
2209 return event->state == PERF_EVENT_STATE_DEAD;
2212 static inline int __pmu_filter_match(struct perf_event *event)
2214 struct pmu *pmu = event->pmu;
2215 return pmu->filter_match ? pmu->filter_match(event) : 1;
2219 * Check whether we should attempt to schedule an event group based on
2220 * PMU-specific filtering. An event group can consist of HW and SW events,
2221 * potentially with a SW leader, so we must check all the filters, to
2222 * determine whether a group is schedulable:
2224 static inline int pmu_filter_match(struct perf_event *event)
2226 struct perf_event *sibling;
2228 if (!__pmu_filter_match(event))
2231 for_each_sibling_event(sibling, event) {
2232 if (!__pmu_filter_match(sibling))
2240 event_filter_match(struct perf_event *event)
2242 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2243 perf_cgroup_match(event) && pmu_filter_match(event);
2247 event_sched_out(struct perf_event *event,
2248 struct perf_cpu_context *cpuctx,
2249 struct perf_event_context *ctx)
2251 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2253 WARN_ON_ONCE(event->ctx != ctx);
2254 lockdep_assert_held(&ctx->lock);
2256 if (event->state != PERF_EVENT_STATE_ACTIVE)
2260 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2261 * we can schedule events _OUT_ individually through things like
2262 * __perf_remove_from_context().
2264 list_del_init(&event->active_list);
2266 perf_pmu_disable(event->pmu);
2268 event->pmu->del(event, 0);
2271 if (READ_ONCE(event->pending_disable) >= 0) {
2272 WRITE_ONCE(event->pending_disable, -1);
2273 perf_cgroup_event_disable(event, ctx);
2274 state = PERF_EVENT_STATE_OFF;
2276 perf_event_set_state(event, state);
2278 if (!is_software_event(event))
2279 cpuctx->active_oncpu--;
2280 if (!--ctx->nr_active)
2281 perf_event_ctx_deactivate(ctx);
2282 if (event->attr.freq && event->attr.sample_freq)
2284 if (event->attr.exclusive || !cpuctx->active_oncpu)
2285 cpuctx->exclusive = 0;
2287 perf_pmu_enable(event->pmu);
2291 group_sched_out(struct perf_event *group_event,
2292 struct perf_cpu_context *cpuctx,
2293 struct perf_event_context *ctx)
2295 struct perf_event *event;
2297 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2300 perf_pmu_disable(ctx->pmu);
2302 event_sched_out(group_event, cpuctx, ctx);
2305 * Schedule out siblings (if any):
2307 for_each_sibling_event(event, group_event)
2308 event_sched_out(event, cpuctx, ctx);
2310 perf_pmu_enable(ctx->pmu);
2313 #define DETACH_GROUP 0x01UL
2316 * Cross CPU call to remove a performance event
2318 * We disable the event on the hardware level first. After that we
2319 * remove it from the context list.
2322 __perf_remove_from_context(struct perf_event *event,
2323 struct perf_cpu_context *cpuctx,
2324 struct perf_event_context *ctx,
2327 unsigned long flags = (unsigned long)info;
2329 if (ctx->is_active & EVENT_TIME) {
2330 update_context_time(ctx);
2331 update_cgrp_time_from_cpuctx(cpuctx);
2334 event_sched_out(event, cpuctx, ctx);
2335 if (flags & DETACH_GROUP)
2336 perf_group_detach(event);
2337 list_del_event(event, ctx);
2339 if (!ctx->nr_events && ctx->is_active) {
2341 ctx->rotate_necessary = 0;
2343 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2344 cpuctx->task_ctx = NULL;
2350 * Remove the event from a task's (or a CPU's) list of events.
2352 * If event->ctx is a cloned context, callers must make sure that
2353 * every task struct that event->ctx->task could possibly point to
2354 * remains valid. This is OK when called from perf_release since
2355 * that only calls us on the top-level context, which can't be a clone.
2356 * When called from perf_event_exit_task, it's OK because the
2357 * context has been detached from its task.
2359 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2361 struct perf_event_context *ctx = event->ctx;
2363 lockdep_assert_held(&ctx->mutex);
2365 event_function_call(event, __perf_remove_from_context, (void *)flags);
2368 * The above event_function_call() can NO-OP when it hits
2369 * TASK_TOMBSTONE. In that case we must already have been detached
2370 * from the context (by perf_event_exit_event()) but the grouping
2371 * might still be in-tact.
2373 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2374 if ((flags & DETACH_GROUP) &&
2375 (event->attach_state & PERF_ATTACH_GROUP)) {
2377 * Since in that case we cannot possibly be scheduled, simply
2380 raw_spin_lock_irq(&ctx->lock);
2381 perf_group_detach(event);
2382 raw_spin_unlock_irq(&ctx->lock);
2387 * Cross CPU call to disable a performance event
2389 static void __perf_event_disable(struct perf_event *event,
2390 struct perf_cpu_context *cpuctx,
2391 struct perf_event_context *ctx,
2394 if (event->state < PERF_EVENT_STATE_INACTIVE)
2397 if (ctx->is_active & EVENT_TIME) {
2398 update_context_time(ctx);
2399 update_cgrp_time_from_event(event);
2402 if (event == event->group_leader)
2403 group_sched_out(event, cpuctx, ctx);
2405 event_sched_out(event, cpuctx, ctx);
2407 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2408 perf_cgroup_event_disable(event, ctx);
2414 * If event->ctx is a cloned context, callers must make sure that
2415 * every task struct that event->ctx->task could possibly point to
2416 * remains valid. This condition is satisfied when called through
2417 * perf_event_for_each_child or perf_event_for_each because they
2418 * hold the top-level event's child_mutex, so any descendant that
2419 * goes to exit will block in perf_event_exit_event().
2421 * When called from perf_pending_event it's OK because event->ctx
2422 * is the current context on this CPU and preemption is disabled,
2423 * hence we can't get into perf_event_task_sched_out for this context.
2425 static void _perf_event_disable(struct perf_event *event)
2427 struct perf_event_context *ctx = event->ctx;
2429 raw_spin_lock_irq(&ctx->lock);
2430 if (event->state <= PERF_EVENT_STATE_OFF) {
2431 raw_spin_unlock_irq(&ctx->lock);
2434 raw_spin_unlock_irq(&ctx->lock);
2436 event_function_call(event, __perf_event_disable, NULL);
2439 void perf_event_disable_local(struct perf_event *event)
2441 event_function_local(event, __perf_event_disable, NULL);
2445 * Strictly speaking kernel users cannot create groups and therefore this
2446 * interface does not need the perf_event_ctx_lock() magic.
2448 void perf_event_disable(struct perf_event *event)
2450 struct perf_event_context *ctx;
2452 ctx = perf_event_ctx_lock(event);
2453 _perf_event_disable(event);
2454 perf_event_ctx_unlock(event, ctx);
2456 EXPORT_SYMBOL_GPL(perf_event_disable);
2458 void perf_event_disable_inatomic(struct perf_event *event)
2460 WRITE_ONCE(event->pending_disable, smp_processor_id());
2461 /* can fail, see perf_pending_event_disable() */
2462 irq_work_queue(&event->pending);
2465 static void perf_set_shadow_time(struct perf_event *event,
2466 struct perf_event_context *ctx)
2469 * use the correct time source for the time snapshot
2471 * We could get by without this by leveraging the
2472 * fact that to get to this function, the caller
2473 * has most likely already called update_context_time()
2474 * and update_cgrp_time_xx() and thus both timestamp
2475 * are identical (or very close). Given that tstamp is,
2476 * already adjusted for cgroup, we could say that:
2477 * tstamp - ctx->timestamp
2479 * tstamp - cgrp->timestamp.
2481 * Then, in perf_output_read(), the calculation would
2482 * work with no changes because:
2483 * - event is guaranteed scheduled in
2484 * - no scheduled out in between
2485 * - thus the timestamp would be the same
2487 * But this is a bit hairy.
2489 * So instead, we have an explicit cgroup call to remain
2490 * within the time source all along. We believe it
2491 * is cleaner and simpler to understand.
2493 if (is_cgroup_event(event))
2494 perf_cgroup_set_shadow_time(event, event->tstamp);
2496 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2499 #define MAX_INTERRUPTS (~0ULL)
2501 static void perf_log_throttle(struct perf_event *event, int enable);
2502 static void perf_log_itrace_start(struct perf_event *event);
2505 event_sched_in(struct perf_event *event,
2506 struct perf_cpu_context *cpuctx,
2507 struct perf_event_context *ctx)
2511 WARN_ON_ONCE(event->ctx != ctx);
2513 lockdep_assert_held(&ctx->lock);
2515 if (event->state <= PERF_EVENT_STATE_OFF)
2518 WRITE_ONCE(event->oncpu, smp_processor_id());
2520 * Order event::oncpu write to happen before the ACTIVE state is
2521 * visible. This allows perf_event_{stop,read}() to observe the correct
2522 * ->oncpu if it sees ACTIVE.
2525 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2528 * Unthrottle events, since we scheduled we might have missed several
2529 * ticks already, also for a heavily scheduling task there is little
2530 * guarantee it'll get a tick in a timely manner.
2532 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2533 perf_log_throttle(event, 1);
2534 event->hw.interrupts = 0;
2537 perf_pmu_disable(event->pmu);
2539 perf_set_shadow_time(event, ctx);
2541 perf_log_itrace_start(event);
2543 if (event->pmu->add(event, PERF_EF_START)) {
2544 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2550 if (!is_software_event(event))
2551 cpuctx->active_oncpu++;
2552 if (!ctx->nr_active++)
2553 perf_event_ctx_activate(ctx);
2554 if (event->attr.freq && event->attr.sample_freq)
2557 if (event->attr.exclusive)
2558 cpuctx->exclusive = 1;
2561 perf_pmu_enable(event->pmu);
2567 group_sched_in(struct perf_event *group_event,
2568 struct perf_cpu_context *cpuctx,
2569 struct perf_event_context *ctx)
2571 struct perf_event *event, *partial_group = NULL;
2572 struct pmu *pmu = ctx->pmu;
2574 if (group_event->state == PERF_EVENT_STATE_OFF)
2577 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2579 if (event_sched_in(group_event, cpuctx, ctx))
2583 * Schedule in siblings as one group (if any):
2585 for_each_sibling_event(event, group_event) {
2586 if (event_sched_in(event, cpuctx, ctx)) {
2587 partial_group = event;
2592 if (!pmu->commit_txn(pmu))
2597 * Groups can be scheduled in as one unit only, so undo any
2598 * partial group before returning:
2599 * The events up to the failed event are scheduled out normally.
2601 for_each_sibling_event(event, group_event) {
2602 if (event == partial_group)
2605 event_sched_out(event, cpuctx, ctx);
2607 event_sched_out(group_event, cpuctx, ctx);
2610 pmu->cancel_txn(pmu);
2615 * Work out whether we can put this event group on the CPU now.
2617 static int group_can_go_on(struct perf_event *event,
2618 struct perf_cpu_context *cpuctx,
2622 * Groups consisting entirely of software events can always go on.
2624 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2627 * If an exclusive group is already on, no other hardware
2630 if (cpuctx->exclusive)
2633 * If this group is exclusive and there are already
2634 * events on the CPU, it can't go on.
2636 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2639 * Otherwise, try to add it if all previous groups were able
2645 static void add_event_to_ctx(struct perf_event *event,
2646 struct perf_event_context *ctx)
2648 list_add_event(event, ctx);
2649 perf_group_attach(event);
2652 static void ctx_sched_out(struct perf_event_context *ctx,
2653 struct perf_cpu_context *cpuctx,
2654 enum event_type_t event_type);
2656 ctx_sched_in(struct perf_event_context *ctx,
2657 struct perf_cpu_context *cpuctx,
2658 enum event_type_t event_type,
2659 struct task_struct *task);
2661 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2662 struct perf_event_context *ctx,
2663 enum event_type_t event_type)
2665 if (!cpuctx->task_ctx)
2668 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2671 ctx_sched_out(ctx, cpuctx, event_type);
2674 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2675 struct perf_event_context *ctx,
2676 struct task_struct *task)
2678 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2680 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2681 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2683 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
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.
2701 static void ctx_resched(struct perf_cpu_context *cpuctx,
2702 struct perf_event_context *task_ctx,
2703 enum event_type_t event_type)
2705 enum event_type_t ctx_event_type;
2706 bool cpu_event = !!(event_type & EVENT_CPU);
2709 * If pinned groups are involved, flexible groups also need to be
2712 if (event_type & EVENT_PINNED)
2713 event_type |= EVENT_FLEXIBLE;
2715 ctx_event_type = event_type & EVENT_ALL;
2717 perf_pmu_disable(cpuctx->ctx.pmu);
2719 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2722 * Decide which cpu ctx groups to schedule out based on the types
2723 * of events that caused rescheduling:
2724 * - EVENT_CPU: schedule out corresponding groups;
2725 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2726 * - otherwise, do nothing more.
2729 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2730 else if (ctx_event_type & EVENT_PINNED)
2731 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2733 perf_event_sched_in(cpuctx, task_ctx, current);
2734 perf_pmu_enable(cpuctx->ctx.pmu);
2737 void perf_pmu_resched(struct pmu *pmu)
2739 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2740 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2742 perf_ctx_lock(cpuctx, task_ctx);
2743 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2744 perf_ctx_unlock(cpuctx, task_ctx);
2748 * Cross CPU call to install and enable a performance event
2750 * Very similar to remote_function() + event_function() but cannot assume that
2751 * things like ctx->is_active and cpuctx->task_ctx are set.
2753 static int __perf_install_in_context(void *info)
2755 struct perf_event *event = info;
2756 struct perf_event_context *ctx = event->ctx;
2757 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2758 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2759 bool reprogram = true;
2762 raw_spin_lock(&cpuctx->ctx.lock);
2764 raw_spin_lock(&ctx->lock);
2767 reprogram = (ctx->task == current);
2770 * If the task is running, it must be running on this CPU,
2771 * otherwise we cannot reprogram things.
2773 * If its not running, we don't care, ctx->lock will
2774 * serialize against it becoming runnable.
2776 if (task_curr(ctx->task) && !reprogram) {
2781 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2782 } else if (task_ctx) {
2783 raw_spin_lock(&task_ctx->lock);
2786 #ifdef CONFIG_CGROUP_PERF
2787 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2789 * If the current cgroup doesn't match the event's
2790 * cgroup, we should not try to schedule it.
2792 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2793 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2794 event->cgrp->css.cgroup);
2799 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2800 add_event_to_ctx(event, ctx);
2801 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2803 add_event_to_ctx(event, ctx);
2807 perf_ctx_unlock(cpuctx, task_ctx);
2812 static bool exclusive_event_installable(struct perf_event *event,
2813 struct perf_event_context *ctx);
2816 * Attach a performance event to a context.
2818 * Very similar to event_function_call, see comment there.
2821 perf_install_in_context(struct perf_event_context *ctx,
2822 struct perf_event *event,
2825 struct task_struct *task = READ_ONCE(ctx->task);
2827 lockdep_assert_held(&ctx->mutex);
2829 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2831 if (event->cpu != -1)
2835 * Ensures that if we can observe event->ctx, both the event and ctx
2836 * will be 'complete'. See perf_iterate_sb_cpu().
2838 smp_store_release(&event->ctx, ctx);
2841 * perf_event_attr::disabled events will not run and can be initialized
2842 * without IPI. Except when this is the first event for the context, in
2843 * that case we need the magic of the IPI to set ctx->is_active.
2845 * The IOC_ENABLE that is sure to follow the creation of a disabled
2846 * event will issue the IPI and reprogram the hardware.
2848 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2849 raw_spin_lock_irq(&ctx->lock);
2850 if (ctx->task == TASK_TOMBSTONE) {
2851 raw_spin_unlock_irq(&ctx->lock);
2854 add_event_to_ctx(event, ctx);
2855 raw_spin_unlock_irq(&ctx->lock);
2860 cpu_function_call(cpu, __perf_install_in_context, event);
2865 * Should not happen, we validate the ctx is still alive before calling.
2867 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2871 * Installing events is tricky because we cannot rely on ctx->is_active
2872 * to be set in case this is the nr_events 0 -> 1 transition.
2874 * Instead we use task_curr(), which tells us if the task is running.
2875 * However, since we use task_curr() outside of rq::lock, we can race
2876 * against the actual state. This means the result can be wrong.
2878 * If we get a false positive, we retry, this is harmless.
2880 * If we get a false negative, things are complicated. If we are after
2881 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2882 * value must be correct. If we're before, it doesn't matter since
2883 * perf_event_context_sched_in() will program the counter.
2885 * However, this hinges on the remote context switch having observed
2886 * our task->perf_event_ctxp[] store, such that it will in fact take
2887 * ctx::lock in perf_event_context_sched_in().
2889 * We do this by task_function_call(), if the IPI fails to hit the task
2890 * we know any future context switch of task must see the
2891 * perf_event_ctpx[] store.
2895 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2896 * task_cpu() load, such that if the IPI then does not find the task
2897 * running, a future context switch of that task must observe the
2902 if (!task_function_call(task, __perf_install_in_context, event))
2905 raw_spin_lock_irq(&ctx->lock);
2907 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2909 * Cannot happen because we already checked above (which also
2910 * cannot happen), and we hold ctx->mutex, which serializes us
2911 * against perf_event_exit_task_context().
2913 raw_spin_unlock_irq(&ctx->lock);
2917 * If the task is not running, ctx->lock will avoid it becoming so,
2918 * thus we can safely install the event.
2920 if (task_curr(task)) {
2921 raw_spin_unlock_irq(&ctx->lock);
2924 add_event_to_ctx(event, ctx);
2925 raw_spin_unlock_irq(&ctx->lock);
2929 * Cross CPU call to enable a performance event
2931 static void __perf_event_enable(struct perf_event *event,
2932 struct perf_cpu_context *cpuctx,
2933 struct perf_event_context *ctx,
2936 struct perf_event *leader = event->group_leader;
2937 struct perf_event_context *task_ctx;
2939 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2940 event->state <= PERF_EVENT_STATE_ERROR)
2944 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2946 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2947 perf_cgroup_event_enable(event, ctx);
2949 if (!ctx->is_active)
2952 if (!event_filter_match(event)) {
2953 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2958 * If the event is in a group and isn't the group leader,
2959 * then don't put it on unless the group is on.
2961 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2962 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2966 task_ctx = cpuctx->task_ctx;
2968 WARN_ON_ONCE(task_ctx != ctx);
2970 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2976 * If event->ctx is a cloned context, callers must make sure that
2977 * every task struct that event->ctx->task could possibly point to
2978 * remains valid. This condition is satisfied when called through
2979 * perf_event_for_each_child or perf_event_for_each as described
2980 * for perf_event_disable.
2982 static void _perf_event_enable(struct perf_event *event)
2984 struct perf_event_context *ctx = event->ctx;
2986 raw_spin_lock_irq(&ctx->lock);
2987 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2988 event->state < PERF_EVENT_STATE_ERROR) {
2990 raw_spin_unlock_irq(&ctx->lock);
2995 * If the event is in error state, clear that first.
2997 * That way, if we see the event in error state below, we know that it
2998 * has gone back into error state, as distinct from the task having
2999 * been scheduled away before the cross-call arrived.
3001 if (event->state == PERF_EVENT_STATE_ERROR) {
3003 * Detached SIBLING events cannot leave ERROR state.
3005 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3006 event->group_leader == event)
3009 event->state = PERF_EVENT_STATE_OFF;
3011 raw_spin_unlock_irq(&ctx->lock);
3013 event_function_call(event, __perf_event_enable, NULL);
3017 * See perf_event_disable();
3019 void perf_event_enable(struct perf_event *event)
3021 struct perf_event_context *ctx;
3023 ctx = perf_event_ctx_lock(event);
3024 _perf_event_enable(event);
3025 perf_event_ctx_unlock(event, ctx);
3027 EXPORT_SYMBOL_GPL(perf_event_enable);
3029 struct stop_event_data {
3030 struct perf_event *event;
3031 unsigned int restart;
3034 static int __perf_event_stop(void *info)
3036 struct stop_event_data *sd = info;
3037 struct perf_event *event = sd->event;
3039 /* if it's already INACTIVE, do nothing */
3040 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3043 /* matches smp_wmb() in event_sched_in() */
3047 * There is a window with interrupts enabled before we get here,
3048 * so we need to check again lest we try to stop another CPU's event.
3050 if (READ_ONCE(event->oncpu) != smp_processor_id())
3053 event->pmu->stop(event, PERF_EF_UPDATE);
3056 * May race with the actual stop (through perf_pmu_output_stop()),
3057 * but it is only used for events with AUX ring buffer, and such
3058 * events will refuse to restart because of rb::aux_mmap_count==0,
3059 * see comments in perf_aux_output_begin().
3061 * Since this is happening on an event-local CPU, no trace is lost
3065 event->pmu->start(event, 0);
3070 static int perf_event_stop(struct perf_event *event, int restart)
3072 struct stop_event_data sd = {
3079 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3082 /* matches smp_wmb() in event_sched_in() */
3086 * We only want to restart ACTIVE events, so if the event goes
3087 * inactive here (event->oncpu==-1), there's nothing more to do;
3088 * fall through with ret==-ENXIO.
3090 ret = cpu_function_call(READ_ONCE(event->oncpu),
3091 __perf_event_stop, &sd);
3092 } while (ret == -EAGAIN);
3098 * In order to contain the amount of racy and tricky in the address filter
3099 * configuration management, it is a two part process:
3101 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3102 * we update the addresses of corresponding vmas in
3103 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3104 * (p2) when an event is scheduled in (pmu::add), it calls
3105 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3106 * if the generation has changed since the previous call.
3108 * If (p1) happens while the event is active, we restart it to force (p2).
3110 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3111 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3113 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3114 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3116 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3119 void perf_event_addr_filters_sync(struct perf_event *event)
3121 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3123 if (!has_addr_filter(event))
3126 raw_spin_lock(&ifh->lock);
3127 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3128 event->pmu->addr_filters_sync(event);
3129 event->hw.addr_filters_gen = event->addr_filters_gen;
3131 raw_spin_unlock(&ifh->lock);
3133 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3135 static int _perf_event_refresh(struct perf_event *event, int refresh)
3138 * not supported on inherited events
3140 if (event->attr.inherit || !is_sampling_event(event))
3143 atomic_add(refresh, &event->event_limit);
3144 _perf_event_enable(event);
3150 * See perf_event_disable()
3152 int perf_event_refresh(struct perf_event *event, int refresh)
3154 struct perf_event_context *ctx;
3157 ctx = perf_event_ctx_lock(event);
3158 ret = _perf_event_refresh(event, refresh);
3159 perf_event_ctx_unlock(event, ctx);
3163 EXPORT_SYMBOL_GPL(perf_event_refresh);
3165 static int perf_event_modify_breakpoint(struct perf_event *bp,
3166 struct perf_event_attr *attr)
3170 _perf_event_disable(bp);
3172 err = modify_user_hw_breakpoint_check(bp, attr, true);
3174 if (!bp->attr.disabled)
3175 _perf_event_enable(bp);
3180 static int perf_event_modify_attr(struct perf_event *event,
3181 struct perf_event_attr *attr)
3183 if (event->attr.type != attr->type)
3186 switch (event->attr.type) {
3187 case PERF_TYPE_BREAKPOINT:
3188 return perf_event_modify_breakpoint(event, attr);
3190 /* Place holder for future additions. */
3195 static void ctx_sched_out(struct perf_event_context *ctx,
3196 struct perf_cpu_context *cpuctx,
3197 enum event_type_t event_type)
3199 struct perf_event *event, *tmp;
3200 int is_active = ctx->is_active;
3202 lockdep_assert_held(&ctx->lock);
3204 if (likely(!ctx->nr_events)) {
3206 * See __perf_remove_from_context().
3208 WARN_ON_ONCE(ctx->is_active);
3210 WARN_ON_ONCE(cpuctx->task_ctx);
3214 ctx->is_active &= ~event_type;
3215 if (!(ctx->is_active & EVENT_ALL))
3219 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3220 if (!ctx->is_active)
3221 cpuctx->task_ctx = NULL;
3225 * Always update time if it was set; not only when it changes.
3226 * Otherwise we can 'forget' to update time for any but the last
3227 * context we sched out. For example:
3229 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3230 * ctx_sched_out(.event_type = EVENT_PINNED)
3232 * would only update time for the pinned events.
3234 if (is_active & EVENT_TIME) {
3235 /* update (and stop) ctx time */
3236 update_context_time(ctx);
3237 update_cgrp_time_from_cpuctx(cpuctx);
3240 is_active ^= ctx->is_active; /* changed bits */
3242 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3245 perf_pmu_disable(ctx->pmu);
3246 if (is_active & EVENT_PINNED) {
3247 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3248 group_sched_out(event, cpuctx, ctx);
3251 if (is_active & EVENT_FLEXIBLE) {
3252 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3253 group_sched_out(event, cpuctx, ctx);
3256 * Since we cleared EVENT_FLEXIBLE, also clear
3257 * rotate_necessary, is will be reset by
3258 * ctx_flexible_sched_in() when needed.
3260 ctx->rotate_necessary = 0;
3262 perf_pmu_enable(ctx->pmu);
3266 * Test whether two contexts are equivalent, i.e. whether they have both been
3267 * cloned from the same version of the same context.
3269 * Equivalence is measured using a generation number in the context that is
3270 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3271 * and list_del_event().
3273 static int context_equiv(struct perf_event_context *ctx1,
3274 struct perf_event_context *ctx2)
3276 lockdep_assert_held(&ctx1->lock);
3277 lockdep_assert_held(&ctx2->lock);
3279 /* Pinning disables the swap optimization */
3280 if (ctx1->pin_count || ctx2->pin_count)
3283 /* If ctx1 is the parent of ctx2 */
3284 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3287 /* If ctx2 is the parent of ctx1 */
3288 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3292 * If ctx1 and ctx2 have the same parent; we flatten the parent
3293 * hierarchy, see perf_event_init_context().
3295 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3296 ctx1->parent_gen == ctx2->parent_gen)
3303 static void __perf_event_sync_stat(struct perf_event *event,
3304 struct perf_event *next_event)
3308 if (!event->attr.inherit_stat)
3312 * Update the event value, we cannot use perf_event_read()
3313 * because we're in the middle of a context switch and have IRQs
3314 * disabled, which upsets smp_call_function_single(), however
3315 * we know the event must be on the current CPU, therefore we
3316 * don't need to use it.
3318 if (event->state == PERF_EVENT_STATE_ACTIVE)
3319 event->pmu->read(event);
3321 perf_event_update_time(event);
3324 * In order to keep per-task stats reliable we need to flip the event
3325 * values when we flip the contexts.
3327 value = local64_read(&next_event->count);
3328 value = local64_xchg(&event->count, value);
3329 local64_set(&next_event->count, value);
3331 swap(event->total_time_enabled, next_event->total_time_enabled);
3332 swap(event->total_time_running, next_event->total_time_running);
3335 * Since we swizzled the values, update the user visible data too.
3337 perf_event_update_userpage(event);
3338 perf_event_update_userpage(next_event);
3341 static void perf_event_sync_stat(struct perf_event_context *ctx,
3342 struct perf_event_context *next_ctx)
3344 struct perf_event *event, *next_event;
3349 update_context_time(ctx);
3351 event = list_first_entry(&ctx->event_list,
3352 struct perf_event, event_entry);
3354 next_event = list_first_entry(&next_ctx->event_list,
3355 struct perf_event, event_entry);
3357 while (&event->event_entry != &ctx->event_list &&
3358 &next_event->event_entry != &next_ctx->event_list) {
3360 __perf_event_sync_stat(event, next_event);
3362 event = list_next_entry(event, event_entry);
3363 next_event = list_next_entry(next_event, event_entry);
3367 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3368 struct task_struct *next)
3370 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3371 struct perf_event_context *next_ctx;
3372 struct perf_event_context *parent, *next_parent;
3373 struct perf_cpu_context *cpuctx;
3381 cpuctx = __get_cpu_context(ctx);
3382 if (!cpuctx->task_ctx)
3386 next_ctx = next->perf_event_ctxp[ctxn];
3390 parent = rcu_dereference(ctx->parent_ctx);
3391 next_parent = rcu_dereference(next_ctx->parent_ctx);
3393 /* If neither context have a parent context; they cannot be clones. */
3394 if (!parent && !next_parent)
3397 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3399 * Looks like the two contexts are clones, so we might be
3400 * able to optimize the context switch. We lock both
3401 * contexts and check that they are clones under the
3402 * lock (including re-checking that neither has been
3403 * uncloned in the meantime). It doesn't matter which
3404 * order we take the locks because no other cpu could
3405 * be trying to lock both of these tasks.
3407 raw_spin_lock(&ctx->lock);
3408 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3409 if (context_equiv(ctx, next_ctx)) {
3411 WRITE_ONCE(ctx->task, next);
3412 WRITE_ONCE(next_ctx->task, task);
3414 perf_pmu_disable(pmu);
3416 if (cpuctx->sched_cb_usage && pmu->sched_task)
3417 pmu->sched_task(ctx, false);
3420 * PMU specific parts of task perf context can require
3421 * additional synchronization. As an example of such
3422 * synchronization see implementation details of Intel
3423 * LBR call stack data profiling;
3425 if (pmu->swap_task_ctx)
3426 pmu->swap_task_ctx(ctx, next_ctx);
3428 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3430 perf_pmu_enable(pmu);
3433 * RCU_INIT_POINTER here is safe because we've not
3434 * modified the ctx and the above modification of
3435 * ctx->task and ctx->task_ctx_data are immaterial
3436 * since those values are always verified under
3437 * ctx->lock which we're now holding.
3439 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3440 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3444 perf_event_sync_stat(ctx, next_ctx);
3446 raw_spin_unlock(&next_ctx->lock);
3447 raw_spin_unlock(&ctx->lock);
3453 raw_spin_lock(&ctx->lock);
3454 perf_pmu_disable(pmu);
3456 if (cpuctx->sched_cb_usage && pmu->sched_task)
3457 pmu->sched_task(ctx, false);
3458 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3460 perf_pmu_enable(pmu);
3461 raw_spin_unlock(&ctx->lock);
3465 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3467 void perf_sched_cb_dec(struct pmu *pmu)
3469 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3471 this_cpu_dec(perf_sched_cb_usages);
3473 if (!--cpuctx->sched_cb_usage)
3474 list_del(&cpuctx->sched_cb_entry);
3478 void perf_sched_cb_inc(struct pmu *pmu)
3480 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3482 if (!cpuctx->sched_cb_usage++)
3483 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3485 this_cpu_inc(perf_sched_cb_usages);
3489 * This function provides the context switch callback to the lower code
3490 * layer. It is invoked ONLY when the context switch callback is enabled.
3492 * This callback is relevant even to per-cpu events; for example multi event
3493 * PEBS requires this to provide PID/TID information. This requires we flush
3494 * all queued PEBS records before we context switch to a new task.
3496 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3500 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3502 if (WARN_ON_ONCE(!pmu->sched_task))
3505 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3506 perf_pmu_disable(pmu);
3508 pmu->sched_task(cpuctx->task_ctx, sched_in);
3510 perf_pmu_enable(pmu);
3511 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3514 static void perf_pmu_sched_task(struct task_struct *prev,
3515 struct task_struct *next,
3518 struct perf_cpu_context *cpuctx;
3523 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3524 /* will be handled in perf_event_context_sched_in/out */
3525 if (cpuctx->task_ctx)
3528 __perf_pmu_sched_task(cpuctx, sched_in);
3532 static void perf_event_switch(struct task_struct *task,
3533 struct task_struct *next_prev, bool sched_in);
3535 #define for_each_task_context_nr(ctxn) \
3536 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3539 * Called from scheduler to remove the events of the current task,
3540 * with interrupts disabled.
3542 * We stop each event and update the event value in event->count.
3544 * This does not protect us against NMI, but disable()
3545 * sets the disabled bit in the control field of event _before_
3546 * accessing the event control register. If a NMI hits, then it will
3547 * not restart the event.
3549 void __perf_event_task_sched_out(struct task_struct *task,
3550 struct task_struct *next)
3554 if (__this_cpu_read(perf_sched_cb_usages))
3555 perf_pmu_sched_task(task, next, false);
3557 if (atomic_read(&nr_switch_events))
3558 perf_event_switch(task, next, false);
3560 for_each_task_context_nr(ctxn)
3561 perf_event_context_sched_out(task, ctxn, next);
3564 * if cgroup events exist on this CPU, then we need
3565 * to check if we have to switch out PMU state.
3566 * cgroup event are system-wide mode only
3568 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3569 perf_cgroup_sched_out(task, next);
3573 * Called with IRQs disabled
3575 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3576 enum event_type_t event_type)
3578 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3581 static bool perf_less_group_idx(const void *l, const void *r)
3583 const struct perf_event *le = *(const struct perf_event **)l;
3584 const struct perf_event *re = *(const struct perf_event **)r;
3586 return le->group_index < re->group_index;
3589 static void swap_ptr(void *l, void *r)
3591 void **lp = l, **rp = r;
3596 static const struct min_heap_callbacks perf_min_heap = {
3597 .elem_size = sizeof(struct perf_event *),
3598 .less = perf_less_group_idx,
3602 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3604 struct perf_event **itrs = heap->data;
3607 itrs[heap->nr] = event;
3612 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3613 struct perf_event_groups *groups, int cpu,
3614 int (*func)(struct perf_event *, void *),
3617 #ifdef CONFIG_CGROUP_PERF
3618 struct cgroup_subsys_state *css = NULL;
3620 /* Space for per CPU and/or any CPU event iterators. */
3621 struct perf_event *itrs[2];
3622 struct min_heap event_heap;
3623 struct perf_event **evt;
3627 event_heap = (struct min_heap){
3628 .data = cpuctx->heap,
3630 .size = cpuctx->heap_size,
3633 lockdep_assert_held(&cpuctx->ctx.lock);
3635 #ifdef CONFIG_CGROUP_PERF
3637 css = &cpuctx->cgrp->css;
3640 event_heap = (struct min_heap){
3643 .size = ARRAY_SIZE(itrs),
3645 /* Events not within a CPU context may be on any CPU. */
3646 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3648 evt = event_heap.data;
3650 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3652 #ifdef CONFIG_CGROUP_PERF
3653 for (; css; css = css->parent)
3654 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3657 min_heapify_all(&event_heap, &perf_min_heap);
3659 while (event_heap.nr) {
3660 ret = func(*evt, data);
3664 *evt = perf_event_groups_next(*evt);
3666 min_heapify(&event_heap, 0, &perf_min_heap);
3668 min_heap_pop(&event_heap, &perf_min_heap);
3674 static int merge_sched_in(struct perf_event *event, void *data)
3676 struct perf_event_context *ctx = event->ctx;
3677 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3678 int *can_add_hw = data;
3680 if (event->state <= PERF_EVENT_STATE_OFF)
3683 if (!event_filter_match(event))
3686 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3687 if (!group_sched_in(event, cpuctx, ctx))
3688 list_add_tail(&event->active_list, get_event_list(event));
3691 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3692 if (event->attr.pinned) {
3693 perf_cgroup_event_disable(event, ctx);
3694 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3698 ctx->rotate_necessary = 1;
3699 perf_mux_hrtimer_restart(cpuctx);
3706 ctx_pinned_sched_in(struct perf_event_context *ctx,
3707 struct perf_cpu_context *cpuctx)
3711 if (ctx != &cpuctx->ctx)
3714 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3716 merge_sched_in, &can_add_hw);
3720 ctx_flexible_sched_in(struct perf_event_context *ctx,
3721 struct perf_cpu_context *cpuctx)
3725 if (ctx != &cpuctx->ctx)
3728 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3730 merge_sched_in, &can_add_hw);
3734 ctx_sched_in(struct perf_event_context *ctx,
3735 struct perf_cpu_context *cpuctx,
3736 enum event_type_t event_type,
3737 struct task_struct *task)
3739 int is_active = ctx->is_active;
3742 lockdep_assert_held(&ctx->lock);
3744 if (likely(!ctx->nr_events))
3747 ctx->is_active |= (event_type | EVENT_TIME);
3750 cpuctx->task_ctx = ctx;
3752 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3755 is_active ^= ctx->is_active; /* changed bits */
3757 if (is_active & EVENT_TIME) {
3758 /* start ctx time */
3760 ctx->timestamp = now;
3761 perf_cgroup_set_timestamp(task, ctx);
3765 * First go through the list and put on any pinned groups
3766 * in order to give them the best chance of going on.
3768 if (is_active & EVENT_PINNED)
3769 ctx_pinned_sched_in(ctx, cpuctx);
3771 /* Then walk through the lower prio flexible groups */
3772 if (is_active & EVENT_FLEXIBLE)
3773 ctx_flexible_sched_in(ctx, cpuctx);
3776 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3777 enum event_type_t event_type,
3778 struct task_struct *task)
3780 struct perf_event_context *ctx = &cpuctx->ctx;
3782 ctx_sched_in(ctx, cpuctx, event_type, task);
3785 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3786 struct task_struct *task)
3788 struct perf_cpu_context *cpuctx;
3789 struct pmu *pmu = ctx->pmu;
3791 cpuctx = __get_cpu_context(ctx);
3792 if (cpuctx->task_ctx == ctx) {
3793 if (cpuctx->sched_cb_usage)
3794 __perf_pmu_sched_task(cpuctx, true);
3798 perf_ctx_lock(cpuctx, ctx);
3800 * We must check ctx->nr_events while holding ctx->lock, such
3801 * that we serialize against perf_install_in_context().
3803 if (!ctx->nr_events)
3806 perf_pmu_disable(pmu);
3808 * We want to keep the following priority order:
3809 * cpu pinned (that don't need to move), task pinned,
3810 * cpu flexible, task flexible.
3812 * However, if task's ctx is not carrying any pinned
3813 * events, no need to flip the cpuctx's events around.
3815 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3816 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3817 perf_event_sched_in(cpuctx, ctx, task);
3819 if (cpuctx->sched_cb_usage && pmu->sched_task)
3820 pmu->sched_task(cpuctx->task_ctx, true);
3822 perf_pmu_enable(pmu);
3825 perf_ctx_unlock(cpuctx, ctx);
3829 * Called from scheduler to add the events of the current task
3830 * with interrupts disabled.
3832 * We restore the event value and then enable it.
3834 * This does not protect us against NMI, but enable()
3835 * sets the enabled bit in the control field of event _before_
3836 * accessing the event control register. If a NMI hits, then it will
3837 * keep the event running.
3839 void __perf_event_task_sched_in(struct task_struct *prev,
3840 struct task_struct *task)
3842 struct perf_event_context *ctx;
3846 * If cgroup events exist on this CPU, then we need to check if we have
3847 * to switch in PMU state; cgroup event are system-wide mode only.
3849 * Since cgroup events are CPU events, we must schedule these in before
3850 * we schedule in the task events.
3852 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3853 perf_cgroup_sched_in(prev, task);
3855 for_each_task_context_nr(ctxn) {
3856 ctx = task->perf_event_ctxp[ctxn];
3860 perf_event_context_sched_in(ctx, task);
3863 if (atomic_read(&nr_switch_events))
3864 perf_event_switch(task, prev, true);
3866 if (__this_cpu_read(perf_sched_cb_usages))
3867 perf_pmu_sched_task(prev, task, true);
3870 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3872 u64 frequency = event->attr.sample_freq;
3873 u64 sec = NSEC_PER_SEC;
3874 u64 divisor, dividend;
3876 int count_fls, nsec_fls, frequency_fls, sec_fls;
3878 count_fls = fls64(count);
3879 nsec_fls = fls64(nsec);
3880 frequency_fls = fls64(frequency);
3884 * We got @count in @nsec, with a target of sample_freq HZ
3885 * the target period becomes:
3888 * period = -------------------
3889 * @nsec * sample_freq
3894 * Reduce accuracy by one bit such that @a and @b converge
3895 * to a similar magnitude.
3897 #define REDUCE_FLS(a, b) \
3899 if (a##_fls > b##_fls) { \
3909 * Reduce accuracy until either term fits in a u64, then proceed with
3910 * the other, so that finally we can do a u64/u64 division.
3912 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3913 REDUCE_FLS(nsec, frequency);
3914 REDUCE_FLS(sec, count);
3917 if (count_fls + sec_fls > 64) {
3918 divisor = nsec * frequency;
3920 while (count_fls + sec_fls > 64) {
3921 REDUCE_FLS(count, sec);
3925 dividend = count * sec;
3927 dividend = count * sec;
3929 while (nsec_fls + frequency_fls > 64) {
3930 REDUCE_FLS(nsec, frequency);
3934 divisor = nsec * frequency;
3940 return div64_u64(dividend, divisor);
3943 static DEFINE_PER_CPU(int, perf_throttled_count);
3944 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3946 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3948 struct hw_perf_event *hwc = &event->hw;
3949 s64 period, sample_period;
3952 period = perf_calculate_period(event, nsec, count);
3954 delta = (s64)(period - hwc->sample_period);
3955 delta = (delta + 7) / 8; /* low pass filter */
3957 sample_period = hwc->sample_period + delta;
3962 hwc->sample_period = sample_period;
3964 if (local64_read(&hwc->period_left) > 8*sample_period) {
3966 event->pmu->stop(event, PERF_EF_UPDATE);
3968 local64_set(&hwc->period_left, 0);
3971 event->pmu->start(event, PERF_EF_RELOAD);
3976 * combine freq adjustment with unthrottling to avoid two passes over the
3977 * events. At the same time, make sure, having freq events does not change
3978 * the rate of unthrottling as that would introduce bias.
3980 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3983 struct perf_event *event;
3984 struct hw_perf_event *hwc;
3985 u64 now, period = TICK_NSEC;
3989 * only need to iterate over all events iff:
3990 * - context have events in frequency mode (needs freq adjust)
3991 * - there are events to unthrottle on this cpu
3993 if (!(ctx->nr_freq || needs_unthr))
3996 raw_spin_lock(&ctx->lock);
3997 perf_pmu_disable(ctx->pmu);
3999 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4000 if (event->state != PERF_EVENT_STATE_ACTIVE)
4003 if (!event_filter_match(event))
4006 perf_pmu_disable(event->pmu);
4010 if (hwc->interrupts == MAX_INTERRUPTS) {
4011 hwc->interrupts = 0;
4012 perf_log_throttle(event, 1);
4013 event->pmu->start(event, 0);
4016 if (!event->attr.freq || !event->attr.sample_freq)
4020 * stop the event and update event->count
4022 event->pmu->stop(event, PERF_EF_UPDATE);
4024 now = local64_read(&event->count);
4025 delta = now - hwc->freq_count_stamp;
4026 hwc->freq_count_stamp = now;
4030 * reload only if value has changed
4031 * we have stopped the event so tell that
4032 * to perf_adjust_period() to avoid stopping it
4036 perf_adjust_period(event, period, delta, false);
4038 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4040 perf_pmu_enable(event->pmu);
4043 perf_pmu_enable(ctx->pmu);
4044 raw_spin_unlock(&ctx->lock);
4048 * Move @event to the tail of the @ctx's elegible events.
4050 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4053 * Rotate the first entry last of non-pinned groups. Rotation might be
4054 * disabled by the inheritance code.
4056 if (ctx->rotate_disable)
4059 perf_event_groups_delete(&ctx->flexible_groups, event);
4060 perf_event_groups_insert(&ctx->flexible_groups, event);
4063 /* pick an event from the flexible_groups to rotate */
4064 static inline struct perf_event *
4065 ctx_event_to_rotate(struct perf_event_context *ctx)
4067 struct perf_event *event;
4069 /* pick the first active flexible event */
4070 event = list_first_entry_or_null(&ctx->flexible_active,
4071 struct perf_event, active_list);
4073 /* if no active flexible event, pick the first event */
4075 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4076 typeof(*event), group_node);
4080 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4081 * finds there are unschedulable events, it will set it again.
4083 ctx->rotate_necessary = 0;
4088 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4090 struct perf_event *cpu_event = NULL, *task_event = NULL;
4091 struct perf_event_context *task_ctx = NULL;
4092 int cpu_rotate, task_rotate;
4095 * Since we run this from IRQ context, nobody can install new
4096 * events, thus the event count values are stable.
4099 cpu_rotate = cpuctx->ctx.rotate_necessary;
4100 task_ctx = cpuctx->task_ctx;
4101 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4103 if (!(cpu_rotate || task_rotate))
4106 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4107 perf_pmu_disable(cpuctx->ctx.pmu);
4110 task_event = ctx_event_to_rotate(task_ctx);
4112 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4115 * As per the order given at ctx_resched() first 'pop' task flexible
4116 * and then, if needed CPU flexible.
4118 if (task_event || (task_ctx && cpu_event))
4119 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4121 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4124 rotate_ctx(task_ctx, task_event);
4126 rotate_ctx(&cpuctx->ctx, cpu_event);
4128 perf_event_sched_in(cpuctx, task_ctx, current);
4130 perf_pmu_enable(cpuctx->ctx.pmu);
4131 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4136 void perf_event_task_tick(void)
4138 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4139 struct perf_event_context *ctx, *tmp;
4142 lockdep_assert_irqs_disabled();
4144 __this_cpu_inc(perf_throttled_seq);
4145 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4146 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4148 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4149 perf_adjust_freq_unthr_context(ctx, throttled);
4152 static int event_enable_on_exec(struct perf_event *event,
4153 struct perf_event_context *ctx)
4155 if (!event->attr.enable_on_exec)
4158 event->attr.enable_on_exec = 0;
4159 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4162 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4168 * Enable all of a task's events that have been marked enable-on-exec.
4169 * This expects task == current.
4171 static void perf_event_enable_on_exec(int ctxn)
4173 struct perf_event_context *ctx, *clone_ctx = NULL;
4174 enum event_type_t event_type = 0;
4175 struct perf_cpu_context *cpuctx;
4176 struct perf_event *event;
4177 unsigned long flags;
4180 local_irq_save(flags);
4181 ctx = current->perf_event_ctxp[ctxn];
4182 if (!ctx || !ctx->nr_events)
4185 cpuctx = __get_cpu_context(ctx);
4186 perf_ctx_lock(cpuctx, ctx);
4187 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4188 list_for_each_entry(event, &ctx->event_list, event_entry) {
4189 enabled |= event_enable_on_exec(event, ctx);
4190 event_type |= get_event_type(event);
4194 * Unclone and reschedule this context if we enabled any event.
4197 clone_ctx = unclone_ctx(ctx);
4198 ctx_resched(cpuctx, ctx, event_type);
4200 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4202 perf_ctx_unlock(cpuctx, ctx);
4205 local_irq_restore(flags);
4211 struct perf_read_data {
4212 struct perf_event *event;
4217 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4219 u16 local_pkg, event_pkg;
4221 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4222 int local_cpu = smp_processor_id();
4224 event_pkg = topology_physical_package_id(event_cpu);
4225 local_pkg = topology_physical_package_id(local_cpu);
4227 if (event_pkg == local_pkg)
4235 * Cross CPU call to read the hardware event
4237 static void __perf_event_read(void *info)
4239 struct perf_read_data *data = info;
4240 struct perf_event *sub, *event = data->event;
4241 struct perf_event_context *ctx = event->ctx;
4242 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4243 struct pmu *pmu = event->pmu;
4246 * If this is a task context, we need to check whether it is
4247 * the current task context of this cpu. If not it has been
4248 * scheduled out before the smp call arrived. In that case
4249 * event->count would have been updated to a recent sample
4250 * when the event was scheduled out.
4252 if (ctx->task && cpuctx->task_ctx != ctx)
4255 raw_spin_lock(&ctx->lock);
4256 if (ctx->is_active & EVENT_TIME) {
4257 update_context_time(ctx);
4258 update_cgrp_time_from_event(event);
4261 perf_event_update_time(event);
4263 perf_event_update_sibling_time(event);
4265 if (event->state != PERF_EVENT_STATE_ACTIVE)
4274 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4278 for_each_sibling_event(sub, event) {
4279 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4281 * Use sibling's PMU rather than @event's since
4282 * sibling could be on different (eg: software) PMU.
4284 sub->pmu->read(sub);
4288 data->ret = pmu->commit_txn(pmu);
4291 raw_spin_unlock(&ctx->lock);
4294 static inline u64 perf_event_count(struct perf_event *event)
4296 return local64_read(&event->count) + atomic64_read(&event->child_count);
4300 * NMI-safe method to read a local event, that is an event that
4302 * - either for the current task, or for this CPU
4303 * - does not have inherit set, for inherited task events
4304 * will not be local and we cannot read them atomically
4305 * - must not have a pmu::count method
4307 int perf_event_read_local(struct perf_event *event, u64 *value,
4308 u64 *enabled, u64 *running)
4310 unsigned long flags;
4314 * Disabling interrupts avoids all counter scheduling (context
4315 * switches, timer based rotation and IPIs).
4317 local_irq_save(flags);
4320 * It must not be an event with inherit set, we cannot read
4321 * all child counters from atomic context.
4323 if (event->attr.inherit) {
4328 /* If this is a per-task event, it must be for current */
4329 if ((event->attach_state & PERF_ATTACH_TASK) &&
4330 event->hw.target != current) {
4335 /* If this is a per-CPU event, it must be for this CPU */
4336 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4337 event->cpu != smp_processor_id()) {
4342 /* If this is a pinned event it must be running on this CPU */
4343 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4349 * If the event is currently on this CPU, its either a per-task event,
4350 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4353 if (event->oncpu == smp_processor_id())
4354 event->pmu->read(event);
4356 *value = local64_read(&event->count);
4357 if (enabled || running) {
4358 u64 now = event->shadow_ctx_time + perf_clock();
4359 u64 __enabled, __running;
4361 __perf_update_times(event, now, &__enabled, &__running);
4363 *enabled = __enabled;
4365 *running = __running;
4368 local_irq_restore(flags);
4373 static int perf_event_read(struct perf_event *event, bool group)
4375 enum perf_event_state state = READ_ONCE(event->state);
4376 int event_cpu, ret = 0;
4379 * If event is enabled and currently active on a CPU, update the
4380 * value in the event structure:
4383 if (state == PERF_EVENT_STATE_ACTIVE) {
4384 struct perf_read_data data;
4387 * Orders the ->state and ->oncpu loads such that if we see
4388 * ACTIVE we must also see the right ->oncpu.
4390 * Matches the smp_wmb() from event_sched_in().
4394 event_cpu = READ_ONCE(event->oncpu);
4395 if ((unsigned)event_cpu >= nr_cpu_ids)
4398 data = (struct perf_read_data){
4405 event_cpu = __perf_event_read_cpu(event, event_cpu);
4408 * Purposely ignore the smp_call_function_single() return
4411 * If event_cpu isn't a valid CPU it means the event got
4412 * scheduled out and that will have updated the event count.
4414 * Therefore, either way, we'll have an up-to-date event count
4417 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4421 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4422 struct perf_event_context *ctx = event->ctx;
4423 unsigned long flags;
4425 raw_spin_lock_irqsave(&ctx->lock, flags);
4426 state = event->state;
4427 if (state != PERF_EVENT_STATE_INACTIVE) {
4428 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4433 * May read while context is not active (e.g., thread is
4434 * blocked), in that case we cannot update context time
4436 if (ctx->is_active & EVENT_TIME) {
4437 update_context_time(ctx);
4438 update_cgrp_time_from_event(event);
4441 perf_event_update_time(event);
4443 perf_event_update_sibling_time(event);
4444 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4451 * Initialize the perf_event context in a task_struct:
4453 static void __perf_event_init_context(struct perf_event_context *ctx)
4455 raw_spin_lock_init(&ctx->lock);
4456 mutex_init(&ctx->mutex);
4457 INIT_LIST_HEAD(&ctx->active_ctx_list);
4458 perf_event_groups_init(&ctx->pinned_groups);
4459 perf_event_groups_init(&ctx->flexible_groups);
4460 INIT_LIST_HEAD(&ctx->event_list);
4461 INIT_LIST_HEAD(&ctx->pinned_active);
4462 INIT_LIST_HEAD(&ctx->flexible_active);
4463 refcount_set(&ctx->refcount, 1);
4466 static struct perf_event_context *
4467 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4469 struct perf_event_context *ctx;
4471 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4475 __perf_event_init_context(ctx);
4477 ctx->task = get_task_struct(task);
4483 static struct task_struct *
4484 find_lively_task_by_vpid(pid_t vpid)
4486 struct task_struct *task;
4492 task = find_task_by_vpid(vpid);
4494 get_task_struct(task);
4498 return ERR_PTR(-ESRCH);
4504 * Returns a matching context with refcount and pincount.
4506 static struct perf_event_context *
4507 find_get_context(struct pmu *pmu, struct task_struct *task,
4508 struct perf_event *event)
4510 struct perf_event_context *ctx, *clone_ctx = NULL;
4511 struct perf_cpu_context *cpuctx;
4512 void *task_ctx_data = NULL;
4513 unsigned long flags;
4515 int cpu = event->cpu;
4518 /* Must be root to operate on a CPU event: */
4519 err = perf_allow_cpu(&event->attr);
4521 return ERR_PTR(err);
4523 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4532 ctxn = pmu->task_ctx_nr;
4536 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4537 task_ctx_data = alloc_task_ctx_data(pmu);
4538 if (!task_ctx_data) {
4545 ctx = perf_lock_task_context(task, ctxn, &flags);
4547 clone_ctx = unclone_ctx(ctx);
4550 if (task_ctx_data && !ctx->task_ctx_data) {
4551 ctx->task_ctx_data = task_ctx_data;
4552 task_ctx_data = NULL;
4554 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4559 ctx = alloc_perf_context(pmu, task);
4564 if (task_ctx_data) {
4565 ctx->task_ctx_data = task_ctx_data;
4566 task_ctx_data = NULL;
4570 mutex_lock(&task->perf_event_mutex);
4572 * If it has already passed perf_event_exit_task().
4573 * we must see PF_EXITING, it takes this mutex too.
4575 if (task->flags & PF_EXITING)
4577 else if (task->perf_event_ctxp[ctxn])
4582 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4584 mutex_unlock(&task->perf_event_mutex);
4586 if (unlikely(err)) {
4595 free_task_ctx_data(pmu, task_ctx_data);
4599 free_task_ctx_data(pmu, task_ctx_data);
4600 return ERR_PTR(err);
4603 static void perf_event_free_filter(struct perf_event *event);
4604 static void perf_event_free_bpf_prog(struct perf_event *event);
4606 static void free_event_rcu(struct rcu_head *head)
4608 struct perf_event *event;
4610 event = container_of(head, struct perf_event, rcu_head);
4612 put_pid_ns(event->ns);
4613 perf_event_free_filter(event);
4617 static void ring_buffer_attach(struct perf_event *event,
4618 struct perf_buffer *rb);
4620 static void detach_sb_event(struct perf_event *event)
4622 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4624 raw_spin_lock(&pel->lock);
4625 list_del_rcu(&event->sb_list);
4626 raw_spin_unlock(&pel->lock);
4629 static bool is_sb_event(struct perf_event *event)
4631 struct perf_event_attr *attr = &event->attr;
4636 if (event->attach_state & PERF_ATTACH_TASK)
4639 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4640 attr->comm || attr->comm_exec ||
4641 attr->task || attr->ksymbol ||
4642 attr->context_switch || attr->text_poke ||
4648 static void unaccount_pmu_sb_event(struct perf_event *event)
4650 if (is_sb_event(event))
4651 detach_sb_event(event);
4654 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4659 if (is_cgroup_event(event))
4660 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4663 #ifdef CONFIG_NO_HZ_FULL
4664 static DEFINE_SPINLOCK(nr_freq_lock);
4667 static void unaccount_freq_event_nohz(void)
4669 #ifdef CONFIG_NO_HZ_FULL
4670 spin_lock(&nr_freq_lock);
4671 if (atomic_dec_and_test(&nr_freq_events))
4672 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4673 spin_unlock(&nr_freq_lock);
4677 static void unaccount_freq_event(void)
4679 if (tick_nohz_full_enabled())
4680 unaccount_freq_event_nohz();
4682 atomic_dec(&nr_freq_events);
4685 static void unaccount_event(struct perf_event *event)
4692 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4694 if (event->attr.mmap || event->attr.mmap_data)
4695 atomic_dec(&nr_mmap_events);
4696 if (event->attr.build_id)
4697 atomic_dec(&nr_build_id_events);
4698 if (event->attr.comm)
4699 atomic_dec(&nr_comm_events);
4700 if (event->attr.namespaces)
4701 atomic_dec(&nr_namespaces_events);
4702 if (event->attr.cgroup)
4703 atomic_dec(&nr_cgroup_events);
4704 if (event->attr.task)
4705 atomic_dec(&nr_task_events);
4706 if (event->attr.freq)
4707 unaccount_freq_event();
4708 if (event->attr.context_switch) {
4710 atomic_dec(&nr_switch_events);
4712 if (is_cgroup_event(event))
4714 if (has_branch_stack(event))
4716 if (event->attr.ksymbol)
4717 atomic_dec(&nr_ksymbol_events);
4718 if (event->attr.bpf_event)
4719 atomic_dec(&nr_bpf_events);
4720 if (event->attr.text_poke)
4721 atomic_dec(&nr_text_poke_events);
4724 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4725 schedule_delayed_work(&perf_sched_work, HZ);
4728 unaccount_event_cpu(event, event->cpu);
4730 unaccount_pmu_sb_event(event);
4733 static void perf_sched_delayed(struct work_struct *work)
4735 mutex_lock(&perf_sched_mutex);
4736 if (atomic_dec_and_test(&perf_sched_count))
4737 static_branch_disable(&perf_sched_events);
4738 mutex_unlock(&perf_sched_mutex);
4742 * The following implement mutual exclusion of events on "exclusive" pmus
4743 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4744 * at a time, so we disallow creating events that might conflict, namely:
4746 * 1) cpu-wide events in the presence of per-task events,
4747 * 2) per-task events in the presence of cpu-wide events,
4748 * 3) two matching events on the same context.
4750 * The former two cases are handled in the allocation path (perf_event_alloc(),
4751 * _free_event()), the latter -- before the first perf_install_in_context().
4753 static int exclusive_event_init(struct perf_event *event)
4755 struct pmu *pmu = event->pmu;
4757 if (!is_exclusive_pmu(pmu))
4761 * Prevent co-existence of per-task and cpu-wide events on the
4762 * same exclusive pmu.
4764 * Negative pmu::exclusive_cnt means there are cpu-wide
4765 * events on this "exclusive" pmu, positive means there are
4768 * Since this is called in perf_event_alloc() path, event::ctx
4769 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4770 * to mean "per-task event", because unlike other attach states it
4771 * never gets cleared.
4773 if (event->attach_state & PERF_ATTACH_TASK) {
4774 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4777 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4784 static void exclusive_event_destroy(struct perf_event *event)
4786 struct pmu *pmu = event->pmu;
4788 if (!is_exclusive_pmu(pmu))
4791 /* see comment in exclusive_event_init() */
4792 if (event->attach_state & PERF_ATTACH_TASK)
4793 atomic_dec(&pmu->exclusive_cnt);
4795 atomic_inc(&pmu->exclusive_cnt);
4798 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4800 if ((e1->pmu == e2->pmu) &&
4801 (e1->cpu == e2->cpu ||
4808 static bool exclusive_event_installable(struct perf_event *event,
4809 struct perf_event_context *ctx)
4811 struct perf_event *iter_event;
4812 struct pmu *pmu = event->pmu;
4814 lockdep_assert_held(&ctx->mutex);
4816 if (!is_exclusive_pmu(pmu))
4819 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4820 if (exclusive_event_match(iter_event, event))
4827 static void perf_addr_filters_splice(struct perf_event *event,
4828 struct list_head *head);
4830 static void _free_event(struct perf_event *event)
4832 irq_work_sync(&event->pending);
4834 unaccount_event(event);
4836 security_perf_event_free(event);
4840 * Can happen when we close an event with re-directed output.
4842 * Since we have a 0 refcount, perf_mmap_close() will skip
4843 * over us; possibly making our ring_buffer_put() the last.
4845 mutex_lock(&event->mmap_mutex);
4846 ring_buffer_attach(event, NULL);
4847 mutex_unlock(&event->mmap_mutex);
4850 if (is_cgroup_event(event))
4851 perf_detach_cgroup(event);
4853 if (!event->parent) {
4854 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4855 put_callchain_buffers();
4858 perf_event_free_bpf_prog(event);
4859 perf_addr_filters_splice(event, NULL);
4860 kfree(event->addr_filter_ranges);
4863 event->destroy(event);
4866 * Must be after ->destroy(), due to uprobe_perf_close() using
4869 if (event->hw.target)
4870 put_task_struct(event->hw.target);
4873 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4874 * all task references must be cleaned up.
4877 put_ctx(event->ctx);
4879 exclusive_event_destroy(event);
4880 module_put(event->pmu->module);
4882 call_rcu(&event->rcu_head, free_event_rcu);
4886 * Used to free events which have a known refcount of 1, such as in error paths
4887 * where the event isn't exposed yet and inherited events.
4889 static void free_event(struct perf_event *event)
4891 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4892 "unexpected event refcount: %ld; ptr=%p\n",
4893 atomic_long_read(&event->refcount), event)) {
4894 /* leak to avoid use-after-free */
4902 * Remove user event from the owner task.
4904 static void perf_remove_from_owner(struct perf_event *event)
4906 struct task_struct *owner;
4910 * Matches the smp_store_release() in perf_event_exit_task(). If we
4911 * observe !owner it means the list deletion is complete and we can
4912 * indeed free this event, otherwise we need to serialize on
4913 * owner->perf_event_mutex.
4915 owner = READ_ONCE(event->owner);
4918 * Since delayed_put_task_struct() also drops the last
4919 * task reference we can safely take a new reference
4920 * while holding the rcu_read_lock().
4922 get_task_struct(owner);
4928 * If we're here through perf_event_exit_task() we're already
4929 * holding ctx->mutex which would be an inversion wrt. the
4930 * normal lock order.
4932 * However we can safely take this lock because its the child
4935 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4938 * We have to re-check the event->owner field, if it is cleared
4939 * we raced with perf_event_exit_task(), acquiring the mutex
4940 * ensured they're done, and we can proceed with freeing the
4944 list_del_init(&event->owner_entry);
4945 smp_store_release(&event->owner, NULL);
4947 mutex_unlock(&owner->perf_event_mutex);
4948 put_task_struct(owner);
4952 static void put_event(struct perf_event *event)
4954 if (!atomic_long_dec_and_test(&event->refcount))
4961 * Kill an event dead; while event:refcount will preserve the event
4962 * object, it will not preserve its functionality. Once the last 'user'
4963 * gives up the object, we'll destroy the thing.
4965 int perf_event_release_kernel(struct perf_event *event)
4967 struct perf_event_context *ctx = event->ctx;
4968 struct perf_event *child, *tmp;
4969 LIST_HEAD(free_list);
4972 * If we got here through err_file: fput(event_file); we will not have
4973 * attached to a context yet.
4976 WARN_ON_ONCE(event->attach_state &
4977 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4981 if (!is_kernel_event(event))
4982 perf_remove_from_owner(event);
4984 ctx = perf_event_ctx_lock(event);
4985 WARN_ON_ONCE(ctx->parent_ctx);
4986 perf_remove_from_context(event, DETACH_GROUP);
4988 raw_spin_lock_irq(&ctx->lock);
4990 * Mark this event as STATE_DEAD, there is no external reference to it
4993 * Anybody acquiring event->child_mutex after the below loop _must_
4994 * also see this, most importantly inherit_event() which will avoid
4995 * placing more children on the list.
4997 * Thus this guarantees that we will in fact observe and kill _ALL_
5000 event->state = PERF_EVENT_STATE_DEAD;
5001 raw_spin_unlock_irq(&ctx->lock);
5003 perf_event_ctx_unlock(event, ctx);
5006 mutex_lock(&event->child_mutex);
5007 list_for_each_entry(child, &event->child_list, child_list) {
5010 * Cannot change, child events are not migrated, see the
5011 * comment with perf_event_ctx_lock_nested().
5013 ctx = READ_ONCE(child->ctx);
5015 * Since child_mutex nests inside ctx::mutex, we must jump
5016 * through hoops. We start by grabbing a reference on the ctx.
5018 * Since the event cannot get freed while we hold the
5019 * child_mutex, the context must also exist and have a !0
5025 * Now that we have a ctx ref, we can drop child_mutex, and
5026 * acquire ctx::mutex without fear of it going away. Then we
5027 * can re-acquire child_mutex.
5029 mutex_unlock(&event->child_mutex);
5030 mutex_lock(&ctx->mutex);
5031 mutex_lock(&event->child_mutex);
5034 * Now that we hold ctx::mutex and child_mutex, revalidate our
5035 * state, if child is still the first entry, it didn't get freed
5036 * and we can continue doing so.
5038 tmp = list_first_entry_or_null(&event->child_list,
5039 struct perf_event, child_list);
5041 perf_remove_from_context(child, DETACH_GROUP);
5042 list_move(&child->child_list, &free_list);
5044 * This matches the refcount bump in inherit_event();
5045 * this can't be the last reference.
5050 mutex_unlock(&event->child_mutex);
5051 mutex_unlock(&ctx->mutex);
5055 mutex_unlock(&event->child_mutex);
5057 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5058 void *var = &child->ctx->refcount;
5060 list_del(&child->child_list);
5064 * Wake any perf_event_free_task() waiting for this event to be
5067 smp_mb(); /* pairs with wait_var_event() */
5072 put_event(event); /* Must be the 'last' reference */
5075 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5078 * Called when the last reference to the file is gone.
5080 static int perf_release(struct inode *inode, struct file *file)
5082 perf_event_release_kernel(file->private_data);
5086 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5088 struct perf_event *child;
5094 mutex_lock(&event->child_mutex);
5096 (void)perf_event_read(event, false);
5097 total += perf_event_count(event);
5099 *enabled += event->total_time_enabled +
5100 atomic64_read(&event->child_total_time_enabled);
5101 *running += event->total_time_running +
5102 atomic64_read(&event->child_total_time_running);
5104 list_for_each_entry(child, &event->child_list, child_list) {
5105 (void)perf_event_read(child, false);
5106 total += perf_event_count(child);
5107 *enabled += child->total_time_enabled;
5108 *running += child->total_time_running;
5110 mutex_unlock(&event->child_mutex);
5115 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5117 struct perf_event_context *ctx;
5120 ctx = perf_event_ctx_lock(event);
5121 count = __perf_event_read_value(event, enabled, running);
5122 perf_event_ctx_unlock(event, ctx);
5126 EXPORT_SYMBOL_GPL(perf_event_read_value);
5128 static int __perf_read_group_add(struct perf_event *leader,
5129 u64 read_format, u64 *values)
5131 struct perf_event_context *ctx = leader->ctx;
5132 struct perf_event *sub;
5133 unsigned long flags;
5134 int n = 1; /* skip @nr */
5137 ret = perf_event_read(leader, true);
5141 raw_spin_lock_irqsave(&ctx->lock, flags);
5144 * Since we co-schedule groups, {enabled,running} times of siblings
5145 * will be identical to those of the leader, so we only publish one
5148 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5149 values[n++] += leader->total_time_enabled +
5150 atomic64_read(&leader->child_total_time_enabled);
5153 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5154 values[n++] += leader->total_time_running +
5155 atomic64_read(&leader->child_total_time_running);
5159 * Write {count,id} tuples for every sibling.
5161 values[n++] += perf_event_count(leader);
5162 if (read_format & PERF_FORMAT_ID)
5163 values[n++] = primary_event_id(leader);
5165 for_each_sibling_event(sub, leader) {
5166 values[n++] += perf_event_count(sub);
5167 if (read_format & PERF_FORMAT_ID)
5168 values[n++] = primary_event_id(sub);
5171 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5175 static int perf_read_group(struct perf_event *event,
5176 u64 read_format, char __user *buf)
5178 struct perf_event *leader = event->group_leader, *child;
5179 struct perf_event_context *ctx = leader->ctx;
5183 lockdep_assert_held(&ctx->mutex);
5185 values = kzalloc(event->read_size, GFP_KERNEL);
5189 values[0] = 1 + leader->nr_siblings;
5192 * By locking the child_mutex of the leader we effectively
5193 * lock the child list of all siblings.. XXX explain how.
5195 mutex_lock(&leader->child_mutex);
5197 ret = __perf_read_group_add(leader, read_format, values);
5201 list_for_each_entry(child, &leader->child_list, child_list) {
5202 ret = __perf_read_group_add(child, read_format, values);
5207 mutex_unlock(&leader->child_mutex);
5209 ret = event->read_size;
5210 if (copy_to_user(buf, values, event->read_size))
5215 mutex_unlock(&leader->child_mutex);
5221 static int perf_read_one(struct perf_event *event,
5222 u64 read_format, char __user *buf)
5224 u64 enabled, running;
5228 values[n++] = __perf_event_read_value(event, &enabled, &running);
5229 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5230 values[n++] = enabled;
5231 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5232 values[n++] = running;
5233 if (read_format & PERF_FORMAT_ID)
5234 values[n++] = primary_event_id(event);
5236 if (copy_to_user(buf, values, n * sizeof(u64)))
5239 return n * sizeof(u64);
5242 static bool is_event_hup(struct perf_event *event)
5246 if (event->state > PERF_EVENT_STATE_EXIT)
5249 mutex_lock(&event->child_mutex);
5250 no_children = list_empty(&event->child_list);
5251 mutex_unlock(&event->child_mutex);
5256 * Read the performance event - simple non blocking version for now
5259 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5261 u64 read_format = event->attr.read_format;
5265 * Return end-of-file for a read on an event that is in
5266 * error state (i.e. because it was pinned but it couldn't be
5267 * scheduled on to the CPU at some point).
5269 if (event->state == PERF_EVENT_STATE_ERROR)
5272 if (count < event->read_size)
5275 WARN_ON_ONCE(event->ctx->parent_ctx);
5276 if (read_format & PERF_FORMAT_GROUP)
5277 ret = perf_read_group(event, read_format, buf);
5279 ret = perf_read_one(event, read_format, buf);
5285 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5287 struct perf_event *event = file->private_data;
5288 struct perf_event_context *ctx;
5291 ret = security_perf_event_read(event);
5295 ctx = perf_event_ctx_lock(event);
5296 ret = __perf_read(event, buf, count);
5297 perf_event_ctx_unlock(event, ctx);
5302 static __poll_t perf_poll(struct file *file, poll_table *wait)
5304 struct perf_event *event = file->private_data;
5305 struct perf_buffer *rb;
5306 __poll_t events = EPOLLHUP;
5308 poll_wait(file, &event->waitq, wait);
5310 if (is_event_hup(event))
5314 * Pin the event->rb by taking event->mmap_mutex; otherwise
5315 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5317 mutex_lock(&event->mmap_mutex);
5320 events = atomic_xchg(&rb->poll, 0);
5321 mutex_unlock(&event->mmap_mutex);
5325 static void _perf_event_reset(struct perf_event *event)
5327 (void)perf_event_read(event, false);
5328 local64_set(&event->count, 0);
5329 perf_event_update_userpage(event);
5332 /* Assume it's not an event with inherit set. */
5333 u64 perf_event_pause(struct perf_event *event, bool reset)
5335 struct perf_event_context *ctx;
5338 ctx = perf_event_ctx_lock(event);
5339 WARN_ON_ONCE(event->attr.inherit);
5340 _perf_event_disable(event);
5341 count = local64_read(&event->count);
5343 local64_set(&event->count, 0);
5344 perf_event_ctx_unlock(event, ctx);
5348 EXPORT_SYMBOL_GPL(perf_event_pause);
5351 * Holding the top-level event's child_mutex means that any
5352 * descendant process that has inherited this event will block
5353 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5354 * task existence requirements of perf_event_enable/disable.
5356 static void perf_event_for_each_child(struct perf_event *event,
5357 void (*func)(struct perf_event *))
5359 struct perf_event *child;
5361 WARN_ON_ONCE(event->ctx->parent_ctx);
5363 mutex_lock(&event->child_mutex);
5365 list_for_each_entry(child, &event->child_list, child_list)
5367 mutex_unlock(&event->child_mutex);
5370 static void perf_event_for_each(struct perf_event *event,
5371 void (*func)(struct perf_event *))
5373 struct perf_event_context *ctx = event->ctx;
5374 struct perf_event *sibling;
5376 lockdep_assert_held(&ctx->mutex);
5378 event = event->group_leader;
5380 perf_event_for_each_child(event, func);
5381 for_each_sibling_event(sibling, event)
5382 perf_event_for_each_child(sibling, func);
5385 static void __perf_event_period(struct perf_event *event,
5386 struct perf_cpu_context *cpuctx,
5387 struct perf_event_context *ctx,
5390 u64 value = *((u64 *)info);
5393 if (event->attr.freq) {
5394 event->attr.sample_freq = value;
5396 event->attr.sample_period = value;
5397 event->hw.sample_period = value;
5400 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5402 perf_pmu_disable(ctx->pmu);
5404 * We could be throttled; unthrottle now to avoid the tick
5405 * trying to unthrottle while we already re-started the event.
5407 if (event->hw.interrupts == MAX_INTERRUPTS) {
5408 event->hw.interrupts = 0;
5409 perf_log_throttle(event, 1);
5411 event->pmu->stop(event, PERF_EF_UPDATE);
5414 local64_set(&event->hw.period_left, 0);
5417 event->pmu->start(event, PERF_EF_RELOAD);
5418 perf_pmu_enable(ctx->pmu);
5422 static int perf_event_check_period(struct perf_event *event, u64 value)
5424 return event->pmu->check_period(event, value);
5427 static int _perf_event_period(struct perf_event *event, u64 value)
5429 if (!is_sampling_event(event))
5435 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5438 if (perf_event_check_period(event, value))
5441 if (!event->attr.freq && (value & (1ULL << 63)))
5444 event_function_call(event, __perf_event_period, &value);
5449 int perf_event_period(struct perf_event *event, u64 value)
5451 struct perf_event_context *ctx;
5454 ctx = perf_event_ctx_lock(event);
5455 ret = _perf_event_period(event, value);
5456 perf_event_ctx_unlock(event, ctx);
5460 EXPORT_SYMBOL_GPL(perf_event_period);
5462 static const struct file_operations perf_fops;
5464 static inline int perf_fget_light(int fd, struct fd *p)
5466 struct fd f = fdget(fd);
5470 if (f.file->f_op != &perf_fops) {
5478 static int perf_event_set_output(struct perf_event *event,
5479 struct perf_event *output_event);
5480 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5481 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5482 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5483 struct perf_event_attr *attr);
5485 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5487 void (*func)(struct perf_event *);
5491 case PERF_EVENT_IOC_ENABLE:
5492 func = _perf_event_enable;
5494 case PERF_EVENT_IOC_DISABLE:
5495 func = _perf_event_disable;
5497 case PERF_EVENT_IOC_RESET:
5498 func = _perf_event_reset;
5501 case PERF_EVENT_IOC_REFRESH:
5502 return _perf_event_refresh(event, arg);
5504 case PERF_EVENT_IOC_PERIOD:
5508 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5511 return _perf_event_period(event, value);
5513 case PERF_EVENT_IOC_ID:
5515 u64 id = primary_event_id(event);
5517 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5522 case PERF_EVENT_IOC_SET_OUTPUT:
5526 struct perf_event *output_event;
5528 ret = perf_fget_light(arg, &output);
5531 output_event = output.file->private_data;
5532 ret = perf_event_set_output(event, output_event);
5535 ret = perf_event_set_output(event, NULL);
5540 case PERF_EVENT_IOC_SET_FILTER:
5541 return perf_event_set_filter(event, (void __user *)arg);
5543 case PERF_EVENT_IOC_SET_BPF:
5544 return perf_event_set_bpf_prog(event, arg);
5546 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5547 struct perf_buffer *rb;
5550 rb = rcu_dereference(event->rb);
5551 if (!rb || !rb->nr_pages) {
5555 rb_toggle_paused(rb, !!arg);
5560 case PERF_EVENT_IOC_QUERY_BPF:
5561 return perf_event_query_prog_array(event, (void __user *)arg);
5563 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5564 struct perf_event_attr new_attr;
5565 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5571 return perf_event_modify_attr(event, &new_attr);
5577 if (flags & PERF_IOC_FLAG_GROUP)
5578 perf_event_for_each(event, func);
5580 perf_event_for_each_child(event, func);
5585 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5587 struct perf_event *event = file->private_data;
5588 struct perf_event_context *ctx;
5591 /* Treat ioctl like writes as it is likely a mutating operation. */
5592 ret = security_perf_event_write(event);
5596 ctx = perf_event_ctx_lock(event);
5597 ret = _perf_ioctl(event, cmd, arg);
5598 perf_event_ctx_unlock(event, ctx);
5603 #ifdef CONFIG_COMPAT
5604 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5607 switch (_IOC_NR(cmd)) {
5608 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5609 case _IOC_NR(PERF_EVENT_IOC_ID):
5610 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5611 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5612 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5613 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5614 cmd &= ~IOCSIZE_MASK;
5615 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5619 return perf_ioctl(file, cmd, arg);
5622 # define perf_compat_ioctl NULL
5625 int perf_event_task_enable(void)
5627 struct perf_event_context *ctx;
5628 struct perf_event *event;
5630 mutex_lock(¤t->perf_event_mutex);
5631 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5632 ctx = perf_event_ctx_lock(event);
5633 perf_event_for_each_child(event, _perf_event_enable);
5634 perf_event_ctx_unlock(event, ctx);
5636 mutex_unlock(¤t->perf_event_mutex);
5641 int perf_event_task_disable(void)
5643 struct perf_event_context *ctx;
5644 struct perf_event *event;
5646 mutex_lock(¤t->perf_event_mutex);
5647 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5648 ctx = perf_event_ctx_lock(event);
5649 perf_event_for_each_child(event, _perf_event_disable);
5650 perf_event_ctx_unlock(event, ctx);
5652 mutex_unlock(¤t->perf_event_mutex);
5657 static int perf_event_index(struct perf_event *event)
5659 if (event->hw.state & PERF_HES_STOPPED)
5662 if (event->state != PERF_EVENT_STATE_ACTIVE)
5665 return event->pmu->event_idx(event);
5668 static void calc_timer_values(struct perf_event *event,
5675 *now = perf_clock();
5676 ctx_time = event->shadow_ctx_time + *now;
5677 __perf_update_times(event, ctx_time, enabled, running);
5680 static void perf_event_init_userpage(struct perf_event *event)
5682 struct perf_event_mmap_page *userpg;
5683 struct perf_buffer *rb;
5686 rb = rcu_dereference(event->rb);
5690 userpg = rb->user_page;
5692 /* Allow new userspace to detect that bit 0 is deprecated */
5693 userpg->cap_bit0_is_deprecated = 1;
5694 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5695 userpg->data_offset = PAGE_SIZE;
5696 userpg->data_size = perf_data_size(rb);
5702 void __weak arch_perf_update_userpage(
5703 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5708 * Callers need to ensure there can be no nesting of this function, otherwise
5709 * the seqlock logic goes bad. We can not serialize this because the arch
5710 * code calls this from NMI context.
5712 void perf_event_update_userpage(struct perf_event *event)
5714 struct perf_event_mmap_page *userpg;
5715 struct perf_buffer *rb;
5716 u64 enabled, running, now;
5719 rb = rcu_dereference(event->rb);
5724 * compute total_time_enabled, total_time_running
5725 * based on snapshot values taken when the event
5726 * was last scheduled in.
5728 * we cannot simply called update_context_time()
5729 * because of locking issue as we can be called in
5732 calc_timer_values(event, &now, &enabled, &running);
5734 userpg = rb->user_page;
5736 * Disable preemption to guarantee consistent time stamps are stored to
5742 userpg->index = perf_event_index(event);
5743 userpg->offset = perf_event_count(event);
5745 userpg->offset -= local64_read(&event->hw.prev_count);
5747 userpg->time_enabled = enabled +
5748 atomic64_read(&event->child_total_time_enabled);
5750 userpg->time_running = running +
5751 atomic64_read(&event->child_total_time_running);
5753 arch_perf_update_userpage(event, userpg, now);
5761 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5763 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5765 struct perf_event *event = vmf->vma->vm_file->private_data;
5766 struct perf_buffer *rb;
5767 vm_fault_t ret = VM_FAULT_SIGBUS;
5769 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5770 if (vmf->pgoff == 0)
5776 rb = rcu_dereference(event->rb);
5780 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5783 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5787 get_page(vmf->page);
5788 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5789 vmf->page->index = vmf->pgoff;
5798 static void ring_buffer_attach(struct perf_event *event,
5799 struct perf_buffer *rb)
5801 struct perf_buffer *old_rb = NULL;
5802 unsigned long flags;
5806 * Should be impossible, we set this when removing
5807 * event->rb_entry and wait/clear when adding event->rb_entry.
5809 WARN_ON_ONCE(event->rcu_pending);
5812 spin_lock_irqsave(&old_rb->event_lock, flags);
5813 list_del_rcu(&event->rb_entry);
5814 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5816 event->rcu_batches = get_state_synchronize_rcu();
5817 event->rcu_pending = 1;
5821 if (event->rcu_pending) {
5822 cond_synchronize_rcu(event->rcu_batches);
5823 event->rcu_pending = 0;
5826 spin_lock_irqsave(&rb->event_lock, flags);
5827 list_add_rcu(&event->rb_entry, &rb->event_list);
5828 spin_unlock_irqrestore(&rb->event_lock, flags);
5832 * Avoid racing with perf_mmap_close(AUX): stop the event
5833 * before swizzling the event::rb pointer; if it's getting
5834 * unmapped, its aux_mmap_count will be 0 and it won't
5835 * restart. See the comment in __perf_pmu_output_stop().
5837 * Data will inevitably be lost when set_output is done in
5838 * mid-air, but then again, whoever does it like this is
5839 * not in for the data anyway.
5842 perf_event_stop(event, 0);
5844 rcu_assign_pointer(event->rb, rb);
5847 ring_buffer_put(old_rb);
5849 * Since we detached before setting the new rb, so that we
5850 * could attach the new rb, we could have missed a wakeup.
5853 wake_up_all(&event->waitq);
5857 static void ring_buffer_wakeup(struct perf_event *event)
5859 struct perf_buffer *rb;
5862 rb = rcu_dereference(event->rb);
5864 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5865 wake_up_all(&event->waitq);
5870 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5872 struct perf_buffer *rb;
5875 rb = rcu_dereference(event->rb);
5877 if (!refcount_inc_not_zero(&rb->refcount))
5885 void ring_buffer_put(struct perf_buffer *rb)
5887 if (!refcount_dec_and_test(&rb->refcount))
5890 WARN_ON_ONCE(!list_empty(&rb->event_list));
5892 call_rcu(&rb->rcu_head, rb_free_rcu);
5895 static void perf_mmap_open(struct vm_area_struct *vma)
5897 struct perf_event *event = vma->vm_file->private_data;
5899 atomic_inc(&event->mmap_count);
5900 atomic_inc(&event->rb->mmap_count);
5903 atomic_inc(&event->rb->aux_mmap_count);
5905 if (event->pmu->event_mapped)
5906 event->pmu->event_mapped(event, vma->vm_mm);
5909 static void perf_pmu_output_stop(struct perf_event *event);
5912 * A buffer can be mmap()ed multiple times; either directly through the same
5913 * event, or through other events by use of perf_event_set_output().
5915 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5916 * the buffer here, where we still have a VM context. This means we need
5917 * to detach all events redirecting to us.
5919 static void perf_mmap_close(struct vm_area_struct *vma)
5921 struct perf_event *event = vma->vm_file->private_data;
5922 struct perf_buffer *rb = ring_buffer_get(event);
5923 struct user_struct *mmap_user = rb->mmap_user;
5924 int mmap_locked = rb->mmap_locked;
5925 unsigned long size = perf_data_size(rb);
5926 bool detach_rest = false;
5928 if (event->pmu->event_unmapped)
5929 event->pmu->event_unmapped(event, vma->vm_mm);
5932 * rb->aux_mmap_count will always drop before rb->mmap_count and
5933 * event->mmap_count, so it is ok to use event->mmap_mutex to
5934 * serialize with perf_mmap here.
5936 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5937 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5939 * Stop all AUX events that are writing to this buffer,
5940 * so that we can free its AUX pages and corresponding PMU
5941 * data. Note that after rb::aux_mmap_count dropped to zero,
5942 * they won't start any more (see perf_aux_output_begin()).
5944 perf_pmu_output_stop(event);
5946 /* now it's safe to free the pages */
5947 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5948 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5950 /* this has to be the last one */
5952 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5954 mutex_unlock(&event->mmap_mutex);
5957 if (atomic_dec_and_test(&rb->mmap_count))
5960 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5963 ring_buffer_attach(event, NULL);
5964 mutex_unlock(&event->mmap_mutex);
5966 /* If there's still other mmap()s of this buffer, we're done. */
5971 * No other mmap()s, detach from all other events that might redirect
5972 * into the now unreachable buffer. Somewhat complicated by the
5973 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5977 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5978 if (!atomic_long_inc_not_zero(&event->refcount)) {
5980 * This event is en-route to free_event() which will
5981 * detach it and remove it from the list.
5987 mutex_lock(&event->mmap_mutex);
5989 * Check we didn't race with perf_event_set_output() which can
5990 * swizzle the rb from under us while we were waiting to
5991 * acquire mmap_mutex.
5993 * If we find a different rb; ignore this event, a next
5994 * iteration will no longer find it on the list. We have to
5995 * still restart the iteration to make sure we're not now
5996 * iterating the wrong list.
5998 if (event->rb == rb)
5999 ring_buffer_attach(event, NULL);
6001 mutex_unlock(&event->mmap_mutex);
6005 * Restart the iteration; either we're on the wrong list or
6006 * destroyed its integrity by doing a deletion.
6013 * It could be there's still a few 0-ref events on the list; they'll
6014 * get cleaned up by free_event() -- they'll also still have their
6015 * ref on the rb and will free it whenever they are done with it.
6017 * Aside from that, this buffer is 'fully' detached and unmapped,
6018 * undo the VM accounting.
6021 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6022 &mmap_user->locked_vm);
6023 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6024 free_uid(mmap_user);
6027 ring_buffer_put(rb); /* could be last */
6030 static const struct vm_operations_struct perf_mmap_vmops = {
6031 .open = perf_mmap_open,
6032 .close = perf_mmap_close, /* non mergeable */
6033 .fault = perf_mmap_fault,
6034 .page_mkwrite = perf_mmap_fault,
6037 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6039 struct perf_event *event = file->private_data;
6040 unsigned long user_locked, user_lock_limit;
6041 struct user_struct *user = current_user();
6042 struct perf_buffer *rb = NULL;
6043 unsigned long locked, lock_limit;
6044 unsigned long vma_size;
6045 unsigned long nr_pages;
6046 long user_extra = 0, extra = 0;
6047 int ret = 0, flags = 0;
6050 * Don't allow mmap() of inherited per-task counters. This would
6051 * create a performance issue due to all children writing to the
6054 if (event->cpu == -1 && event->attr.inherit)
6057 if (!(vma->vm_flags & VM_SHARED))
6060 ret = security_perf_event_read(event);
6064 vma_size = vma->vm_end - vma->vm_start;
6066 if (vma->vm_pgoff == 0) {
6067 nr_pages = (vma_size / PAGE_SIZE) - 1;
6070 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6071 * mapped, all subsequent mappings should have the same size
6072 * and offset. Must be above the normal perf buffer.
6074 u64 aux_offset, aux_size;
6079 nr_pages = vma_size / PAGE_SIZE;
6081 mutex_lock(&event->mmap_mutex);
6088 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6089 aux_size = READ_ONCE(rb->user_page->aux_size);
6091 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6094 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6097 /* already mapped with a different offset */
6098 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6101 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6104 /* already mapped with a different size */
6105 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6108 if (!is_power_of_2(nr_pages))
6111 if (!atomic_inc_not_zero(&rb->mmap_count))
6114 if (rb_has_aux(rb)) {
6115 atomic_inc(&rb->aux_mmap_count);
6120 atomic_set(&rb->aux_mmap_count, 1);
6121 user_extra = nr_pages;
6127 * If we have rb pages ensure they're a power-of-two number, so we
6128 * can do bitmasks instead of modulo.
6130 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6133 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6136 WARN_ON_ONCE(event->ctx->parent_ctx);
6138 mutex_lock(&event->mmap_mutex);
6140 if (event->rb->nr_pages != nr_pages) {
6145 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6147 * Raced against perf_mmap_close() through
6148 * perf_event_set_output(). Try again, hope for better
6151 mutex_unlock(&event->mmap_mutex);
6158 user_extra = nr_pages + 1;
6161 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6164 * Increase the limit linearly with more CPUs:
6166 user_lock_limit *= num_online_cpus();
6168 user_locked = atomic_long_read(&user->locked_vm);
6171 * sysctl_perf_event_mlock may have changed, so that
6172 * user->locked_vm > user_lock_limit
6174 if (user_locked > user_lock_limit)
6175 user_locked = user_lock_limit;
6176 user_locked += user_extra;
6178 if (user_locked > user_lock_limit) {
6180 * charge locked_vm until it hits user_lock_limit;
6181 * charge the rest from pinned_vm
6183 extra = user_locked - user_lock_limit;
6184 user_extra -= extra;
6187 lock_limit = rlimit(RLIMIT_MEMLOCK);
6188 lock_limit >>= PAGE_SHIFT;
6189 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6191 if ((locked > lock_limit) && perf_is_paranoid() &&
6192 !capable(CAP_IPC_LOCK)) {
6197 WARN_ON(!rb && event->rb);
6199 if (vma->vm_flags & VM_WRITE)
6200 flags |= RING_BUFFER_WRITABLE;
6203 rb = rb_alloc(nr_pages,
6204 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6212 atomic_set(&rb->mmap_count, 1);
6213 rb->mmap_user = get_current_user();
6214 rb->mmap_locked = extra;
6216 ring_buffer_attach(event, rb);
6218 perf_event_init_userpage(event);
6219 perf_event_update_userpage(event);
6221 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6222 event->attr.aux_watermark, flags);
6224 rb->aux_mmap_locked = extra;
6229 atomic_long_add(user_extra, &user->locked_vm);
6230 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6232 atomic_inc(&event->mmap_count);
6234 atomic_dec(&rb->mmap_count);
6237 mutex_unlock(&event->mmap_mutex);
6240 * Since pinned accounting is per vm we cannot allow fork() to copy our
6243 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6244 vma->vm_ops = &perf_mmap_vmops;
6246 if (event->pmu->event_mapped)
6247 event->pmu->event_mapped(event, vma->vm_mm);
6252 static int perf_fasync(int fd, struct file *filp, int on)
6254 struct inode *inode = file_inode(filp);
6255 struct perf_event *event = filp->private_data;
6259 retval = fasync_helper(fd, filp, on, &event->fasync);
6260 inode_unlock(inode);
6268 static const struct file_operations perf_fops = {
6269 .llseek = no_llseek,
6270 .release = perf_release,
6273 .unlocked_ioctl = perf_ioctl,
6274 .compat_ioctl = perf_compat_ioctl,
6276 .fasync = perf_fasync,
6282 * If there's data, ensure we set the poll() state and publish everything
6283 * to user-space before waking everybody up.
6286 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6288 /* only the parent has fasync state */
6290 event = event->parent;
6291 return &event->fasync;
6294 void perf_event_wakeup(struct perf_event *event)
6296 ring_buffer_wakeup(event);
6298 if (event->pending_kill) {
6299 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6300 event->pending_kill = 0;
6304 static void perf_pending_event_disable(struct perf_event *event)
6306 int cpu = READ_ONCE(event->pending_disable);
6311 if (cpu == smp_processor_id()) {
6312 WRITE_ONCE(event->pending_disable, -1);
6313 perf_event_disable_local(event);
6320 * perf_event_disable_inatomic()
6321 * @pending_disable = CPU-A;
6325 * @pending_disable = -1;
6328 * perf_event_disable_inatomic()
6329 * @pending_disable = CPU-B;
6330 * irq_work_queue(); // FAILS
6333 * perf_pending_event()
6335 * But the event runs on CPU-B and wants disabling there.
6337 irq_work_queue_on(&event->pending, cpu);
6340 static void perf_pending_event(struct irq_work *entry)
6342 struct perf_event *event = container_of(entry, struct perf_event, pending);
6345 rctx = perf_swevent_get_recursion_context();
6347 * If we 'fail' here, that's OK, it means recursion is already disabled
6348 * and we won't recurse 'further'.
6351 perf_pending_event_disable(event);
6353 if (event->pending_wakeup) {
6354 event->pending_wakeup = 0;
6355 perf_event_wakeup(event);
6359 perf_swevent_put_recursion_context(rctx);
6363 * We assume there is only KVM supporting the callbacks.
6364 * Later on, we might change it to a list if there is
6365 * another virtualization implementation supporting the callbacks.
6367 struct perf_guest_info_callbacks *perf_guest_cbs;
6369 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6371 perf_guest_cbs = cbs;
6374 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6376 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6378 perf_guest_cbs = NULL;
6381 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6384 perf_output_sample_regs(struct perf_output_handle *handle,
6385 struct pt_regs *regs, u64 mask)
6388 DECLARE_BITMAP(_mask, 64);
6390 bitmap_from_u64(_mask, mask);
6391 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6394 val = perf_reg_value(regs, bit);
6395 perf_output_put(handle, val);
6399 static void perf_sample_regs_user(struct perf_regs *regs_user,
6400 struct pt_regs *regs)
6402 if (user_mode(regs)) {
6403 regs_user->abi = perf_reg_abi(current);
6404 regs_user->regs = regs;
6405 } else if (!(current->flags & PF_KTHREAD)) {
6406 perf_get_regs_user(regs_user, regs);
6408 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6409 regs_user->regs = NULL;
6413 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6414 struct pt_regs *regs)
6416 regs_intr->regs = regs;
6417 regs_intr->abi = perf_reg_abi(current);
6422 * Get remaining task size from user stack pointer.
6424 * It'd be better to take stack vma map and limit this more
6425 * precisely, but there's no way to get it safely under interrupt,
6426 * so using TASK_SIZE as limit.
6428 static u64 perf_ustack_task_size(struct pt_regs *regs)
6430 unsigned long addr = perf_user_stack_pointer(regs);
6432 if (!addr || addr >= TASK_SIZE)
6435 return TASK_SIZE - addr;
6439 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6440 struct pt_regs *regs)
6444 /* No regs, no stack pointer, no dump. */
6449 * Check if we fit in with the requested stack size into the:
6451 * If we don't, we limit the size to the TASK_SIZE.
6453 * - remaining sample size
6454 * If we don't, we customize the stack size to
6455 * fit in to the remaining sample size.
6458 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6459 stack_size = min(stack_size, (u16) task_size);
6461 /* Current header size plus static size and dynamic size. */
6462 header_size += 2 * sizeof(u64);
6464 /* Do we fit in with the current stack dump size? */
6465 if ((u16) (header_size + stack_size) < header_size) {
6467 * If we overflow the maximum size for the sample,
6468 * we customize the stack dump size to fit in.
6470 stack_size = USHRT_MAX - header_size - sizeof(u64);
6471 stack_size = round_up(stack_size, sizeof(u64));
6478 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6479 struct pt_regs *regs)
6481 /* Case of a kernel thread, nothing to dump */
6484 perf_output_put(handle, size);
6494 * - the size requested by user or the best one we can fit
6495 * in to the sample max size
6497 * - user stack dump data
6499 * - the actual dumped size
6503 perf_output_put(handle, dump_size);
6506 sp = perf_user_stack_pointer(regs);
6507 fs = force_uaccess_begin();
6508 rem = __output_copy_user(handle, (void *) sp, dump_size);
6509 force_uaccess_end(fs);
6510 dyn_size = dump_size - rem;
6512 perf_output_skip(handle, rem);
6515 perf_output_put(handle, dyn_size);
6519 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6520 struct perf_sample_data *data,
6523 struct perf_event *sampler = event->aux_event;
6524 struct perf_buffer *rb;
6531 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6534 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6537 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6542 * If this is an NMI hit inside sampling code, don't take
6543 * the sample. See also perf_aux_sample_output().
6545 if (READ_ONCE(rb->aux_in_sampling)) {
6548 size = min_t(size_t, size, perf_aux_size(rb));
6549 data->aux_size = ALIGN(size, sizeof(u64));
6551 ring_buffer_put(rb);
6554 return data->aux_size;
6557 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6558 struct perf_event *event,
6559 struct perf_output_handle *handle,
6562 unsigned long flags;
6566 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6567 * paths. If we start calling them in NMI context, they may race with
6568 * the IRQ ones, that is, for example, re-starting an event that's just
6569 * been stopped, which is why we're using a separate callback that
6570 * doesn't change the event state.
6572 * IRQs need to be disabled to prevent IPIs from racing with us.
6574 local_irq_save(flags);
6576 * Guard against NMI hits inside the critical section;
6577 * see also perf_prepare_sample_aux().
6579 WRITE_ONCE(rb->aux_in_sampling, 1);
6582 ret = event->pmu->snapshot_aux(event, handle, size);
6585 WRITE_ONCE(rb->aux_in_sampling, 0);
6586 local_irq_restore(flags);
6591 static void perf_aux_sample_output(struct perf_event *event,
6592 struct perf_output_handle *handle,
6593 struct perf_sample_data *data)
6595 struct perf_event *sampler = event->aux_event;
6596 struct perf_buffer *rb;
6600 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6603 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6607 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6610 * An error here means that perf_output_copy() failed (returned a
6611 * non-zero surplus that it didn't copy), which in its current
6612 * enlightened implementation is not possible. If that changes, we'd
6615 if (WARN_ON_ONCE(size < 0))
6619 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6620 * perf_prepare_sample_aux(), so should not be more than that.
6622 pad = data->aux_size - size;
6623 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6628 perf_output_copy(handle, &zero, pad);
6632 ring_buffer_put(rb);
6635 static void __perf_event_header__init_id(struct perf_event_header *header,
6636 struct perf_sample_data *data,
6637 struct perf_event *event)
6639 u64 sample_type = event->attr.sample_type;
6641 data->type = sample_type;
6642 header->size += event->id_header_size;
6644 if (sample_type & PERF_SAMPLE_TID) {
6645 /* namespace issues */
6646 data->tid_entry.pid = perf_event_pid(event, current);
6647 data->tid_entry.tid = perf_event_tid(event, current);
6650 if (sample_type & PERF_SAMPLE_TIME)
6651 data->time = perf_event_clock(event);
6653 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6654 data->id = primary_event_id(event);
6656 if (sample_type & PERF_SAMPLE_STREAM_ID)
6657 data->stream_id = event->id;
6659 if (sample_type & PERF_SAMPLE_CPU) {
6660 data->cpu_entry.cpu = raw_smp_processor_id();
6661 data->cpu_entry.reserved = 0;
6665 void perf_event_header__init_id(struct perf_event_header *header,
6666 struct perf_sample_data *data,
6667 struct perf_event *event)
6669 if (event->attr.sample_id_all)
6670 __perf_event_header__init_id(header, data, event);
6673 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6674 struct perf_sample_data *data)
6676 u64 sample_type = data->type;
6678 if (sample_type & PERF_SAMPLE_TID)
6679 perf_output_put(handle, data->tid_entry);
6681 if (sample_type & PERF_SAMPLE_TIME)
6682 perf_output_put(handle, data->time);
6684 if (sample_type & PERF_SAMPLE_ID)
6685 perf_output_put(handle, data->id);
6687 if (sample_type & PERF_SAMPLE_STREAM_ID)
6688 perf_output_put(handle, data->stream_id);
6690 if (sample_type & PERF_SAMPLE_CPU)
6691 perf_output_put(handle, data->cpu_entry);
6693 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6694 perf_output_put(handle, data->id);
6697 void perf_event__output_id_sample(struct perf_event *event,
6698 struct perf_output_handle *handle,
6699 struct perf_sample_data *sample)
6701 if (event->attr.sample_id_all)
6702 __perf_event__output_id_sample(handle, sample);
6705 static void perf_output_read_one(struct perf_output_handle *handle,
6706 struct perf_event *event,
6707 u64 enabled, u64 running)
6709 u64 read_format = event->attr.read_format;
6713 values[n++] = perf_event_count(event);
6714 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6715 values[n++] = enabled +
6716 atomic64_read(&event->child_total_time_enabled);
6718 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6719 values[n++] = running +
6720 atomic64_read(&event->child_total_time_running);
6722 if (read_format & PERF_FORMAT_ID)
6723 values[n++] = primary_event_id(event);
6725 __output_copy(handle, values, n * sizeof(u64));
6728 static void perf_output_read_group(struct perf_output_handle *handle,
6729 struct perf_event *event,
6730 u64 enabled, u64 running)
6732 struct perf_event *leader = event->group_leader, *sub;
6733 u64 read_format = event->attr.read_format;
6737 values[n++] = 1 + leader->nr_siblings;
6739 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6740 values[n++] = enabled;
6742 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6743 values[n++] = running;
6745 if ((leader != event) &&
6746 (leader->state == PERF_EVENT_STATE_ACTIVE))
6747 leader->pmu->read(leader);
6749 values[n++] = perf_event_count(leader);
6750 if (read_format & PERF_FORMAT_ID)
6751 values[n++] = primary_event_id(leader);
6753 __output_copy(handle, values, n * sizeof(u64));
6755 for_each_sibling_event(sub, leader) {
6758 if ((sub != event) &&
6759 (sub->state == PERF_EVENT_STATE_ACTIVE))
6760 sub->pmu->read(sub);
6762 values[n++] = perf_event_count(sub);
6763 if (read_format & PERF_FORMAT_ID)
6764 values[n++] = primary_event_id(sub);
6766 __output_copy(handle, values, n * sizeof(u64));
6770 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6771 PERF_FORMAT_TOTAL_TIME_RUNNING)
6774 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6776 * The problem is that its both hard and excessively expensive to iterate the
6777 * child list, not to mention that its impossible to IPI the children running
6778 * on another CPU, from interrupt/NMI context.
6780 static void perf_output_read(struct perf_output_handle *handle,
6781 struct perf_event *event)
6783 u64 enabled = 0, running = 0, now;
6784 u64 read_format = event->attr.read_format;
6787 * compute total_time_enabled, total_time_running
6788 * based on snapshot values taken when the event
6789 * was last scheduled in.
6791 * we cannot simply called update_context_time()
6792 * because of locking issue as we are called in
6795 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6796 calc_timer_values(event, &now, &enabled, &running);
6798 if (event->attr.read_format & PERF_FORMAT_GROUP)
6799 perf_output_read_group(handle, event, enabled, running);
6801 perf_output_read_one(handle, event, enabled, running);
6804 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6806 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6809 void perf_output_sample(struct perf_output_handle *handle,
6810 struct perf_event_header *header,
6811 struct perf_sample_data *data,
6812 struct perf_event *event)
6814 u64 sample_type = data->type;
6816 perf_output_put(handle, *header);
6818 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6819 perf_output_put(handle, data->id);
6821 if (sample_type & PERF_SAMPLE_IP)
6822 perf_output_put(handle, data->ip);
6824 if (sample_type & PERF_SAMPLE_TID)
6825 perf_output_put(handle, data->tid_entry);
6827 if (sample_type & PERF_SAMPLE_TIME)
6828 perf_output_put(handle, data->time);
6830 if (sample_type & PERF_SAMPLE_ADDR)
6831 perf_output_put(handle, data->addr);
6833 if (sample_type & PERF_SAMPLE_ID)
6834 perf_output_put(handle, data->id);
6836 if (sample_type & PERF_SAMPLE_STREAM_ID)
6837 perf_output_put(handle, data->stream_id);
6839 if (sample_type & PERF_SAMPLE_CPU)
6840 perf_output_put(handle, data->cpu_entry);
6842 if (sample_type & PERF_SAMPLE_PERIOD)
6843 perf_output_put(handle, data->period);
6845 if (sample_type & PERF_SAMPLE_READ)
6846 perf_output_read(handle, event);
6848 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6851 size += data->callchain->nr;
6852 size *= sizeof(u64);
6853 __output_copy(handle, data->callchain, size);
6856 if (sample_type & PERF_SAMPLE_RAW) {
6857 struct perf_raw_record *raw = data->raw;
6860 struct perf_raw_frag *frag = &raw->frag;
6862 perf_output_put(handle, raw->size);
6865 __output_custom(handle, frag->copy,
6866 frag->data, frag->size);
6868 __output_copy(handle, frag->data,
6871 if (perf_raw_frag_last(frag))
6876 __output_skip(handle, NULL, frag->pad);
6882 .size = sizeof(u32),
6885 perf_output_put(handle, raw);
6889 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6890 if (data->br_stack) {
6893 size = data->br_stack->nr
6894 * sizeof(struct perf_branch_entry);
6896 perf_output_put(handle, data->br_stack->nr);
6897 if (perf_sample_save_hw_index(event))
6898 perf_output_put(handle, data->br_stack->hw_idx);
6899 perf_output_copy(handle, data->br_stack->entries, size);
6902 * we always store at least the value of nr
6905 perf_output_put(handle, nr);
6909 if (sample_type & PERF_SAMPLE_REGS_USER) {
6910 u64 abi = data->regs_user.abi;
6913 * If there are no regs to dump, notice it through
6914 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6916 perf_output_put(handle, abi);
6919 u64 mask = event->attr.sample_regs_user;
6920 perf_output_sample_regs(handle,
6921 data->regs_user.regs,
6926 if (sample_type & PERF_SAMPLE_STACK_USER) {
6927 perf_output_sample_ustack(handle,
6928 data->stack_user_size,
6929 data->regs_user.regs);
6932 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
6933 perf_output_put(handle, data->weight.full);
6935 if (sample_type & PERF_SAMPLE_DATA_SRC)
6936 perf_output_put(handle, data->data_src.val);
6938 if (sample_type & PERF_SAMPLE_TRANSACTION)
6939 perf_output_put(handle, data->txn);
6941 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6942 u64 abi = data->regs_intr.abi;
6944 * If there are no regs to dump, notice it through
6945 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6947 perf_output_put(handle, abi);
6950 u64 mask = event->attr.sample_regs_intr;
6952 perf_output_sample_regs(handle,
6953 data->regs_intr.regs,
6958 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6959 perf_output_put(handle, data->phys_addr);
6961 if (sample_type & PERF_SAMPLE_CGROUP)
6962 perf_output_put(handle, data->cgroup);
6964 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
6965 perf_output_put(handle, data->data_page_size);
6967 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
6968 perf_output_put(handle, data->code_page_size);
6970 if (sample_type & PERF_SAMPLE_AUX) {
6971 perf_output_put(handle, data->aux_size);
6974 perf_aux_sample_output(event, handle, data);
6977 if (!event->attr.watermark) {
6978 int wakeup_events = event->attr.wakeup_events;
6980 if (wakeup_events) {
6981 struct perf_buffer *rb = handle->rb;
6982 int events = local_inc_return(&rb->events);
6984 if (events >= wakeup_events) {
6985 local_sub(wakeup_events, &rb->events);
6986 local_inc(&rb->wakeup);
6992 static u64 perf_virt_to_phys(u64 virt)
6995 struct page *p = NULL;
7000 if (virt >= TASK_SIZE) {
7001 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7002 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7003 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7004 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7007 * Walking the pages tables for user address.
7008 * Interrupts are disabled, so it prevents any tear down
7009 * of the page tables.
7010 * Try IRQ-safe get_user_page_fast_only first.
7011 * If failed, leave phys_addr as 0.
7013 if (current->mm != NULL) {
7014 pagefault_disable();
7015 if (get_user_page_fast_only(virt, 0, &p))
7016 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7028 * Return the pagetable size of a given virtual address.
7030 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7034 #ifdef CONFIG_HAVE_FAST_GUP
7041 pgdp = pgd_offset(mm, addr);
7042 pgd = READ_ONCE(*pgdp);
7047 return pgd_leaf_size(pgd);
7049 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7050 p4d = READ_ONCE(*p4dp);
7051 if (!p4d_present(p4d))
7055 return p4d_leaf_size(p4d);
7057 pudp = pud_offset_lockless(p4dp, p4d, addr);
7058 pud = READ_ONCE(*pudp);
7059 if (!pud_present(pud))
7063 return pud_leaf_size(pud);
7065 pmdp = pmd_offset_lockless(pudp, pud, addr);
7066 pmd = READ_ONCE(*pmdp);
7067 if (!pmd_present(pmd))
7071 return pmd_leaf_size(pmd);
7073 ptep = pte_offset_map(&pmd, addr);
7074 pte = ptep_get_lockless(ptep);
7075 if (pte_present(pte))
7076 size = pte_leaf_size(pte);
7078 #endif /* CONFIG_HAVE_FAST_GUP */
7083 static u64 perf_get_page_size(unsigned long addr)
7085 struct mm_struct *mm;
7086 unsigned long flags;
7093 * Software page-table walkers must disable IRQs,
7094 * which prevents any tear down of the page tables.
7096 local_irq_save(flags);
7101 * For kernel threads and the like, use init_mm so that
7102 * we can find kernel memory.
7107 size = perf_get_pgtable_size(mm, addr);
7109 local_irq_restore(flags);
7114 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7116 struct perf_callchain_entry *
7117 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7119 bool kernel = !event->attr.exclude_callchain_kernel;
7120 bool user = !event->attr.exclude_callchain_user;
7121 /* Disallow cross-task user callchains. */
7122 bool crosstask = event->ctx->task && event->ctx->task != current;
7123 const u32 max_stack = event->attr.sample_max_stack;
7124 struct perf_callchain_entry *callchain;
7126 if (!kernel && !user)
7127 return &__empty_callchain;
7129 callchain = get_perf_callchain(regs, 0, kernel, user,
7130 max_stack, crosstask, true);
7131 return callchain ?: &__empty_callchain;
7134 void perf_prepare_sample(struct perf_event_header *header,
7135 struct perf_sample_data *data,
7136 struct perf_event *event,
7137 struct pt_regs *regs)
7139 u64 sample_type = event->attr.sample_type;
7141 header->type = PERF_RECORD_SAMPLE;
7142 header->size = sizeof(*header) + event->header_size;
7145 header->misc |= perf_misc_flags(regs);
7147 __perf_event_header__init_id(header, data, event);
7149 if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7150 data->ip = perf_instruction_pointer(regs);
7152 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7155 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7156 data->callchain = perf_callchain(event, regs);
7158 size += data->callchain->nr;
7160 header->size += size * sizeof(u64);
7163 if (sample_type & PERF_SAMPLE_RAW) {
7164 struct perf_raw_record *raw = data->raw;
7168 struct perf_raw_frag *frag = &raw->frag;
7173 if (perf_raw_frag_last(frag))
7178 size = round_up(sum + sizeof(u32), sizeof(u64));
7179 raw->size = size - sizeof(u32);
7180 frag->pad = raw->size - sum;
7185 header->size += size;
7188 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7189 int size = sizeof(u64); /* nr */
7190 if (data->br_stack) {
7191 if (perf_sample_save_hw_index(event))
7192 size += sizeof(u64);
7194 size += data->br_stack->nr
7195 * sizeof(struct perf_branch_entry);
7197 header->size += size;
7200 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7201 perf_sample_regs_user(&data->regs_user, regs);
7203 if (sample_type & PERF_SAMPLE_REGS_USER) {
7204 /* regs dump ABI info */
7205 int size = sizeof(u64);
7207 if (data->regs_user.regs) {
7208 u64 mask = event->attr.sample_regs_user;
7209 size += hweight64(mask) * sizeof(u64);
7212 header->size += size;
7215 if (sample_type & PERF_SAMPLE_STACK_USER) {
7217 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7218 * processed as the last one or have additional check added
7219 * in case new sample type is added, because we could eat
7220 * up the rest of the sample size.
7222 u16 stack_size = event->attr.sample_stack_user;
7223 u16 size = sizeof(u64);
7225 stack_size = perf_sample_ustack_size(stack_size, header->size,
7226 data->regs_user.regs);
7229 * If there is something to dump, add space for the dump
7230 * itself and for the field that tells the dynamic size,
7231 * which is how many have been actually dumped.
7234 size += sizeof(u64) + stack_size;
7236 data->stack_user_size = stack_size;
7237 header->size += size;
7240 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7241 /* regs dump ABI info */
7242 int size = sizeof(u64);
7244 perf_sample_regs_intr(&data->regs_intr, regs);
7246 if (data->regs_intr.regs) {
7247 u64 mask = event->attr.sample_regs_intr;
7249 size += hweight64(mask) * sizeof(u64);
7252 header->size += size;
7255 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7256 data->phys_addr = perf_virt_to_phys(data->addr);
7258 #ifdef CONFIG_CGROUP_PERF
7259 if (sample_type & PERF_SAMPLE_CGROUP) {
7260 struct cgroup *cgrp;
7262 /* protected by RCU */
7263 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7264 data->cgroup = cgroup_id(cgrp);
7269 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7270 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7271 * but the value will not dump to the userspace.
7273 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7274 data->data_page_size = perf_get_page_size(data->addr);
7276 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7277 data->code_page_size = perf_get_page_size(data->ip);
7279 if (sample_type & PERF_SAMPLE_AUX) {
7282 header->size += sizeof(u64); /* size */
7285 * Given the 16bit nature of header::size, an AUX sample can
7286 * easily overflow it, what with all the preceding sample bits.
7287 * Make sure this doesn't happen by using up to U16_MAX bytes
7288 * per sample in total (rounded down to 8 byte boundary).
7290 size = min_t(size_t, U16_MAX - header->size,
7291 event->attr.aux_sample_size);
7292 size = rounddown(size, 8);
7293 size = perf_prepare_sample_aux(event, data, size);
7295 WARN_ON_ONCE(size + header->size > U16_MAX);
7296 header->size += size;
7299 * If you're adding more sample types here, you likely need to do
7300 * something about the overflowing header::size, like repurpose the
7301 * lowest 3 bits of size, which should be always zero at the moment.
7302 * This raises a more important question, do we really need 512k sized
7303 * samples and why, so good argumentation is in order for whatever you
7306 WARN_ON_ONCE(header->size & 7);
7309 static __always_inline int
7310 __perf_event_output(struct perf_event *event,
7311 struct perf_sample_data *data,
7312 struct pt_regs *regs,
7313 int (*output_begin)(struct perf_output_handle *,
7314 struct perf_sample_data *,
7315 struct perf_event *,
7318 struct perf_output_handle handle;
7319 struct perf_event_header header;
7322 /* protect the callchain buffers */
7325 perf_prepare_sample(&header, data, event, regs);
7327 err = output_begin(&handle, data, event, header.size);
7331 perf_output_sample(&handle, &header, data, event);
7333 perf_output_end(&handle);
7341 perf_event_output_forward(struct perf_event *event,
7342 struct perf_sample_data *data,
7343 struct pt_regs *regs)
7345 __perf_event_output(event, data, regs, perf_output_begin_forward);
7349 perf_event_output_backward(struct perf_event *event,
7350 struct perf_sample_data *data,
7351 struct pt_regs *regs)
7353 __perf_event_output(event, data, regs, perf_output_begin_backward);
7357 perf_event_output(struct perf_event *event,
7358 struct perf_sample_data *data,
7359 struct pt_regs *regs)
7361 return __perf_event_output(event, data, regs, perf_output_begin);
7368 struct perf_read_event {
7369 struct perf_event_header header;
7376 perf_event_read_event(struct perf_event *event,
7377 struct task_struct *task)
7379 struct perf_output_handle handle;
7380 struct perf_sample_data sample;
7381 struct perf_read_event read_event = {
7383 .type = PERF_RECORD_READ,
7385 .size = sizeof(read_event) + event->read_size,
7387 .pid = perf_event_pid(event, task),
7388 .tid = perf_event_tid(event, task),
7392 perf_event_header__init_id(&read_event.header, &sample, event);
7393 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7397 perf_output_put(&handle, read_event);
7398 perf_output_read(&handle, event);
7399 perf_event__output_id_sample(event, &handle, &sample);
7401 perf_output_end(&handle);
7404 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7407 perf_iterate_ctx(struct perf_event_context *ctx,
7408 perf_iterate_f output,
7409 void *data, bool all)
7411 struct perf_event *event;
7413 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7415 if (event->state < PERF_EVENT_STATE_INACTIVE)
7417 if (!event_filter_match(event))
7421 output(event, data);
7425 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7427 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7428 struct perf_event *event;
7430 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7432 * Skip events that are not fully formed yet; ensure that
7433 * if we observe event->ctx, both event and ctx will be
7434 * complete enough. See perf_install_in_context().
7436 if (!smp_load_acquire(&event->ctx))
7439 if (event->state < PERF_EVENT_STATE_INACTIVE)
7441 if (!event_filter_match(event))
7443 output(event, data);
7448 * Iterate all events that need to receive side-band events.
7450 * For new callers; ensure that account_pmu_sb_event() includes
7451 * your event, otherwise it might not get delivered.
7454 perf_iterate_sb(perf_iterate_f output, void *data,
7455 struct perf_event_context *task_ctx)
7457 struct perf_event_context *ctx;
7464 * If we have task_ctx != NULL we only notify the task context itself.
7465 * The task_ctx is set only for EXIT events before releasing task
7469 perf_iterate_ctx(task_ctx, output, data, false);
7473 perf_iterate_sb_cpu(output, data);
7475 for_each_task_context_nr(ctxn) {
7476 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7478 perf_iterate_ctx(ctx, output, data, false);
7486 * Clear all file-based filters at exec, they'll have to be
7487 * re-instated when/if these objects are mmapped again.
7489 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7491 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7492 struct perf_addr_filter *filter;
7493 unsigned int restart = 0, count = 0;
7494 unsigned long flags;
7496 if (!has_addr_filter(event))
7499 raw_spin_lock_irqsave(&ifh->lock, flags);
7500 list_for_each_entry(filter, &ifh->list, entry) {
7501 if (filter->path.dentry) {
7502 event->addr_filter_ranges[count].start = 0;
7503 event->addr_filter_ranges[count].size = 0;
7511 event->addr_filters_gen++;
7512 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7515 perf_event_stop(event, 1);
7518 void perf_event_exec(void)
7520 struct perf_event_context *ctx;
7524 for_each_task_context_nr(ctxn) {
7525 ctx = current->perf_event_ctxp[ctxn];
7529 perf_event_enable_on_exec(ctxn);
7531 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7537 struct remote_output {
7538 struct perf_buffer *rb;
7542 static void __perf_event_output_stop(struct perf_event *event, void *data)
7544 struct perf_event *parent = event->parent;
7545 struct remote_output *ro = data;
7546 struct perf_buffer *rb = ro->rb;
7547 struct stop_event_data sd = {
7551 if (!has_aux(event))
7558 * In case of inheritance, it will be the parent that links to the
7559 * ring-buffer, but it will be the child that's actually using it.
7561 * We are using event::rb to determine if the event should be stopped,
7562 * however this may race with ring_buffer_attach() (through set_output),
7563 * which will make us skip the event that actually needs to be stopped.
7564 * So ring_buffer_attach() has to stop an aux event before re-assigning
7567 if (rcu_dereference(parent->rb) == rb)
7568 ro->err = __perf_event_stop(&sd);
7571 static int __perf_pmu_output_stop(void *info)
7573 struct perf_event *event = info;
7574 struct pmu *pmu = event->ctx->pmu;
7575 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7576 struct remote_output ro = {
7581 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7582 if (cpuctx->task_ctx)
7583 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7590 static void perf_pmu_output_stop(struct perf_event *event)
7592 struct perf_event *iter;
7597 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7599 * For per-CPU events, we need to make sure that neither they
7600 * nor their children are running; for cpu==-1 events it's
7601 * sufficient to stop the event itself if it's active, since
7602 * it can't have children.
7606 cpu = READ_ONCE(iter->oncpu);
7611 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7612 if (err == -EAGAIN) {
7621 * task tracking -- fork/exit
7623 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7626 struct perf_task_event {
7627 struct task_struct *task;
7628 struct perf_event_context *task_ctx;
7631 struct perf_event_header header;
7641 static int perf_event_task_match(struct perf_event *event)
7643 return event->attr.comm || event->attr.mmap ||
7644 event->attr.mmap2 || event->attr.mmap_data ||
7648 static void perf_event_task_output(struct perf_event *event,
7651 struct perf_task_event *task_event = data;
7652 struct perf_output_handle handle;
7653 struct perf_sample_data sample;
7654 struct task_struct *task = task_event->task;
7655 int ret, size = task_event->event_id.header.size;
7657 if (!perf_event_task_match(event))
7660 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7662 ret = perf_output_begin(&handle, &sample, event,
7663 task_event->event_id.header.size);
7667 task_event->event_id.pid = perf_event_pid(event, task);
7668 task_event->event_id.tid = perf_event_tid(event, task);
7670 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7671 task_event->event_id.ppid = perf_event_pid(event,
7673 task_event->event_id.ptid = perf_event_pid(event,
7675 } else { /* PERF_RECORD_FORK */
7676 task_event->event_id.ppid = perf_event_pid(event, current);
7677 task_event->event_id.ptid = perf_event_tid(event, current);
7680 task_event->event_id.time = perf_event_clock(event);
7682 perf_output_put(&handle, task_event->event_id);
7684 perf_event__output_id_sample(event, &handle, &sample);
7686 perf_output_end(&handle);
7688 task_event->event_id.header.size = size;
7691 static void perf_event_task(struct task_struct *task,
7692 struct perf_event_context *task_ctx,
7695 struct perf_task_event task_event;
7697 if (!atomic_read(&nr_comm_events) &&
7698 !atomic_read(&nr_mmap_events) &&
7699 !atomic_read(&nr_task_events))
7702 task_event = (struct perf_task_event){
7704 .task_ctx = task_ctx,
7707 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7709 .size = sizeof(task_event.event_id),
7719 perf_iterate_sb(perf_event_task_output,
7724 void perf_event_fork(struct task_struct *task)
7726 perf_event_task(task, NULL, 1);
7727 perf_event_namespaces(task);
7734 struct perf_comm_event {
7735 struct task_struct *task;
7740 struct perf_event_header header;
7747 static int perf_event_comm_match(struct perf_event *event)
7749 return event->attr.comm;
7752 static void perf_event_comm_output(struct perf_event *event,
7755 struct perf_comm_event *comm_event = data;
7756 struct perf_output_handle handle;
7757 struct perf_sample_data sample;
7758 int size = comm_event->event_id.header.size;
7761 if (!perf_event_comm_match(event))
7764 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7765 ret = perf_output_begin(&handle, &sample, event,
7766 comm_event->event_id.header.size);
7771 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7772 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7774 perf_output_put(&handle, comm_event->event_id);
7775 __output_copy(&handle, comm_event->comm,
7776 comm_event->comm_size);
7778 perf_event__output_id_sample(event, &handle, &sample);
7780 perf_output_end(&handle);
7782 comm_event->event_id.header.size = size;
7785 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7787 char comm[TASK_COMM_LEN];
7790 memset(comm, 0, sizeof(comm));
7791 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7792 size = ALIGN(strlen(comm)+1, sizeof(u64));
7794 comm_event->comm = comm;
7795 comm_event->comm_size = size;
7797 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7799 perf_iterate_sb(perf_event_comm_output,
7804 void perf_event_comm(struct task_struct *task, bool exec)
7806 struct perf_comm_event comm_event;
7808 if (!atomic_read(&nr_comm_events))
7811 comm_event = (struct perf_comm_event){
7817 .type = PERF_RECORD_COMM,
7818 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7826 perf_event_comm_event(&comm_event);
7830 * namespaces tracking
7833 struct perf_namespaces_event {
7834 struct task_struct *task;
7837 struct perf_event_header header;
7842 struct perf_ns_link_info link_info[NR_NAMESPACES];
7846 static int perf_event_namespaces_match(struct perf_event *event)
7848 return event->attr.namespaces;
7851 static void perf_event_namespaces_output(struct perf_event *event,
7854 struct perf_namespaces_event *namespaces_event = data;
7855 struct perf_output_handle handle;
7856 struct perf_sample_data sample;
7857 u16 header_size = namespaces_event->event_id.header.size;
7860 if (!perf_event_namespaces_match(event))
7863 perf_event_header__init_id(&namespaces_event->event_id.header,
7865 ret = perf_output_begin(&handle, &sample, event,
7866 namespaces_event->event_id.header.size);
7870 namespaces_event->event_id.pid = perf_event_pid(event,
7871 namespaces_event->task);
7872 namespaces_event->event_id.tid = perf_event_tid(event,
7873 namespaces_event->task);
7875 perf_output_put(&handle, namespaces_event->event_id);
7877 perf_event__output_id_sample(event, &handle, &sample);
7879 perf_output_end(&handle);
7881 namespaces_event->event_id.header.size = header_size;
7884 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7885 struct task_struct *task,
7886 const struct proc_ns_operations *ns_ops)
7888 struct path ns_path;
7889 struct inode *ns_inode;
7892 error = ns_get_path(&ns_path, task, ns_ops);
7894 ns_inode = ns_path.dentry->d_inode;
7895 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7896 ns_link_info->ino = ns_inode->i_ino;
7901 void perf_event_namespaces(struct task_struct *task)
7903 struct perf_namespaces_event namespaces_event;
7904 struct perf_ns_link_info *ns_link_info;
7906 if (!atomic_read(&nr_namespaces_events))
7909 namespaces_event = (struct perf_namespaces_event){
7913 .type = PERF_RECORD_NAMESPACES,
7915 .size = sizeof(namespaces_event.event_id),
7919 .nr_namespaces = NR_NAMESPACES,
7920 /* .link_info[NR_NAMESPACES] */
7924 ns_link_info = namespaces_event.event_id.link_info;
7926 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7927 task, &mntns_operations);
7929 #ifdef CONFIG_USER_NS
7930 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7931 task, &userns_operations);
7933 #ifdef CONFIG_NET_NS
7934 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7935 task, &netns_operations);
7937 #ifdef CONFIG_UTS_NS
7938 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7939 task, &utsns_operations);
7941 #ifdef CONFIG_IPC_NS
7942 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7943 task, &ipcns_operations);
7945 #ifdef CONFIG_PID_NS
7946 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7947 task, &pidns_operations);
7949 #ifdef CONFIG_CGROUPS
7950 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7951 task, &cgroupns_operations);
7954 perf_iterate_sb(perf_event_namespaces_output,
7962 #ifdef CONFIG_CGROUP_PERF
7964 struct perf_cgroup_event {
7968 struct perf_event_header header;
7974 static int perf_event_cgroup_match(struct perf_event *event)
7976 return event->attr.cgroup;
7979 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7981 struct perf_cgroup_event *cgroup_event = data;
7982 struct perf_output_handle handle;
7983 struct perf_sample_data sample;
7984 u16 header_size = cgroup_event->event_id.header.size;
7987 if (!perf_event_cgroup_match(event))
7990 perf_event_header__init_id(&cgroup_event->event_id.header,
7992 ret = perf_output_begin(&handle, &sample, event,
7993 cgroup_event->event_id.header.size);
7997 perf_output_put(&handle, cgroup_event->event_id);
7998 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8000 perf_event__output_id_sample(event, &handle, &sample);
8002 perf_output_end(&handle);
8004 cgroup_event->event_id.header.size = header_size;
8007 static void perf_event_cgroup(struct cgroup *cgrp)
8009 struct perf_cgroup_event cgroup_event;
8010 char path_enomem[16] = "//enomem";
8014 if (!atomic_read(&nr_cgroup_events))
8017 cgroup_event = (struct perf_cgroup_event){
8020 .type = PERF_RECORD_CGROUP,
8022 .size = sizeof(cgroup_event.event_id),
8024 .id = cgroup_id(cgrp),
8028 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8029 if (pathname == NULL) {
8030 cgroup_event.path = path_enomem;
8032 /* just to be sure to have enough space for alignment */
8033 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8034 cgroup_event.path = pathname;
8038 * Since our buffer works in 8 byte units we need to align our string
8039 * size to a multiple of 8. However, we must guarantee the tail end is
8040 * zero'd out to avoid leaking random bits to userspace.
8042 size = strlen(cgroup_event.path) + 1;
8043 while (!IS_ALIGNED(size, sizeof(u64)))
8044 cgroup_event.path[size++] = '\0';
8046 cgroup_event.event_id.header.size += size;
8047 cgroup_event.path_size = size;
8049 perf_iterate_sb(perf_event_cgroup_output,
8062 struct perf_mmap_event {
8063 struct vm_area_struct *vma;
8065 const char *file_name;
8071 u8 build_id[BUILD_ID_SIZE_MAX];
8075 struct perf_event_header header;
8085 static int perf_event_mmap_match(struct perf_event *event,
8088 struct perf_mmap_event *mmap_event = data;
8089 struct vm_area_struct *vma = mmap_event->vma;
8090 int executable = vma->vm_flags & VM_EXEC;
8092 return (!executable && event->attr.mmap_data) ||
8093 (executable && (event->attr.mmap || event->attr.mmap2));
8096 static void perf_event_mmap_output(struct perf_event *event,
8099 struct perf_mmap_event *mmap_event = data;
8100 struct perf_output_handle handle;
8101 struct perf_sample_data sample;
8102 int size = mmap_event->event_id.header.size;
8103 u32 type = mmap_event->event_id.header.type;
8107 if (!perf_event_mmap_match(event, data))
8110 if (event->attr.mmap2) {
8111 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8112 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8113 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8114 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8115 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8116 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8117 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8120 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8121 ret = perf_output_begin(&handle, &sample, event,
8122 mmap_event->event_id.header.size);
8126 mmap_event->event_id.pid = perf_event_pid(event, current);
8127 mmap_event->event_id.tid = perf_event_tid(event, current);
8129 use_build_id = event->attr.build_id && mmap_event->build_id_size;
8131 if (event->attr.mmap2 && use_build_id)
8132 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8134 perf_output_put(&handle, mmap_event->event_id);
8136 if (event->attr.mmap2) {
8138 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8140 __output_copy(&handle, size, 4);
8141 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8143 perf_output_put(&handle, mmap_event->maj);
8144 perf_output_put(&handle, mmap_event->min);
8145 perf_output_put(&handle, mmap_event->ino);
8146 perf_output_put(&handle, mmap_event->ino_generation);
8148 perf_output_put(&handle, mmap_event->prot);
8149 perf_output_put(&handle, mmap_event->flags);
8152 __output_copy(&handle, mmap_event->file_name,
8153 mmap_event->file_size);
8155 perf_event__output_id_sample(event, &handle, &sample);
8157 perf_output_end(&handle);
8159 mmap_event->event_id.header.size = size;
8160 mmap_event->event_id.header.type = type;
8163 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8165 struct vm_area_struct *vma = mmap_event->vma;
8166 struct file *file = vma->vm_file;
8167 int maj = 0, min = 0;
8168 u64 ino = 0, gen = 0;
8169 u32 prot = 0, flags = 0;
8175 if (vma->vm_flags & VM_READ)
8177 if (vma->vm_flags & VM_WRITE)
8179 if (vma->vm_flags & VM_EXEC)
8182 if (vma->vm_flags & VM_MAYSHARE)
8185 flags = MAP_PRIVATE;
8187 if (vma->vm_flags & VM_DENYWRITE)
8188 flags |= MAP_DENYWRITE;
8189 if (vma->vm_flags & VM_MAYEXEC)
8190 flags |= MAP_EXECUTABLE;
8191 if (vma->vm_flags & VM_LOCKED)
8192 flags |= MAP_LOCKED;
8193 if (is_vm_hugetlb_page(vma))
8194 flags |= MAP_HUGETLB;
8197 struct inode *inode;
8200 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8206 * d_path() works from the end of the rb backwards, so we
8207 * need to add enough zero bytes after the string to handle
8208 * the 64bit alignment we do later.
8210 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8215 inode = file_inode(vma->vm_file);
8216 dev = inode->i_sb->s_dev;
8218 gen = inode->i_generation;
8224 if (vma->vm_ops && vma->vm_ops->name) {
8225 name = (char *) vma->vm_ops->name(vma);
8230 name = (char *)arch_vma_name(vma);
8234 if (vma->vm_start <= vma->vm_mm->start_brk &&
8235 vma->vm_end >= vma->vm_mm->brk) {
8239 if (vma->vm_start <= vma->vm_mm->start_stack &&
8240 vma->vm_end >= vma->vm_mm->start_stack) {
8250 strlcpy(tmp, name, sizeof(tmp));
8254 * Since our buffer works in 8 byte units we need to align our string
8255 * size to a multiple of 8. However, we must guarantee the tail end is
8256 * zero'd out to avoid leaking random bits to userspace.
8258 size = strlen(name)+1;
8259 while (!IS_ALIGNED(size, sizeof(u64)))
8260 name[size++] = '\0';
8262 mmap_event->file_name = name;
8263 mmap_event->file_size = size;
8264 mmap_event->maj = maj;
8265 mmap_event->min = min;
8266 mmap_event->ino = ino;
8267 mmap_event->ino_generation = gen;
8268 mmap_event->prot = prot;
8269 mmap_event->flags = flags;
8271 if (!(vma->vm_flags & VM_EXEC))
8272 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8274 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8276 if (atomic_read(&nr_build_id_events))
8277 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8279 perf_iterate_sb(perf_event_mmap_output,
8287 * Check whether inode and address range match filter criteria.
8289 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8290 struct file *file, unsigned long offset,
8293 /* d_inode(NULL) won't be equal to any mapped user-space file */
8294 if (!filter->path.dentry)
8297 if (d_inode(filter->path.dentry) != file_inode(file))
8300 if (filter->offset > offset + size)
8303 if (filter->offset + filter->size < offset)
8309 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8310 struct vm_area_struct *vma,
8311 struct perf_addr_filter_range *fr)
8313 unsigned long vma_size = vma->vm_end - vma->vm_start;
8314 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8315 struct file *file = vma->vm_file;
8317 if (!perf_addr_filter_match(filter, file, off, vma_size))
8320 if (filter->offset < off) {
8321 fr->start = vma->vm_start;
8322 fr->size = min(vma_size, filter->size - (off - filter->offset));
8324 fr->start = vma->vm_start + filter->offset - off;
8325 fr->size = min(vma->vm_end - fr->start, filter->size);
8331 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8333 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8334 struct vm_area_struct *vma = data;
8335 struct perf_addr_filter *filter;
8336 unsigned int restart = 0, count = 0;
8337 unsigned long flags;
8339 if (!has_addr_filter(event))
8345 raw_spin_lock_irqsave(&ifh->lock, flags);
8346 list_for_each_entry(filter, &ifh->list, entry) {
8347 if (perf_addr_filter_vma_adjust(filter, vma,
8348 &event->addr_filter_ranges[count]))
8355 event->addr_filters_gen++;
8356 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8359 perf_event_stop(event, 1);
8363 * Adjust all task's events' filters to the new vma
8365 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8367 struct perf_event_context *ctx;
8371 * Data tracing isn't supported yet and as such there is no need
8372 * to keep track of anything that isn't related to executable code:
8374 if (!(vma->vm_flags & VM_EXEC))
8378 for_each_task_context_nr(ctxn) {
8379 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8383 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8388 void perf_event_mmap(struct vm_area_struct *vma)
8390 struct perf_mmap_event mmap_event;
8392 if (!atomic_read(&nr_mmap_events))
8395 mmap_event = (struct perf_mmap_event){
8401 .type = PERF_RECORD_MMAP,
8402 .misc = PERF_RECORD_MISC_USER,
8407 .start = vma->vm_start,
8408 .len = vma->vm_end - vma->vm_start,
8409 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8411 /* .maj (attr_mmap2 only) */
8412 /* .min (attr_mmap2 only) */
8413 /* .ino (attr_mmap2 only) */
8414 /* .ino_generation (attr_mmap2 only) */
8415 /* .prot (attr_mmap2 only) */
8416 /* .flags (attr_mmap2 only) */
8419 perf_addr_filters_adjust(vma);
8420 perf_event_mmap_event(&mmap_event);
8423 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8424 unsigned long size, u64 flags)
8426 struct perf_output_handle handle;
8427 struct perf_sample_data sample;
8428 struct perf_aux_event {
8429 struct perf_event_header header;
8435 .type = PERF_RECORD_AUX,
8437 .size = sizeof(rec),
8445 perf_event_header__init_id(&rec.header, &sample, event);
8446 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8451 perf_output_put(&handle, rec);
8452 perf_event__output_id_sample(event, &handle, &sample);
8454 perf_output_end(&handle);
8458 * Lost/dropped samples logging
8460 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8462 struct perf_output_handle handle;
8463 struct perf_sample_data sample;
8467 struct perf_event_header header;
8469 } lost_samples_event = {
8471 .type = PERF_RECORD_LOST_SAMPLES,
8473 .size = sizeof(lost_samples_event),
8478 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8480 ret = perf_output_begin(&handle, &sample, event,
8481 lost_samples_event.header.size);
8485 perf_output_put(&handle, lost_samples_event);
8486 perf_event__output_id_sample(event, &handle, &sample);
8487 perf_output_end(&handle);
8491 * context_switch tracking
8494 struct perf_switch_event {
8495 struct task_struct *task;
8496 struct task_struct *next_prev;
8499 struct perf_event_header header;
8505 static int perf_event_switch_match(struct perf_event *event)
8507 return event->attr.context_switch;
8510 static void perf_event_switch_output(struct perf_event *event, void *data)
8512 struct perf_switch_event *se = data;
8513 struct perf_output_handle handle;
8514 struct perf_sample_data sample;
8517 if (!perf_event_switch_match(event))
8520 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8521 if (event->ctx->task) {
8522 se->event_id.header.type = PERF_RECORD_SWITCH;
8523 se->event_id.header.size = sizeof(se->event_id.header);
8525 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8526 se->event_id.header.size = sizeof(se->event_id);
8527 se->event_id.next_prev_pid =
8528 perf_event_pid(event, se->next_prev);
8529 se->event_id.next_prev_tid =
8530 perf_event_tid(event, se->next_prev);
8533 perf_event_header__init_id(&se->event_id.header, &sample, event);
8535 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8539 if (event->ctx->task)
8540 perf_output_put(&handle, se->event_id.header);
8542 perf_output_put(&handle, se->event_id);
8544 perf_event__output_id_sample(event, &handle, &sample);
8546 perf_output_end(&handle);
8549 static void perf_event_switch(struct task_struct *task,
8550 struct task_struct *next_prev, bool sched_in)
8552 struct perf_switch_event switch_event;
8554 /* N.B. caller checks nr_switch_events != 0 */
8556 switch_event = (struct perf_switch_event){
8558 .next_prev = next_prev,
8562 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8565 /* .next_prev_pid */
8566 /* .next_prev_tid */
8570 if (!sched_in && task->state == TASK_RUNNING)
8571 switch_event.event_id.header.misc |=
8572 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8574 perf_iterate_sb(perf_event_switch_output,
8580 * IRQ throttle logging
8583 static void perf_log_throttle(struct perf_event *event, int enable)
8585 struct perf_output_handle handle;
8586 struct perf_sample_data sample;
8590 struct perf_event_header header;
8594 } throttle_event = {
8596 .type = PERF_RECORD_THROTTLE,
8598 .size = sizeof(throttle_event),
8600 .time = perf_event_clock(event),
8601 .id = primary_event_id(event),
8602 .stream_id = event->id,
8606 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8608 perf_event_header__init_id(&throttle_event.header, &sample, event);
8610 ret = perf_output_begin(&handle, &sample, event,
8611 throttle_event.header.size);
8615 perf_output_put(&handle, throttle_event);
8616 perf_event__output_id_sample(event, &handle, &sample);
8617 perf_output_end(&handle);
8621 * ksymbol register/unregister tracking
8624 struct perf_ksymbol_event {
8628 struct perf_event_header header;
8636 static int perf_event_ksymbol_match(struct perf_event *event)
8638 return event->attr.ksymbol;
8641 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8643 struct perf_ksymbol_event *ksymbol_event = data;
8644 struct perf_output_handle handle;
8645 struct perf_sample_data sample;
8648 if (!perf_event_ksymbol_match(event))
8651 perf_event_header__init_id(&ksymbol_event->event_id.header,
8653 ret = perf_output_begin(&handle, &sample, event,
8654 ksymbol_event->event_id.header.size);
8658 perf_output_put(&handle, ksymbol_event->event_id);
8659 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8660 perf_event__output_id_sample(event, &handle, &sample);
8662 perf_output_end(&handle);
8665 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8668 struct perf_ksymbol_event ksymbol_event;
8669 char name[KSYM_NAME_LEN];
8673 if (!atomic_read(&nr_ksymbol_events))
8676 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8677 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8680 strlcpy(name, sym, KSYM_NAME_LEN);
8681 name_len = strlen(name) + 1;
8682 while (!IS_ALIGNED(name_len, sizeof(u64)))
8683 name[name_len++] = '\0';
8684 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8687 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8689 ksymbol_event = (struct perf_ksymbol_event){
8691 .name_len = name_len,
8694 .type = PERF_RECORD_KSYMBOL,
8695 .size = sizeof(ksymbol_event.event_id) +
8700 .ksym_type = ksym_type,
8705 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8708 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8712 * bpf program load/unload tracking
8715 struct perf_bpf_event {
8716 struct bpf_prog *prog;
8718 struct perf_event_header header;
8722 u8 tag[BPF_TAG_SIZE];
8726 static int perf_event_bpf_match(struct perf_event *event)
8728 return event->attr.bpf_event;
8731 static void perf_event_bpf_output(struct perf_event *event, void *data)
8733 struct perf_bpf_event *bpf_event = data;
8734 struct perf_output_handle handle;
8735 struct perf_sample_data sample;
8738 if (!perf_event_bpf_match(event))
8741 perf_event_header__init_id(&bpf_event->event_id.header,
8743 ret = perf_output_begin(&handle, data, event,
8744 bpf_event->event_id.header.size);
8748 perf_output_put(&handle, bpf_event->event_id);
8749 perf_event__output_id_sample(event, &handle, &sample);
8751 perf_output_end(&handle);
8754 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8755 enum perf_bpf_event_type type)
8757 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8760 if (prog->aux->func_cnt == 0) {
8761 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8762 (u64)(unsigned long)prog->bpf_func,
8763 prog->jited_len, unregister,
8764 prog->aux->ksym.name);
8766 for (i = 0; i < prog->aux->func_cnt; i++) {
8767 struct bpf_prog *subprog = prog->aux->func[i];
8770 PERF_RECORD_KSYMBOL_TYPE_BPF,
8771 (u64)(unsigned long)subprog->bpf_func,
8772 subprog->jited_len, unregister,
8773 prog->aux->ksym.name);
8778 void perf_event_bpf_event(struct bpf_prog *prog,
8779 enum perf_bpf_event_type type,
8782 struct perf_bpf_event bpf_event;
8784 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8785 type >= PERF_BPF_EVENT_MAX)
8789 case PERF_BPF_EVENT_PROG_LOAD:
8790 case PERF_BPF_EVENT_PROG_UNLOAD:
8791 if (atomic_read(&nr_ksymbol_events))
8792 perf_event_bpf_emit_ksymbols(prog, type);
8798 if (!atomic_read(&nr_bpf_events))
8801 bpf_event = (struct perf_bpf_event){
8805 .type = PERF_RECORD_BPF_EVENT,
8806 .size = sizeof(bpf_event.event_id),
8810 .id = prog->aux->id,
8814 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8816 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8817 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8820 struct perf_text_poke_event {
8821 const void *old_bytes;
8822 const void *new_bytes;
8828 struct perf_event_header header;
8834 static int perf_event_text_poke_match(struct perf_event *event)
8836 return event->attr.text_poke;
8839 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8841 struct perf_text_poke_event *text_poke_event = data;
8842 struct perf_output_handle handle;
8843 struct perf_sample_data sample;
8847 if (!perf_event_text_poke_match(event))
8850 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8852 ret = perf_output_begin(&handle, &sample, event,
8853 text_poke_event->event_id.header.size);
8857 perf_output_put(&handle, text_poke_event->event_id);
8858 perf_output_put(&handle, text_poke_event->old_len);
8859 perf_output_put(&handle, text_poke_event->new_len);
8861 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8862 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8864 if (text_poke_event->pad)
8865 __output_copy(&handle, &padding, text_poke_event->pad);
8867 perf_event__output_id_sample(event, &handle, &sample);
8869 perf_output_end(&handle);
8872 void perf_event_text_poke(const void *addr, const void *old_bytes,
8873 size_t old_len, const void *new_bytes, size_t new_len)
8875 struct perf_text_poke_event text_poke_event;
8878 if (!atomic_read(&nr_text_poke_events))
8881 tot = sizeof(text_poke_event.old_len) + old_len;
8882 tot += sizeof(text_poke_event.new_len) + new_len;
8883 pad = ALIGN(tot, sizeof(u64)) - tot;
8885 text_poke_event = (struct perf_text_poke_event){
8886 .old_bytes = old_bytes,
8887 .new_bytes = new_bytes,
8893 .type = PERF_RECORD_TEXT_POKE,
8894 .misc = PERF_RECORD_MISC_KERNEL,
8895 .size = sizeof(text_poke_event.event_id) + tot + pad,
8897 .addr = (unsigned long)addr,
8901 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8904 void perf_event_itrace_started(struct perf_event *event)
8906 event->attach_state |= PERF_ATTACH_ITRACE;
8909 static void perf_log_itrace_start(struct perf_event *event)
8911 struct perf_output_handle handle;
8912 struct perf_sample_data sample;
8913 struct perf_aux_event {
8914 struct perf_event_header header;
8921 event = event->parent;
8923 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8924 event->attach_state & PERF_ATTACH_ITRACE)
8927 rec.header.type = PERF_RECORD_ITRACE_START;
8928 rec.header.misc = 0;
8929 rec.header.size = sizeof(rec);
8930 rec.pid = perf_event_pid(event, current);
8931 rec.tid = perf_event_tid(event, current);
8933 perf_event_header__init_id(&rec.header, &sample, event);
8934 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8939 perf_output_put(&handle, rec);
8940 perf_event__output_id_sample(event, &handle, &sample);
8942 perf_output_end(&handle);
8946 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8948 struct hw_perf_event *hwc = &event->hw;
8952 seq = __this_cpu_read(perf_throttled_seq);
8953 if (seq != hwc->interrupts_seq) {
8954 hwc->interrupts_seq = seq;
8955 hwc->interrupts = 1;
8958 if (unlikely(throttle
8959 && hwc->interrupts >= max_samples_per_tick)) {
8960 __this_cpu_inc(perf_throttled_count);
8961 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8962 hwc->interrupts = MAX_INTERRUPTS;
8963 perf_log_throttle(event, 0);
8968 if (event->attr.freq) {
8969 u64 now = perf_clock();
8970 s64 delta = now - hwc->freq_time_stamp;
8972 hwc->freq_time_stamp = now;
8974 if (delta > 0 && delta < 2*TICK_NSEC)
8975 perf_adjust_period(event, delta, hwc->last_period, true);
8981 int perf_event_account_interrupt(struct perf_event *event)
8983 return __perf_event_account_interrupt(event, 1);
8987 * Generic event overflow handling, sampling.
8990 static int __perf_event_overflow(struct perf_event *event,
8991 int throttle, struct perf_sample_data *data,
8992 struct pt_regs *regs)
8994 int events = atomic_read(&event->event_limit);
8998 * Non-sampling counters might still use the PMI to fold short
8999 * hardware counters, ignore those.
9001 if (unlikely(!is_sampling_event(event)))
9004 ret = __perf_event_account_interrupt(event, throttle);
9007 * XXX event_limit might not quite work as expected on inherited
9011 event->pending_kill = POLL_IN;
9012 if (events && atomic_dec_and_test(&event->event_limit)) {
9014 event->pending_kill = POLL_HUP;
9016 perf_event_disable_inatomic(event);
9019 READ_ONCE(event->overflow_handler)(event, data, regs);
9021 if (*perf_event_fasync(event) && event->pending_kill) {
9022 event->pending_wakeup = 1;
9023 irq_work_queue(&event->pending);
9029 int perf_event_overflow(struct perf_event *event,
9030 struct perf_sample_data *data,
9031 struct pt_regs *regs)
9033 return __perf_event_overflow(event, 1, data, regs);
9037 * Generic software event infrastructure
9040 struct swevent_htable {
9041 struct swevent_hlist *swevent_hlist;
9042 struct mutex hlist_mutex;
9045 /* Recursion avoidance in each contexts */
9046 int recursion[PERF_NR_CONTEXTS];
9049 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9052 * We directly increment event->count and keep a second value in
9053 * event->hw.period_left to count intervals. This period event
9054 * is kept in the range [-sample_period, 0] so that we can use the
9058 u64 perf_swevent_set_period(struct perf_event *event)
9060 struct hw_perf_event *hwc = &event->hw;
9061 u64 period = hwc->last_period;
9065 hwc->last_period = hwc->sample_period;
9068 old = val = local64_read(&hwc->period_left);
9072 nr = div64_u64(period + val, period);
9073 offset = nr * period;
9075 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9081 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9082 struct perf_sample_data *data,
9083 struct pt_regs *regs)
9085 struct hw_perf_event *hwc = &event->hw;
9089 overflow = perf_swevent_set_period(event);
9091 if (hwc->interrupts == MAX_INTERRUPTS)
9094 for (; overflow; overflow--) {
9095 if (__perf_event_overflow(event, throttle,
9098 * We inhibit the overflow from happening when
9099 * hwc->interrupts == MAX_INTERRUPTS.
9107 static void perf_swevent_event(struct perf_event *event, u64 nr,
9108 struct perf_sample_data *data,
9109 struct pt_regs *regs)
9111 struct hw_perf_event *hwc = &event->hw;
9113 local64_add(nr, &event->count);
9118 if (!is_sampling_event(event))
9121 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9123 return perf_swevent_overflow(event, 1, data, regs);
9125 data->period = event->hw.last_period;
9127 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9128 return perf_swevent_overflow(event, 1, data, regs);
9130 if (local64_add_negative(nr, &hwc->period_left))
9133 perf_swevent_overflow(event, 0, data, regs);
9136 static int perf_exclude_event(struct perf_event *event,
9137 struct pt_regs *regs)
9139 if (event->hw.state & PERF_HES_STOPPED)
9143 if (event->attr.exclude_user && user_mode(regs))
9146 if (event->attr.exclude_kernel && !user_mode(regs))
9153 static int perf_swevent_match(struct perf_event *event,
9154 enum perf_type_id type,
9156 struct perf_sample_data *data,
9157 struct pt_regs *regs)
9159 if (event->attr.type != type)
9162 if (event->attr.config != event_id)
9165 if (perf_exclude_event(event, regs))
9171 static inline u64 swevent_hash(u64 type, u32 event_id)
9173 u64 val = event_id | (type << 32);
9175 return hash_64(val, SWEVENT_HLIST_BITS);
9178 static inline struct hlist_head *
9179 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9181 u64 hash = swevent_hash(type, event_id);
9183 return &hlist->heads[hash];
9186 /* For the read side: events when they trigger */
9187 static inline struct hlist_head *
9188 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9190 struct swevent_hlist *hlist;
9192 hlist = rcu_dereference(swhash->swevent_hlist);
9196 return __find_swevent_head(hlist, type, event_id);
9199 /* For the event head insertion and removal in the hlist */
9200 static inline struct hlist_head *
9201 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9203 struct swevent_hlist *hlist;
9204 u32 event_id = event->attr.config;
9205 u64 type = event->attr.type;
9208 * Event scheduling is always serialized against hlist allocation
9209 * and release. Which makes the protected version suitable here.
9210 * The context lock guarantees that.
9212 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9213 lockdep_is_held(&event->ctx->lock));
9217 return __find_swevent_head(hlist, type, event_id);
9220 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9222 struct perf_sample_data *data,
9223 struct pt_regs *regs)
9225 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9226 struct perf_event *event;
9227 struct hlist_head *head;
9230 head = find_swevent_head_rcu(swhash, type, event_id);
9234 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9235 if (perf_swevent_match(event, type, event_id, data, regs))
9236 perf_swevent_event(event, nr, data, regs);
9242 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9244 int perf_swevent_get_recursion_context(void)
9246 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9248 return get_recursion_context(swhash->recursion);
9250 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9252 void perf_swevent_put_recursion_context(int rctx)
9254 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9256 put_recursion_context(swhash->recursion, rctx);
9259 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9261 struct perf_sample_data data;
9263 if (WARN_ON_ONCE(!regs))
9266 perf_sample_data_init(&data, addr, 0);
9267 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9270 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9274 preempt_disable_notrace();
9275 rctx = perf_swevent_get_recursion_context();
9276 if (unlikely(rctx < 0))
9279 ___perf_sw_event(event_id, nr, regs, addr);
9281 perf_swevent_put_recursion_context(rctx);
9283 preempt_enable_notrace();
9286 static void perf_swevent_read(struct perf_event *event)
9290 static int perf_swevent_add(struct perf_event *event, int flags)
9292 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9293 struct hw_perf_event *hwc = &event->hw;
9294 struct hlist_head *head;
9296 if (is_sampling_event(event)) {
9297 hwc->last_period = hwc->sample_period;
9298 perf_swevent_set_period(event);
9301 hwc->state = !(flags & PERF_EF_START);
9303 head = find_swevent_head(swhash, event);
9304 if (WARN_ON_ONCE(!head))
9307 hlist_add_head_rcu(&event->hlist_entry, head);
9308 perf_event_update_userpage(event);
9313 static void perf_swevent_del(struct perf_event *event, int flags)
9315 hlist_del_rcu(&event->hlist_entry);
9318 static void perf_swevent_start(struct perf_event *event, int flags)
9320 event->hw.state = 0;
9323 static void perf_swevent_stop(struct perf_event *event, int flags)
9325 event->hw.state = PERF_HES_STOPPED;
9328 /* Deref the hlist from the update side */
9329 static inline struct swevent_hlist *
9330 swevent_hlist_deref(struct swevent_htable *swhash)
9332 return rcu_dereference_protected(swhash->swevent_hlist,
9333 lockdep_is_held(&swhash->hlist_mutex));
9336 static void swevent_hlist_release(struct swevent_htable *swhash)
9338 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9343 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9344 kfree_rcu(hlist, rcu_head);
9347 static void swevent_hlist_put_cpu(int cpu)
9349 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9351 mutex_lock(&swhash->hlist_mutex);
9353 if (!--swhash->hlist_refcount)
9354 swevent_hlist_release(swhash);
9356 mutex_unlock(&swhash->hlist_mutex);
9359 static void swevent_hlist_put(void)
9363 for_each_possible_cpu(cpu)
9364 swevent_hlist_put_cpu(cpu);
9367 static int swevent_hlist_get_cpu(int cpu)
9369 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9372 mutex_lock(&swhash->hlist_mutex);
9373 if (!swevent_hlist_deref(swhash) &&
9374 cpumask_test_cpu(cpu, perf_online_mask)) {
9375 struct swevent_hlist *hlist;
9377 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9382 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9384 swhash->hlist_refcount++;
9386 mutex_unlock(&swhash->hlist_mutex);
9391 static int swevent_hlist_get(void)
9393 int err, cpu, failed_cpu;
9395 mutex_lock(&pmus_lock);
9396 for_each_possible_cpu(cpu) {
9397 err = swevent_hlist_get_cpu(cpu);
9403 mutex_unlock(&pmus_lock);
9406 for_each_possible_cpu(cpu) {
9407 if (cpu == failed_cpu)
9409 swevent_hlist_put_cpu(cpu);
9411 mutex_unlock(&pmus_lock);
9415 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9417 static void sw_perf_event_destroy(struct perf_event *event)
9419 u64 event_id = event->attr.config;
9421 WARN_ON(event->parent);
9423 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9424 swevent_hlist_put();
9427 static int perf_swevent_init(struct perf_event *event)
9429 u64 event_id = event->attr.config;
9431 if (event->attr.type != PERF_TYPE_SOFTWARE)
9435 * no branch sampling for software events
9437 if (has_branch_stack(event))
9441 case PERF_COUNT_SW_CPU_CLOCK:
9442 case PERF_COUNT_SW_TASK_CLOCK:
9449 if (event_id >= PERF_COUNT_SW_MAX)
9452 if (!event->parent) {
9455 err = swevent_hlist_get();
9459 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9460 event->destroy = sw_perf_event_destroy;
9466 static struct pmu perf_swevent = {
9467 .task_ctx_nr = perf_sw_context,
9469 .capabilities = PERF_PMU_CAP_NO_NMI,
9471 .event_init = perf_swevent_init,
9472 .add = perf_swevent_add,
9473 .del = perf_swevent_del,
9474 .start = perf_swevent_start,
9475 .stop = perf_swevent_stop,
9476 .read = perf_swevent_read,
9479 #ifdef CONFIG_EVENT_TRACING
9481 static int perf_tp_filter_match(struct perf_event *event,
9482 struct perf_sample_data *data)
9484 void *record = data->raw->frag.data;
9486 /* only top level events have filters set */
9488 event = event->parent;
9490 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9495 static int perf_tp_event_match(struct perf_event *event,
9496 struct perf_sample_data *data,
9497 struct pt_regs *regs)
9499 if (event->hw.state & PERF_HES_STOPPED)
9502 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9504 if (event->attr.exclude_kernel && !user_mode(regs))
9507 if (!perf_tp_filter_match(event, data))
9513 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9514 struct trace_event_call *call, u64 count,
9515 struct pt_regs *regs, struct hlist_head *head,
9516 struct task_struct *task)
9518 if (bpf_prog_array_valid(call)) {
9519 *(struct pt_regs **)raw_data = regs;
9520 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9521 perf_swevent_put_recursion_context(rctx);
9525 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9528 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9530 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9531 struct pt_regs *regs, struct hlist_head *head, int rctx,
9532 struct task_struct *task)
9534 struct perf_sample_data data;
9535 struct perf_event *event;
9537 struct perf_raw_record raw = {
9544 perf_sample_data_init(&data, 0, 0);
9547 perf_trace_buf_update(record, event_type);
9549 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9550 if (perf_tp_event_match(event, &data, regs))
9551 perf_swevent_event(event, count, &data, regs);
9555 * If we got specified a target task, also iterate its context and
9556 * deliver this event there too.
9558 if (task && task != current) {
9559 struct perf_event_context *ctx;
9560 struct trace_entry *entry = record;
9563 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9567 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9568 if (event->cpu != smp_processor_id())
9570 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9572 if (event->attr.config != entry->type)
9574 if (perf_tp_event_match(event, &data, regs))
9575 perf_swevent_event(event, count, &data, regs);
9581 perf_swevent_put_recursion_context(rctx);
9583 EXPORT_SYMBOL_GPL(perf_tp_event);
9585 static void tp_perf_event_destroy(struct perf_event *event)
9587 perf_trace_destroy(event);
9590 static int perf_tp_event_init(struct perf_event *event)
9594 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9598 * no branch sampling for tracepoint events
9600 if (has_branch_stack(event))
9603 err = perf_trace_init(event);
9607 event->destroy = tp_perf_event_destroy;
9612 static struct pmu perf_tracepoint = {
9613 .task_ctx_nr = perf_sw_context,
9615 .event_init = perf_tp_event_init,
9616 .add = perf_trace_add,
9617 .del = perf_trace_del,
9618 .start = perf_swevent_start,
9619 .stop = perf_swevent_stop,
9620 .read = perf_swevent_read,
9623 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9625 * Flags in config, used by dynamic PMU kprobe and uprobe
9626 * The flags should match following PMU_FORMAT_ATTR().
9628 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9629 * if not set, create kprobe/uprobe
9631 * The following values specify a reference counter (or semaphore in the
9632 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9633 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9635 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9636 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9638 enum perf_probe_config {
9639 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9640 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9641 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9644 PMU_FORMAT_ATTR(retprobe, "config:0");
9647 #ifdef CONFIG_KPROBE_EVENTS
9648 static struct attribute *kprobe_attrs[] = {
9649 &format_attr_retprobe.attr,
9653 static struct attribute_group kprobe_format_group = {
9655 .attrs = kprobe_attrs,
9658 static const struct attribute_group *kprobe_attr_groups[] = {
9659 &kprobe_format_group,
9663 static int perf_kprobe_event_init(struct perf_event *event);
9664 static struct pmu perf_kprobe = {
9665 .task_ctx_nr = perf_sw_context,
9666 .event_init = perf_kprobe_event_init,
9667 .add = perf_trace_add,
9668 .del = perf_trace_del,
9669 .start = perf_swevent_start,
9670 .stop = perf_swevent_stop,
9671 .read = perf_swevent_read,
9672 .attr_groups = kprobe_attr_groups,
9675 static int perf_kprobe_event_init(struct perf_event *event)
9680 if (event->attr.type != perf_kprobe.type)
9683 if (!perfmon_capable())
9687 * no branch sampling for probe events
9689 if (has_branch_stack(event))
9692 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9693 err = perf_kprobe_init(event, is_retprobe);
9697 event->destroy = perf_kprobe_destroy;
9701 #endif /* CONFIG_KPROBE_EVENTS */
9703 #ifdef CONFIG_UPROBE_EVENTS
9704 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9706 static struct attribute *uprobe_attrs[] = {
9707 &format_attr_retprobe.attr,
9708 &format_attr_ref_ctr_offset.attr,
9712 static struct attribute_group uprobe_format_group = {
9714 .attrs = uprobe_attrs,
9717 static const struct attribute_group *uprobe_attr_groups[] = {
9718 &uprobe_format_group,
9722 static int perf_uprobe_event_init(struct perf_event *event);
9723 static struct pmu perf_uprobe = {
9724 .task_ctx_nr = perf_sw_context,
9725 .event_init = perf_uprobe_event_init,
9726 .add = perf_trace_add,
9727 .del = perf_trace_del,
9728 .start = perf_swevent_start,
9729 .stop = perf_swevent_stop,
9730 .read = perf_swevent_read,
9731 .attr_groups = uprobe_attr_groups,
9734 static int perf_uprobe_event_init(struct perf_event *event)
9737 unsigned long ref_ctr_offset;
9740 if (event->attr.type != perf_uprobe.type)
9743 if (!perfmon_capable())
9747 * no branch sampling for probe events
9749 if (has_branch_stack(event))
9752 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9753 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9754 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9758 event->destroy = perf_uprobe_destroy;
9762 #endif /* CONFIG_UPROBE_EVENTS */
9764 static inline void perf_tp_register(void)
9766 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9767 #ifdef CONFIG_KPROBE_EVENTS
9768 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9770 #ifdef CONFIG_UPROBE_EVENTS
9771 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9775 static void perf_event_free_filter(struct perf_event *event)
9777 ftrace_profile_free_filter(event);
9780 #ifdef CONFIG_BPF_SYSCALL
9781 static void bpf_overflow_handler(struct perf_event *event,
9782 struct perf_sample_data *data,
9783 struct pt_regs *regs)
9785 struct bpf_perf_event_data_kern ctx = {
9791 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9792 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9795 ret = BPF_PROG_RUN(event->prog, &ctx);
9798 __this_cpu_dec(bpf_prog_active);
9802 event->orig_overflow_handler(event, data, regs);
9805 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9807 struct bpf_prog *prog;
9809 if (event->overflow_handler_context)
9810 /* hw breakpoint or kernel counter */
9816 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9818 return PTR_ERR(prog);
9820 if (event->attr.precise_ip &&
9821 prog->call_get_stack &&
9822 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9823 event->attr.exclude_callchain_kernel ||
9824 event->attr.exclude_callchain_user)) {
9826 * On perf_event with precise_ip, calling bpf_get_stack()
9827 * may trigger unwinder warnings and occasional crashes.
9828 * bpf_get_[stack|stackid] works around this issue by using
9829 * callchain attached to perf_sample_data. If the
9830 * perf_event does not full (kernel and user) callchain
9831 * attached to perf_sample_data, do not allow attaching BPF
9832 * program that calls bpf_get_[stack|stackid].
9839 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9840 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9844 static void perf_event_free_bpf_handler(struct perf_event *event)
9846 struct bpf_prog *prog = event->prog;
9851 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9856 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9860 static void perf_event_free_bpf_handler(struct perf_event *event)
9866 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9867 * with perf_event_open()
9869 static inline bool perf_event_is_tracing(struct perf_event *event)
9871 if (event->pmu == &perf_tracepoint)
9873 #ifdef CONFIG_KPROBE_EVENTS
9874 if (event->pmu == &perf_kprobe)
9877 #ifdef CONFIG_UPROBE_EVENTS
9878 if (event->pmu == &perf_uprobe)
9884 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9886 bool is_kprobe, is_tracepoint, is_syscall_tp;
9887 struct bpf_prog *prog;
9890 if (!perf_event_is_tracing(event))
9891 return perf_event_set_bpf_handler(event, prog_fd);
9893 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9894 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9895 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9896 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9897 /* bpf programs can only be attached to u/kprobe or tracepoint */
9900 prog = bpf_prog_get(prog_fd);
9902 return PTR_ERR(prog);
9904 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9905 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9906 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9907 /* valid fd, but invalid bpf program type */
9912 /* Kprobe override only works for kprobes, not uprobes. */
9913 if (prog->kprobe_override &&
9914 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9919 if (is_tracepoint || is_syscall_tp) {
9920 int off = trace_event_get_offsets(event->tp_event);
9922 if (prog->aux->max_ctx_offset > off) {
9928 ret = perf_event_attach_bpf_prog(event, prog);
9934 static void perf_event_free_bpf_prog(struct perf_event *event)
9936 if (!perf_event_is_tracing(event)) {
9937 perf_event_free_bpf_handler(event);
9940 perf_event_detach_bpf_prog(event);
9945 static inline void perf_tp_register(void)
9949 static void perf_event_free_filter(struct perf_event *event)
9953 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9958 static void perf_event_free_bpf_prog(struct perf_event *event)
9961 #endif /* CONFIG_EVENT_TRACING */
9963 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9964 void perf_bp_event(struct perf_event *bp, void *data)
9966 struct perf_sample_data sample;
9967 struct pt_regs *regs = data;
9969 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9971 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9972 perf_swevent_event(bp, 1, &sample, regs);
9977 * Allocate a new address filter
9979 static struct perf_addr_filter *
9980 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9982 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9983 struct perf_addr_filter *filter;
9985 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9989 INIT_LIST_HEAD(&filter->entry);
9990 list_add_tail(&filter->entry, filters);
9995 static void free_filters_list(struct list_head *filters)
9997 struct perf_addr_filter *filter, *iter;
9999 list_for_each_entry_safe(filter, iter, filters, entry) {
10000 path_put(&filter->path);
10001 list_del(&filter->entry);
10007 * Free existing address filters and optionally install new ones
10009 static void perf_addr_filters_splice(struct perf_event *event,
10010 struct list_head *head)
10012 unsigned long flags;
10015 if (!has_addr_filter(event))
10018 /* don't bother with children, they don't have their own filters */
10022 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10024 list_splice_init(&event->addr_filters.list, &list);
10026 list_splice(head, &event->addr_filters.list);
10028 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10030 free_filters_list(&list);
10034 * Scan through mm's vmas and see if one of them matches the
10035 * @filter; if so, adjust filter's address range.
10036 * Called with mm::mmap_lock down for reading.
10038 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10039 struct mm_struct *mm,
10040 struct perf_addr_filter_range *fr)
10042 struct vm_area_struct *vma;
10044 for (vma = mm->mmap; vma; vma = vma->vm_next) {
10048 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10054 * Update event's address range filters based on the
10055 * task's existing mappings, if any.
10057 static void perf_event_addr_filters_apply(struct perf_event *event)
10059 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10060 struct task_struct *task = READ_ONCE(event->ctx->task);
10061 struct perf_addr_filter *filter;
10062 struct mm_struct *mm = NULL;
10063 unsigned int count = 0;
10064 unsigned long flags;
10067 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10068 * will stop on the parent's child_mutex that our caller is also holding
10070 if (task == TASK_TOMBSTONE)
10073 if (ifh->nr_file_filters) {
10074 mm = get_task_mm(event->ctx->task);
10078 mmap_read_lock(mm);
10081 raw_spin_lock_irqsave(&ifh->lock, flags);
10082 list_for_each_entry(filter, &ifh->list, entry) {
10083 if (filter->path.dentry) {
10085 * Adjust base offset if the filter is associated to a
10086 * binary that needs to be mapped:
10088 event->addr_filter_ranges[count].start = 0;
10089 event->addr_filter_ranges[count].size = 0;
10091 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10093 event->addr_filter_ranges[count].start = filter->offset;
10094 event->addr_filter_ranges[count].size = filter->size;
10100 event->addr_filters_gen++;
10101 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10103 if (ifh->nr_file_filters) {
10104 mmap_read_unlock(mm);
10110 perf_event_stop(event, 1);
10114 * Address range filtering: limiting the data to certain
10115 * instruction address ranges. Filters are ioctl()ed to us from
10116 * userspace as ascii strings.
10118 * Filter string format:
10120 * ACTION RANGE_SPEC
10121 * where ACTION is one of the
10122 * * "filter": limit the trace to this region
10123 * * "start": start tracing from this address
10124 * * "stop": stop tracing at this address/region;
10126 * * for kernel addresses: <start address>[/<size>]
10127 * * for object files: <start address>[/<size>]@</path/to/object/file>
10129 * if <size> is not specified or is zero, the range is treated as a single
10130 * address; not valid for ACTION=="filter".
10144 IF_STATE_ACTION = 0,
10149 static const match_table_t if_tokens = {
10150 { IF_ACT_FILTER, "filter" },
10151 { IF_ACT_START, "start" },
10152 { IF_ACT_STOP, "stop" },
10153 { IF_SRC_FILE, "%u/%u@%s" },
10154 { IF_SRC_KERNEL, "%u/%u" },
10155 { IF_SRC_FILEADDR, "%u@%s" },
10156 { IF_SRC_KERNELADDR, "%u" },
10157 { IF_ACT_NONE, NULL },
10161 * Address filter string parser
10164 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10165 struct list_head *filters)
10167 struct perf_addr_filter *filter = NULL;
10168 char *start, *orig, *filename = NULL;
10169 substring_t args[MAX_OPT_ARGS];
10170 int state = IF_STATE_ACTION, token;
10171 unsigned int kernel = 0;
10174 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10178 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10179 static const enum perf_addr_filter_action_t actions[] = {
10180 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10181 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10182 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10189 /* filter definition begins */
10190 if (state == IF_STATE_ACTION) {
10191 filter = perf_addr_filter_new(event, filters);
10196 token = match_token(start, if_tokens, args);
10198 case IF_ACT_FILTER:
10201 if (state != IF_STATE_ACTION)
10204 filter->action = actions[token];
10205 state = IF_STATE_SOURCE;
10208 case IF_SRC_KERNELADDR:
10209 case IF_SRC_KERNEL:
10213 case IF_SRC_FILEADDR:
10215 if (state != IF_STATE_SOURCE)
10219 ret = kstrtoul(args[0].from, 0, &filter->offset);
10223 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10225 ret = kstrtoul(args[1].from, 0, &filter->size);
10230 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10231 int fpos = token == IF_SRC_FILE ? 2 : 1;
10234 filename = match_strdup(&args[fpos]);
10241 state = IF_STATE_END;
10249 * Filter definition is fully parsed, validate and install it.
10250 * Make sure that it doesn't contradict itself or the event's
10253 if (state == IF_STATE_END) {
10255 if (kernel && event->attr.exclude_kernel)
10259 * ACTION "filter" must have a non-zero length region
10262 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10271 * For now, we only support file-based filters
10272 * in per-task events; doing so for CPU-wide
10273 * events requires additional context switching
10274 * trickery, since same object code will be
10275 * mapped at different virtual addresses in
10276 * different processes.
10279 if (!event->ctx->task)
10282 /* look up the path and grab its inode */
10283 ret = kern_path(filename, LOOKUP_FOLLOW,
10289 if (!filter->path.dentry ||
10290 !S_ISREG(d_inode(filter->path.dentry)
10294 event->addr_filters.nr_file_filters++;
10297 /* ready to consume more filters */
10298 state = IF_STATE_ACTION;
10303 if (state != IF_STATE_ACTION)
10313 free_filters_list(filters);
10320 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10322 LIST_HEAD(filters);
10326 * Since this is called in perf_ioctl() path, we're already holding
10329 lockdep_assert_held(&event->ctx->mutex);
10331 if (WARN_ON_ONCE(event->parent))
10334 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10336 goto fail_clear_files;
10338 ret = event->pmu->addr_filters_validate(&filters);
10340 goto fail_free_filters;
10342 /* remove existing filters, if any */
10343 perf_addr_filters_splice(event, &filters);
10345 /* install new filters */
10346 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10351 free_filters_list(&filters);
10354 event->addr_filters.nr_file_filters = 0;
10359 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10364 filter_str = strndup_user(arg, PAGE_SIZE);
10365 if (IS_ERR(filter_str))
10366 return PTR_ERR(filter_str);
10368 #ifdef CONFIG_EVENT_TRACING
10369 if (perf_event_is_tracing(event)) {
10370 struct perf_event_context *ctx = event->ctx;
10373 * Beware, here be dragons!!
10375 * the tracepoint muck will deadlock against ctx->mutex, but
10376 * the tracepoint stuff does not actually need it. So
10377 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10378 * already have a reference on ctx.
10380 * This can result in event getting moved to a different ctx,
10381 * but that does not affect the tracepoint state.
10383 mutex_unlock(&ctx->mutex);
10384 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10385 mutex_lock(&ctx->mutex);
10388 if (has_addr_filter(event))
10389 ret = perf_event_set_addr_filter(event, filter_str);
10396 * hrtimer based swevent callback
10399 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10401 enum hrtimer_restart ret = HRTIMER_RESTART;
10402 struct perf_sample_data data;
10403 struct pt_regs *regs;
10404 struct perf_event *event;
10407 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10409 if (event->state != PERF_EVENT_STATE_ACTIVE)
10410 return HRTIMER_NORESTART;
10412 event->pmu->read(event);
10414 perf_sample_data_init(&data, 0, event->hw.last_period);
10415 regs = get_irq_regs();
10417 if (regs && !perf_exclude_event(event, regs)) {
10418 if (!(event->attr.exclude_idle && is_idle_task(current)))
10419 if (__perf_event_overflow(event, 1, &data, regs))
10420 ret = HRTIMER_NORESTART;
10423 period = max_t(u64, 10000, event->hw.sample_period);
10424 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10429 static void perf_swevent_start_hrtimer(struct perf_event *event)
10431 struct hw_perf_event *hwc = &event->hw;
10434 if (!is_sampling_event(event))
10437 period = local64_read(&hwc->period_left);
10442 local64_set(&hwc->period_left, 0);
10444 period = max_t(u64, 10000, hwc->sample_period);
10446 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10447 HRTIMER_MODE_REL_PINNED_HARD);
10450 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10452 struct hw_perf_event *hwc = &event->hw;
10454 if (is_sampling_event(event)) {
10455 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10456 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10458 hrtimer_cancel(&hwc->hrtimer);
10462 static void perf_swevent_init_hrtimer(struct perf_event *event)
10464 struct hw_perf_event *hwc = &event->hw;
10466 if (!is_sampling_event(event))
10469 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10470 hwc->hrtimer.function = perf_swevent_hrtimer;
10473 * Since hrtimers have a fixed rate, we can do a static freq->period
10474 * mapping and avoid the whole period adjust feedback stuff.
10476 if (event->attr.freq) {
10477 long freq = event->attr.sample_freq;
10479 event->attr.sample_period = NSEC_PER_SEC / freq;
10480 hwc->sample_period = event->attr.sample_period;
10481 local64_set(&hwc->period_left, hwc->sample_period);
10482 hwc->last_period = hwc->sample_period;
10483 event->attr.freq = 0;
10488 * Software event: cpu wall time clock
10491 static void cpu_clock_event_update(struct perf_event *event)
10496 now = local_clock();
10497 prev = local64_xchg(&event->hw.prev_count, now);
10498 local64_add(now - prev, &event->count);
10501 static void cpu_clock_event_start(struct perf_event *event, int flags)
10503 local64_set(&event->hw.prev_count, local_clock());
10504 perf_swevent_start_hrtimer(event);
10507 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10509 perf_swevent_cancel_hrtimer(event);
10510 cpu_clock_event_update(event);
10513 static int cpu_clock_event_add(struct perf_event *event, int flags)
10515 if (flags & PERF_EF_START)
10516 cpu_clock_event_start(event, flags);
10517 perf_event_update_userpage(event);
10522 static void cpu_clock_event_del(struct perf_event *event, int flags)
10524 cpu_clock_event_stop(event, flags);
10527 static void cpu_clock_event_read(struct perf_event *event)
10529 cpu_clock_event_update(event);
10532 static int cpu_clock_event_init(struct perf_event *event)
10534 if (event->attr.type != PERF_TYPE_SOFTWARE)
10537 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10541 * no branch sampling for software events
10543 if (has_branch_stack(event))
10544 return -EOPNOTSUPP;
10546 perf_swevent_init_hrtimer(event);
10551 static struct pmu perf_cpu_clock = {
10552 .task_ctx_nr = perf_sw_context,
10554 .capabilities = PERF_PMU_CAP_NO_NMI,
10556 .event_init = cpu_clock_event_init,
10557 .add = cpu_clock_event_add,
10558 .del = cpu_clock_event_del,
10559 .start = cpu_clock_event_start,
10560 .stop = cpu_clock_event_stop,
10561 .read = cpu_clock_event_read,
10565 * Software event: task time clock
10568 static void task_clock_event_update(struct perf_event *event, u64 now)
10573 prev = local64_xchg(&event->hw.prev_count, now);
10574 delta = now - prev;
10575 local64_add(delta, &event->count);
10578 static void task_clock_event_start(struct perf_event *event, int flags)
10580 local64_set(&event->hw.prev_count, event->ctx->time);
10581 perf_swevent_start_hrtimer(event);
10584 static void task_clock_event_stop(struct perf_event *event, int flags)
10586 perf_swevent_cancel_hrtimer(event);
10587 task_clock_event_update(event, event->ctx->time);
10590 static int task_clock_event_add(struct perf_event *event, int flags)
10592 if (flags & PERF_EF_START)
10593 task_clock_event_start(event, flags);
10594 perf_event_update_userpage(event);
10599 static void task_clock_event_del(struct perf_event *event, int flags)
10601 task_clock_event_stop(event, PERF_EF_UPDATE);
10604 static void task_clock_event_read(struct perf_event *event)
10606 u64 now = perf_clock();
10607 u64 delta = now - event->ctx->timestamp;
10608 u64 time = event->ctx->time + delta;
10610 task_clock_event_update(event, time);
10613 static int task_clock_event_init(struct perf_event *event)
10615 if (event->attr.type != PERF_TYPE_SOFTWARE)
10618 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10622 * no branch sampling for software events
10624 if (has_branch_stack(event))
10625 return -EOPNOTSUPP;
10627 perf_swevent_init_hrtimer(event);
10632 static struct pmu perf_task_clock = {
10633 .task_ctx_nr = perf_sw_context,
10635 .capabilities = PERF_PMU_CAP_NO_NMI,
10637 .event_init = task_clock_event_init,
10638 .add = task_clock_event_add,
10639 .del = task_clock_event_del,
10640 .start = task_clock_event_start,
10641 .stop = task_clock_event_stop,
10642 .read = task_clock_event_read,
10645 static void perf_pmu_nop_void(struct pmu *pmu)
10649 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10653 static int perf_pmu_nop_int(struct pmu *pmu)
10658 static int perf_event_nop_int(struct perf_event *event, u64 value)
10663 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10665 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10667 __this_cpu_write(nop_txn_flags, flags);
10669 if (flags & ~PERF_PMU_TXN_ADD)
10672 perf_pmu_disable(pmu);
10675 static int perf_pmu_commit_txn(struct pmu *pmu)
10677 unsigned int flags = __this_cpu_read(nop_txn_flags);
10679 __this_cpu_write(nop_txn_flags, 0);
10681 if (flags & ~PERF_PMU_TXN_ADD)
10684 perf_pmu_enable(pmu);
10688 static void perf_pmu_cancel_txn(struct pmu *pmu)
10690 unsigned int flags = __this_cpu_read(nop_txn_flags);
10692 __this_cpu_write(nop_txn_flags, 0);
10694 if (flags & ~PERF_PMU_TXN_ADD)
10697 perf_pmu_enable(pmu);
10700 static int perf_event_idx_default(struct perf_event *event)
10706 * Ensures all contexts with the same task_ctx_nr have the same
10707 * pmu_cpu_context too.
10709 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10716 list_for_each_entry(pmu, &pmus, entry) {
10717 if (pmu->task_ctx_nr == ctxn)
10718 return pmu->pmu_cpu_context;
10724 static void free_pmu_context(struct pmu *pmu)
10727 * Static contexts such as perf_sw_context have a global lifetime
10728 * and may be shared between different PMUs. Avoid freeing them
10729 * when a single PMU is going away.
10731 if (pmu->task_ctx_nr > perf_invalid_context)
10734 free_percpu(pmu->pmu_cpu_context);
10738 * Let userspace know that this PMU supports address range filtering:
10740 static ssize_t nr_addr_filters_show(struct device *dev,
10741 struct device_attribute *attr,
10744 struct pmu *pmu = dev_get_drvdata(dev);
10746 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10748 DEVICE_ATTR_RO(nr_addr_filters);
10750 static struct idr pmu_idr;
10753 type_show(struct device *dev, struct device_attribute *attr, char *page)
10755 struct pmu *pmu = dev_get_drvdata(dev);
10757 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10759 static DEVICE_ATTR_RO(type);
10762 perf_event_mux_interval_ms_show(struct device *dev,
10763 struct device_attribute *attr,
10766 struct pmu *pmu = dev_get_drvdata(dev);
10768 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10771 static DEFINE_MUTEX(mux_interval_mutex);
10774 perf_event_mux_interval_ms_store(struct device *dev,
10775 struct device_attribute *attr,
10776 const char *buf, size_t count)
10778 struct pmu *pmu = dev_get_drvdata(dev);
10779 int timer, cpu, ret;
10781 ret = kstrtoint(buf, 0, &timer);
10788 /* same value, noting to do */
10789 if (timer == pmu->hrtimer_interval_ms)
10792 mutex_lock(&mux_interval_mutex);
10793 pmu->hrtimer_interval_ms = timer;
10795 /* update all cpuctx for this PMU */
10797 for_each_online_cpu(cpu) {
10798 struct perf_cpu_context *cpuctx;
10799 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10800 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10802 cpu_function_call(cpu,
10803 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10805 cpus_read_unlock();
10806 mutex_unlock(&mux_interval_mutex);
10810 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10812 static struct attribute *pmu_dev_attrs[] = {
10813 &dev_attr_type.attr,
10814 &dev_attr_perf_event_mux_interval_ms.attr,
10817 ATTRIBUTE_GROUPS(pmu_dev);
10819 static int pmu_bus_running;
10820 static struct bus_type pmu_bus = {
10821 .name = "event_source",
10822 .dev_groups = pmu_dev_groups,
10825 static void pmu_dev_release(struct device *dev)
10830 static int pmu_dev_alloc(struct pmu *pmu)
10834 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10838 pmu->dev->groups = pmu->attr_groups;
10839 device_initialize(pmu->dev);
10840 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10844 dev_set_drvdata(pmu->dev, pmu);
10845 pmu->dev->bus = &pmu_bus;
10846 pmu->dev->release = pmu_dev_release;
10847 ret = device_add(pmu->dev);
10851 /* For PMUs with address filters, throw in an extra attribute: */
10852 if (pmu->nr_addr_filters)
10853 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10858 if (pmu->attr_update)
10859 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10868 device_del(pmu->dev);
10871 put_device(pmu->dev);
10875 static struct lock_class_key cpuctx_mutex;
10876 static struct lock_class_key cpuctx_lock;
10878 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10880 int cpu, ret, max = PERF_TYPE_MAX;
10882 mutex_lock(&pmus_lock);
10884 pmu->pmu_disable_count = alloc_percpu(int);
10885 if (!pmu->pmu_disable_count)
10893 if (type != PERF_TYPE_SOFTWARE) {
10897 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10901 WARN_ON(type >= 0 && ret != type);
10907 if (pmu_bus_running) {
10908 ret = pmu_dev_alloc(pmu);
10914 if (pmu->task_ctx_nr == perf_hw_context) {
10915 static int hw_context_taken = 0;
10918 * Other than systems with heterogeneous CPUs, it never makes
10919 * sense for two PMUs to share perf_hw_context. PMUs which are
10920 * uncore must use perf_invalid_context.
10922 if (WARN_ON_ONCE(hw_context_taken &&
10923 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10924 pmu->task_ctx_nr = perf_invalid_context;
10926 hw_context_taken = 1;
10929 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10930 if (pmu->pmu_cpu_context)
10931 goto got_cpu_context;
10934 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10935 if (!pmu->pmu_cpu_context)
10938 for_each_possible_cpu(cpu) {
10939 struct perf_cpu_context *cpuctx;
10941 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10942 __perf_event_init_context(&cpuctx->ctx);
10943 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10944 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10945 cpuctx->ctx.pmu = pmu;
10946 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10948 __perf_mux_hrtimer_init(cpuctx, cpu);
10950 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10951 cpuctx->heap = cpuctx->heap_default;
10955 if (!pmu->start_txn) {
10956 if (pmu->pmu_enable) {
10958 * If we have pmu_enable/pmu_disable calls, install
10959 * transaction stubs that use that to try and batch
10960 * hardware accesses.
10962 pmu->start_txn = perf_pmu_start_txn;
10963 pmu->commit_txn = perf_pmu_commit_txn;
10964 pmu->cancel_txn = perf_pmu_cancel_txn;
10966 pmu->start_txn = perf_pmu_nop_txn;
10967 pmu->commit_txn = perf_pmu_nop_int;
10968 pmu->cancel_txn = perf_pmu_nop_void;
10972 if (!pmu->pmu_enable) {
10973 pmu->pmu_enable = perf_pmu_nop_void;
10974 pmu->pmu_disable = perf_pmu_nop_void;
10977 if (!pmu->check_period)
10978 pmu->check_period = perf_event_nop_int;
10980 if (!pmu->event_idx)
10981 pmu->event_idx = perf_event_idx_default;
10984 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10985 * since these cannot be in the IDR. This way the linear search
10986 * is fast, provided a valid software event is provided.
10988 if (type == PERF_TYPE_SOFTWARE || !name)
10989 list_add_rcu(&pmu->entry, &pmus);
10991 list_add_tail_rcu(&pmu->entry, &pmus);
10993 atomic_set(&pmu->exclusive_cnt, 0);
10996 mutex_unlock(&pmus_lock);
11001 device_del(pmu->dev);
11002 put_device(pmu->dev);
11005 if (pmu->type != PERF_TYPE_SOFTWARE)
11006 idr_remove(&pmu_idr, pmu->type);
11009 free_percpu(pmu->pmu_disable_count);
11012 EXPORT_SYMBOL_GPL(perf_pmu_register);
11014 void perf_pmu_unregister(struct pmu *pmu)
11016 mutex_lock(&pmus_lock);
11017 list_del_rcu(&pmu->entry);
11020 * We dereference the pmu list under both SRCU and regular RCU, so
11021 * synchronize against both of those.
11023 synchronize_srcu(&pmus_srcu);
11026 free_percpu(pmu->pmu_disable_count);
11027 if (pmu->type != PERF_TYPE_SOFTWARE)
11028 idr_remove(&pmu_idr, pmu->type);
11029 if (pmu_bus_running) {
11030 if (pmu->nr_addr_filters)
11031 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11032 device_del(pmu->dev);
11033 put_device(pmu->dev);
11035 free_pmu_context(pmu);
11036 mutex_unlock(&pmus_lock);
11038 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11040 static inline bool has_extended_regs(struct perf_event *event)
11042 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11043 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11046 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11048 struct perf_event_context *ctx = NULL;
11051 if (!try_module_get(pmu->module))
11055 * A number of pmu->event_init() methods iterate the sibling_list to,
11056 * for example, validate if the group fits on the PMU. Therefore,
11057 * if this is a sibling event, acquire the ctx->mutex to protect
11058 * the sibling_list.
11060 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11062 * This ctx->mutex can nest when we're called through
11063 * inheritance. See the perf_event_ctx_lock_nested() comment.
11065 ctx = perf_event_ctx_lock_nested(event->group_leader,
11066 SINGLE_DEPTH_NESTING);
11071 ret = pmu->event_init(event);
11074 perf_event_ctx_unlock(event->group_leader, ctx);
11077 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11078 has_extended_regs(event))
11081 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11082 event_has_any_exclude_flag(event))
11085 if (ret && event->destroy)
11086 event->destroy(event);
11090 module_put(pmu->module);
11095 static struct pmu *perf_init_event(struct perf_event *event)
11097 int idx, type, ret;
11100 idx = srcu_read_lock(&pmus_srcu);
11102 /* Try parent's PMU first: */
11103 if (event->parent && event->parent->pmu) {
11104 pmu = event->parent->pmu;
11105 ret = perf_try_init_event(pmu, event);
11111 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11112 * are often aliases for PERF_TYPE_RAW.
11114 type = event->attr.type;
11115 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11116 type = PERF_TYPE_RAW;
11120 pmu = idr_find(&pmu_idr, type);
11123 ret = perf_try_init_event(pmu, event);
11124 if (ret == -ENOENT && event->attr.type != type) {
11125 type = event->attr.type;
11130 pmu = ERR_PTR(ret);
11135 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11136 ret = perf_try_init_event(pmu, event);
11140 if (ret != -ENOENT) {
11141 pmu = ERR_PTR(ret);
11145 pmu = ERR_PTR(-ENOENT);
11147 srcu_read_unlock(&pmus_srcu, idx);
11152 static void attach_sb_event(struct perf_event *event)
11154 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11156 raw_spin_lock(&pel->lock);
11157 list_add_rcu(&event->sb_list, &pel->list);
11158 raw_spin_unlock(&pel->lock);
11162 * We keep a list of all !task (and therefore per-cpu) events
11163 * that need to receive side-band records.
11165 * This avoids having to scan all the various PMU per-cpu contexts
11166 * looking for them.
11168 static void account_pmu_sb_event(struct perf_event *event)
11170 if (is_sb_event(event))
11171 attach_sb_event(event);
11174 static void account_event_cpu(struct perf_event *event, int cpu)
11179 if (is_cgroup_event(event))
11180 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11183 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11184 static void account_freq_event_nohz(void)
11186 #ifdef CONFIG_NO_HZ_FULL
11187 /* Lock so we don't race with concurrent unaccount */
11188 spin_lock(&nr_freq_lock);
11189 if (atomic_inc_return(&nr_freq_events) == 1)
11190 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11191 spin_unlock(&nr_freq_lock);
11195 static void account_freq_event(void)
11197 if (tick_nohz_full_enabled())
11198 account_freq_event_nohz();
11200 atomic_inc(&nr_freq_events);
11204 static void account_event(struct perf_event *event)
11211 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11213 if (event->attr.mmap || event->attr.mmap_data)
11214 atomic_inc(&nr_mmap_events);
11215 if (event->attr.build_id)
11216 atomic_inc(&nr_build_id_events);
11217 if (event->attr.comm)
11218 atomic_inc(&nr_comm_events);
11219 if (event->attr.namespaces)
11220 atomic_inc(&nr_namespaces_events);
11221 if (event->attr.cgroup)
11222 atomic_inc(&nr_cgroup_events);
11223 if (event->attr.task)
11224 atomic_inc(&nr_task_events);
11225 if (event->attr.freq)
11226 account_freq_event();
11227 if (event->attr.context_switch) {
11228 atomic_inc(&nr_switch_events);
11231 if (has_branch_stack(event))
11233 if (is_cgroup_event(event))
11235 if (event->attr.ksymbol)
11236 atomic_inc(&nr_ksymbol_events);
11237 if (event->attr.bpf_event)
11238 atomic_inc(&nr_bpf_events);
11239 if (event->attr.text_poke)
11240 atomic_inc(&nr_text_poke_events);
11244 * We need the mutex here because static_branch_enable()
11245 * must complete *before* the perf_sched_count increment
11248 if (atomic_inc_not_zero(&perf_sched_count))
11251 mutex_lock(&perf_sched_mutex);
11252 if (!atomic_read(&perf_sched_count)) {
11253 static_branch_enable(&perf_sched_events);
11255 * Guarantee that all CPUs observe they key change and
11256 * call the perf scheduling hooks before proceeding to
11257 * install events that need them.
11262 * Now that we have waited for the sync_sched(), allow further
11263 * increments to by-pass the mutex.
11265 atomic_inc(&perf_sched_count);
11266 mutex_unlock(&perf_sched_mutex);
11270 account_event_cpu(event, event->cpu);
11272 account_pmu_sb_event(event);
11276 * Allocate and initialize an event structure
11278 static struct perf_event *
11279 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11280 struct task_struct *task,
11281 struct perf_event *group_leader,
11282 struct perf_event *parent_event,
11283 perf_overflow_handler_t overflow_handler,
11284 void *context, int cgroup_fd)
11287 struct perf_event *event;
11288 struct hw_perf_event *hwc;
11289 long err = -EINVAL;
11291 if ((unsigned)cpu >= nr_cpu_ids) {
11292 if (!task || cpu != -1)
11293 return ERR_PTR(-EINVAL);
11296 event = kzalloc(sizeof(*event), GFP_KERNEL);
11298 return ERR_PTR(-ENOMEM);
11301 * Single events are their own group leaders, with an
11302 * empty sibling list:
11305 group_leader = event;
11307 mutex_init(&event->child_mutex);
11308 INIT_LIST_HEAD(&event->child_list);
11310 INIT_LIST_HEAD(&event->event_entry);
11311 INIT_LIST_HEAD(&event->sibling_list);
11312 INIT_LIST_HEAD(&event->active_list);
11313 init_event_group(event);
11314 INIT_LIST_HEAD(&event->rb_entry);
11315 INIT_LIST_HEAD(&event->active_entry);
11316 INIT_LIST_HEAD(&event->addr_filters.list);
11317 INIT_HLIST_NODE(&event->hlist_entry);
11320 init_waitqueue_head(&event->waitq);
11321 event->pending_disable = -1;
11322 init_irq_work(&event->pending, perf_pending_event);
11324 mutex_init(&event->mmap_mutex);
11325 raw_spin_lock_init(&event->addr_filters.lock);
11327 atomic_long_set(&event->refcount, 1);
11329 event->attr = *attr;
11330 event->group_leader = group_leader;
11334 event->parent = parent_event;
11336 event->ns = get_pid_ns(task_active_pid_ns(current));
11337 event->id = atomic64_inc_return(&perf_event_id);
11339 event->state = PERF_EVENT_STATE_INACTIVE;
11342 event->attach_state = PERF_ATTACH_TASK;
11344 * XXX pmu::event_init needs to know what task to account to
11345 * and we cannot use the ctx information because we need the
11346 * pmu before we get a ctx.
11348 event->hw.target = get_task_struct(task);
11351 event->clock = &local_clock;
11353 event->clock = parent_event->clock;
11355 if (!overflow_handler && parent_event) {
11356 overflow_handler = parent_event->overflow_handler;
11357 context = parent_event->overflow_handler_context;
11358 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11359 if (overflow_handler == bpf_overflow_handler) {
11360 struct bpf_prog *prog = parent_event->prog;
11362 bpf_prog_inc(prog);
11363 event->prog = prog;
11364 event->orig_overflow_handler =
11365 parent_event->orig_overflow_handler;
11370 if (overflow_handler) {
11371 event->overflow_handler = overflow_handler;
11372 event->overflow_handler_context = context;
11373 } else if (is_write_backward(event)){
11374 event->overflow_handler = perf_event_output_backward;
11375 event->overflow_handler_context = NULL;
11377 event->overflow_handler = perf_event_output_forward;
11378 event->overflow_handler_context = NULL;
11381 perf_event__state_init(event);
11386 hwc->sample_period = attr->sample_period;
11387 if (attr->freq && attr->sample_freq)
11388 hwc->sample_period = 1;
11389 hwc->last_period = hwc->sample_period;
11391 local64_set(&hwc->period_left, hwc->sample_period);
11394 * We currently do not support PERF_SAMPLE_READ on inherited events.
11395 * See perf_output_read().
11397 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11400 if (!has_branch_stack(event))
11401 event->attr.branch_sample_type = 0;
11403 pmu = perf_init_event(event);
11405 err = PTR_ERR(pmu);
11410 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11411 * be different on other CPUs in the uncore mask.
11413 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11418 if (event->attr.aux_output &&
11419 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11424 if (cgroup_fd != -1) {
11425 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11430 err = exclusive_event_init(event);
11434 if (has_addr_filter(event)) {
11435 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11436 sizeof(struct perf_addr_filter_range),
11438 if (!event->addr_filter_ranges) {
11444 * Clone the parent's vma offsets: they are valid until exec()
11445 * even if the mm is not shared with the parent.
11447 if (event->parent) {
11448 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11450 raw_spin_lock_irq(&ifh->lock);
11451 memcpy(event->addr_filter_ranges,
11452 event->parent->addr_filter_ranges,
11453 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11454 raw_spin_unlock_irq(&ifh->lock);
11457 /* force hw sync on the address filters */
11458 event->addr_filters_gen = 1;
11461 if (!event->parent) {
11462 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11463 err = get_callchain_buffers(attr->sample_max_stack);
11465 goto err_addr_filters;
11469 err = security_perf_event_alloc(event);
11471 goto err_callchain_buffer;
11473 /* symmetric to unaccount_event() in _free_event() */
11474 account_event(event);
11478 err_callchain_buffer:
11479 if (!event->parent) {
11480 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11481 put_callchain_buffers();
11484 kfree(event->addr_filter_ranges);
11487 exclusive_event_destroy(event);
11490 if (is_cgroup_event(event))
11491 perf_detach_cgroup(event);
11492 if (event->destroy)
11493 event->destroy(event);
11494 module_put(pmu->module);
11497 put_pid_ns(event->ns);
11498 if (event->hw.target)
11499 put_task_struct(event->hw.target);
11502 return ERR_PTR(err);
11505 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11506 struct perf_event_attr *attr)
11511 /* Zero the full structure, so that a short copy will be nice. */
11512 memset(attr, 0, sizeof(*attr));
11514 ret = get_user(size, &uattr->size);
11518 /* ABI compatibility quirk: */
11520 size = PERF_ATTR_SIZE_VER0;
11521 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11524 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11533 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11536 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11539 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11542 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11543 u64 mask = attr->branch_sample_type;
11545 /* only using defined bits */
11546 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11549 /* at least one branch bit must be set */
11550 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11553 /* propagate priv level, when not set for branch */
11554 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11556 /* exclude_kernel checked on syscall entry */
11557 if (!attr->exclude_kernel)
11558 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11560 if (!attr->exclude_user)
11561 mask |= PERF_SAMPLE_BRANCH_USER;
11563 if (!attr->exclude_hv)
11564 mask |= PERF_SAMPLE_BRANCH_HV;
11566 * adjust user setting (for HW filter setup)
11568 attr->branch_sample_type = mask;
11570 /* privileged levels capture (kernel, hv): check permissions */
11571 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11572 ret = perf_allow_kernel(attr);
11578 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11579 ret = perf_reg_validate(attr->sample_regs_user);
11584 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11585 if (!arch_perf_have_user_stack_dump())
11589 * We have __u32 type for the size, but so far
11590 * we can only use __u16 as maximum due to the
11591 * __u16 sample size limit.
11593 if (attr->sample_stack_user >= USHRT_MAX)
11595 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11599 if (!attr->sample_max_stack)
11600 attr->sample_max_stack = sysctl_perf_event_max_stack;
11602 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11603 ret = perf_reg_validate(attr->sample_regs_intr);
11605 #ifndef CONFIG_CGROUP_PERF
11606 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11609 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
11610 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
11617 put_user(sizeof(*attr), &uattr->size);
11623 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11625 struct perf_buffer *rb = NULL;
11631 /* don't allow circular references */
11632 if (event == output_event)
11636 * Don't allow cross-cpu buffers
11638 if (output_event->cpu != event->cpu)
11642 * If its not a per-cpu rb, it must be the same task.
11644 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11648 * Mixing clocks in the same buffer is trouble you don't need.
11650 if (output_event->clock != event->clock)
11654 * Either writing ring buffer from beginning or from end.
11655 * Mixing is not allowed.
11657 if (is_write_backward(output_event) != is_write_backward(event))
11661 * If both events generate aux data, they must be on the same PMU
11663 if (has_aux(event) && has_aux(output_event) &&
11664 event->pmu != output_event->pmu)
11668 mutex_lock(&event->mmap_mutex);
11669 /* Can't redirect output if we've got an active mmap() */
11670 if (atomic_read(&event->mmap_count))
11673 if (output_event) {
11674 /* get the rb we want to redirect to */
11675 rb = ring_buffer_get(output_event);
11680 ring_buffer_attach(event, rb);
11684 mutex_unlock(&event->mmap_mutex);
11690 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11696 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11699 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11701 bool nmi_safe = false;
11704 case CLOCK_MONOTONIC:
11705 event->clock = &ktime_get_mono_fast_ns;
11709 case CLOCK_MONOTONIC_RAW:
11710 event->clock = &ktime_get_raw_fast_ns;
11714 case CLOCK_REALTIME:
11715 event->clock = &ktime_get_real_ns;
11718 case CLOCK_BOOTTIME:
11719 event->clock = &ktime_get_boottime_ns;
11723 event->clock = &ktime_get_clocktai_ns;
11730 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11737 * Variation on perf_event_ctx_lock_nested(), except we take two context
11740 static struct perf_event_context *
11741 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11742 struct perf_event_context *ctx)
11744 struct perf_event_context *gctx;
11748 gctx = READ_ONCE(group_leader->ctx);
11749 if (!refcount_inc_not_zero(&gctx->refcount)) {
11755 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11757 if (group_leader->ctx != gctx) {
11758 mutex_unlock(&ctx->mutex);
11759 mutex_unlock(&gctx->mutex);
11768 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11770 * @attr_uptr: event_id type attributes for monitoring/sampling
11773 * @group_fd: group leader event fd
11775 SYSCALL_DEFINE5(perf_event_open,
11776 struct perf_event_attr __user *, attr_uptr,
11777 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11779 struct perf_event *group_leader = NULL, *output_event = NULL;
11780 struct perf_event *event, *sibling;
11781 struct perf_event_attr attr;
11782 struct perf_event_context *ctx, *gctx;
11783 struct file *event_file = NULL;
11784 struct fd group = {NULL, 0};
11785 struct task_struct *task = NULL;
11788 int move_group = 0;
11790 int f_flags = O_RDWR;
11791 int cgroup_fd = -1;
11793 /* for future expandability... */
11794 if (flags & ~PERF_FLAG_ALL)
11797 /* Do we allow access to perf_event_open(2) ? */
11798 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11802 err = perf_copy_attr(attr_uptr, &attr);
11806 if (!attr.exclude_kernel) {
11807 err = perf_allow_kernel(&attr);
11812 if (attr.namespaces) {
11813 if (!perfmon_capable())
11818 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11821 if (attr.sample_period & (1ULL << 63))
11825 /* Only privileged users can get physical addresses */
11826 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11827 err = perf_allow_kernel(&attr);
11832 err = security_locked_down(LOCKDOWN_PERF);
11833 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11834 /* REGS_INTR can leak data, lockdown must prevent this */
11840 * In cgroup mode, the pid argument is used to pass the fd
11841 * opened to the cgroup directory in cgroupfs. The cpu argument
11842 * designates the cpu on which to monitor threads from that
11845 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11848 if (flags & PERF_FLAG_FD_CLOEXEC)
11849 f_flags |= O_CLOEXEC;
11851 event_fd = get_unused_fd_flags(f_flags);
11855 if (group_fd != -1) {
11856 err = perf_fget_light(group_fd, &group);
11859 group_leader = group.file->private_data;
11860 if (flags & PERF_FLAG_FD_OUTPUT)
11861 output_event = group_leader;
11862 if (flags & PERF_FLAG_FD_NO_GROUP)
11863 group_leader = NULL;
11866 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11867 task = find_lively_task_by_vpid(pid);
11868 if (IS_ERR(task)) {
11869 err = PTR_ERR(task);
11874 if (task && group_leader &&
11875 group_leader->attr.inherit != attr.inherit) {
11880 if (flags & PERF_FLAG_PID_CGROUP)
11883 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11884 NULL, NULL, cgroup_fd);
11885 if (IS_ERR(event)) {
11886 err = PTR_ERR(event);
11890 if (is_sampling_event(event)) {
11891 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11898 * Special case software events and allow them to be part of
11899 * any hardware group.
11903 if (attr.use_clockid) {
11904 err = perf_event_set_clock(event, attr.clockid);
11909 if (pmu->task_ctx_nr == perf_sw_context)
11910 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11912 if (group_leader) {
11913 if (is_software_event(event) &&
11914 !in_software_context(group_leader)) {
11916 * If the event is a sw event, but the group_leader
11917 * is on hw context.
11919 * Allow the addition of software events to hw
11920 * groups, this is safe because software events
11921 * never fail to schedule.
11923 pmu = group_leader->ctx->pmu;
11924 } else if (!is_software_event(event) &&
11925 is_software_event(group_leader) &&
11926 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11928 * In case the group is a pure software group, and we
11929 * try to add a hardware event, move the whole group to
11930 * the hardware context.
11937 * Get the target context (task or percpu):
11939 ctx = find_get_context(pmu, task, event);
11941 err = PTR_ERR(ctx);
11946 * Look up the group leader (we will attach this event to it):
11948 if (group_leader) {
11952 * Do not allow a recursive hierarchy (this new sibling
11953 * becoming part of another group-sibling):
11955 if (group_leader->group_leader != group_leader)
11958 /* All events in a group should have the same clock */
11959 if (group_leader->clock != event->clock)
11963 * Make sure we're both events for the same CPU;
11964 * grouping events for different CPUs is broken; since
11965 * you can never concurrently schedule them anyhow.
11967 if (group_leader->cpu != event->cpu)
11971 * Make sure we're both on the same task, or both
11974 if (group_leader->ctx->task != ctx->task)
11978 * Do not allow to attach to a group in a different task
11979 * or CPU context. If we're moving SW events, we'll fix
11980 * this up later, so allow that.
11982 if (!move_group && group_leader->ctx != ctx)
11986 * Only a group leader can be exclusive or pinned
11988 if (attr.exclusive || attr.pinned)
11992 if (output_event) {
11993 err = perf_event_set_output(event, output_event);
11998 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
12000 if (IS_ERR(event_file)) {
12001 err = PTR_ERR(event_file);
12007 err = down_read_interruptible(&task->signal->exec_update_lock);
12012 * Preserve ptrace permission check for backwards compatibility.
12014 * We must hold exec_update_lock across this and any potential
12015 * perf_install_in_context() call for this new event to
12016 * serialize against exec() altering our credentials (and the
12017 * perf_event_exit_task() that could imply).
12020 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
12025 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12027 if (gctx->task == TASK_TOMBSTONE) {
12033 * Check if we raced against another sys_perf_event_open() call
12034 * moving the software group underneath us.
12036 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12038 * If someone moved the group out from under us, check
12039 * if this new event wound up on the same ctx, if so
12040 * its the regular !move_group case, otherwise fail.
12046 perf_event_ctx_unlock(group_leader, gctx);
12052 * Failure to create exclusive events returns -EBUSY.
12055 if (!exclusive_event_installable(group_leader, ctx))
12058 for_each_sibling_event(sibling, group_leader) {
12059 if (!exclusive_event_installable(sibling, ctx))
12063 mutex_lock(&ctx->mutex);
12066 if (ctx->task == TASK_TOMBSTONE) {
12071 if (!perf_event_validate_size(event)) {
12078 * Check if the @cpu we're creating an event for is online.
12080 * We use the perf_cpu_context::ctx::mutex to serialize against
12081 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12083 struct perf_cpu_context *cpuctx =
12084 container_of(ctx, struct perf_cpu_context, ctx);
12086 if (!cpuctx->online) {
12092 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12098 * Must be under the same ctx::mutex as perf_install_in_context(),
12099 * because we need to serialize with concurrent event creation.
12101 if (!exclusive_event_installable(event, ctx)) {
12106 WARN_ON_ONCE(ctx->parent_ctx);
12109 * This is the point on no return; we cannot fail hereafter. This is
12110 * where we start modifying current state.
12115 * See perf_event_ctx_lock() for comments on the details
12116 * of swizzling perf_event::ctx.
12118 perf_remove_from_context(group_leader, 0);
12121 for_each_sibling_event(sibling, group_leader) {
12122 perf_remove_from_context(sibling, 0);
12127 * Wait for everybody to stop referencing the events through
12128 * the old lists, before installing it on new lists.
12133 * Install the group siblings before the group leader.
12135 * Because a group leader will try and install the entire group
12136 * (through the sibling list, which is still in-tact), we can
12137 * end up with siblings installed in the wrong context.
12139 * By installing siblings first we NO-OP because they're not
12140 * reachable through the group lists.
12142 for_each_sibling_event(sibling, group_leader) {
12143 perf_event__state_init(sibling);
12144 perf_install_in_context(ctx, sibling, sibling->cpu);
12149 * Removing from the context ends up with disabled
12150 * event. What we want here is event in the initial
12151 * startup state, ready to be add into new context.
12153 perf_event__state_init(group_leader);
12154 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12159 * Precalculate sample_data sizes; do while holding ctx::mutex such
12160 * that we're serialized against further additions and before
12161 * perf_install_in_context() which is the point the event is active and
12162 * can use these values.
12164 perf_event__header_size(event);
12165 perf_event__id_header_size(event);
12167 event->owner = current;
12169 perf_install_in_context(ctx, event, event->cpu);
12170 perf_unpin_context(ctx);
12173 perf_event_ctx_unlock(group_leader, gctx);
12174 mutex_unlock(&ctx->mutex);
12177 up_read(&task->signal->exec_update_lock);
12178 put_task_struct(task);
12181 mutex_lock(¤t->perf_event_mutex);
12182 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12183 mutex_unlock(¤t->perf_event_mutex);
12186 * Drop the reference on the group_event after placing the
12187 * new event on the sibling_list. This ensures destruction
12188 * of the group leader will find the pointer to itself in
12189 * perf_group_detach().
12192 fd_install(event_fd, event_file);
12197 perf_event_ctx_unlock(group_leader, gctx);
12198 mutex_unlock(&ctx->mutex);
12201 up_read(&task->signal->exec_update_lock);
12205 perf_unpin_context(ctx);
12209 * If event_file is set, the fput() above will have called ->release()
12210 * and that will take care of freeing the event.
12216 put_task_struct(task);
12220 put_unused_fd(event_fd);
12225 * perf_event_create_kernel_counter
12227 * @attr: attributes of the counter to create
12228 * @cpu: cpu in which the counter is bound
12229 * @task: task to profile (NULL for percpu)
12231 struct perf_event *
12232 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12233 struct task_struct *task,
12234 perf_overflow_handler_t overflow_handler,
12237 struct perf_event_context *ctx;
12238 struct perf_event *event;
12242 * Grouping is not supported for kernel events, neither is 'AUX',
12243 * make sure the caller's intentions are adjusted.
12245 if (attr->aux_output)
12246 return ERR_PTR(-EINVAL);
12248 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12249 overflow_handler, context, -1);
12250 if (IS_ERR(event)) {
12251 err = PTR_ERR(event);
12255 /* Mark owner so we could distinguish it from user events. */
12256 event->owner = TASK_TOMBSTONE;
12259 * Get the target context (task or percpu):
12261 ctx = find_get_context(event->pmu, task, event);
12263 err = PTR_ERR(ctx);
12267 WARN_ON_ONCE(ctx->parent_ctx);
12268 mutex_lock(&ctx->mutex);
12269 if (ctx->task == TASK_TOMBSTONE) {
12276 * Check if the @cpu we're creating an event for is online.
12278 * We use the perf_cpu_context::ctx::mutex to serialize against
12279 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12281 struct perf_cpu_context *cpuctx =
12282 container_of(ctx, struct perf_cpu_context, ctx);
12283 if (!cpuctx->online) {
12289 if (!exclusive_event_installable(event, ctx)) {
12294 perf_install_in_context(ctx, event, event->cpu);
12295 perf_unpin_context(ctx);
12296 mutex_unlock(&ctx->mutex);
12301 mutex_unlock(&ctx->mutex);
12302 perf_unpin_context(ctx);
12307 return ERR_PTR(err);
12309 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12311 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12313 struct perf_event_context *src_ctx;
12314 struct perf_event_context *dst_ctx;
12315 struct perf_event *event, *tmp;
12318 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12319 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12322 * See perf_event_ctx_lock() for comments on the details
12323 * of swizzling perf_event::ctx.
12325 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12326 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12328 perf_remove_from_context(event, 0);
12329 unaccount_event_cpu(event, src_cpu);
12331 list_add(&event->migrate_entry, &events);
12335 * Wait for the events to quiesce before re-instating them.
12340 * Re-instate events in 2 passes.
12342 * Skip over group leaders and only install siblings on this first
12343 * pass, siblings will not get enabled without a leader, however a
12344 * leader will enable its siblings, even if those are still on the old
12347 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12348 if (event->group_leader == event)
12351 list_del(&event->migrate_entry);
12352 if (event->state >= PERF_EVENT_STATE_OFF)
12353 event->state = PERF_EVENT_STATE_INACTIVE;
12354 account_event_cpu(event, dst_cpu);
12355 perf_install_in_context(dst_ctx, event, dst_cpu);
12360 * Once all the siblings are setup properly, install the group leaders
12363 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12364 list_del(&event->migrate_entry);
12365 if (event->state >= PERF_EVENT_STATE_OFF)
12366 event->state = PERF_EVENT_STATE_INACTIVE;
12367 account_event_cpu(event, dst_cpu);
12368 perf_install_in_context(dst_ctx, event, dst_cpu);
12371 mutex_unlock(&dst_ctx->mutex);
12372 mutex_unlock(&src_ctx->mutex);
12374 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12376 static void sync_child_event(struct perf_event *child_event,
12377 struct task_struct *child)
12379 struct perf_event *parent_event = child_event->parent;
12382 if (child_event->attr.inherit_stat)
12383 perf_event_read_event(child_event, child);
12385 child_val = perf_event_count(child_event);
12388 * Add back the child's count to the parent's count:
12390 atomic64_add(child_val, &parent_event->child_count);
12391 atomic64_add(child_event->total_time_enabled,
12392 &parent_event->child_total_time_enabled);
12393 atomic64_add(child_event->total_time_running,
12394 &parent_event->child_total_time_running);
12398 perf_event_exit_event(struct perf_event *child_event,
12399 struct perf_event_context *child_ctx,
12400 struct task_struct *child)
12402 struct perf_event *parent_event = child_event->parent;
12405 * Do not destroy the 'original' grouping; because of the context
12406 * switch optimization the original events could've ended up in a
12407 * random child task.
12409 * If we were to destroy the original group, all group related
12410 * operations would cease to function properly after this random
12413 * Do destroy all inherited groups, we don't care about those
12414 * and being thorough is better.
12416 raw_spin_lock_irq(&child_ctx->lock);
12417 WARN_ON_ONCE(child_ctx->is_active);
12420 perf_group_detach(child_event);
12421 list_del_event(child_event, child_ctx);
12422 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12423 raw_spin_unlock_irq(&child_ctx->lock);
12426 * Parent events are governed by their filedesc, retain them.
12428 if (!parent_event) {
12429 perf_event_wakeup(child_event);
12433 * Child events can be cleaned up.
12436 sync_child_event(child_event, child);
12439 * Remove this event from the parent's list
12441 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12442 mutex_lock(&parent_event->child_mutex);
12443 list_del_init(&child_event->child_list);
12444 mutex_unlock(&parent_event->child_mutex);
12447 * Kick perf_poll() for is_event_hup().
12449 perf_event_wakeup(parent_event);
12450 free_event(child_event);
12451 put_event(parent_event);
12454 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12456 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12457 struct perf_event *child_event, *next;
12459 WARN_ON_ONCE(child != current);
12461 child_ctx = perf_pin_task_context(child, ctxn);
12466 * In order to reduce the amount of tricky in ctx tear-down, we hold
12467 * ctx::mutex over the entire thing. This serializes against almost
12468 * everything that wants to access the ctx.
12470 * The exception is sys_perf_event_open() /
12471 * perf_event_create_kernel_count() which does find_get_context()
12472 * without ctx::mutex (it cannot because of the move_group double mutex
12473 * lock thing). See the comments in perf_install_in_context().
12475 mutex_lock(&child_ctx->mutex);
12478 * In a single ctx::lock section, de-schedule the events and detach the
12479 * context from the task such that we cannot ever get it scheduled back
12482 raw_spin_lock_irq(&child_ctx->lock);
12483 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12486 * Now that the context is inactive, destroy the task <-> ctx relation
12487 * and mark the context dead.
12489 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12490 put_ctx(child_ctx); /* cannot be last */
12491 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12492 put_task_struct(current); /* cannot be last */
12494 clone_ctx = unclone_ctx(child_ctx);
12495 raw_spin_unlock_irq(&child_ctx->lock);
12498 put_ctx(clone_ctx);
12501 * Report the task dead after unscheduling the events so that we
12502 * won't get any samples after PERF_RECORD_EXIT. We can however still
12503 * get a few PERF_RECORD_READ events.
12505 perf_event_task(child, child_ctx, 0);
12507 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12508 perf_event_exit_event(child_event, child_ctx, child);
12510 mutex_unlock(&child_ctx->mutex);
12512 put_ctx(child_ctx);
12516 * When a child task exits, feed back event values to parent events.
12518 * Can be called with exec_update_lock held when called from
12519 * setup_new_exec().
12521 void perf_event_exit_task(struct task_struct *child)
12523 struct perf_event *event, *tmp;
12526 mutex_lock(&child->perf_event_mutex);
12527 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12529 list_del_init(&event->owner_entry);
12532 * Ensure the list deletion is visible before we clear
12533 * the owner, closes a race against perf_release() where
12534 * we need to serialize on the owner->perf_event_mutex.
12536 smp_store_release(&event->owner, NULL);
12538 mutex_unlock(&child->perf_event_mutex);
12540 for_each_task_context_nr(ctxn)
12541 perf_event_exit_task_context(child, ctxn);
12544 * The perf_event_exit_task_context calls perf_event_task
12545 * with child's task_ctx, which generates EXIT events for
12546 * child contexts and sets child->perf_event_ctxp[] to NULL.
12547 * At this point we need to send EXIT events to cpu contexts.
12549 perf_event_task(child, NULL, 0);
12552 static void perf_free_event(struct perf_event *event,
12553 struct perf_event_context *ctx)
12555 struct perf_event *parent = event->parent;
12557 if (WARN_ON_ONCE(!parent))
12560 mutex_lock(&parent->child_mutex);
12561 list_del_init(&event->child_list);
12562 mutex_unlock(&parent->child_mutex);
12566 raw_spin_lock_irq(&ctx->lock);
12567 perf_group_detach(event);
12568 list_del_event(event, ctx);
12569 raw_spin_unlock_irq(&ctx->lock);
12574 * Free a context as created by inheritance by perf_event_init_task() below,
12575 * used by fork() in case of fail.
12577 * Even though the task has never lived, the context and events have been
12578 * exposed through the child_list, so we must take care tearing it all down.
12580 void perf_event_free_task(struct task_struct *task)
12582 struct perf_event_context *ctx;
12583 struct perf_event *event, *tmp;
12586 for_each_task_context_nr(ctxn) {
12587 ctx = task->perf_event_ctxp[ctxn];
12591 mutex_lock(&ctx->mutex);
12592 raw_spin_lock_irq(&ctx->lock);
12594 * Destroy the task <-> ctx relation and mark the context dead.
12596 * This is important because even though the task hasn't been
12597 * exposed yet the context has been (through child_list).
12599 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12600 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12601 put_task_struct(task); /* cannot be last */
12602 raw_spin_unlock_irq(&ctx->lock);
12604 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12605 perf_free_event(event, ctx);
12607 mutex_unlock(&ctx->mutex);
12610 * perf_event_release_kernel() could've stolen some of our
12611 * child events and still have them on its free_list. In that
12612 * case we must wait for these events to have been freed (in
12613 * particular all their references to this task must've been
12616 * Without this copy_process() will unconditionally free this
12617 * task (irrespective of its reference count) and
12618 * _free_event()'s put_task_struct(event->hw.target) will be a
12621 * Wait for all events to drop their context reference.
12623 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12624 put_ctx(ctx); /* must be last */
12628 void perf_event_delayed_put(struct task_struct *task)
12632 for_each_task_context_nr(ctxn)
12633 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12636 struct file *perf_event_get(unsigned int fd)
12638 struct file *file = fget(fd);
12640 return ERR_PTR(-EBADF);
12642 if (file->f_op != &perf_fops) {
12644 return ERR_PTR(-EBADF);
12650 const struct perf_event *perf_get_event(struct file *file)
12652 if (file->f_op != &perf_fops)
12653 return ERR_PTR(-EINVAL);
12655 return file->private_data;
12658 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12661 return ERR_PTR(-EINVAL);
12663 return &event->attr;
12667 * Inherit an event from parent task to child task.
12670 * - valid pointer on success
12671 * - NULL for orphaned events
12672 * - IS_ERR() on error
12674 static struct perf_event *
12675 inherit_event(struct perf_event *parent_event,
12676 struct task_struct *parent,
12677 struct perf_event_context *parent_ctx,
12678 struct task_struct *child,
12679 struct perf_event *group_leader,
12680 struct perf_event_context *child_ctx)
12682 enum perf_event_state parent_state = parent_event->state;
12683 struct perf_event *child_event;
12684 unsigned long flags;
12687 * Instead of creating recursive hierarchies of events,
12688 * we link inherited events back to the original parent,
12689 * which has a filp for sure, which we use as the reference
12692 if (parent_event->parent)
12693 parent_event = parent_event->parent;
12695 child_event = perf_event_alloc(&parent_event->attr,
12698 group_leader, parent_event,
12700 if (IS_ERR(child_event))
12701 return child_event;
12704 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12705 !child_ctx->task_ctx_data) {
12706 struct pmu *pmu = child_event->pmu;
12708 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12709 if (!child_ctx->task_ctx_data) {
12710 free_event(child_event);
12711 return ERR_PTR(-ENOMEM);
12716 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12717 * must be under the same lock in order to serialize against
12718 * perf_event_release_kernel(), such that either we must observe
12719 * is_orphaned_event() or they will observe us on the child_list.
12721 mutex_lock(&parent_event->child_mutex);
12722 if (is_orphaned_event(parent_event) ||
12723 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12724 mutex_unlock(&parent_event->child_mutex);
12725 /* task_ctx_data is freed with child_ctx */
12726 free_event(child_event);
12730 get_ctx(child_ctx);
12733 * Make the child state follow the state of the parent event,
12734 * not its attr.disabled bit. We hold the parent's mutex,
12735 * so we won't race with perf_event_{en, dis}able_family.
12737 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12738 child_event->state = PERF_EVENT_STATE_INACTIVE;
12740 child_event->state = PERF_EVENT_STATE_OFF;
12742 if (parent_event->attr.freq) {
12743 u64 sample_period = parent_event->hw.sample_period;
12744 struct hw_perf_event *hwc = &child_event->hw;
12746 hwc->sample_period = sample_period;
12747 hwc->last_period = sample_period;
12749 local64_set(&hwc->period_left, sample_period);
12752 child_event->ctx = child_ctx;
12753 child_event->overflow_handler = parent_event->overflow_handler;
12754 child_event->overflow_handler_context
12755 = parent_event->overflow_handler_context;
12758 * Precalculate sample_data sizes
12760 perf_event__header_size(child_event);
12761 perf_event__id_header_size(child_event);
12764 * Link it up in the child's context:
12766 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12767 add_event_to_ctx(child_event, child_ctx);
12768 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12771 * Link this into the parent event's child list
12773 list_add_tail(&child_event->child_list, &parent_event->child_list);
12774 mutex_unlock(&parent_event->child_mutex);
12776 return child_event;
12780 * Inherits an event group.
12782 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12783 * This matches with perf_event_release_kernel() removing all child events.
12789 static int inherit_group(struct perf_event *parent_event,
12790 struct task_struct *parent,
12791 struct perf_event_context *parent_ctx,
12792 struct task_struct *child,
12793 struct perf_event_context *child_ctx)
12795 struct perf_event *leader;
12796 struct perf_event *sub;
12797 struct perf_event *child_ctr;
12799 leader = inherit_event(parent_event, parent, parent_ctx,
12800 child, NULL, child_ctx);
12801 if (IS_ERR(leader))
12802 return PTR_ERR(leader);
12804 * @leader can be NULL here because of is_orphaned_event(). In this
12805 * case inherit_event() will create individual events, similar to what
12806 * perf_group_detach() would do anyway.
12808 for_each_sibling_event(sub, parent_event) {
12809 child_ctr = inherit_event(sub, parent, parent_ctx,
12810 child, leader, child_ctx);
12811 if (IS_ERR(child_ctr))
12812 return PTR_ERR(child_ctr);
12814 if (sub->aux_event == parent_event && child_ctr &&
12815 !perf_get_aux_event(child_ctr, leader))
12822 * Creates the child task context and tries to inherit the event-group.
12824 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12825 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12826 * consistent with perf_event_release_kernel() removing all child events.
12833 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12834 struct perf_event_context *parent_ctx,
12835 struct task_struct *child, int ctxn,
12836 int *inherited_all)
12839 struct perf_event_context *child_ctx;
12841 if (!event->attr.inherit) {
12842 *inherited_all = 0;
12846 child_ctx = child->perf_event_ctxp[ctxn];
12849 * This is executed from the parent task context, so
12850 * inherit events that have been marked for cloning.
12851 * First allocate and initialize a context for the
12854 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12858 child->perf_event_ctxp[ctxn] = child_ctx;
12861 ret = inherit_group(event, parent, parent_ctx,
12865 *inherited_all = 0;
12871 * Initialize the perf_event context in task_struct
12873 static int perf_event_init_context(struct task_struct *child, int ctxn)
12875 struct perf_event_context *child_ctx, *parent_ctx;
12876 struct perf_event_context *cloned_ctx;
12877 struct perf_event *event;
12878 struct task_struct *parent = current;
12879 int inherited_all = 1;
12880 unsigned long flags;
12883 if (likely(!parent->perf_event_ctxp[ctxn]))
12887 * If the parent's context is a clone, pin it so it won't get
12888 * swapped under us.
12890 parent_ctx = perf_pin_task_context(parent, ctxn);
12895 * No need to check if parent_ctx != NULL here; since we saw
12896 * it non-NULL earlier, the only reason for it to become NULL
12897 * is if we exit, and since we're currently in the middle of
12898 * a fork we can't be exiting at the same time.
12902 * Lock the parent list. No need to lock the child - not PID
12903 * hashed yet and not running, so nobody can access it.
12905 mutex_lock(&parent_ctx->mutex);
12908 * We dont have to disable NMIs - we are only looking at
12909 * the list, not manipulating it:
12911 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12912 ret = inherit_task_group(event, parent, parent_ctx,
12913 child, ctxn, &inherited_all);
12919 * We can't hold ctx->lock when iterating the ->flexible_group list due
12920 * to allocations, but we need to prevent rotation because
12921 * rotate_ctx() will change the list from interrupt context.
12923 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12924 parent_ctx->rotate_disable = 1;
12925 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12927 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12928 ret = inherit_task_group(event, parent, parent_ctx,
12929 child, ctxn, &inherited_all);
12934 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12935 parent_ctx->rotate_disable = 0;
12937 child_ctx = child->perf_event_ctxp[ctxn];
12939 if (child_ctx && inherited_all) {
12941 * Mark the child context as a clone of the parent
12942 * context, or of whatever the parent is a clone of.
12944 * Note that if the parent is a clone, the holding of
12945 * parent_ctx->lock avoids it from being uncloned.
12947 cloned_ctx = parent_ctx->parent_ctx;
12949 child_ctx->parent_ctx = cloned_ctx;
12950 child_ctx->parent_gen = parent_ctx->parent_gen;
12952 child_ctx->parent_ctx = parent_ctx;
12953 child_ctx->parent_gen = parent_ctx->generation;
12955 get_ctx(child_ctx->parent_ctx);
12958 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12960 mutex_unlock(&parent_ctx->mutex);
12962 perf_unpin_context(parent_ctx);
12963 put_ctx(parent_ctx);
12969 * Initialize the perf_event context in task_struct
12971 int perf_event_init_task(struct task_struct *child)
12975 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12976 mutex_init(&child->perf_event_mutex);
12977 INIT_LIST_HEAD(&child->perf_event_list);
12979 for_each_task_context_nr(ctxn) {
12980 ret = perf_event_init_context(child, ctxn);
12982 perf_event_free_task(child);
12990 static void __init perf_event_init_all_cpus(void)
12992 struct swevent_htable *swhash;
12995 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12997 for_each_possible_cpu(cpu) {
12998 swhash = &per_cpu(swevent_htable, cpu);
12999 mutex_init(&swhash->hlist_mutex);
13000 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
13002 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13003 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13005 #ifdef CONFIG_CGROUP_PERF
13006 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13008 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13012 static void perf_swevent_init_cpu(unsigned int cpu)
13014 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13016 mutex_lock(&swhash->hlist_mutex);
13017 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13018 struct swevent_hlist *hlist;
13020 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13022 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13024 mutex_unlock(&swhash->hlist_mutex);
13027 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13028 static void __perf_event_exit_context(void *__info)
13030 struct perf_event_context *ctx = __info;
13031 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13032 struct perf_event *event;
13034 raw_spin_lock(&ctx->lock);
13035 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13036 list_for_each_entry(event, &ctx->event_list, event_entry)
13037 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13038 raw_spin_unlock(&ctx->lock);
13041 static void perf_event_exit_cpu_context(int cpu)
13043 struct perf_cpu_context *cpuctx;
13044 struct perf_event_context *ctx;
13047 mutex_lock(&pmus_lock);
13048 list_for_each_entry(pmu, &pmus, entry) {
13049 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13050 ctx = &cpuctx->ctx;
13052 mutex_lock(&ctx->mutex);
13053 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13054 cpuctx->online = 0;
13055 mutex_unlock(&ctx->mutex);
13057 cpumask_clear_cpu(cpu, perf_online_mask);
13058 mutex_unlock(&pmus_lock);
13062 static void perf_event_exit_cpu_context(int cpu) { }
13066 int perf_event_init_cpu(unsigned int cpu)
13068 struct perf_cpu_context *cpuctx;
13069 struct perf_event_context *ctx;
13072 perf_swevent_init_cpu(cpu);
13074 mutex_lock(&pmus_lock);
13075 cpumask_set_cpu(cpu, perf_online_mask);
13076 list_for_each_entry(pmu, &pmus, entry) {
13077 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13078 ctx = &cpuctx->ctx;
13080 mutex_lock(&ctx->mutex);
13081 cpuctx->online = 1;
13082 mutex_unlock(&ctx->mutex);
13084 mutex_unlock(&pmus_lock);
13089 int perf_event_exit_cpu(unsigned int cpu)
13091 perf_event_exit_cpu_context(cpu);
13096 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13100 for_each_online_cpu(cpu)
13101 perf_event_exit_cpu(cpu);
13107 * Run the perf reboot notifier at the very last possible moment so that
13108 * the generic watchdog code runs as long as possible.
13110 static struct notifier_block perf_reboot_notifier = {
13111 .notifier_call = perf_reboot,
13112 .priority = INT_MIN,
13115 void __init perf_event_init(void)
13119 idr_init(&pmu_idr);
13121 perf_event_init_all_cpus();
13122 init_srcu_struct(&pmus_srcu);
13123 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13124 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13125 perf_pmu_register(&perf_task_clock, NULL, -1);
13126 perf_tp_register();
13127 perf_event_init_cpu(smp_processor_id());
13128 register_reboot_notifier(&perf_reboot_notifier);
13130 ret = init_hw_breakpoint();
13131 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13134 * Build time assertion that we keep the data_head at the intended
13135 * location. IOW, validation we got the __reserved[] size right.
13137 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13141 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13144 struct perf_pmu_events_attr *pmu_attr =
13145 container_of(attr, struct perf_pmu_events_attr, attr);
13147 if (pmu_attr->event_str)
13148 return sprintf(page, "%s\n", pmu_attr->event_str);
13152 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13154 static int __init perf_event_sysfs_init(void)
13159 mutex_lock(&pmus_lock);
13161 ret = bus_register(&pmu_bus);
13165 list_for_each_entry(pmu, &pmus, entry) {
13166 if (!pmu->name || pmu->type < 0)
13169 ret = pmu_dev_alloc(pmu);
13170 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13172 pmu_bus_running = 1;
13176 mutex_unlock(&pmus_lock);
13180 device_initcall(perf_event_sysfs_init);
13182 #ifdef CONFIG_CGROUP_PERF
13183 static struct cgroup_subsys_state *
13184 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13186 struct perf_cgroup *jc;
13188 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13190 return ERR_PTR(-ENOMEM);
13192 jc->info = alloc_percpu(struct perf_cgroup_info);
13195 return ERR_PTR(-ENOMEM);
13201 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13203 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13205 free_percpu(jc->info);
13209 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13211 perf_event_cgroup(css->cgroup);
13215 static int __perf_cgroup_move(void *info)
13217 struct task_struct *task = info;
13219 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13224 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13226 struct task_struct *task;
13227 struct cgroup_subsys_state *css;
13229 cgroup_taskset_for_each(task, css, tset)
13230 task_function_call(task, __perf_cgroup_move, task);
13233 struct cgroup_subsys perf_event_cgrp_subsys = {
13234 .css_alloc = perf_cgroup_css_alloc,
13235 .css_free = perf_cgroup_css_free,
13236 .css_online = perf_cgroup_css_online,
13237 .attach = perf_cgroup_attach,
13239 * Implicitly enable on dfl hierarchy so that perf events can
13240 * always be filtered by cgroup2 path as long as perf_event
13241 * controller is not mounted on a legacy hierarchy.
13243 .implicit_on_dfl = true,
13246 #endif /* CONFIG_CGROUP_PERF */