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>
57 #include <asm/irq_regs.h>
59 typedef int (*remote_function_f)(void *);
61 struct remote_function_call {
62 struct task_struct *p;
63 remote_function_f func;
68 static void remote_function(void *data)
70 struct remote_function_call *tfc = data;
71 struct task_struct *p = tfc->p;
75 if (task_cpu(p) != smp_processor_id())
79 * Now that we're on right CPU with IRQs disabled, we can test
80 * if we hit the right task without races.
83 tfc->ret = -ESRCH; /* No such (running) process */
88 tfc->ret = tfc->func(tfc->info);
92 * task_function_call - call a function on the cpu on which a task runs
93 * @p: the task to evaluate
94 * @func: the function to be called
95 * @info: the function call argument
97 * Calls the function @func when the task is currently running. This might
98 * be on the current CPU, which just calls the function directly. This will
99 * retry due to any failures in smp_call_function_single(), such as if the
100 * task_cpu() goes offline concurrently.
102 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
105 task_function_call(struct task_struct *p, remote_function_f func, void *info)
107 struct remote_function_call data = {
116 ret = smp_call_function_single(task_cpu(p), remote_function,
131 * cpu_function_call - call a function on the cpu
132 * @func: the function to be called
133 * @info: the function call argument
135 * Calls the function @func on the remote cpu.
137 * returns: @func return value or -ENXIO when the cpu is offline
139 static int cpu_function_call(int cpu, remote_function_f func, void *info)
141 struct remote_function_call data = {
145 .ret = -ENXIO, /* No such CPU */
148 smp_call_function_single(cpu, remote_function, &data, 1);
153 static inline struct perf_cpu_context *
154 __get_cpu_context(struct perf_event_context *ctx)
156 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
159 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
160 struct perf_event_context *ctx)
162 raw_spin_lock(&cpuctx->ctx.lock);
164 raw_spin_lock(&ctx->lock);
167 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
168 struct perf_event_context *ctx)
171 raw_spin_unlock(&ctx->lock);
172 raw_spin_unlock(&cpuctx->ctx.lock);
175 #define TASK_TOMBSTONE ((void *)-1L)
177 static bool is_kernel_event(struct perf_event *event)
179 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
183 * On task ctx scheduling...
185 * When !ctx->nr_events a task context will not be scheduled. This means
186 * we can disable the scheduler hooks (for performance) without leaving
187 * pending task ctx state.
189 * This however results in two special cases:
191 * - removing the last event from a task ctx; this is relatively straight
192 * forward and is done in __perf_remove_from_context.
194 * - adding the first event to a task ctx; this is tricky because we cannot
195 * rely on ctx->is_active and therefore cannot use event_function_call().
196 * See perf_install_in_context().
198 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
201 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
202 struct perf_event_context *, void *);
204 struct event_function_struct {
205 struct perf_event *event;
210 static int event_function(void *info)
212 struct event_function_struct *efs = info;
213 struct perf_event *event = efs->event;
214 struct perf_event_context *ctx = event->ctx;
215 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
216 struct perf_event_context *task_ctx = cpuctx->task_ctx;
219 lockdep_assert_irqs_disabled();
221 perf_ctx_lock(cpuctx, task_ctx);
223 * Since we do the IPI call without holding ctx->lock things can have
224 * changed, double check we hit the task we set out to hit.
227 if (ctx->task != current) {
233 * We only use event_function_call() on established contexts,
234 * and event_function() is only ever called when active (or
235 * rather, we'll have bailed in task_function_call() or the
236 * above ctx->task != current test), therefore we must have
237 * ctx->is_active here.
239 WARN_ON_ONCE(!ctx->is_active);
241 * And since we have ctx->is_active, cpuctx->task_ctx must
244 WARN_ON_ONCE(task_ctx != ctx);
246 WARN_ON_ONCE(&cpuctx->ctx != ctx);
249 efs->func(event, cpuctx, ctx, efs->data);
251 perf_ctx_unlock(cpuctx, task_ctx);
256 static void event_function_call(struct perf_event *event, event_f func, void *data)
258 struct perf_event_context *ctx = event->ctx;
259 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
260 struct event_function_struct efs = {
266 if (!event->parent) {
268 * If this is a !child event, we must hold ctx::mutex to
269 * stabilize the event->ctx relation. See
270 * perf_event_ctx_lock().
272 lockdep_assert_held(&ctx->mutex);
276 cpu_function_call(event->cpu, event_function, &efs);
280 if (task == TASK_TOMBSTONE)
284 if (!task_function_call(task, event_function, &efs))
287 raw_spin_lock_irq(&ctx->lock);
289 * Reload the task pointer, it might have been changed by
290 * a concurrent perf_event_context_sched_out().
293 if (task == TASK_TOMBSTONE) {
294 raw_spin_unlock_irq(&ctx->lock);
297 if (ctx->is_active) {
298 raw_spin_unlock_irq(&ctx->lock);
301 func(event, NULL, ctx, data);
302 raw_spin_unlock_irq(&ctx->lock);
306 * Similar to event_function_call() + event_function(), but hard assumes IRQs
307 * are already disabled and we're on the right CPU.
309 static void event_function_local(struct perf_event *event, event_f func, void *data)
311 struct perf_event_context *ctx = event->ctx;
312 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
313 struct task_struct *task = READ_ONCE(ctx->task);
314 struct perf_event_context *task_ctx = NULL;
316 lockdep_assert_irqs_disabled();
319 if (task == TASK_TOMBSTONE)
325 perf_ctx_lock(cpuctx, task_ctx);
328 if (task == TASK_TOMBSTONE)
333 * We must be either inactive or active and the right task,
334 * otherwise we're screwed, since we cannot IPI to somewhere
337 if (ctx->is_active) {
338 if (WARN_ON_ONCE(task != current))
341 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
345 WARN_ON_ONCE(&cpuctx->ctx != ctx);
348 func(event, cpuctx, ctx, data);
350 perf_ctx_unlock(cpuctx, task_ctx);
353 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
354 PERF_FLAG_FD_OUTPUT |\
355 PERF_FLAG_PID_CGROUP |\
356 PERF_FLAG_FD_CLOEXEC)
359 * branch priv levels that need permission checks
361 #define PERF_SAMPLE_BRANCH_PERM_PLM \
362 (PERF_SAMPLE_BRANCH_KERNEL |\
363 PERF_SAMPLE_BRANCH_HV)
366 EVENT_FLEXIBLE = 0x1,
369 /* see ctx_resched() for details */
371 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
375 * perf_sched_events : >0 events exist
376 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
379 static void perf_sched_delayed(struct work_struct *work);
380 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
381 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
382 static DEFINE_MUTEX(perf_sched_mutex);
383 static atomic_t perf_sched_count;
385 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
386 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
387 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
389 static atomic_t nr_mmap_events __read_mostly;
390 static atomic_t nr_comm_events __read_mostly;
391 static atomic_t nr_namespaces_events __read_mostly;
392 static atomic_t nr_task_events __read_mostly;
393 static atomic_t nr_freq_events __read_mostly;
394 static atomic_t nr_switch_events __read_mostly;
395 static atomic_t nr_ksymbol_events __read_mostly;
396 static atomic_t nr_bpf_events __read_mostly;
397 static atomic_t nr_cgroup_events __read_mostly;
398 static atomic_t nr_text_poke_events __read_mostly;
400 static LIST_HEAD(pmus);
401 static DEFINE_MUTEX(pmus_lock);
402 static struct srcu_struct pmus_srcu;
403 static cpumask_var_t perf_online_mask;
406 * perf event paranoia level:
407 * -1 - not paranoid at all
408 * 0 - disallow raw tracepoint access for unpriv
409 * 1 - disallow cpu events for unpriv
410 * 2 - disallow kernel profiling for unpriv
412 int sysctl_perf_event_paranoid __read_mostly = 2;
414 /* Minimum for 512 kiB + 1 user control page */
415 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
418 * max perf event sample rate
420 #define DEFAULT_MAX_SAMPLE_RATE 100000
421 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
422 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
424 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
426 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
427 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
429 static int perf_sample_allowed_ns __read_mostly =
430 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
432 static void update_perf_cpu_limits(void)
434 u64 tmp = perf_sample_period_ns;
436 tmp *= sysctl_perf_cpu_time_max_percent;
437 tmp = div_u64(tmp, 100);
441 WRITE_ONCE(perf_sample_allowed_ns, tmp);
444 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
446 int perf_proc_update_handler(struct ctl_table *table, int write,
447 void *buffer, size_t *lenp, loff_t *ppos)
450 int perf_cpu = sysctl_perf_cpu_time_max_percent;
452 * If throttling is disabled don't allow the write:
454 if (write && (perf_cpu == 100 || perf_cpu == 0))
457 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
461 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
462 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
463 update_perf_cpu_limits();
468 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
470 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
471 void *buffer, size_t *lenp, loff_t *ppos)
473 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
478 if (sysctl_perf_cpu_time_max_percent == 100 ||
479 sysctl_perf_cpu_time_max_percent == 0) {
481 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
482 WRITE_ONCE(perf_sample_allowed_ns, 0);
484 update_perf_cpu_limits();
491 * perf samples are done in some very critical code paths (NMIs).
492 * If they take too much CPU time, the system can lock up and not
493 * get any real work done. This will drop the sample rate when
494 * we detect that events are taking too long.
496 #define NR_ACCUMULATED_SAMPLES 128
497 static DEFINE_PER_CPU(u64, running_sample_length);
499 static u64 __report_avg;
500 static u64 __report_allowed;
502 static void perf_duration_warn(struct irq_work *w)
504 printk_ratelimited(KERN_INFO
505 "perf: interrupt took too long (%lld > %lld), lowering "
506 "kernel.perf_event_max_sample_rate to %d\n",
507 __report_avg, __report_allowed,
508 sysctl_perf_event_sample_rate);
511 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
513 void perf_sample_event_took(u64 sample_len_ns)
515 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
523 /* Decay the counter by 1 average sample. */
524 running_len = __this_cpu_read(running_sample_length);
525 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
526 running_len += sample_len_ns;
527 __this_cpu_write(running_sample_length, running_len);
530 * Note: this will be biased artifically low until we have
531 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
532 * from having to maintain a count.
534 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
535 if (avg_len <= max_len)
538 __report_avg = avg_len;
539 __report_allowed = max_len;
542 * Compute a throttle threshold 25% below the current duration.
544 avg_len += avg_len / 4;
545 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
551 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
552 WRITE_ONCE(max_samples_per_tick, max);
554 sysctl_perf_event_sample_rate = max * HZ;
555 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
557 if (!irq_work_queue(&perf_duration_work)) {
558 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
559 "kernel.perf_event_max_sample_rate to %d\n",
560 __report_avg, __report_allowed,
561 sysctl_perf_event_sample_rate);
565 static atomic64_t perf_event_id;
567 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
568 enum event_type_t event_type);
570 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
571 enum event_type_t event_type,
572 struct task_struct *task);
574 static void update_context_time(struct perf_event_context *ctx);
575 static u64 perf_event_time(struct perf_event *event);
577 void __weak perf_event_print_debug(void) { }
579 extern __weak const char *perf_pmu_name(void)
584 static inline u64 perf_clock(void)
586 return local_clock();
589 static inline u64 perf_event_clock(struct perf_event *event)
591 return event->clock();
595 * State based event timekeeping...
597 * The basic idea is to use event->state to determine which (if any) time
598 * fields to increment with the current delta. This means we only need to
599 * update timestamps when we change state or when they are explicitly requested
602 * Event groups make things a little more complicated, but not terribly so. The
603 * rules for a group are that if the group leader is OFF the entire group is
604 * OFF, irrespecive of what the group member states are. This results in
605 * __perf_effective_state().
607 * A futher ramification is that when a group leader flips between OFF and
608 * !OFF, we need to update all group member times.
611 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
612 * need to make sure the relevant context time is updated before we try and
613 * update our timestamps.
616 static __always_inline enum perf_event_state
617 __perf_effective_state(struct perf_event *event)
619 struct perf_event *leader = event->group_leader;
621 if (leader->state <= PERF_EVENT_STATE_OFF)
622 return leader->state;
627 static __always_inline void
628 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
630 enum perf_event_state state = __perf_effective_state(event);
631 u64 delta = now - event->tstamp;
633 *enabled = event->total_time_enabled;
634 if (state >= PERF_EVENT_STATE_INACTIVE)
637 *running = event->total_time_running;
638 if (state >= PERF_EVENT_STATE_ACTIVE)
642 static void perf_event_update_time(struct perf_event *event)
644 u64 now = perf_event_time(event);
646 __perf_update_times(event, now, &event->total_time_enabled,
647 &event->total_time_running);
651 static void perf_event_update_sibling_time(struct perf_event *leader)
653 struct perf_event *sibling;
655 for_each_sibling_event(sibling, leader)
656 perf_event_update_time(sibling);
660 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
662 if (event->state == state)
665 perf_event_update_time(event);
667 * If a group leader gets enabled/disabled all its siblings
670 if ((event->state < 0) ^ (state < 0))
671 perf_event_update_sibling_time(event);
673 WRITE_ONCE(event->state, state);
677 * UP store-release, load-acquire
680 #define __store_release(ptr, val) \
683 WRITE_ONCE(*(ptr), (val)); \
686 #define __load_acquire(ptr) \
688 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
693 #ifdef CONFIG_CGROUP_PERF
696 perf_cgroup_match(struct perf_event *event)
698 struct perf_event_context *ctx = event->ctx;
699 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
701 /* @event doesn't care about cgroup */
705 /* wants specific cgroup scope but @cpuctx isn't associated with any */
710 * Cgroup scoping is recursive. An event enabled for a cgroup is
711 * also enabled for all its descendant cgroups. If @cpuctx's
712 * cgroup is a descendant of @event's (the test covers identity
713 * case), it's a match.
715 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
716 event->cgrp->css.cgroup);
719 static inline void perf_detach_cgroup(struct perf_event *event)
721 css_put(&event->cgrp->css);
725 static inline int is_cgroup_event(struct perf_event *event)
727 return event->cgrp != NULL;
730 static inline u64 perf_cgroup_event_time(struct perf_event *event)
732 struct perf_cgroup_info *t;
734 t = per_cpu_ptr(event->cgrp->info, event->cpu);
738 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
740 struct perf_cgroup_info *t;
742 t = per_cpu_ptr(event->cgrp->info, event->cpu);
743 if (!__load_acquire(&t->active))
745 now += READ_ONCE(t->timeoffset);
749 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
752 info->time += now - info->timestamp;
753 info->timestamp = now;
755 * see update_context_time()
757 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
760 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
762 struct perf_cgroup *cgrp = cpuctx->cgrp;
763 struct cgroup_subsys_state *css;
764 struct perf_cgroup_info *info;
767 u64 now = perf_clock();
769 for (css = &cgrp->css; css; css = css->parent) {
770 cgrp = container_of(css, struct perf_cgroup, css);
771 info = this_cpu_ptr(cgrp->info);
773 __update_cgrp_time(info, now, true);
775 __store_release(&info->active, 0);
780 static inline void update_cgrp_time_from_event(struct perf_event *event)
782 struct perf_cgroup_info *info;
783 struct perf_cgroup *cgrp;
786 * ensure we access cgroup data only when needed and
787 * when we know the cgroup is pinned (css_get)
789 if (!is_cgroup_event(event))
792 cgrp = perf_cgroup_from_task(current, event->ctx);
794 * Do not update time when cgroup is not active
796 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup)) {
797 info = this_cpu_ptr(event->cgrp->info);
798 __update_cgrp_time(info, perf_clock(), true);
803 perf_cgroup_set_timestamp(struct task_struct *task,
804 struct perf_event_context *ctx)
806 struct perf_cgroup *cgrp;
807 struct perf_cgroup_info *info;
808 struct cgroup_subsys_state *css;
811 * ctx->lock held by caller
812 * ensure we do not access cgroup data
813 * unless we have the cgroup pinned (css_get)
815 if (!task || !ctx->nr_cgroups)
818 cgrp = perf_cgroup_from_task(task, ctx);
820 for (css = &cgrp->css; css; css = css->parent) {
821 cgrp = container_of(css, struct perf_cgroup, css);
822 info = this_cpu_ptr(cgrp->info);
823 __update_cgrp_time(info, ctx->timestamp, false);
824 __store_release(&info->active, 1);
828 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
830 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
831 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
834 * reschedule events based on the cgroup constraint of task.
836 * mode SWOUT : schedule out everything
837 * mode SWIN : schedule in based on cgroup for next
839 static void perf_cgroup_switch(struct task_struct *task, int mode)
841 struct perf_cpu_context *cpuctx, *tmp;
842 struct list_head *list;
846 * Disable interrupts and preemption to avoid this CPU's
847 * cgrp_cpuctx_entry to change under us.
849 local_irq_save(flags);
851 list = this_cpu_ptr(&cgrp_cpuctx_list);
852 list_for_each_entry_safe(cpuctx, tmp, list, cgrp_cpuctx_entry) {
853 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
855 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
856 perf_pmu_disable(cpuctx->ctx.pmu);
858 if (mode & PERF_CGROUP_SWOUT) {
859 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
861 * must not be done before ctxswout due
862 * to event_filter_match() in event_sched_out()
867 if (mode & PERF_CGROUP_SWIN) {
868 WARN_ON_ONCE(cpuctx->cgrp);
870 * set cgrp before ctxsw in to allow
871 * event_filter_match() to not have to pass
873 * we pass the cpuctx->ctx to perf_cgroup_from_task()
874 * because cgorup events are only per-cpu
876 cpuctx->cgrp = perf_cgroup_from_task(task,
878 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
880 perf_pmu_enable(cpuctx->ctx.pmu);
881 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
884 local_irq_restore(flags);
887 static inline void perf_cgroup_sched_out(struct task_struct *task,
888 struct task_struct *next)
890 struct perf_cgroup *cgrp1;
891 struct perf_cgroup *cgrp2 = NULL;
895 * we come here when we know perf_cgroup_events > 0
896 * we do not need to pass the ctx here because we know
897 * we are holding the rcu lock
899 cgrp1 = perf_cgroup_from_task(task, NULL);
900 cgrp2 = perf_cgroup_from_task(next, NULL);
903 * only schedule out current cgroup events if we know
904 * that we are switching to a different cgroup. Otherwise,
905 * do no touch the cgroup events.
908 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
913 static inline void perf_cgroup_sched_in(struct task_struct *prev,
914 struct task_struct *task)
916 struct perf_cgroup *cgrp1;
917 struct perf_cgroup *cgrp2 = NULL;
921 * we come here when we know perf_cgroup_events > 0
922 * we do not need to pass the ctx here because we know
923 * we are holding the rcu lock
925 cgrp1 = perf_cgroup_from_task(task, NULL);
926 cgrp2 = perf_cgroup_from_task(prev, NULL);
929 * only need to schedule in cgroup events if we are changing
930 * cgroup during ctxsw. Cgroup events were not scheduled
931 * out of ctxsw out if that was not the case.
934 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
939 static int perf_cgroup_ensure_storage(struct perf_event *event,
940 struct cgroup_subsys_state *css)
942 struct perf_cpu_context *cpuctx;
943 struct perf_event **storage;
944 int cpu, heap_size, ret = 0;
947 * Allow storage to have sufficent space for an iterator for each
948 * possibly nested cgroup plus an iterator for events with no cgroup.
950 for (heap_size = 1; css; css = css->parent)
953 for_each_possible_cpu(cpu) {
954 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
955 if (heap_size <= cpuctx->heap_size)
958 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
959 GFP_KERNEL, cpu_to_node(cpu));
965 raw_spin_lock_irq(&cpuctx->ctx.lock);
966 if (cpuctx->heap_size < heap_size) {
967 swap(cpuctx->heap, storage);
968 if (storage == cpuctx->heap_default)
970 cpuctx->heap_size = heap_size;
972 raw_spin_unlock_irq(&cpuctx->ctx.lock);
980 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
981 struct perf_event_attr *attr,
982 struct perf_event *group_leader)
984 struct perf_cgroup *cgrp;
985 struct cgroup_subsys_state *css;
986 struct fd f = fdget(fd);
992 css = css_tryget_online_from_dir(f.file->f_path.dentry,
993 &perf_event_cgrp_subsys);
999 ret = perf_cgroup_ensure_storage(event, css);
1003 cgrp = container_of(css, struct perf_cgroup, css);
1007 * all events in a group must monitor
1008 * the same cgroup because a task belongs
1009 * to only one perf cgroup at a time
1011 if (group_leader && group_leader->cgrp != cgrp) {
1012 perf_detach_cgroup(event);
1021 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1023 struct perf_cpu_context *cpuctx;
1025 if (!is_cgroup_event(event))
1029 * Because cgroup events are always per-cpu events,
1030 * @ctx == &cpuctx->ctx.
1032 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1035 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1036 * matching the event's cgroup, we must do this for every new event,
1037 * because if the first would mismatch, the second would not try again
1038 * and we would leave cpuctx->cgrp unset.
1040 if (ctx->is_active && !cpuctx->cgrp) {
1041 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1043 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1044 cpuctx->cgrp = cgrp;
1047 if (ctx->nr_cgroups++)
1050 list_add(&cpuctx->cgrp_cpuctx_entry,
1051 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1055 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1057 struct perf_cpu_context *cpuctx;
1059 if (!is_cgroup_event(event))
1063 * Because cgroup events are always per-cpu events,
1064 * @ctx == &cpuctx->ctx.
1066 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1068 if (--ctx->nr_cgroups)
1071 if (ctx->is_active && cpuctx->cgrp)
1072 cpuctx->cgrp = NULL;
1074 list_del(&cpuctx->cgrp_cpuctx_entry);
1077 #else /* !CONFIG_CGROUP_PERF */
1080 perf_cgroup_match(struct perf_event *event)
1085 static inline void perf_detach_cgroup(struct perf_event *event)
1088 static inline int is_cgroup_event(struct perf_event *event)
1093 static inline void update_cgrp_time_from_event(struct perf_event *event)
1097 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1102 static inline void perf_cgroup_sched_out(struct task_struct *task,
1103 struct task_struct *next)
1107 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1108 struct task_struct *task)
1112 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1113 struct perf_event_attr *attr,
1114 struct perf_event *group_leader)
1120 perf_cgroup_set_timestamp(struct task_struct *task,
1121 struct perf_event_context *ctx)
1126 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1130 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1135 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1141 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1146 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1152 * set default to be dependent on timer tick just
1153 * like original code
1155 #define PERF_CPU_HRTIMER (1000 / HZ)
1157 * function must be called with interrupts disabled
1159 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1161 struct perf_cpu_context *cpuctx;
1164 lockdep_assert_irqs_disabled();
1166 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1167 rotations = perf_rotate_context(cpuctx);
1169 raw_spin_lock(&cpuctx->hrtimer_lock);
1171 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1173 cpuctx->hrtimer_active = 0;
1174 raw_spin_unlock(&cpuctx->hrtimer_lock);
1176 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1179 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1181 struct hrtimer *timer = &cpuctx->hrtimer;
1182 struct pmu *pmu = cpuctx->ctx.pmu;
1185 /* no multiplexing needed for SW PMU */
1186 if (pmu->task_ctx_nr == perf_sw_context)
1190 * check default is sane, if not set then force to
1191 * default interval (1/tick)
1193 interval = pmu->hrtimer_interval_ms;
1195 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1197 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1199 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1200 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1201 timer->function = perf_mux_hrtimer_handler;
1204 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1206 struct hrtimer *timer = &cpuctx->hrtimer;
1207 struct pmu *pmu = cpuctx->ctx.pmu;
1208 unsigned long flags;
1210 /* not for SW PMU */
1211 if (pmu->task_ctx_nr == perf_sw_context)
1214 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1215 if (!cpuctx->hrtimer_active) {
1216 cpuctx->hrtimer_active = 1;
1217 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1218 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1220 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1225 static int perf_mux_hrtimer_restart_ipi(void *arg)
1227 return perf_mux_hrtimer_restart(arg);
1230 void perf_pmu_disable(struct pmu *pmu)
1232 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1234 pmu->pmu_disable(pmu);
1237 void perf_pmu_enable(struct pmu *pmu)
1239 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1241 pmu->pmu_enable(pmu);
1244 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1247 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1248 * perf_event_task_tick() are fully serialized because they're strictly cpu
1249 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1250 * disabled, while perf_event_task_tick is called from IRQ context.
1252 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1254 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1256 lockdep_assert_irqs_disabled();
1258 WARN_ON(!list_empty(&ctx->active_ctx_list));
1260 list_add(&ctx->active_ctx_list, head);
1263 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1265 lockdep_assert_irqs_disabled();
1267 WARN_ON(list_empty(&ctx->active_ctx_list));
1269 list_del_init(&ctx->active_ctx_list);
1272 static void get_ctx(struct perf_event_context *ctx)
1274 refcount_inc(&ctx->refcount);
1277 static void *alloc_task_ctx_data(struct pmu *pmu)
1279 if (pmu->task_ctx_cache)
1280 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1285 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1287 if (pmu->task_ctx_cache && task_ctx_data)
1288 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1291 static void free_ctx(struct rcu_head *head)
1293 struct perf_event_context *ctx;
1295 ctx = container_of(head, struct perf_event_context, rcu_head);
1296 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1300 static void put_ctx(struct perf_event_context *ctx)
1302 if (refcount_dec_and_test(&ctx->refcount)) {
1303 if (ctx->parent_ctx)
1304 put_ctx(ctx->parent_ctx);
1305 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1306 put_task_struct(ctx->task);
1307 call_rcu(&ctx->rcu_head, free_ctx);
1312 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1313 * perf_pmu_migrate_context() we need some magic.
1315 * Those places that change perf_event::ctx will hold both
1316 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1318 * Lock ordering is by mutex address. There are two other sites where
1319 * perf_event_context::mutex nests and those are:
1321 * - perf_event_exit_task_context() [ child , 0 ]
1322 * perf_event_exit_event()
1323 * put_event() [ parent, 1 ]
1325 * - perf_event_init_context() [ parent, 0 ]
1326 * inherit_task_group()
1329 * perf_event_alloc()
1331 * perf_try_init_event() [ child , 1 ]
1333 * While it appears there is an obvious deadlock here -- the parent and child
1334 * nesting levels are inverted between the two. This is in fact safe because
1335 * life-time rules separate them. That is an exiting task cannot fork, and a
1336 * spawning task cannot (yet) exit.
1338 * But remember that these are parent<->child context relations, and
1339 * migration does not affect children, therefore these two orderings should not
1342 * The change in perf_event::ctx does not affect children (as claimed above)
1343 * because the sys_perf_event_open() case will install a new event and break
1344 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1345 * concerned with cpuctx and that doesn't have children.
1347 * The places that change perf_event::ctx will issue:
1349 * perf_remove_from_context();
1350 * synchronize_rcu();
1351 * perf_install_in_context();
1353 * to affect the change. The remove_from_context() + synchronize_rcu() should
1354 * quiesce the event, after which we can install it in the new location. This
1355 * means that only external vectors (perf_fops, prctl) can perturb the event
1356 * while in transit. Therefore all such accessors should also acquire
1357 * perf_event_context::mutex to serialize against this.
1359 * However; because event->ctx can change while we're waiting to acquire
1360 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1365 * task_struct::perf_event_mutex
1366 * perf_event_context::mutex
1367 * perf_event::child_mutex;
1368 * perf_event_context::lock
1369 * perf_event::mmap_mutex
1371 * perf_addr_filters_head::lock
1375 * cpuctx->mutex / perf_event_context::mutex
1377 static struct perf_event_context *
1378 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1380 struct perf_event_context *ctx;
1384 ctx = READ_ONCE(event->ctx);
1385 if (!refcount_inc_not_zero(&ctx->refcount)) {
1391 mutex_lock_nested(&ctx->mutex, nesting);
1392 if (event->ctx != ctx) {
1393 mutex_unlock(&ctx->mutex);
1401 static inline struct perf_event_context *
1402 perf_event_ctx_lock(struct perf_event *event)
1404 return perf_event_ctx_lock_nested(event, 0);
1407 static void perf_event_ctx_unlock(struct perf_event *event,
1408 struct perf_event_context *ctx)
1410 mutex_unlock(&ctx->mutex);
1415 * This must be done under the ctx->lock, such as to serialize against
1416 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1417 * calling scheduler related locks and ctx->lock nests inside those.
1419 static __must_check struct perf_event_context *
1420 unclone_ctx(struct perf_event_context *ctx)
1422 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1424 lockdep_assert_held(&ctx->lock);
1427 ctx->parent_ctx = NULL;
1433 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1438 * only top level events have the pid namespace they were created in
1441 event = event->parent;
1443 nr = __task_pid_nr_ns(p, type, event->ns);
1444 /* avoid -1 if it is idle thread or runs in another ns */
1445 if (!nr && !pid_alive(p))
1450 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1452 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1455 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1457 return perf_event_pid_type(event, p, PIDTYPE_PID);
1461 * If we inherit events we want to return the parent event id
1464 static u64 primary_event_id(struct perf_event *event)
1469 id = event->parent->id;
1475 * Get the perf_event_context for a task and lock it.
1477 * This has to cope with the fact that until it is locked,
1478 * the context could get moved to another task.
1480 static struct perf_event_context *
1481 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1483 struct perf_event_context *ctx;
1487 * One of the few rules of preemptible RCU is that one cannot do
1488 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1489 * part of the read side critical section was irqs-enabled -- see
1490 * rcu_read_unlock_special().
1492 * Since ctx->lock nests under rq->lock we must ensure the entire read
1493 * side critical section has interrupts disabled.
1495 local_irq_save(*flags);
1497 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1500 * If this context is a clone of another, it might
1501 * get swapped for another underneath us by
1502 * perf_event_task_sched_out, though the
1503 * rcu_read_lock() protects us from any context
1504 * getting freed. Lock the context and check if it
1505 * got swapped before we could get the lock, and retry
1506 * if so. If we locked the right context, then it
1507 * can't get swapped on us any more.
1509 raw_spin_lock(&ctx->lock);
1510 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1511 raw_spin_unlock(&ctx->lock);
1513 local_irq_restore(*flags);
1517 if (ctx->task == TASK_TOMBSTONE ||
1518 !refcount_inc_not_zero(&ctx->refcount)) {
1519 raw_spin_unlock(&ctx->lock);
1522 WARN_ON_ONCE(ctx->task != task);
1527 local_irq_restore(*flags);
1532 * Get the context for a task and increment its pin_count so it
1533 * can't get swapped to another task. This also increments its
1534 * reference count so that the context can't get freed.
1536 static struct perf_event_context *
1537 perf_pin_task_context(struct task_struct *task, int ctxn)
1539 struct perf_event_context *ctx;
1540 unsigned long flags;
1542 ctx = perf_lock_task_context(task, ctxn, &flags);
1545 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1550 static void perf_unpin_context(struct perf_event_context *ctx)
1552 unsigned long flags;
1554 raw_spin_lock_irqsave(&ctx->lock, flags);
1556 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1560 * Update the record of the current time in a context.
1562 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1564 u64 now = perf_clock();
1567 ctx->time += now - ctx->timestamp;
1568 ctx->timestamp = now;
1571 * The above: time' = time + (now - timestamp), can be re-arranged
1572 * into: time` = now + (time - timestamp), which gives a single value
1573 * offset to compute future time without locks on.
1575 * See perf_event_time_now(), which can be used from NMI context where
1576 * it's (obviously) not possible to acquire ctx->lock in order to read
1577 * both the above values in a consistent manner.
1579 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1582 static void update_context_time(struct perf_event_context *ctx)
1584 __update_context_time(ctx, true);
1587 static u64 perf_event_time(struct perf_event *event)
1589 struct perf_event_context *ctx = event->ctx;
1594 if (is_cgroup_event(event))
1595 return perf_cgroup_event_time(event);
1600 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1602 struct perf_event_context *ctx = event->ctx;
1607 if (is_cgroup_event(event))
1608 return perf_cgroup_event_time_now(event, now);
1610 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1613 now += READ_ONCE(ctx->timeoffset);
1617 static enum event_type_t get_event_type(struct perf_event *event)
1619 struct perf_event_context *ctx = event->ctx;
1620 enum event_type_t event_type;
1622 lockdep_assert_held(&ctx->lock);
1625 * It's 'group type', really, because if our group leader is
1626 * pinned, so are we.
1628 if (event->group_leader != event)
1629 event = event->group_leader;
1631 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1633 event_type |= EVENT_CPU;
1639 * Helper function to initialize event group nodes.
1641 static void init_event_group(struct perf_event *event)
1643 RB_CLEAR_NODE(&event->group_node);
1644 event->group_index = 0;
1648 * Extract pinned or flexible groups from the context
1649 * based on event attrs bits.
1651 static struct perf_event_groups *
1652 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1654 if (event->attr.pinned)
1655 return &ctx->pinned_groups;
1657 return &ctx->flexible_groups;
1661 * Helper function to initializes perf_event_group trees.
1663 static void perf_event_groups_init(struct perf_event_groups *groups)
1665 groups->tree = RB_ROOT;
1670 * Compare function for event groups;
1672 * Implements complex key that first sorts by CPU and then by virtual index
1673 * which provides ordering when rotating groups for the same CPU.
1676 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1678 if (left->cpu < right->cpu)
1680 if (left->cpu > right->cpu)
1683 #ifdef CONFIG_CGROUP_PERF
1684 if (left->cgrp != right->cgrp) {
1685 if (!left->cgrp || !left->cgrp->css.cgroup) {
1687 * Left has no cgroup but right does, no cgroups come
1692 if (!right->cgrp || !right->cgrp->css.cgroup) {
1694 * Right has no cgroup but left does, no cgroups come
1699 /* Two dissimilar cgroups, order by id. */
1700 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1707 if (left->group_index < right->group_index)
1709 if (left->group_index > right->group_index)
1716 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1717 * key (see perf_event_groups_less). This places it last inside the CPU
1721 perf_event_groups_insert(struct perf_event_groups *groups,
1722 struct perf_event *event)
1724 struct perf_event *node_event;
1725 struct rb_node *parent;
1726 struct rb_node **node;
1728 event->group_index = ++groups->index;
1730 node = &groups->tree.rb_node;
1735 node_event = container_of(*node, struct perf_event, group_node);
1737 if (perf_event_groups_less(event, node_event))
1738 node = &parent->rb_left;
1740 node = &parent->rb_right;
1743 rb_link_node(&event->group_node, parent, node);
1744 rb_insert_color(&event->group_node, &groups->tree);
1748 * Helper function to insert event into the pinned or flexible groups.
1751 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1753 struct perf_event_groups *groups;
1755 groups = get_event_groups(event, ctx);
1756 perf_event_groups_insert(groups, event);
1760 * Delete a group from a tree.
1763 perf_event_groups_delete(struct perf_event_groups *groups,
1764 struct perf_event *event)
1766 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1767 RB_EMPTY_ROOT(&groups->tree));
1769 rb_erase(&event->group_node, &groups->tree);
1770 init_event_group(event);
1774 * Helper function to delete event from its groups.
1777 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1779 struct perf_event_groups *groups;
1781 groups = get_event_groups(event, ctx);
1782 perf_event_groups_delete(groups, event);
1786 * Get the leftmost event in the cpu/cgroup subtree.
1788 static struct perf_event *
1789 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1790 struct cgroup *cgrp)
1792 struct perf_event *node_event = NULL, *match = NULL;
1793 struct rb_node *node = groups->tree.rb_node;
1794 #ifdef CONFIG_CGROUP_PERF
1795 u64 node_cgrp_id, cgrp_id = 0;
1798 cgrp_id = cgrp->kn->id;
1802 node_event = container_of(node, struct perf_event, group_node);
1804 if (cpu < node_event->cpu) {
1805 node = node->rb_left;
1808 if (cpu > node_event->cpu) {
1809 node = node->rb_right;
1812 #ifdef CONFIG_CGROUP_PERF
1814 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1815 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1817 if (cgrp_id < node_cgrp_id) {
1818 node = node->rb_left;
1821 if (cgrp_id > node_cgrp_id) {
1822 node = node->rb_right;
1827 node = node->rb_left;
1834 * Like rb_entry_next_safe() for the @cpu subtree.
1836 static struct perf_event *
1837 perf_event_groups_next(struct perf_event *event)
1839 struct perf_event *next;
1840 #ifdef CONFIG_CGROUP_PERF
1841 u64 curr_cgrp_id = 0;
1842 u64 next_cgrp_id = 0;
1845 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1846 if (next == NULL || next->cpu != event->cpu)
1849 #ifdef CONFIG_CGROUP_PERF
1850 if (event->cgrp && event->cgrp->css.cgroup)
1851 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1853 if (next->cgrp && next->cgrp->css.cgroup)
1854 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1856 if (curr_cgrp_id != next_cgrp_id)
1863 * Iterate through the whole groups tree.
1865 #define perf_event_groups_for_each(event, groups) \
1866 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1867 typeof(*event), group_node); event; \
1868 event = rb_entry_safe(rb_next(&event->group_node), \
1869 typeof(*event), group_node))
1872 * Add an event from the lists for its context.
1873 * Must be called with ctx->mutex and ctx->lock held.
1876 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1878 lockdep_assert_held(&ctx->lock);
1880 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1881 event->attach_state |= PERF_ATTACH_CONTEXT;
1883 event->tstamp = perf_event_time(event);
1886 * If we're a stand alone event or group leader, we go to the context
1887 * list, group events are kept attached to the group so that
1888 * perf_group_detach can, at all times, locate all siblings.
1890 if (event->group_leader == event) {
1891 event->group_caps = event->event_caps;
1892 add_event_to_groups(event, ctx);
1895 list_add_rcu(&event->event_entry, &ctx->event_list);
1897 if (event->attr.inherit_stat)
1900 if (event->state > PERF_EVENT_STATE_OFF)
1901 perf_cgroup_event_enable(event, ctx);
1907 * Initialize event state based on the perf_event_attr::disabled.
1909 static inline void perf_event__state_init(struct perf_event *event)
1911 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1912 PERF_EVENT_STATE_INACTIVE;
1915 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1917 int entry = sizeof(u64); /* value */
1921 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1922 size += sizeof(u64);
1924 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1925 size += sizeof(u64);
1927 if (read_format & PERF_FORMAT_ID)
1928 entry += sizeof(u64);
1930 if (read_format & PERF_FORMAT_LOST)
1931 entry += sizeof(u64);
1933 if (read_format & PERF_FORMAT_GROUP) {
1935 size += sizeof(u64);
1939 * Since perf_event_validate_size() limits this to 16k and inhibits
1940 * adding more siblings, this will never overflow.
1942 return size + nr * entry;
1945 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1947 struct perf_sample_data *data;
1950 if (sample_type & PERF_SAMPLE_IP)
1951 size += sizeof(data->ip);
1953 if (sample_type & PERF_SAMPLE_ADDR)
1954 size += sizeof(data->addr);
1956 if (sample_type & PERF_SAMPLE_PERIOD)
1957 size += sizeof(data->period);
1959 if (sample_type & PERF_SAMPLE_WEIGHT)
1960 size += sizeof(data->weight);
1962 if (sample_type & PERF_SAMPLE_READ)
1963 size += event->read_size;
1965 if (sample_type & PERF_SAMPLE_DATA_SRC)
1966 size += sizeof(data->data_src.val);
1968 if (sample_type & PERF_SAMPLE_TRANSACTION)
1969 size += sizeof(data->txn);
1971 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1972 size += sizeof(data->phys_addr);
1974 if (sample_type & PERF_SAMPLE_CGROUP)
1975 size += sizeof(data->cgroup);
1977 event->header_size = size;
1981 * Called at perf_event creation and when events are attached/detached from a
1984 static void perf_event__header_size(struct perf_event *event)
1987 __perf_event_read_size(event->attr.read_format,
1988 event->group_leader->nr_siblings);
1989 __perf_event_header_size(event, event->attr.sample_type);
1992 static void perf_event__id_header_size(struct perf_event *event)
1994 struct perf_sample_data *data;
1995 u64 sample_type = event->attr.sample_type;
1998 if (sample_type & PERF_SAMPLE_TID)
1999 size += sizeof(data->tid_entry);
2001 if (sample_type & PERF_SAMPLE_TIME)
2002 size += sizeof(data->time);
2004 if (sample_type & PERF_SAMPLE_IDENTIFIER)
2005 size += sizeof(data->id);
2007 if (sample_type & PERF_SAMPLE_ID)
2008 size += sizeof(data->id);
2010 if (sample_type & PERF_SAMPLE_STREAM_ID)
2011 size += sizeof(data->stream_id);
2013 if (sample_type & PERF_SAMPLE_CPU)
2014 size += sizeof(data->cpu_entry);
2016 event->id_header_size = size;
2020 * Check that adding an event to the group does not result in anybody
2021 * overflowing the 64k event limit imposed by the output buffer.
2023 * Specifically, check that the read_size for the event does not exceed 16k,
2024 * read_size being the one term that grows with groups size. Since read_size
2025 * depends on per-event read_format, also (re)check the existing events.
2027 * This leaves 48k for the constant size fields and things like callchains,
2028 * branch stacks and register sets.
2030 static bool perf_event_validate_size(struct perf_event *event)
2032 struct perf_event *sibling, *group_leader = event->group_leader;
2034 if (__perf_event_read_size(event->attr.read_format,
2035 group_leader->nr_siblings + 1) > 16*1024)
2038 if (__perf_event_read_size(group_leader->attr.read_format,
2039 group_leader->nr_siblings + 1) > 16*1024)
2043 * When creating a new group leader, group_leader->ctx is initialized
2044 * after the size has been validated, but we cannot safely use
2045 * for_each_sibling_event() until group_leader->ctx is set. A new group
2046 * leader cannot have any siblings yet, so we can safely skip checking
2047 * the non-existent siblings.
2049 if (event == group_leader)
2052 for_each_sibling_event(sibling, group_leader) {
2053 if (__perf_event_read_size(sibling->attr.read_format,
2054 group_leader->nr_siblings + 1) > 16*1024)
2061 static void perf_group_attach(struct perf_event *event)
2063 struct perf_event *group_leader = event->group_leader, *pos;
2065 lockdep_assert_held(&event->ctx->lock);
2068 * We can have double attach due to group movement in perf_event_open.
2070 if (event->attach_state & PERF_ATTACH_GROUP)
2073 event->attach_state |= PERF_ATTACH_GROUP;
2075 if (group_leader == event)
2078 WARN_ON_ONCE(group_leader->ctx != event->ctx);
2080 group_leader->group_caps &= event->event_caps;
2082 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2083 group_leader->nr_siblings++;
2084 group_leader->group_generation++;
2086 perf_event__header_size(group_leader);
2088 for_each_sibling_event(pos, group_leader)
2089 perf_event__header_size(pos);
2093 * Remove an event from the lists for its context.
2094 * Must be called with ctx->mutex and ctx->lock held.
2097 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2099 WARN_ON_ONCE(event->ctx != ctx);
2100 lockdep_assert_held(&ctx->lock);
2103 * We can have double detach due to exit/hot-unplug + close.
2105 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2108 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2111 if (event->attr.inherit_stat)
2114 list_del_rcu(&event->event_entry);
2116 if (event->group_leader == event)
2117 del_event_from_groups(event, ctx);
2120 * If event was in error state, then keep it
2121 * that way, otherwise bogus counts will be
2122 * returned on read(). The only way to get out
2123 * of error state is by explicit re-enabling
2126 if (event->state > PERF_EVENT_STATE_OFF) {
2127 perf_cgroup_event_disable(event, ctx);
2128 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2135 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2137 if (!has_aux(aux_event))
2140 if (!event->pmu->aux_output_match)
2143 return event->pmu->aux_output_match(aux_event);
2146 static void put_event(struct perf_event *event);
2147 static void event_sched_out(struct perf_event *event,
2148 struct perf_cpu_context *cpuctx,
2149 struct perf_event_context *ctx);
2151 static void perf_put_aux_event(struct perf_event *event)
2153 struct perf_event_context *ctx = event->ctx;
2154 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2155 struct perf_event *iter;
2158 * If event uses aux_event tear down the link
2160 if (event->aux_event) {
2161 iter = event->aux_event;
2162 event->aux_event = NULL;
2168 * If the event is an aux_event, tear down all links to
2169 * it from other events.
2171 for_each_sibling_event(iter, event->group_leader) {
2172 if (iter->aux_event != event)
2175 iter->aux_event = NULL;
2179 * If it's ACTIVE, schedule it out and put it into ERROR
2180 * state so that we don't try to schedule it again. Note
2181 * that perf_event_enable() will clear the ERROR status.
2183 event_sched_out(iter, cpuctx, ctx);
2184 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2188 static bool perf_need_aux_event(struct perf_event *event)
2190 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2193 static int perf_get_aux_event(struct perf_event *event,
2194 struct perf_event *group_leader)
2197 * Our group leader must be an aux event if we want to be
2198 * an aux_output. This way, the aux event will precede its
2199 * aux_output events in the group, and therefore will always
2206 * aux_output and aux_sample_size are mutually exclusive.
2208 if (event->attr.aux_output && event->attr.aux_sample_size)
2211 if (event->attr.aux_output &&
2212 !perf_aux_output_match(event, group_leader))
2215 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2218 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2222 * Link aux_outputs to their aux event; this is undone in
2223 * perf_group_detach() by perf_put_aux_event(). When the
2224 * group in torn down, the aux_output events loose their
2225 * link to the aux_event and can't schedule any more.
2227 event->aux_event = group_leader;
2232 static inline struct list_head *get_event_list(struct perf_event *event)
2234 struct perf_event_context *ctx = event->ctx;
2235 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2239 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2240 * cannot exist on their own, schedule them out and move them into the ERROR
2241 * state. Also see _perf_event_enable(), it will not be able to recover
2244 static inline void perf_remove_sibling_event(struct perf_event *event)
2246 struct perf_event_context *ctx = event->ctx;
2247 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2249 event_sched_out(event, cpuctx, ctx);
2250 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2253 static void perf_group_detach(struct perf_event *event)
2255 struct perf_event *leader = event->group_leader;
2256 struct perf_event *sibling, *tmp;
2257 struct perf_event_context *ctx = event->ctx;
2259 lockdep_assert_held(&ctx->lock);
2262 * We can have double detach due to exit/hot-unplug + close.
2264 if (!(event->attach_state & PERF_ATTACH_GROUP))
2267 event->attach_state &= ~PERF_ATTACH_GROUP;
2269 perf_put_aux_event(event);
2272 * If this is a sibling, remove it from its group.
2274 if (leader != event) {
2275 list_del_init(&event->sibling_list);
2276 event->group_leader->nr_siblings--;
2277 event->group_leader->group_generation++;
2282 * If this was a group event with sibling events then
2283 * upgrade the siblings to singleton events by adding them
2284 * to whatever list we are on.
2286 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2288 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2289 perf_remove_sibling_event(sibling);
2291 sibling->group_leader = sibling;
2292 list_del_init(&sibling->sibling_list);
2294 /* Inherit group flags from the previous leader */
2295 sibling->group_caps = event->group_caps;
2297 if (!RB_EMPTY_NODE(&event->group_node)) {
2298 add_event_to_groups(sibling, event->ctx);
2300 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2301 list_add_tail(&sibling->active_list, get_event_list(sibling));
2304 WARN_ON_ONCE(sibling->ctx != event->ctx);
2308 for_each_sibling_event(tmp, leader)
2309 perf_event__header_size(tmp);
2311 perf_event__header_size(leader);
2314 static bool is_orphaned_event(struct perf_event *event)
2316 return event->state == PERF_EVENT_STATE_DEAD;
2319 static inline int __pmu_filter_match(struct perf_event *event)
2321 struct pmu *pmu = event->pmu;
2322 return pmu->filter_match ? pmu->filter_match(event) : 1;
2326 * Check whether we should attempt to schedule an event group based on
2327 * PMU-specific filtering. An event group can consist of HW and SW events,
2328 * potentially with a SW leader, so we must check all the filters, to
2329 * determine whether a group is schedulable:
2331 static inline int pmu_filter_match(struct perf_event *event)
2333 struct perf_event *sibling;
2335 if (!__pmu_filter_match(event))
2338 for_each_sibling_event(sibling, event) {
2339 if (!__pmu_filter_match(sibling))
2347 event_filter_match(struct perf_event *event)
2349 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2350 perf_cgroup_match(event) && pmu_filter_match(event);
2354 event_sched_out(struct perf_event *event,
2355 struct perf_cpu_context *cpuctx,
2356 struct perf_event_context *ctx)
2358 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2360 WARN_ON_ONCE(event->ctx != ctx);
2361 lockdep_assert_held(&ctx->lock);
2363 if (event->state != PERF_EVENT_STATE_ACTIVE)
2367 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2368 * we can schedule events _OUT_ individually through things like
2369 * __perf_remove_from_context().
2371 list_del_init(&event->active_list);
2373 perf_pmu_disable(event->pmu);
2375 event->pmu->del(event, 0);
2378 if (READ_ONCE(event->pending_disable) >= 0) {
2379 WRITE_ONCE(event->pending_disable, -1);
2380 perf_cgroup_event_disable(event, ctx);
2381 state = PERF_EVENT_STATE_OFF;
2383 perf_event_set_state(event, state);
2385 if (!is_software_event(event))
2386 cpuctx->active_oncpu--;
2387 if (!--ctx->nr_active)
2388 perf_event_ctx_deactivate(ctx);
2389 if (event->attr.freq && event->attr.sample_freq)
2391 if (event->attr.exclusive || !cpuctx->active_oncpu)
2392 cpuctx->exclusive = 0;
2394 perf_pmu_enable(event->pmu);
2398 group_sched_out(struct perf_event *group_event,
2399 struct perf_cpu_context *cpuctx,
2400 struct perf_event_context *ctx)
2402 struct perf_event *event;
2404 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2407 perf_pmu_disable(ctx->pmu);
2409 event_sched_out(group_event, cpuctx, ctx);
2412 * Schedule out siblings (if any):
2414 for_each_sibling_event(event, group_event)
2415 event_sched_out(event, cpuctx, ctx);
2417 perf_pmu_enable(ctx->pmu);
2420 #define DETACH_GROUP 0x01UL
2423 * Cross CPU call to remove a performance event
2425 * We disable the event on the hardware level first. After that we
2426 * remove it from the context list.
2429 __perf_remove_from_context(struct perf_event *event,
2430 struct perf_cpu_context *cpuctx,
2431 struct perf_event_context *ctx,
2434 unsigned long flags = (unsigned long)info;
2436 if (ctx->is_active & EVENT_TIME) {
2437 update_context_time(ctx);
2438 update_cgrp_time_from_cpuctx(cpuctx, false);
2441 event_sched_out(event, cpuctx, ctx);
2442 if (flags & DETACH_GROUP)
2443 perf_group_detach(event);
2444 list_del_event(event, ctx);
2446 if (!ctx->nr_events && ctx->is_active) {
2447 if (ctx == &cpuctx->ctx)
2448 update_cgrp_time_from_cpuctx(cpuctx, true);
2451 ctx->rotate_necessary = 0;
2453 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2454 cpuctx->task_ctx = NULL;
2460 * Remove the event from a task's (or a CPU's) list of events.
2462 * If event->ctx is a cloned context, callers must make sure that
2463 * every task struct that event->ctx->task could possibly point to
2464 * remains valid. This is OK when called from perf_release since
2465 * that only calls us on the top-level context, which can't be a clone.
2466 * When called from perf_event_exit_task, it's OK because the
2467 * context has been detached from its task.
2469 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2471 struct perf_event_context *ctx = event->ctx;
2473 lockdep_assert_held(&ctx->mutex);
2475 event_function_call(event, __perf_remove_from_context, (void *)flags);
2478 * The above event_function_call() can NO-OP when it hits
2479 * TASK_TOMBSTONE. In that case we must already have been detached
2480 * from the context (by perf_event_exit_event()) but the grouping
2481 * might still be in-tact.
2483 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2484 if ((flags & DETACH_GROUP) &&
2485 (event->attach_state & PERF_ATTACH_GROUP)) {
2487 * Since in that case we cannot possibly be scheduled, simply
2490 raw_spin_lock_irq(&ctx->lock);
2491 perf_group_detach(event);
2492 raw_spin_unlock_irq(&ctx->lock);
2497 * Cross CPU call to disable a performance event
2499 static void __perf_event_disable(struct perf_event *event,
2500 struct perf_cpu_context *cpuctx,
2501 struct perf_event_context *ctx,
2504 if (event->state < PERF_EVENT_STATE_INACTIVE)
2507 if (ctx->is_active & EVENT_TIME) {
2508 update_context_time(ctx);
2509 update_cgrp_time_from_event(event);
2512 if (event == event->group_leader)
2513 group_sched_out(event, cpuctx, ctx);
2515 event_sched_out(event, cpuctx, ctx);
2517 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2518 perf_cgroup_event_disable(event, ctx);
2524 * If event->ctx is a cloned context, callers must make sure that
2525 * every task struct that event->ctx->task could possibly point to
2526 * remains valid. This condition is satisfied when called through
2527 * perf_event_for_each_child or perf_event_for_each because they
2528 * hold the top-level event's child_mutex, so any descendant that
2529 * goes to exit will block in perf_event_exit_event().
2531 * When called from perf_pending_event it's OK because event->ctx
2532 * is the current context on this CPU and preemption is disabled,
2533 * hence we can't get into perf_event_task_sched_out for this context.
2535 static void _perf_event_disable(struct perf_event *event)
2537 struct perf_event_context *ctx = event->ctx;
2539 raw_spin_lock_irq(&ctx->lock);
2540 if (event->state <= PERF_EVENT_STATE_OFF) {
2541 raw_spin_unlock_irq(&ctx->lock);
2544 raw_spin_unlock_irq(&ctx->lock);
2546 event_function_call(event, __perf_event_disable, NULL);
2549 void perf_event_disable_local(struct perf_event *event)
2551 event_function_local(event, __perf_event_disable, NULL);
2555 * Strictly speaking kernel users cannot create groups and therefore this
2556 * interface does not need the perf_event_ctx_lock() magic.
2558 void perf_event_disable(struct perf_event *event)
2560 struct perf_event_context *ctx;
2562 ctx = perf_event_ctx_lock(event);
2563 _perf_event_disable(event);
2564 perf_event_ctx_unlock(event, ctx);
2566 EXPORT_SYMBOL_GPL(perf_event_disable);
2568 void perf_event_disable_inatomic(struct perf_event *event)
2570 WRITE_ONCE(event->pending_disable, smp_processor_id());
2571 /* can fail, see perf_pending_event_disable() */
2572 irq_work_queue(&event->pending);
2575 #define MAX_INTERRUPTS (~0ULL)
2577 static void perf_log_throttle(struct perf_event *event, int enable);
2578 static void perf_log_itrace_start(struct perf_event *event);
2581 event_sched_in(struct perf_event *event,
2582 struct perf_cpu_context *cpuctx,
2583 struct perf_event_context *ctx)
2587 WARN_ON_ONCE(event->ctx != ctx);
2589 lockdep_assert_held(&ctx->lock);
2591 if (event->state <= PERF_EVENT_STATE_OFF)
2594 WRITE_ONCE(event->oncpu, smp_processor_id());
2596 * Order event::oncpu write to happen before the ACTIVE state is
2597 * visible. This allows perf_event_{stop,read}() to observe the correct
2598 * ->oncpu if it sees ACTIVE.
2601 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2604 * Unthrottle events, since we scheduled we might have missed several
2605 * ticks already, also for a heavily scheduling task there is little
2606 * guarantee it'll get a tick in a timely manner.
2608 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2609 perf_log_throttle(event, 1);
2610 event->hw.interrupts = 0;
2613 perf_pmu_disable(event->pmu);
2615 perf_log_itrace_start(event);
2617 if (event->pmu->add(event, PERF_EF_START)) {
2618 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2624 if (!is_software_event(event))
2625 cpuctx->active_oncpu++;
2626 if (!ctx->nr_active++)
2627 perf_event_ctx_activate(ctx);
2628 if (event->attr.freq && event->attr.sample_freq)
2631 if (event->attr.exclusive)
2632 cpuctx->exclusive = 1;
2635 perf_pmu_enable(event->pmu);
2641 group_sched_in(struct perf_event *group_event,
2642 struct perf_cpu_context *cpuctx,
2643 struct perf_event_context *ctx)
2645 struct perf_event *event, *partial_group = NULL;
2646 struct pmu *pmu = ctx->pmu;
2648 if (group_event->state == PERF_EVENT_STATE_OFF)
2651 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2653 if (event_sched_in(group_event, cpuctx, ctx))
2657 * Schedule in siblings as one group (if any):
2659 for_each_sibling_event(event, group_event) {
2660 if (event_sched_in(event, cpuctx, ctx)) {
2661 partial_group = event;
2666 if (!pmu->commit_txn(pmu))
2671 * Groups can be scheduled in as one unit only, so undo any
2672 * partial group before returning:
2673 * The events up to the failed event are scheduled out normally.
2675 for_each_sibling_event(event, group_event) {
2676 if (event == partial_group)
2679 event_sched_out(event, cpuctx, ctx);
2681 event_sched_out(group_event, cpuctx, ctx);
2684 pmu->cancel_txn(pmu);
2689 * Work out whether we can put this event group on the CPU now.
2691 static int group_can_go_on(struct perf_event *event,
2692 struct perf_cpu_context *cpuctx,
2696 * Groups consisting entirely of software events can always go on.
2698 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2701 * If an exclusive group is already on, no other hardware
2704 if (cpuctx->exclusive)
2707 * If this group is exclusive and there are already
2708 * events on the CPU, it can't go on.
2710 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2713 * Otherwise, try to add it if all previous groups were able
2719 static void add_event_to_ctx(struct perf_event *event,
2720 struct perf_event_context *ctx)
2722 list_add_event(event, ctx);
2723 perf_group_attach(event);
2726 static void ctx_sched_out(struct perf_event_context *ctx,
2727 struct perf_cpu_context *cpuctx,
2728 enum event_type_t event_type);
2730 ctx_sched_in(struct perf_event_context *ctx,
2731 struct perf_cpu_context *cpuctx,
2732 enum event_type_t event_type,
2733 struct task_struct *task);
2735 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2736 struct perf_event_context *ctx,
2737 enum event_type_t event_type)
2739 if (!cpuctx->task_ctx)
2742 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2745 ctx_sched_out(ctx, cpuctx, event_type);
2748 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2749 struct perf_event_context *ctx,
2750 struct task_struct *task)
2752 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2754 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2755 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2757 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2761 * We want to maintain the following priority of scheduling:
2762 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2763 * - task pinned (EVENT_PINNED)
2764 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2765 * - task flexible (EVENT_FLEXIBLE).
2767 * In order to avoid unscheduling and scheduling back in everything every
2768 * time an event is added, only do it for the groups of equal priority and
2771 * This can be called after a batch operation on task events, in which case
2772 * event_type is a bit mask of the types of events involved. For CPU events,
2773 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2775 static void ctx_resched(struct perf_cpu_context *cpuctx,
2776 struct perf_event_context *task_ctx,
2777 enum event_type_t event_type)
2779 enum event_type_t ctx_event_type;
2780 bool cpu_event = !!(event_type & EVENT_CPU);
2783 * If pinned groups are involved, flexible groups also need to be
2786 if (event_type & EVENT_PINNED)
2787 event_type |= EVENT_FLEXIBLE;
2789 ctx_event_type = event_type & EVENT_ALL;
2791 perf_pmu_disable(cpuctx->ctx.pmu);
2793 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2796 * Decide which cpu ctx groups to schedule out based on the types
2797 * of events that caused rescheduling:
2798 * - EVENT_CPU: schedule out corresponding groups;
2799 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2800 * - otherwise, do nothing more.
2803 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2804 else if (ctx_event_type & EVENT_PINNED)
2805 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2807 perf_event_sched_in(cpuctx, task_ctx, current);
2808 perf_pmu_enable(cpuctx->ctx.pmu);
2811 void perf_pmu_resched(struct pmu *pmu)
2813 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2814 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2816 perf_ctx_lock(cpuctx, task_ctx);
2817 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2818 perf_ctx_unlock(cpuctx, task_ctx);
2822 * Cross CPU call to install and enable a performance event
2824 * Very similar to remote_function() + event_function() but cannot assume that
2825 * things like ctx->is_active and cpuctx->task_ctx are set.
2827 static int __perf_install_in_context(void *info)
2829 struct perf_event *event = info;
2830 struct perf_event_context *ctx = event->ctx;
2831 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2832 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2833 bool reprogram = true;
2836 raw_spin_lock(&cpuctx->ctx.lock);
2838 raw_spin_lock(&ctx->lock);
2841 reprogram = (ctx->task == current);
2844 * If the task is running, it must be running on this CPU,
2845 * otherwise we cannot reprogram things.
2847 * If its not running, we don't care, ctx->lock will
2848 * serialize against it becoming runnable.
2850 if (task_curr(ctx->task) && !reprogram) {
2855 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2856 } else if (task_ctx) {
2857 raw_spin_lock(&task_ctx->lock);
2860 #ifdef CONFIG_CGROUP_PERF
2861 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2863 * If the current cgroup doesn't match the event's
2864 * cgroup, we should not try to schedule it.
2866 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2867 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2868 event->cgrp->css.cgroup);
2873 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2874 add_event_to_ctx(event, ctx);
2875 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2877 add_event_to_ctx(event, ctx);
2881 perf_ctx_unlock(cpuctx, task_ctx);
2886 static bool exclusive_event_installable(struct perf_event *event,
2887 struct perf_event_context *ctx);
2890 * Attach a performance event to a context.
2892 * Very similar to event_function_call, see comment there.
2895 perf_install_in_context(struct perf_event_context *ctx,
2896 struct perf_event *event,
2899 struct task_struct *task = READ_ONCE(ctx->task);
2901 lockdep_assert_held(&ctx->mutex);
2903 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2905 if (event->cpu != -1)
2909 * Ensures that if we can observe event->ctx, both the event and ctx
2910 * will be 'complete'. See perf_iterate_sb_cpu().
2912 smp_store_release(&event->ctx, ctx);
2915 * perf_event_attr::disabled events will not run and can be initialized
2916 * without IPI. Except when this is the first event for the context, in
2917 * that case we need the magic of the IPI to set ctx->is_active.
2919 * The IOC_ENABLE that is sure to follow the creation of a disabled
2920 * event will issue the IPI and reprogram the hardware.
2922 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2923 raw_spin_lock_irq(&ctx->lock);
2924 if (ctx->task == TASK_TOMBSTONE) {
2925 raw_spin_unlock_irq(&ctx->lock);
2928 add_event_to_ctx(event, ctx);
2929 raw_spin_unlock_irq(&ctx->lock);
2934 cpu_function_call(cpu, __perf_install_in_context, event);
2939 * Should not happen, we validate the ctx is still alive before calling.
2941 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2945 * Installing events is tricky because we cannot rely on ctx->is_active
2946 * to be set in case this is the nr_events 0 -> 1 transition.
2948 * Instead we use task_curr(), which tells us if the task is running.
2949 * However, since we use task_curr() outside of rq::lock, we can race
2950 * against the actual state. This means the result can be wrong.
2952 * If we get a false positive, we retry, this is harmless.
2954 * If we get a false negative, things are complicated. If we are after
2955 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2956 * value must be correct. If we're before, it doesn't matter since
2957 * perf_event_context_sched_in() will program the counter.
2959 * However, this hinges on the remote context switch having observed
2960 * our task->perf_event_ctxp[] store, such that it will in fact take
2961 * ctx::lock in perf_event_context_sched_in().
2963 * We do this by task_function_call(), if the IPI fails to hit the task
2964 * we know any future context switch of task must see the
2965 * perf_event_ctpx[] store.
2969 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2970 * task_cpu() load, such that if the IPI then does not find the task
2971 * running, a future context switch of that task must observe the
2976 if (!task_function_call(task, __perf_install_in_context, event))
2979 raw_spin_lock_irq(&ctx->lock);
2981 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2983 * Cannot happen because we already checked above (which also
2984 * cannot happen), and we hold ctx->mutex, which serializes us
2985 * against perf_event_exit_task_context().
2987 raw_spin_unlock_irq(&ctx->lock);
2991 * If the task is not running, ctx->lock will avoid it becoming so,
2992 * thus we can safely install the event.
2994 if (task_curr(task)) {
2995 raw_spin_unlock_irq(&ctx->lock);
2998 add_event_to_ctx(event, ctx);
2999 raw_spin_unlock_irq(&ctx->lock);
3003 * Cross CPU call to enable a performance event
3005 static void __perf_event_enable(struct perf_event *event,
3006 struct perf_cpu_context *cpuctx,
3007 struct perf_event_context *ctx,
3010 struct perf_event *leader = event->group_leader;
3011 struct perf_event_context *task_ctx;
3013 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3014 event->state <= PERF_EVENT_STATE_ERROR)
3018 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3020 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3021 perf_cgroup_event_enable(event, ctx);
3023 if (!ctx->is_active)
3026 if (!event_filter_match(event)) {
3027 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3032 * If the event is in a group and isn't the group leader,
3033 * then don't put it on unless the group is on.
3035 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
3036 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3040 task_ctx = cpuctx->task_ctx;
3042 WARN_ON_ONCE(task_ctx != ctx);
3044 ctx_resched(cpuctx, task_ctx, get_event_type(event));
3050 * If event->ctx is a cloned context, callers must make sure that
3051 * every task struct that event->ctx->task could possibly point to
3052 * remains valid. This condition is satisfied when called through
3053 * perf_event_for_each_child or perf_event_for_each as described
3054 * for perf_event_disable.
3056 static void _perf_event_enable(struct perf_event *event)
3058 struct perf_event_context *ctx = event->ctx;
3060 raw_spin_lock_irq(&ctx->lock);
3061 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3062 event->state < PERF_EVENT_STATE_ERROR) {
3064 raw_spin_unlock_irq(&ctx->lock);
3069 * If the event is in error state, clear that first.
3071 * That way, if we see the event in error state below, we know that it
3072 * has gone back into error state, as distinct from the task having
3073 * been scheduled away before the cross-call arrived.
3075 if (event->state == PERF_EVENT_STATE_ERROR) {
3077 * Detached SIBLING events cannot leave ERROR state.
3079 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3080 event->group_leader == event)
3083 event->state = PERF_EVENT_STATE_OFF;
3085 raw_spin_unlock_irq(&ctx->lock);
3087 event_function_call(event, __perf_event_enable, NULL);
3091 * See perf_event_disable();
3093 void perf_event_enable(struct perf_event *event)
3095 struct perf_event_context *ctx;
3097 ctx = perf_event_ctx_lock(event);
3098 _perf_event_enable(event);
3099 perf_event_ctx_unlock(event, ctx);
3101 EXPORT_SYMBOL_GPL(perf_event_enable);
3103 struct stop_event_data {
3104 struct perf_event *event;
3105 unsigned int restart;
3108 static int __perf_event_stop(void *info)
3110 struct stop_event_data *sd = info;
3111 struct perf_event *event = sd->event;
3113 /* if it's already INACTIVE, do nothing */
3114 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3117 /* matches smp_wmb() in event_sched_in() */
3121 * There is a window with interrupts enabled before we get here,
3122 * so we need to check again lest we try to stop another CPU's event.
3124 if (READ_ONCE(event->oncpu) != smp_processor_id())
3127 event->pmu->stop(event, PERF_EF_UPDATE);
3130 * May race with the actual stop (through perf_pmu_output_stop()),
3131 * but it is only used for events with AUX ring buffer, and such
3132 * events will refuse to restart because of rb::aux_mmap_count==0,
3133 * see comments in perf_aux_output_begin().
3135 * Since this is happening on an event-local CPU, no trace is lost
3139 event->pmu->start(event, 0);
3144 static int perf_event_stop(struct perf_event *event, int restart)
3146 struct stop_event_data sd = {
3153 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3156 /* matches smp_wmb() in event_sched_in() */
3160 * We only want to restart ACTIVE events, so if the event goes
3161 * inactive here (event->oncpu==-1), there's nothing more to do;
3162 * fall through with ret==-ENXIO.
3164 ret = cpu_function_call(READ_ONCE(event->oncpu),
3165 __perf_event_stop, &sd);
3166 } while (ret == -EAGAIN);
3172 * In order to contain the amount of racy and tricky in the address filter
3173 * configuration management, it is a two part process:
3175 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3176 * we update the addresses of corresponding vmas in
3177 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3178 * (p2) when an event is scheduled in (pmu::add), it calls
3179 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3180 * if the generation has changed since the previous call.
3182 * If (p1) happens while the event is active, we restart it to force (p2).
3184 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3185 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3187 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3188 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3190 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3193 void perf_event_addr_filters_sync(struct perf_event *event)
3195 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3197 if (!has_addr_filter(event))
3200 raw_spin_lock(&ifh->lock);
3201 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3202 event->pmu->addr_filters_sync(event);
3203 event->hw.addr_filters_gen = event->addr_filters_gen;
3205 raw_spin_unlock(&ifh->lock);
3207 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3209 static int _perf_event_refresh(struct perf_event *event, int refresh)
3212 * not supported on inherited events
3214 if (event->attr.inherit || !is_sampling_event(event))
3217 atomic_add(refresh, &event->event_limit);
3218 _perf_event_enable(event);
3224 * See perf_event_disable()
3226 int perf_event_refresh(struct perf_event *event, int refresh)
3228 struct perf_event_context *ctx;
3231 ctx = perf_event_ctx_lock(event);
3232 ret = _perf_event_refresh(event, refresh);
3233 perf_event_ctx_unlock(event, ctx);
3237 EXPORT_SYMBOL_GPL(perf_event_refresh);
3239 static int perf_event_modify_breakpoint(struct perf_event *bp,
3240 struct perf_event_attr *attr)
3244 _perf_event_disable(bp);
3246 err = modify_user_hw_breakpoint_check(bp, attr, true);
3248 if (!bp->attr.disabled)
3249 _perf_event_enable(bp);
3254 static int perf_event_modify_attr(struct perf_event *event,
3255 struct perf_event_attr *attr)
3257 if (event->attr.type != attr->type)
3260 switch (event->attr.type) {
3261 case PERF_TYPE_BREAKPOINT:
3262 return perf_event_modify_breakpoint(event, attr);
3264 /* Place holder for future additions. */
3269 static void ctx_sched_out(struct perf_event_context *ctx,
3270 struct perf_cpu_context *cpuctx,
3271 enum event_type_t event_type)
3273 struct perf_event *event, *tmp;
3274 int is_active = ctx->is_active;
3276 lockdep_assert_held(&ctx->lock);
3278 if (likely(!ctx->nr_events)) {
3280 * See __perf_remove_from_context().
3282 WARN_ON_ONCE(ctx->is_active);
3284 WARN_ON_ONCE(cpuctx->task_ctx);
3289 * Always update time if it was set; not only when it changes.
3290 * Otherwise we can 'forget' to update time for any but the last
3291 * context we sched out. For example:
3293 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3294 * ctx_sched_out(.event_type = EVENT_PINNED)
3296 * would only update time for the pinned events.
3298 if (is_active & EVENT_TIME) {
3299 /* update (and stop) ctx time */
3300 update_context_time(ctx);
3301 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3303 * CPU-release for the below ->is_active store,
3304 * see __load_acquire() in perf_event_time_now()
3309 ctx->is_active &= ~event_type;
3310 if (!(ctx->is_active & EVENT_ALL))
3314 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3315 if (!ctx->is_active)
3316 cpuctx->task_ctx = NULL;
3319 is_active ^= ctx->is_active; /* changed bits */
3321 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3324 perf_pmu_disable(ctx->pmu);
3325 if (is_active & EVENT_PINNED) {
3326 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3327 group_sched_out(event, cpuctx, ctx);
3330 if (is_active & EVENT_FLEXIBLE) {
3331 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3332 group_sched_out(event, cpuctx, ctx);
3335 * Since we cleared EVENT_FLEXIBLE, also clear
3336 * rotate_necessary, is will be reset by
3337 * ctx_flexible_sched_in() when needed.
3339 ctx->rotate_necessary = 0;
3341 perf_pmu_enable(ctx->pmu);
3345 * Test whether two contexts are equivalent, i.e. whether they have both been
3346 * cloned from the same version of the same context.
3348 * Equivalence is measured using a generation number in the context that is
3349 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3350 * and list_del_event().
3352 static int context_equiv(struct perf_event_context *ctx1,
3353 struct perf_event_context *ctx2)
3355 lockdep_assert_held(&ctx1->lock);
3356 lockdep_assert_held(&ctx2->lock);
3358 /* Pinning disables the swap optimization */
3359 if (ctx1->pin_count || ctx2->pin_count)
3362 /* If ctx1 is the parent of ctx2 */
3363 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3366 /* If ctx2 is the parent of ctx1 */
3367 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3371 * If ctx1 and ctx2 have the same parent; we flatten the parent
3372 * hierarchy, see perf_event_init_context().
3374 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3375 ctx1->parent_gen == ctx2->parent_gen)
3382 static void __perf_event_sync_stat(struct perf_event *event,
3383 struct perf_event *next_event)
3387 if (!event->attr.inherit_stat)
3391 * Update the event value, we cannot use perf_event_read()
3392 * because we're in the middle of a context switch and have IRQs
3393 * disabled, which upsets smp_call_function_single(), however
3394 * we know the event must be on the current CPU, therefore we
3395 * don't need to use it.
3397 if (event->state == PERF_EVENT_STATE_ACTIVE)
3398 event->pmu->read(event);
3400 perf_event_update_time(event);
3403 * In order to keep per-task stats reliable we need to flip the event
3404 * values when we flip the contexts.
3406 value = local64_read(&next_event->count);
3407 value = local64_xchg(&event->count, value);
3408 local64_set(&next_event->count, value);
3410 swap(event->total_time_enabled, next_event->total_time_enabled);
3411 swap(event->total_time_running, next_event->total_time_running);
3414 * Since we swizzled the values, update the user visible data too.
3416 perf_event_update_userpage(event);
3417 perf_event_update_userpage(next_event);
3420 static void perf_event_sync_stat(struct perf_event_context *ctx,
3421 struct perf_event_context *next_ctx)
3423 struct perf_event *event, *next_event;
3428 update_context_time(ctx);
3430 event = list_first_entry(&ctx->event_list,
3431 struct perf_event, event_entry);
3433 next_event = list_first_entry(&next_ctx->event_list,
3434 struct perf_event, event_entry);
3436 while (&event->event_entry != &ctx->event_list &&
3437 &next_event->event_entry != &next_ctx->event_list) {
3439 __perf_event_sync_stat(event, next_event);
3441 event = list_next_entry(event, event_entry);
3442 next_event = list_next_entry(next_event, event_entry);
3446 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3447 struct task_struct *next)
3449 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3450 struct perf_event_context *next_ctx;
3451 struct perf_event_context *parent, *next_parent;
3452 struct perf_cpu_context *cpuctx;
3460 cpuctx = __get_cpu_context(ctx);
3461 if (!cpuctx->task_ctx)
3465 next_ctx = next->perf_event_ctxp[ctxn];
3469 parent = rcu_dereference(ctx->parent_ctx);
3470 next_parent = rcu_dereference(next_ctx->parent_ctx);
3472 /* If neither context have a parent context; they cannot be clones. */
3473 if (!parent && !next_parent)
3476 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3478 * Looks like the two contexts are clones, so we might be
3479 * able to optimize the context switch. We lock both
3480 * contexts and check that they are clones under the
3481 * lock (including re-checking that neither has been
3482 * uncloned in the meantime). It doesn't matter which
3483 * order we take the locks because no other cpu could
3484 * be trying to lock both of these tasks.
3486 raw_spin_lock(&ctx->lock);
3487 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3488 if (context_equiv(ctx, next_ctx)) {
3490 WRITE_ONCE(ctx->task, next);
3491 WRITE_ONCE(next_ctx->task, task);
3493 perf_pmu_disable(pmu);
3495 if (cpuctx->sched_cb_usage && pmu->sched_task)
3496 pmu->sched_task(ctx, false);
3499 * PMU specific parts of task perf context can require
3500 * additional synchronization. As an example of such
3501 * synchronization see implementation details of Intel
3502 * LBR call stack data profiling;
3504 if (pmu->swap_task_ctx)
3505 pmu->swap_task_ctx(ctx, next_ctx);
3507 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3509 perf_pmu_enable(pmu);
3512 * RCU_INIT_POINTER here is safe because we've not
3513 * modified the ctx and the above modification of
3514 * ctx->task and ctx->task_ctx_data are immaterial
3515 * since those values are always verified under
3516 * ctx->lock which we're now holding.
3518 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3519 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3523 perf_event_sync_stat(ctx, next_ctx);
3525 raw_spin_unlock(&next_ctx->lock);
3526 raw_spin_unlock(&ctx->lock);
3532 raw_spin_lock(&ctx->lock);
3533 perf_pmu_disable(pmu);
3535 if (cpuctx->sched_cb_usage && pmu->sched_task)
3536 pmu->sched_task(ctx, false);
3537 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3539 perf_pmu_enable(pmu);
3540 raw_spin_unlock(&ctx->lock);
3544 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3546 void perf_sched_cb_dec(struct pmu *pmu)
3548 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3550 this_cpu_dec(perf_sched_cb_usages);
3552 if (!--cpuctx->sched_cb_usage)
3553 list_del(&cpuctx->sched_cb_entry);
3557 void perf_sched_cb_inc(struct pmu *pmu)
3559 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3561 if (!cpuctx->sched_cb_usage++)
3562 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3564 this_cpu_inc(perf_sched_cb_usages);
3568 * This function provides the context switch callback to the lower code
3569 * layer. It is invoked ONLY when the context switch callback is enabled.
3571 * This callback is relevant even to per-cpu events; for example multi event
3572 * PEBS requires this to provide PID/TID information. This requires we flush
3573 * all queued PEBS records before we context switch to a new task.
3575 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3579 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3581 if (WARN_ON_ONCE(!pmu->sched_task))
3584 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3585 perf_pmu_disable(pmu);
3587 pmu->sched_task(cpuctx->task_ctx, sched_in);
3589 perf_pmu_enable(pmu);
3590 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3593 static void perf_pmu_sched_task(struct task_struct *prev,
3594 struct task_struct *next,
3597 struct perf_cpu_context *cpuctx;
3602 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3603 /* will be handled in perf_event_context_sched_in/out */
3604 if (cpuctx->task_ctx)
3607 __perf_pmu_sched_task(cpuctx, sched_in);
3611 static void perf_event_switch(struct task_struct *task,
3612 struct task_struct *next_prev, bool sched_in);
3614 #define for_each_task_context_nr(ctxn) \
3615 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3618 * Called from scheduler to remove the events of the current task,
3619 * with interrupts disabled.
3621 * We stop each event and update the event value in event->count.
3623 * This does not protect us against NMI, but disable()
3624 * sets the disabled bit in the control field of event _before_
3625 * accessing the event control register. If a NMI hits, then it will
3626 * not restart the event.
3628 void __perf_event_task_sched_out(struct task_struct *task,
3629 struct task_struct *next)
3633 if (__this_cpu_read(perf_sched_cb_usages))
3634 perf_pmu_sched_task(task, next, false);
3636 if (atomic_read(&nr_switch_events))
3637 perf_event_switch(task, next, false);
3639 for_each_task_context_nr(ctxn)
3640 perf_event_context_sched_out(task, ctxn, next);
3643 * if cgroup events exist on this CPU, then we need
3644 * to check if we have to switch out PMU state.
3645 * cgroup event are system-wide mode only
3647 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3648 perf_cgroup_sched_out(task, next);
3652 * Called with IRQs disabled
3654 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3655 enum event_type_t event_type)
3657 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3660 static bool perf_less_group_idx(const void *l, const void *r)
3662 const struct perf_event *le = *(const struct perf_event **)l;
3663 const struct perf_event *re = *(const struct perf_event **)r;
3665 return le->group_index < re->group_index;
3668 static void swap_ptr(void *l, void *r)
3670 void **lp = l, **rp = r;
3675 static const struct min_heap_callbacks perf_min_heap = {
3676 .elem_size = sizeof(struct perf_event *),
3677 .less = perf_less_group_idx,
3681 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3683 struct perf_event **itrs = heap->data;
3686 itrs[heap->nr] = event;
3691 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3692 struct perf_event_groups *groups, int cpu,
3693 int (*func)(struct perf_event *, void *),
3696 #ifdef CONFIG_CGROUP_PERF
3697 struct cgroup_subsys_state *css = NULL;
3699 /* Space for per CPU and/or any CPU event iterators. */
3700 struct perf_event *itrs[2];
3701 struct min_heap event_heap;
3702 struct perf_event **evt;
3706 event_heap = (struct min_heap){
3707 .data = cpuctx->heap,
3709 .size = cpuctx->heap_size,
3712 lockdep_assert_held(&cpuctx->ctx.lock);
3714 #ifdef CONFIG_CGROUP_PERF
3716 css = &cpuctx->cgrp->css;
3719 event_heap = (struct min_heap){
3722 .size = ARRAY_SIZE(itrs),
3724 /* Events not within a CPU context may be on any CPU. */
3725 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3727 evt = event_heap.data;
3729 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3731 #ifdef CONFIG_CGROUP_PERF
3732 for (; css; css = css->parent)
3733 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3736 min_heapify_all(&event_heap, &perf_min_heap);
3738 while (event_heap.nr) {
3739 ret = func(*evt, data);
3743 *evt = perf_event_groups_next(*evt);
3745 min_heapify(&event_heap, 0, &perf_min_heap);
3747 min_heap_pop(&event_heap, &perf_min_heap);
3754 * Because the userpage is strictly per-event (there is no concept of context,
3755 * so there cannot be a context indirection), every userpage must be updated
3756 * when context time starts :-(
3758 * IOW, we must not miss EVENT_TIME edges.
3760 static inline bool event_update_userpage(struct perf_event *event)
3762 if (likely(!atomic_read(&event->mmap_count)))
3765 perf_event_update_time(event);
3766 perf_event_update_userpage(event);
3771 static inline void group_update_userpage(struct perf_event *group_event)
3773 struct perf_event *event;
3775 if (!event_update_userpage(group_event))
3778 for_each_sibling_event(event, group_event)
3779 event_update_userpage(event);
3782 static int merge_sched_in(struct perf_event *event, void *data)
3784 struct perf_event_context *ctx = event->ctx;
3785 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3786 int *can_add_hw = data;
3788 if (event->state <= PERF_EVENT_STATE_OFF)
3791 if (!event_filter_match(event))
3794 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3795 if (!group_sched_in(event, cpuctx, ctx))
3796 list_add_tail(&event->active_list, get_event_list(event));
3799 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3801 if (event->attr.pinned) {
3802 perf_cgroup_event_disable(event, ctx);
3803 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3805 ctx->rotate_necessary = 1;
3806 perf_mux_hrtimer_restart(cpuctx);
3807 group_update_userpage(event);
3815 ctx_pinned_sched_in(struct perf_event_context *ctx,
3816 struct perf_cpu_context *cpuctx)
3820 if (ctx != &cpuctx->ctx)
3823 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3825 merge_sched_in, &can_add_hw);
3829 ctx_flexible_sched_in(struct perf_event_context *ctx,
3830 struct perf_cpu_context *cpuctx)
3834 if (ctx != &cpuctx->ctx)
3837 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3839 merge_sched_in, &can_add_hw);
3843 ctx_sched_in(struct perf_event_context *ctx,
3844 struct perf_cpu_context *cpuctx,
3845 enum event_type_t event_type,
3846 struct task_struct *task)
3848 int is_active = ctx->is_active;
3850 lockdep_assert_held(&ctx->lock);
3852 if (likely(!ctx->nr_events))
3855 if (!(is_active & EVENT_TIME)) {
3856 /* start ctx time */
3857 __update_context_time(ctx, false);
3858 perf_cgroup_set_timestamp(task, ctx);
3860 * CPU-release for the below ->is_active store,
3861 * see __load_acquire() in perf_event_time_now()
3866 ctx->is_active |= (event_type | EVENT_TIME);
3869 cpuctx->task_ctx = ctx;
3871 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3874 is_active ^= ctx->is_active; /* changed bits */
3877 * First go through the list and put on any pinned groups
3878 * in order to give them the best chance of going on.
3880 if (is_active & EVENT_PINNED)
3881 ctx_pinned_sched_in(ctx, cpuctx);
3883 /* Then walk through the lower prio flexible groups */
3884 if (is_active & EVENT_FLEXIBLE)
3885 ctx_flexible_sched_in(ctx, cpuctx);
3888 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3889 enum event_type_t event_type,
3890 struct task_struct *task)
3892 struct perf_event_context *ctx = &cpuctx->ctx;
3894 ctx_sched_in(ctx, cpuctx, event_type, task);
3897 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3898 struct task_struct *task)
3900 struct perf_cpu_context *cpuctx;
3901 struct pmu *pmu = ctx->pmu;
3903 cpuctx = __get_cpu_context(ctx);
3904 if (cpuctx->task_ctx == ctx) {
3905 if (cpuctx->sched_cb_usage)
3906 __perf_pmu_sched_task(cpuctx, true);
3910 perf_ctx_lock(cpuctx, ctx);
3912 * We must check ctx->nr_events while holding ctx->lock, such
3913 * that we serialize against perf_install_in_context().
3915 if (!ctx->nr_events)
3918 perf_pmu_disable(pmu);
3920 * We want to keep the following priority order:
3921 * cpu pinned (that don't need to move), task pinned,
3922 * cpu flexible, task flexible.
3924 * However, if task's ctx is not carrying any pinned
3925 * events, no need to flip the cpuctx's events around.
3927 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3928 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3929 perf_event_sched_in(cpuctx, ctx, task);
3931 if (cpuctx->sched_cb_usage && pmu->sched_task)
3932 pmu->sched_task(cpuctx->task_ctx, true);
3934 perf_pmu_enable(pmu);
3937 perf_ctx_unlock(cpuctx, ctx);
3941 * Called from scheduler to add the events of the current task
3942 * with interrupts disabled.
3944 * We restore the event value and then enable it.
3946 * This does not protect us against NMI, but enable()
3947 * sets the enabled bit in the control field of event _before_
3948 * accessing the event control register. If a NMI hits, then it will
3949 * keep the event running.
3951 void __perf_event_task_sched_in(struct task_struct *prev,
3952 struct task_struct *task)
3954 struct perf_event_context *ctx;
3958 * If cgroup events exist on this CPU, then we need to check if we have
3959 * to switch in PMU state; cgroup event are system-wide mode only.
3961 * Since cgroup events are CPU events, we must schedule these in before
3962 * we schedule in the task events.
3964 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3965 perf_cgroup_sched_in(prev, task);
3967 for_each_task_context_nr(ctxn) {
3968 ctx = task->perf_event_ctxp[ctxn];
3972 perf_event_context_sched_in(ctx, task);
3975 if (atomic_read(&nr_switch_events))
3976 perf_event_switch(task, prev, true);
3978 if (__this_cpu_read(perf_sched_cb_usages))
3979 perf_pmu_sched_task(prev, task, true);
3982 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3984 u64 frequency = event->attr.sample_freq;
3985 u64 sec = NSEC_PER_SEC;
3986 u64 divisor, dividend;
3988 int count_fls, nsec_fls, frequency_fls, sec_fls;
3990 count_fls = fls64(count);
3991 nsec_fls = fls64(nsec);
3992 frequency_fls = fls64(frequency);
3996 * We got @count in @nsec, with a target of sample_freq HZ
3997 * the target period becomes:
4000 * period = -------------------
4001 * @nsec * sample_freq
4006 * Reduce accuracy by one bit such that @a and @b converge
4007 * to a similar magnitude.
4009 #define REDUCE_FLS(a, b) \
4011 if (a##_fls > b##_fls) { \
4021 * Reduce accuracy until either term fits in a u64, then proceed with
4022 * the other, so that finally we can do a u64/u64 division.
4024 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4025 REDUCE_FLS(nsec, frequency);
4026 REDUCE_FLS(sec, count);
4029 if (count_fls + sec_fls > 64) {
4030 divisor = nsec * frequency;
4032 while (count_fls + sec_fls > 64) {
4033 REDUCE_FLS(count, sec);
4037 dividend = count * sec;
4039 dividend = count * sec;
4041 while (nsec_fls + frequency_fls > 64) {
4042 REDUCE_FLS(nsec, frequency);
4046 divisor = nsec * frequency;
4052 return div64_u64(dividend, divisor);
4055 static DEFINE_PER_CPU(int, perf_throttled_count);
4056 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4058 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4060 struct hw_perf_event *hwc = &event->hw;
4061 s64 period, sample_period;
4064 period = perf_calculate_period(event, nsec, count);
4066 delta = (s64)(period - hwc->sample_period);
4067 delta = (delta + 7) / 8; /* low pass filter */
4069 sample_period = hwc->sample_period + delta;
4074 hwc->sample_period = sample_period;
4076 if (local64_read(&hwc->period_left) > 8*sample_period) {
4078 event->pmu->stop(event, PERF_EF_UPDATE);
4080 local64_set(&hwc->period_left, 0);
4083 event->pmu->start(event, PERF_EF_RELOAD);
4088 * combine freq adjustment with unthrottling to avoid two passes over the
4089 * events. At the same time, make sure, having freq events does not change
4090 * the rate of unthrottling as that would introduce bias.
4092 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
4095 struct perf_event *event;
4096 struct hw_perf_event *hwc;
4097 u64 now, period = TICK_NSEC;
4101 * only need to iterate over all events iff:
4102 * - context have events in frequency mode (needs freq adjust)
4103 * - there are events to unthrottle on this cpu
4105 if (!(ctx->nr_freq || needs_unthr))
4108 raw_spin_lock(&ctx->lock);
4109 perf_pmu_disable(ctx->pmu);
4111 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4112 if (event->state != PERF_EVENT_STATE_ACTIVE)
4115 if (!event_filter_match(event))
4118 perf_pmu_disable(event->pmu);
4122 if (hwc->interrupts == MAX_INTERRUPTS) {
4123 hwc->interrupts = 0;
4124 perf_log_throttle(event, 1);
4125 event->pmu->start(event, 0);
4128 if (!event->attr.freq || !event->attr.sample_freq)
4132 * stop the event and update event->count
4134 event->pmu->stop(event, PERF_EF_UPDATE);
4136 now = local64_read(&event->count);
4137 delta = now - hwc->freq_count_stamp;
4138 hwc->freq_count_stamp = now;
4142 * reload only if value has changed
4143 * we have stopped the event so tell that
4144 * to perf_adjust_period() to avoid stopping it
4148 perf_adjust_period(event, period, delta, false);
4150 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4152 perf_pmu_enable(event->pmu);
4155 perf_pmu_enable(ctx->pmu);
4156 raw_spin_unlock(&ctx->lock);
4160 * Move @event to the tail of the @ctx's elegible events.
4162 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4165 * Rotate the first entry last of non-pinned groups. Rotation might be
4166 * disabled by the inheritance code.
4168 if (ctx->rotate_disable)
4171 perf_event_groups_delete(&ctx->flexible_groups, event);
4172 perf_event_groups_insert(&ctx->flexible_groups, event);
4175 /* pick an event from the flexible_groups to rotate */
4176 static inline struct perf_event *
4177 ctx_event_to_rotate(struct perf_event_context *ctx)
4179 struct perf_event *event;
4181 /* pick the first active flexible event */
4182 event = list_first_entry_or_null(&ctx->flexible_active,
4183 struct perf_event, active_list);
4185 /* if no active flexible event, pick the first event */
4187 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4188 typeof(*event), group_node);
4192 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4193 * finds there are unschedulable events, it will set it again.
4195 ctx->rotate_necessary = 0;
4200 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4202 struct perf_event *cpu_event = NULL, *task_event = NULL;
4203 struct perf_event_context *task_ctx = NULL;
4204 int cpu_rotate, task_rotate;
4207 * Since we run this from IRQ context, nobody can install new
4208 * events, thus the event count values are stable.
4211 cpu_rotate = cpuctx->ctx.rotate_necessary;
4212 task_ctx = cpuctx->task_ctx;
4213 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4215 if (!(cpu_rotate || task_rotate))
4218 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4219 perf_pmu_disable(cpuctx->ctx.pmu);
4222 task_event = ctx_event_to_rotate(task_ctx);
4224 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4227 * As per the order given at ctx_resched() first 'pop' task flexible
4228 * and then, if needed CPU flexible.
4230 if (task_event || (task_ctx && cpu_event))
4231 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4233 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4236 rotate_ctx(task_ctx, task_event);
4238 rotate_ctx(&cpuctx->ctx, cpu_event);
4240 perf_event_sched_in(cpuctx, task_ctx, current);
4242 perf_pmu_enable(cpuctx->ctx.pmu);
4243 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4248 void perf_event_task_tick(void)
4250 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4251 struct perf_event_context *ctx, *tmp;
4254 lockdep_assert_irqs_disabled();
4256 __this_cpu_inc(perf_throttled_seq);
4257 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4258 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4260 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4261 perf_adjust_freq_unthr_context(ctx, throttled);
4264 static int event_enable_on_exec(struct perf_event *event,
4265 struct perf_event_context *ctx)
4267 if (!event->attr.enable_on_exec)
4270 event->attr.enable_on_exec = 0;
4271 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4274 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4280 * Enable all of a task's events that have been marked enable-on-exec.
4281 * This expects task == current.
4283 static void perf_event_enable_on_exec(int ctxn)
4285 struct perf_event_context *ctx, *clone_ctx = NULL;
4286 enum event_type_t event_type = 0;
4287 struct perf_cpu_context *cpuctx;
4288 struct perf_event *event;
4289 unsigned long flags;
4292 local_irq_save(flags);
4293 ctx = current->perf_event_ctxp[ctxn];
4294 if (!ctx || !ctx->nr_events)
4297 cpuctx = __get_cpu_context(ctx);
4298 perf_ctx_lock(cpuctx, ctx);
4299 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4300 list_for_each_entry(event, &ctx->event_list, event_entry) {
4301 enabled |= event_enable_on_exec(event, ctx);
4302 event_type |= get_event_type(event);
4306 * Unclone and reschedule this context if we enabled any event.
4309 clone_ctx = unclone_ctx(ctx);
4310 ctx_resched(cpuctx, ctx, event_type);
4312 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4314 perf_ctx_unlock(cpuctx, ctx);
4317 local_irq_restore(flags);
4323 struct perf_read_data {
4324 struct perf_event *event;
4329 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4331 u16 local_pkg, event_pkg;
4333 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4334 int local_cpu = smp_processor_id();
4336 event_pkg = topology_physical_package_id(event_cpu);
4337 local_pkg = topology_physical_package_id(local_cpu);
4339 if (event_pkg == local_pkg)
4347 * Cross CPU call to read the hardware event
4349 static void __perf_event_read(void *info)
4351 struct perf_read_data *data = info;
4352 struct perf_event *sub, *event = data->event;
4353 struct perf_event_context *ctx = event->ctx;
4354 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4355 struct pmu *pmu = event->pmu;
4358 * If this is a task context, we need to check whether it is
4359 * the current task context of this cpu. If not it has been
4360 * scheduled out before the smp call arrived. In that case
4361 * event->count would have been updated to a recent sample
4362 * when the event was scheduled out.
4364 if (ctx->task && cpuctx->task_ctx != ctx)
4367 raw_spin_lock(&ctx->lock);
4368 if (ctx->is_active & EVENT_TIME) {
4369 update_context_time(ctx);
4370 update_cgrp_time_from_event(event);
4373 perf_event_update_time(event);
4375 perf_event_update_sibling_time(event);
4377 if (event->state != PERF_EVENT_STATE_ACTIVE)
4386 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4390 for_each_sibling_event(sub, event) {
4391 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4393 * Use sibling's PMU rather than @event's since
4394 * sibling could be on different (eg: software) PMU.
4396 sub->pmu->read(sub);
4400 data->ret = pmu->commit_txn(pmu);
4403 raw_spin_unlock(&ctx->lock);
4406 static inline u64 perf_event_count(struct perf_event *event)
4408 return local64_read(&event->count) + atomic64_read(&event->child_count);
4411 static void calc_timer_values(struct perf_event *event,
4418 *now = perf_clock();
4419 ctx_time = perf_event_time_now(event, *now);
4420 __perf_update_times(event, ctx_time, enabled, running);
4424 * NMI-safe method to read a local event, that is an event that
4426 * - either for the current task, or for this CPU
4427 * - does not have inherit set, for inherited task events
4428 * will not be local and we cannot read them atomically
4429 * - must not have a pmu::count method
4431 int perf_event_read_local(struct perf_event *event, u64 *value,
4432 u64 *enabled, u64 *running)
4434 unsigned long flags;
4438 * Disabling interrupts avoids all counter scheduling (context
4439 * switches, timer based rotation and IPIs).
4441 local_irq_save(flags);
4444 * It must not be an event with inherit set, we cannot read
4445 * all child counters from atomic context.
4447 if (event->attr.inherit) {
4452 /* If this is a per-task event, it must be for current */
4453 if ((event->attach_state & PERF_ATTACH_TASK) &&
4454 event->hw.target != current) {
4459 /* If this is a per-CPU event, it must be for this CPU */
4460 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4461 event->cpu != smp_processor_id()) {
4466 /* If this is a pinned event it must be running on this CPU */
4467 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4473 * If the event is currently on this CPU, its either a per-task event,
4474 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4477 if (event->oncpu == smp_processor_id())
4478 event->pmu->read(event);
4480 *value = local64_read(&event->count);
4481 if (enabled || running) {
4482 u64 __enabled, __running, __now;;
4484 calc_timer_values(event, &__now, &__enabled, &__running);
4486 *enabled = __enabled;
4488 *running = __running;
4491 local_irq_restore(flags);
4496 static int perf_event_read(struct perf_event *event, bool group)
4498 enum perf_event_state state = READ_ONCE(event->state);
4499 int event_cpu, ret = 0;
4502 * If event is enabled and currently active on a CPU, update the
4503 * value in the event structure:
4506 if (state == PERF_EVENT_STATE_ACTIVE) {
4507 struct perf_read_data data;
4510 * Orders the ->state and ->oncpu loads such that if we see
4511 * ACTIVE we must also see the right ->oncpu.
4513 * Matches the smp_wmb() from event_sched_in().
4517 event_cpu = READ_ONCE(event->oncpu);
4518 if ((unsigned)event_cpu >= nr_cpu_ids)
4521 data = (struct perf_read_data){
4528 event_cpu = __perf_event_read_cpu(event, event_cpu);
4531 * Purposely ignore the smp_call_function_single() return
4534 * If event_cpu isn't a valid CPU it means the event got
4535 * scheduled out and that will have updated the event count.
4537 * Therefore, either way, we'll have an up-to-date event count
4540 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4544 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4545 struct perf_event_context *ctx = event->ctx;
4546 unsigned long flags;
4548 raw_spin_lock_irqsave(&ctx->lock, flags);
4549 state = event->state;
4550 if (state != PERF_EVENT_STATE_INACTIVE) {
4551 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4556 * May read while context is not active (e.g., thread is
4557 * blocked), in that case we cannot update context time
4559 if (ctx->is_active & EVENT_TIME) {
4560 update_context_time(ctx);
4561 update_cgrp_time_from_event(event);
4564 perf_event_update_time(event);
4566 perf_event_update_sibling_time(event);
4567 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4574 * Initialize the perf_event context in a task_struct:
4576 static void __perf_event_init_context(struct perf_event_context *ctx)
4578 raw_spin_lock_init(&ctx->lock);
4579 mutex_init(&ctx->mutex);
4580 INIT_LIST_HEAD(&ctx->active_ctx_list);
4581 perf_event_groups_init(&ctx->pinned_groups);
4582 perf_event_groups_init(&ctx->flexible_groups);
4583 INIT_LIST_HEAD(&ctx->event_list);
4584 INIT_LIST_HEAD(&ctx->pinned_active);
4585 INIT_LIST_HEAD(&ctx->flexible_active);
4586 refcount_set(&ctx->refcount, 1);
4589 static struct perf_event_context *
4590 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4592 struct perf_event_context *ctx;
4594 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4598 __perf_event_init_context(ctx);
4600 ctx->task = get_task_struct(task);
4606 static struct task_struct *
4607 find_lively_task_by_vpid(pid_t vpid)
4609 struct task_struct *task;
4615 task = find_task_by_vpid(vpid);
4617 get_task_struct(task);
4621 return ERR_PTR(-ESRCH);
4627 * Returns a matching context with refcount and pincount.
4629 static struct perf_event_context *
4630 find_get_context(struct pmu *pmu, struct task_struct *task,
4631 struct perf_event *event)
4633 struct perf_event_context *ctx, *clone_ctx = NULL;
4634 struct perf_cpu_context *cpuctx;
4635 void *task_ctx_data = NULL;
4636 unsigned long flags;
4638 int cpu = event->cpu;
4641 /* Must be root to operate on a CPU event: */
4642 err = perf_allow_cpu(&event->attr);
4644 return ERR_PTR(err);
4646 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4649 raw_spin_lock_irqsave(&ctx->lock, flags);
4651 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4657 ctxn = pmu->task_ctx_nr;
4661 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4662 task_ctx_data = alloc_task_ctx_data(pmu);
4663 if (!task_ctx_data) {
4670 ctx = perf_lock_task_context(task, ctxn, &flags);
4672 clone_ctx = unclone_ctx(ctx);
4675 if (task_ctx_data && !ctx->task_ctx_data) {
4676 ctx->task_ctx_data = task_ctx_data;
4677 task_ctx_data = NULL;
4679 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4684 ctx = alloc_perf_context(pmu, task);
4689 if (task_ctx_data) {
4690 ctx->task_ctx_data = task_ctx_data;
4691 task_ctx_data = NULL;
4695 mutex_lock(&task->perf_event_mutex);
4697 * If it has already passed perf_event_exit_task().
4698 * we must see PF_EXITING, it takes this mutex too.
4700 if (task->flags & PF_EXITING)
4702 else if (task->perf_event_ctxp[ctxn])
4707 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4709 mutex_unlock(&task->perf_event_mutex);
4711 if (unlikely(err)) {
4720 free_task_ctx_data(pmu, task_ctx_data);
4724 free_task_ctx_data(pmu, task_ctx_data);
4725 return ERR_PTR(err);
4728 static void perf_event_free_filter(struct perf_event *event);
4729 static void perf_event_free_bpf_prog(struct perf_event *event);
4731 static void free_event_rcu(struct rcu_head *head)
4733 struct perf_event *event;
4735 event = container_of(head, struct perf_event, rcu_head);
4737 put_pid_ns(event->ns);
4738 perf_event_free_filter(event);
4742 static void ring_buffer_attach(struct perf_event *event,
4743 struct perf_buffer *rb);
4745 static void detach_sb_event(struct perf_event *event)
4747 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4749 raw_spin_lock(&pel->lock);
4750 list_del_rcu(&event->sb_list);
4751 raw_spin_unlock(&pel->lock);
4754 static bool is_sb_event(struct perf_event *event)
4756 struct perf_event_attr *attr = &event->attr;
4761 if (event->attach_state & PERF_ATTACH_TASK)
4764 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4765 attr->comm || attr->comm_exec ||
4766 attr->task || attr->ksymbol ||
4767 attr->context_switch || attr->text_poke ||
4773 static void unaccount_pmu_sb_event(struct perf_event *event)
4775 if (is_sb_event(event))
4776 detach_sb_event(event);
4779 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4784 if (is_cgroup_event(event))
4785 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4788 #ifdef CONFIG_NO_HZ_FULL
4789 static DEFINE_SPINLOCK(nr_freq_lock);
4792 static void unaccount_freq_event_nohz(void)
4794 #ifdef CONFIG_NO_HZ_FULL
4795 spin_lock(&nr_freq_lock);
4796 if (atomic_dec_and_test(&nr_freq_events))
4797 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4798 spin_unlock(&nr_freq_lock);
4802 static void unaccount_freq_event(void)
4804 if (tick_nohz_full_enabled())
4805 unaccount_freq_event_nohz();
4807 atomic_dec(&nr_freq_events);
4810 static void unaccount_event(struct perf_event *event)
4817 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4819 if (event->attr.mmap || event->attr.mmap_data)
4820 atomic_dec(&nr_mmap_events);
4821 if (event->attr.comm)
4822 atomic_dec(&nr_comm_events);
4823 if (event->attr.namespaces)
4824 atomic_dec(&nr_namespaces_events);
4825 if (event->attr.cgroup)
4826 atomic_dec(&nr_cgroup_events);
4827 if (event->attr.task)
4828 atomic_dec(&nr_task_events);
4829 if (event->attr.freq)
4830 unaccount_freq_event();
4831 if (event->attr.context_switch) {
4833 atomic_dec(&nr_switch_events);
4835 if (is_cgroup_event(event))
4837 if (has_branch_stack(event))
4839 if (event->attr.ksymbol)
4840 atomic_dec(&nr_ksymbol_events);
4841 if (event->attr.bpf_event)
4842 atomic_dec(&nr_bpf_events);
4843 if (event->attr.text_poke)
4844 atomic_dec(&nr_text_poke_events);
4847 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4848 schedule_delayed_work(&perf_sched_work, HZ);
4851 unaccount_event_cpu(event, event->cpu);
4853 unaccount_pmu_sb_event(event);
4856 static void perf_sched_delayed(struct work_struct *work)
4858 mutex_lock(&perf_sched_mutex);
4859 if (atomic_dec_and_test(&perf_sched_count))
4860 static_branch_disable(&perf_sched_events);
4861 mutex_unlock(&perf_sched_mutex);
4865 * The following implement mutual exclusion of events on "exclusive" pmus
4866 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4867 * at a time, so we disallow creating events that might conflict, namely:
4869 * 1) cpu-wide events in the presence of per-task events,
4870 * 2) per-task events in the presence of cpu-wide events,
4871 * 3) two matching events on the same context.
4873 * The former two cases are handled in the allocation path (perf_event_alloc(),
4874 * _free_event()), the latter -- before the first perf_install_in_context().
4876 static int exclusive_event_init(struct perf_event *event)
4878 struct pmu *pmu = event->pmu;
4880 if (!is_exclusive_pmu(pmu))
4884 * Prevent co-existence of per-task and cpu-wide events on the
4885 * same exclusive pmu.
4887 * Negative pmu::exclusive_cnt means there are cpu-wide
4888 * events on this "exclusive" pmu, positive means there are
4891 * Since this is called in perf_event_alloc() path, event::ctx
4892 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4893 * to mean "per-task event", because unlike other attach states it
4894 * never gets cleared.
4896 if (event->attach_state & PERF_ATTACH_TASK) {
4897 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4900 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4907 static void exclusive_event_destroy(struct perf_event *event)
4909 struct pmu *pmu = event->pmu;
4911 if (!is_exclusive_pmu(pmu))
4914 /* see comment in exclusive_event_init() */
4915 if (event->attach_state & PERF_ATTACH_TASK)
4916 atomic_dec(&pmu->exclusive_cnt);
4918 atomic_inc(&pmu->exclusive_cnt);
4921 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4923 if ((e1->pmu == e2->pmu) &&
4924 (e1->cpu == e2->cpu ||
4931 static bool exclusive_event_installable(struct perf_event *event,
4932 struct perf_event_context *ctx)
4934 struct perf_event *iter_event;
4935 struct pmu *pmu = event->pmu;
4937 lockdep_assert_held(&ctx->mutex);
4939 if (!is_exclusive_pmu(pmu))
4942 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4943 if (exclusive_event_match(iter_event, event))
4950 static void perf_addr_filters_splice(struct perf_event *event,
4951 struct list_head *head);
4953 static void _free_event(struct perf_event *event)
4955 irq_work_sync(&event->pending);
4957 unaccount_event(event);
4959 security_perf_event_free(event);
4963 * Can happen when we close an event with re-directed output.
4965 * Since we have a 0 refcount, perf_mmap_close() will skip
4966 * over us; possibly making our ring_buffer_put() the last.
4968 mutex_lock(&event->mmap_mutex);
4969 ring_buffer_attach(event, NULL);
4970 mutex_unlock(&event->mmap_mutex);
4973 if (is_cgroup_event(event))
4974 perf_detach_cgroup(event);
4976 if (!event->parent) {
4977 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4978 put_callchain_buffers();
4981 perf_event_free_bpf_prog(event);
4982 perf_addr_filters_splice(event, NULL);
4983 kfree(event->addr_filter_ranges);
4986 event->destroy(event);
4989 * Must be after ->destroy(), due to uprobe_perf_close() using
4992 if (event->hw.target)
4993 put_task_struct(event->hw.target);
4996 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4997 * all task references must be cleaned up.
5000 put_ctx(event->ctx);
5002 exclusive_event_destroy(event);
5003 module_put(event->pmu->module);
5005 call_rcu(&event->rcu_head, free_event_rcu);
5009 * Used to free events which have a known refcount of 1, such as in error paths
5010 * where the event isn't exposed yet and inherited events.
5012 static void free_event(struct perf_event *event)
5014 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5015 "unexpected event refcount: %ld; ptr=%p\n",
5016 atomic_long_read(&event->refcount), event)) {
5017 /* leak to avoid use-after-free */
5025 * Remove user event from the owner task.
5027 static void perf_remove_from_owner(struct perf_event *event)
5029 struct task_struct *owner;
5033 * Matches the smp_store_release() in perf_event_exit_task(). If we
5034 * observe !owner it means the list deletion is complete and we can
5035 * indeed free this event, otherwise we need to serialize on
5036 * owner->perf_event_mutex.
5038 owner = READ_ONCE(event->owner);
5041 * Since delayed_put_task_struct() also drops the last
5042 * task reference we can safely take a new reference
5043 * while holding the rcu_read_lock().
5045 get_task_struct(owner);
5051 * If we're here through perf_event_exit_task() we're already
5052 * holding ctx->mutex which would be an inversion wrt. the
5053 * normal lock order.
5055 * However we can safely take this lock because its the child
5058 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5061 * We have to re-check the event->owner field, if it is cleared
5062 * we raced with perf_event_exit_task(), acquiring the mutex
5063 * ensured they're done, and we can proceed with freeing the
5067 list_del_init(&event->owner_entry);
5068 smp_store_release(&event->owner, NULL);
5070 mutex_unlock(&owner->perf_event_mutex);
5071 put_task_struct(owner);
5075 static void put_event(struct perf_event *event)
5077 if (!atomic_long_dec_and_test(&event->refcount))
5084 * Kill an event dead; while event:refcount will preserve the event
5085 * object, it will not preserve its functionality. Once the last 'user'
5086 * gives up the object, we'll destroy the thing.
5088 int perf_event_release_kernel(struct perf_event *event)
5090 struct perf_event_context *ctx = event->ctx;
5091 struct perf_event *child, *tmp;
5092 LIST_HEAD(free_list);
5095 * If we got here through err_file: fput(event_file); we will not have
5096 * attached to a context yet.
5099 WARN_ON_ONCE(event->attach_state &
5100 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5104 if (!is_kernel_event(event))
5105 perf_remove_from_owner(event);
5107 ctx = perf_event_ctx_lock(event);
5108 WARN_ON_ONCE(ctx->parent_ctx);
5109 perf_remove_from_context(event, DETACH_GROUP);
5111 raw_spin_lock_irq(&ctx->lock);
5113 * Mark this event as STATE_DEAD, there is no external reference to it
5116 * Anybody acquiring event->child_mutex after the below loop _must_
5117 * also see this, most importantly inherit_event() which will avoid
5118 * placing more children on the list.
5120 * Thus this guarantees that we will in fact observe and kill _ALL_
5123 event->state = PERF_EVENT_STATE_DEAD;
5124 raw_spin_unlock_irq(&ctx->lock);
5126 perf_event_ctx_unlock(event, ctx);
5129 mutex_lock(&event->child_mutex);
5130 list_for_each_entry(child, &event->child_list, child_list) {
5133 * Cannot change, child events are not migrated, see the
5134 * comment with perf_event_ctx_lock_nested().
5136 ctx = READ_ONCE(child->ctx);
5138 * Since child_mutex nests inside ctx::mutex, we must jump
5139 * through hoops. We start by grabbing a reference on the ctx.
5141 * Since the event cannot get freed while we hold the
5142 * child_mutex, the context must also exist and have a !0
5148 * Now that we have a ctx ref, we can drop child_mutex, and
5149 * acquire ctx::mutex without fear of it going away. Then we
5150 * can re-acquire child_mutex.
5152 mutex_unlock(&event->child_mutex);
5153 mutex_lock(&ctx->mutex);
5154 mutex_lock(&event->child_mutex);
5157 * Now that we hold ctx::mutex and child_mutex, revalidate our
5158 * state, if child is still the first entry, it didn't get freed
5159 * and we can continue doing so.
5161 tmp = list_first_entry_or_null(&event->child_list,
5162 struct perf_event, child_list);
5164 perf_remove_from_context(child, DETACH_GROUP);
5165 list_move(&child->child_list, &free_list);
5167 * This matches the refcount bump in inherit_event();
5168 * this can't be the last reference.
5173 mutex_unlock(&event->child_mutex);
5174 mutex_unlock(&ctx->mutex);
5178 mutex_unlock(&event->child_mutex);
5180 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5181 void *var = &child->ctx->refcount;
5183 list_del(&child->child_list);
5187 * Wake any perf_event_free_task() waiting for this event to be
5190 smp_mb(); /* pairs with wait_var_event() */
5195 put_event(event); /* Must be the 'last' reference */
5198 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5201 * Called when the last reference to the file is gone.
5203 static int perf_release(struct inode *inode, struct file *file)
5205 perf_event_release_kernel(file->private_data);
5209 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5211 struct perf_event *child;
5217 mutex_lock(&event->child_mutex);
5219 (void)perf_event_read(event, false);
5220 total += perf_event_count(event);
5222 *enabled += event->total_time_enabled +
5223 atomic64_read(&event->child_total_time_enabled);
5224 *running += event->total_time_running +
5225 atomic64_read(&event->child_total_time_running);
5227 list_for_each_entry(child, &event->child_list, child_list) {
5228 (void)perf_event_read(child, false);
5229 total += perf_event_count(child);
5230 *enabled += child->total_time_enabled;
5231 *running += child->total_time_running;
5233 mutex_unlock(&event->child_mutex);
5238 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5240 struct perf_event_context *ctx;
5243 ctx = perf_event_ctx_lock(event);
5244 count = __perf_event_read_value(event, enabled, running);
5245 perf_event_ctx_unlock(event, ctx);
5249 EXPORT_SYMBOL_GPL(perf_event_read_value);
5251 static int __perf_read_group_add(struct perf_event *leader,
5252 u64 read_format, u64 *values)
5254 struct perf_event_context *ctx = leader->ctx;
5255 struct perf_event *sub, *parent;
5256 unsigned long flags;
5257 int n = 1; /* skip @nr */
5260 ret = perf_event_read(leader, true);
5264 raw_spin_lock_irqsave(&ctx->lock, flags);
5266 * Verify the grouping between the parent and child (inherited)
5267 * events is still in tact.
5270 * - leader->ctx->lock pins leader->sibling_list
5271 * - parent->child_mutex pins parent->child_list
5272 * - parent->ctx->mutex pins parent->sibling_list
5274 * Because parent->ctx != leader->ctx (and child_list nests inside
5275 * ctx->mutex), group destruction is not atomic between children, also
5276 * see perf_event_release_kernel(). Additionally, parent can grow the
5279 * Therefore it is possible to have parent and child groups in a
5280 * different configuration and summing over such a beast makes no sense
5285 parent = leader->parent;
5287 (parent->group_generation != leader->group_generation ||
5288 parent->nr_siblings != leader->nr_siblings)) {
5294 * Since we co-schedule groups, {enabled,running} times of siblings
5295 * will be identical to those of the leader, so we only publish one
5298 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5299 values[n++] += leader->total_time_enabled +
5300 atomic64_read(&leader->child_total_time_enabled);
5303 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5304 values[n++] += leader->total_time_running +
5305 atomic64_read(&leader->child_total_time_running);
5309 * Write {count,id} tuples for every sibling.
5311 values[n++] += perf_event_count(leader);
5312 if (read_format & PERF_FORMAT_ID)
5313 values[n++] = primary_event_id(leader);
5314 if (read_format & PERF_FORMAT_LOST)
5315 values[n++] = atomic64_read(&leader->lost_samples);
5317 for_each_sibling_event(sub, leader) {
5318 values[n++] += perf_event_count(sub);
5319 if (read_format & PERF_FORMAT_ID)
5320 values[n++] = primary_event_id(sub);
5321 if (read_format & PERF_FORMAT_LOST)
5322 values[n++] = atomic64_read(&sub->lost_samples);
5326 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5330 static int perf_read_group(struct perf_event *event,
5331 u64 read_format, char __user *buf)
5333 struct perf_event *leader = event->group_leader, *child;
5334 struct perf_event_context *ctx = leader->ctx;
5338 lockdep_assert_held(&ctx->mutex);
5340 values = kzalloc(event->read_size, GFP_KERNEL);
5344 values[0] = 1 + leader->nr_siblings;
5346 mutex_lock(&leader->child_mutex);
5348 ret = __perf_read_group_add(leader, read_format, values);
5352 list_for_each_entry(child, &leader->child_list, child_list) {
5353 ret = __perf_read_group_add(child, read_format, values);
5358 mutex_unlock(&leader->child_mutex);
5360 ret = event->read_size;
5361 if (copy_to_user(buf, values, event->read_size))
5366 mutex_unlock(&leader->child_mutex);
5372 static int perf_read_one(struct perf_event *event,
5373 u64 read_format, char __user *buf)
5375 u64 enabled, running;
5379 values[n++] = __perf_event_read_value(event, &enabled, &running);
5380 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5381 values[n++] = enabled;
5382 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5383 values[n++] = running;
5384 if (read_format & PERF_FORMAT_ID)
5385 values[n++] = primary_event_id(event);
5386 if (read_format & PERF_FORMAT_LOST)
5387 values[n++] = atomic64_read(&event->lost_samples);
5389 if (copy_to_user(buf, values, n * sizeof(u64)))
5392 return n * sizeof(u64);
5395 static bool is_event_hup(struct perf_event *event)
5399 if (event->state > PERF_EVENT_STATE_EXIT)
5402 mutex_lock(&event->child_mutex);
5403 no_children = list_empty(&event->child_list);
5404 mutex_unlock(&event->child_mutex);
5409 * Read the performance event - simple non blocking version for now
5412 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5414 u64 read_format = event->attr.read_format;
5418 * Return end-of-file for a read on an event that is in
5419 * error state (i.e. because it was pinned but it couldn't be
5420 * scheduled on to the CPU at some point).
5422 if (event->state == PERF_EVENT_STATE_ERROR)
5425 if (count < event->read_size)
5428 WARN_ON_ONCE(event->ctx->parent_ctx);
5429 if (read_format & PERF_FORMAT_GROUP)
5430 ret = perf_read_group(event, read_format, buf);
5432 ret = perf_read_one(event, read_format, buf);
5438 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5440 struct perf_event *event = file->private_data;
5441 struct perf_event_context *ctx;
5444 ret = security_perf_event_read(event);
5448 ctx = perf_event_ctx_lock(event);
5449 ret = __perf_read(event, buf, count);
5450 perf_event_ctx_unlock(event, ctx);
5455 static __poll_t perf_poll(struct file *file, poll_table *wait)
5457 struct perf_event *event = file->private_data;
5458 struct perf_buffer *rb;
5459 __poll_t events = EPOLLHUP;
5461 poll_wait(file, &event->waitq, wait);
5463 if (is_event_hup(event))
5467 * Pin the event->rb by taking event->mmap_mutex; otherwise
5468 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5470 mutex_lock(&event->mmap_mutex);
5473 events = atomic_xchg(&rb->poll, 0);
5474 mutex_unlock(&event->mmap_mutex);
5478 static void _perf_event_reset(struct perf_event *event)
5480 (void)perf_event_read(event, false);
5481 local64_set(&event->count, 0);
5482 perf_event_update_userpage(event);
5485 /* Assume it's not an event with inherit set. */
5486 u64 perf_event_pause(struct perf_event *event, bool reset)
5488 struct perf_event_context *ctx;
5491 ctx = perf_event_ctx_lock(event);
5492 WARN_ON_ONCE(event->attr.inherit);
5493 _perf_event_disable(event);
5494 count = local64_read(&event->count);
5496 local64_set(&event->count, 0);
5497 perf_event_ctx_unlock(event, ctx);
5501 EXPORT_SYMBOL_GPL(perf_event_pause);
5504 * Holding the top-level event's child_mutex means that any
5505 * descendant process that has inherited this event will block
5506 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5507 * task existence requirements of perf_event_enable/disable.
5509 static void perf_event_for_each_child(struct perf_event *event,
5510 void (*func)(struct perf_event *))
5512 struct perf_event *child;
5514 WARN_ON_ONCE(event->ctx->parent_ctx);
5516 mutex_lock(&event->child_mutex);
5518 list_for_each_entry(child, &event->child_list, child_list)
5520 mutex_unlock(&event->child_mutex);
5523 static void perf_event_for_each(struct perf_event *event,
5524 void (*func)(struct perf_event *))
5526 struct perf_event_context *ctx = event->ctx;
5527 struct perf_event *sibling;
5529 lockdep_assert_held(&ctx->mutex);
5531 event = event->group_leader;
5533 perf_event_for_each_child(event, func);
5534 for_each_sibling_event(sibling, event)
5535 perf_event_for_each_child(sibling, func);
5538 static void __perf_event_period(struct perf_event *event,
5539 struct perf_cpu_context *cpuctx,
5540 struct perf_event_context *ctx,
5543 u64 value = *((u64 *)info);
5546 if (event->attr.freq) {
5547 event->attr.sample_freq = value;
5549 event->attr.sample_period = value;
5550 event->hw.sample_period = value;
5553 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5555 perf_pmu_disable(ctx->pmu);
5557 * We could be throttled; unthrottle now to avoid the tick
5558 * trying to unthrottle while we already re-started the event.
5560 if (event->hw.interrupts == MAX_INTERRUPTS) {
5561 event->hw.interrupts = 0;
5562 perf_log_throttle(event, 1);
5564 event->pmu->stop(event, PERF_EF_UPDATE);
5567 local64_set(&event->hw.period_left, 0);
5570 event->pmu->start(event, PERF_EF_RELOAD);
5571 perf_pmu_enable(ctx->pmu);
5575 static int perf_event_check_period(struct perf_event *event, u64 value)
5577 return event->pmu->check_period(event, value);
5580 static int _perf_event_period(struct perf_event *event, u64 value)
5582 if (!is_sampling_event(event))
5588 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5591 if (perf_event_check_period(event, value))
5594 if (!event->attr.freq && (value & (1ULL << 63)))
5597 event_function_call(event, __perf_event_period, &value);
5602 int perf_event_period(struct perf_event *event, u64 value)
5604 struct perf_event_context *ctx;
5607 ctx = perf_event_ctx_lock(event);
5608 ret = _perf_event_period(event, value);
5609 perf_event_ctx_unlock(event, ctx);
5613 EXPORT_SYMBOL_GPL(perf_event_period);
5615 static const struct file_operations perf_fops;
5617 static inline int perf_fget_light(int fd, struct fd *p)
5619 struct fd f = fdget(fd);
5623 if (f.file->f_op != &perf_fops) {
5631 static int perf_event_set_output(struct perf_event *event,
5632 struct perf_event *output_event);
5633 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5634 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5635 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5636 struct perf_event_attr *attr);
5638 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5640 void (*func)(struct perf_event *);
5644 case PERF_EVENT_IOC_ENABLE:
5645 func = _perf_event_enable;
5647 case PERF_EVENT_IOC_DISABLE:
5648 func = _perf_event_disable;
5650 case PERF_EVENT_IOC_RESET:
5651 func = _perf_event_reset;
5654 case PERF_EVENT_IOC_REFRESH:
5655 return _perf_event_refresh(event, arg);
5657 case PERF_EVENT_IOC_PERIOD:
5661 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5664 return _perf_event_period(event, value);
5666 case PERF_EVENT_IOC_ID:
5668 u64 id = primary_event_id(event);
5670 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5675 case PERF_EVENT_IOC_SET_OUTPUT:
5679 struct perf_event *output_event;
5681 ret = perf_fget_light(arg, &output);
5684 output_event = output.file->private_data;
5685 ret = perf_event_set_output(event, output_event);
5688 ret = perf_event_set_output(event, NULL);
5693 case PERF_EVENT_IOC_SET_FILTER:
5694 return perf_event_set_filter(event, (void __user *)arg);
5696 case PERF_EVENT_IOC_SET_BPF:
5697 return perf_event_set_bpf_prog(event, arg);
5699 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5700 struct perf_buffer *rb;
5703 rb = rcu_dereference(event->rb);
5704 if (!rb || !rb->nr_pages) {
5708 rb_toggle_paused(rb, !!arg);
5713 case PERF_EVENT_IOC_QUERY_BPF:
5714 return perf_event_query_prog_array(event, (void __user *)arg);
5716 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5717 struct perf_event_attr new_attr;
5718 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5724 return perf_event_modify_attr(event, &new_attr);
5730 if (flags & PERF_IOC_FLAG_GROUP)
5731 perf_event_for_each(event, func);
5733 perf_event_for_each_child(event, func);
5738 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5740 struct perf_event *event = file->private_data;
5741 struct perf_event_context *ctx;
5744 /* Treat ioctl like writes as it is likely a mutating operation. */
5745 ret = security_perf_event_write(event);
5749 ctx = perf_event_ctx_lock(event);
5750 ret = _perf_ioctl(event, cmd, arg);
5751 perf_event_ctx_unlock(event, ctx);
5756 #ifdef CONFIG_COMPAT
5757 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5760 switch (_IOC_NR(cmd)) {
5761 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5762 case _IOC_NR(PERF_EVENT_IOC_ID):
5763 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5764 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5765 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5766 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5767 cmd &= ~IOCSIZE_MASK;
5768 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5772 return perf_ioctl(file, cmd, arg);
5775 # define perf_compat_ioctl NULL
5778 int perf_event_task_enable(void)
5780 struct perf_event_context *ctx;
5781 struct perf_event *event;
5783 mutex_lock(¤t->perf_event_mutex);
5784 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5785 ctx = perf_event_ctx_lock(event);
5786 perf_event_for_each_child(event, _perf_event_enable);
5787 perf_event_ctx_unlock(event, ctx);
5789 mutex_unlock(¤t->perf_event_mutex);
5794 int perf_event_task_disable(void)
5796 struct perf_event_context *ctx;
5797 struct perf_event *event;
5799 mutex_lock(¤t->perf_event_mutex);
5800 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5801 ctx = perf_event_ctx_lock(event);
5802 perf_event_for_each_child(event, _perf_event_disable);
5803 perf_event_ctx_unlock(event, ctx);
5805 mutex_unlock(¤t->perf_event_mutex);
5810 static int perf_event_index(struct perf_event *event)
5812 if (event->hw.state & PERF_HES_STOPPED)
5815 if (event->state != PERF_EVENT_STATE_ACTIVE)
5818 return event->pmu->event_idx(event);
5821 static void perf_event_init_userpage(struct perf_event *event)
5823 struct perf_event_mmap_page *userpg;
5824 struct perf_buffer *rb;
5827 rb = rcu_dereference(event->rb);
5831 userpg = rb->user_page;
5833 /* Allow new userspace to detect that bit 0 is deprecated */
5834 userpg->cap_bit0_is_deprecated = 1;
5835 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5836 userpg->data_offset = PAGE_SIZE;
5837 userpg->data_size = perf_data_size(rb);
5843 void __weak arch_perf_update_userpage(
5844 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5849 * Callers need to ensure there can be no nesting of this function, otherwise
5850 * the seqlock logic goes bad. We can not serialize this because the arch
5851 * code calls this from NMI context.
5853 void perf_event_update_userpage(struct perf_event *event)
5855 struct perf_event_mmap_page *userpg;
5856 struct perf_buffer *rb;
5857 u64 enabled, running, now;
5860 rb = rcu_dereference(event->rb);
5865 * compute total_time_enabled, total_time_running
5866 * based on snapshot values taken when the event
5867 * was last scheduled in.
5869 * we cannot simply called update_context_time()
5870 * because of locking issue as we can be called in
5873 calc_timer_values(event, &now, &enabled, &running);
5875 userpg = rb->user_page;
5877 * Disable preemption to guarantee consistent time stamps are stored to
5883 userpg->index = perf_event_index(event);
5884 userpg->offset = perf_event_count(event);
5886 userpg->offset -= local64_read(&event->hw.prev_count);
5888 userpg->time_enabled = enabled +
5889 atomic64_read(&event->child_total_time_enabled);
5891 userpg->time_running = running +
5892 atomic64_read(&event->child_total_time_running);
5894 arch_perf_update_userpage(event, userpg, now);
5902 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5904 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5906 struct perf_event *event = vmf->vma->vm_file->private_data;
5907 struct perf_buffer *rb;
5908 vm_fault_t ret = VM_FAULT_SIGBUS;
5910 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5911 if (vmf->pgoff == 0)
5917 rb = rcu_dereference(event->rb);
5921 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5924 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5928 get_page(vmf->page);
5929 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5930 vmf->page->index = vmf->pgoff;
5939 static void ring_buffer_attach(struct perf_event *event,
5940 struct perf_buffer *rb)
5942 struct perf_buffer *old_rb = NULL;
5943 unsigned long flags;
5945 WARN_ON_ONCE(event->parent);
5949 * Should be impossible, we set this when removing
5950 * event->rb_entry and wait/clear when adding event->rb_entry.
5952 WARN_ON_ONCE(event->rcu_pending);
5955 spin_lock_irqsave(&old_rb->event_lock, flags);
5956 list_del_rcu(&event->rb_entry);
5957 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5959 event->rcu_batches = get_state_synchronize_rcu();
5960 event->rcu_pending = 1;
5964 if (event->rcu_pending) {
5965 cond_synchronize_rcu(event->rcu_batches);
5966 event->rcu_pending = 0;
5969 spin_lock_irqsave(&rb->event_lock, flags);
5970 list_add_rcu(&event->rb_entry, &rb->event_list);
5971 spin_unlock_irqrestore(&rb->event_lock, flags);
5975 * Avoid racing with perf_mmap_close(AUX): stop the event
5976 * before swizzling the event::rb pointer; if it's getting
5977 * unmapped, its aux_mmap_count will be 0 and it won't
5978 * restart. See the comment in __perf_pmu_output_stop().
5980 * Data will inevitably be lost when set_output is done in
5981 * mid-air, but then again, whoever does it like this is
5982 * not in for the data anyway.
5985 perf_event_stop(event, 0);
5987 rcu_assign_pointer(event->rb, rb);
5990 ring_buffer_put(old_rb);
5992 * Since we detached before setting the new rb, so that we
5993 * could attach the new rb, we could have missed a wakeup.
5996 wake_up_all(&event->waitq);
6000 static void ring_buffer_wakeup(struct perf_event *event)
6002 struct perf_buffer *rb;
6005 event = event->parent;
6008 rb = rcu_dereference(event->rb);
6010 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6011 wake_up_all(&event->waitq);
6016 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6018 struct perf_buffer *rb;
6021 event = event->parent;
6024 rb = rcu_dereference(event->rb);
6026 if (!refcount_inc_not_zero(&rb->refcount))
6034 void ring_buffer_put(struct perf_buffer *rb)
6036 if (!refcount_dec_and_test(&rb->refcount))
6039 WARN_ON_ONCE(!list_empty(&rb->event_list));
6041 call_rcu(&rb->rcu_head, rb_free_rcu);
6044 static void perf_mmap_open(struct vm_area_struct *vma)
6046 struct perf_event *event = vma->vm_file->private_data;
6048 atomic_inc(&event->mmap_count);
6049 atomic_inc(&event->rb->mmap_count);
6052 atomic_inc(&event->rb->aux_mmap_count);
6054 if (event->pmu->event_mapped)
6055 event->pmu->event_mapped(event, vma->vm_mm);
6058 static void perf_pmu_output_stop(struct perf_event *event);
6061 * A buffer can be mmap()ed multiple times; either directly through the same
6062 * event, or through other events by use of perf_event_set_output().
6064 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6065 * the buffer here, where we still have a VM context. This means we need
6066 * to detach all events redirecting to us.
6068 static void perf_mmap_close(struct vm_area_struct *vma)
6070 struct perf_event *event = vma->vm_file->private_data;
6071 struct perf_buffer *rb = ring_buffer_get(event);
6072 struct user_struct *mmap_user = rb->mmap_user;
6073 int mmap_locked = rb->mmap_locked;
6074 unsigned long size = perf_data_size(rb);
6075 bool detach_rest = false;
6077 if (event->pmu->event_unmapped)
6078 event->pmu->event_unmapped(event, vma->vm_mm);
6081 * rb->aux_mmap_count will always drop before rb->mmap_count and
6082 * event->mmap_count, so it is ok to use event->mmap_mutex to
6083 * serialize with perf_mmap here.
6085 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6086 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6088 * Stop all AUX events that are writing to this buffer,
6089 * so that we can free its AUX pages and corresponding PMU
6090 * data. Note that after rb::aux_mmap_count dropped to zero,
6091 * they won't start any more (see perf_aux_output_begin()).
6093 perf_pmu_output_stop(event);
6095 /* now it's safe to free the pages */
6096 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6097 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6099 /* this has to be the last one */
6101 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6103 mutex_unlock(&event->mmap_mutex);
6106 if (atomic_dec_and_test(&rb->mmap_count))
6109 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6112 ring_buffer_attach(event, NULL);
6113 mutex_unlock(&event->mmap_mutex);
6115 /* If there's still other mmap()s of this buffer, we're done. */
6120 * No other mmap()s, detach from all other events that might redirect
6121 * into the now unreachable buffer. Somewhat complicated by the
6122 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6126 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6127 if (!atomic_long_inc_not_zero(&event->refcount)) {
6129 * This event is en-route to free_event() which will
6130 * detach it and remove it from the list.
6136 mutex_lock(&event->mmap_mutex);
6138 * Check we didn't race with perf_event_set_output() which can
6139 * swizzle the rb from under us while we were waiting to
6140 * acquire mmap_mutex.
6142 * If we find a different rb; ignore this event, a next
6143 * iteration will no longer find it on the list. We have to
6144 * still restart the iteration to make sure we're not now
6145 * iterating the wrong list.
6147 if (event->rb == rb)
6148 ring_buffer_attach(event, NULL);
6150 mutex_unlock(&event->mmap_mutex);
6154 * Restart the iteration; either we're on the wrong list or
6155 * destroyed its integrity by doing a deletion.
6162 * It could be there's still a few 0-ref events on the list; they'll
6163 * get cleaned up by free_event() -- they'll also still have their
6164 * ref on the rb and will free it whenever they are done with it.
6166 * Aside from that, this buffer is 'fully' detached and unmapped,
6167 * undo the VM accounting.
6170 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6171 &mmap_user->locked_vm);
6172 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6173 free_uid(mmap_user);
6176 ring_buffer_put(rb); /* could be last */
6179 static const struct vm_operations_struct perf_mmap_vmops = {
6180 .open = perf_mmap_open,
6181 .close = perf_mmap_close, /* non mergeable */
6182 .fault = perf_mmap_fault,
6183 .page_mkwrite = perf_mmap_fault,
6186 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6188 struct perf_event *event = file->private_data;
6189 unsigned long user_locked, user_lock_limit;
6190 struct user_struct *user = current_user();
6191 struct perf_buffer *rb = NULL;
6192 unsigned long locked, lock_limit;
6193 unsigned long vma_size;
6194 unsigned long nr_pages;
6195 long user_extra = 0, extra = 0;
6196 int ret = 0, flags = 0;
6199 * Don't allow mmap() of inherited per-task counters. This would
6200 * create a performance issue due to all children writing to the
6203 if (event->cpu == -1 && event->attr.inherit)
6206 if (!(vma->vm_flags & VM_SHARED))
6209 ret = security_perf_event_read(event);
6213 vma_size = vma->vm_end - vma->vm_start;
6215 if (vma->vm_pgoff == 0) {
6216 nr_pages = (vma_size / PAGE_SIZE) - 1;
6219 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6220 * mapped, all subsequent mappings should have the same size
6221 * and offset. Must be above the normal perf buffer.
6223 u64 aux_offset, aux_size;
6228 nr_pages = vma_size / PAGE_SIZE;
6230 mutex_lock(&event->mmap_mutex);
6237 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6238 aux_size = READ_ONCE(rb->user_page->aux_size);
6240 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6243 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6246 /* already mapped with a different offset */
6247 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6250 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6253 /* already mapped with a different size */
6254 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6257 if (!is_power_of_2(nr_pages))
6260 if (!atomic_inc_not_zero(&rb->mmap_count))
6263 if (rb_has_aux(rb)) {
6264 atomic_inc(&rb->aux_mmap_count);
6269 atomic_set(&rb->aux_mmap_count, 1);
6270 user_extra = nr_pages;
6276 * If we have rb pages ensure they're a power-of-two number, so we
6277 * can do bitmasks instead of modulo.
6279 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6282 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6285 WARN_ON_ONCE(event->ctx->parent_ctx);
6287 mutex_lock(&event->mmap_mutex);
6289 if (data_page_nr(event->rb) != nr_pages) {
6294 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6296 * Raced against perf_mmap_close(); remove the
6297 * event and try again.
6299 ring_buffer_attach(event, NULL);
6300 mutex_unlock(&event->mmap_mutex);
6307 user_extra = nr_pages + 1;
6310 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6313 * Increase the limit linearly with more CPUs:
6315 user_lock_limit *= num_online_cpus();
6317 user_locked = atomic_long_read(&user->locked_vm);
6320 * sysctl_perf_event_mlock may have changed, so that
6321 * user->locked_vm > user_lock_limit
6323 if (user_locked > user_lock_limit)
6324 user_locked = user_lock_limit;
6325 user_locked += user_extra;
6327 if (user_locked > user_lock_limit) {
6329 * charge locked_vm until it hits user_lock_limit;
6330 * charge the rest from pinned_vm
6332 extra = user_locked - user_lock_limit;
6333 user_extra -= extra;
6336 lock_limit = rlimit(RLIMIT_MEMLOCK);
6337 lock_limit >>= PAGE_SHIFT;
6338 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6340 if ((locked > lock_limit) && perf_is_paranoid() &&
6341 !capable(CAP_IPC_LOCK)) {
6346 WARN_ON(!rb && event->rb);
6348 if (vma->vm_flags & VM_WRITE)
6349 flags |= RING_BUFFER_WRITABLE;
6352 rb = rb_alloc(nr_pages,
6353 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6361 atomic_set(&rb->mmap_count, 1);
6362 rb->mmap_user = get_current_user();
6363 rb->mmap_locked = extra;
6365 ring_buffer_attach(event, rb);
6367 perf_event_update_time(event);
6368 perf_event_init_userpage(event);
6369 perf_event_update_userpage(event);
6371 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6372 event->attr.aux_watermark, flags);
6374 rb->aux_mmap_locked = extra;
6379 atomic_long_add(user_extra, &user->locked_vm);
6380 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6382 atomic_inc(&event->mmap_count);
6384 atomic_dec(&rb->mmap_count);
6387 mutex_unlock(&event->mmap_mutex);
6390 * Since pinned accounting is per vm we cannot allow fork() to copy our
6393 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6394 vma->vm_ops = &perf_mmap_vmops;
6396 if (event->pmu->event_mapped)
6397 event->pmu->event_mapped(event, vma->vm_mm);
6402 static int perf_fasync(int fd, struct file *filp, int on)
6404 struct inode *inode = file_inode(filp);
6405 struct perf_event *event = filp->private_data;
6409 retval = fasync_helper(fd, filp, on, &event->fasync);
6410 inode_unlock(inode);
6418 static const struct file_operations perf_fops = {
6419 .llseek = no_llseek,
6420 .release = perf_release,
6423 .unlocked_ioctl = perf_ioctl,
6424 .compat_ioctl = perf_compat_ioctl,
6426 .fasync = perf_fasync,
6432 * If there's data, ensure we set the poll() state and publish everything
6433 * to user-space before waking everybody up.
6436 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6438 /* only the parent has fasync state */
6440 event = event->parent;
6441 return &event->fasync;
6444 void perf_event_wakeup(struct perf_event *event)
6446 ring_buffer_wakeup(event);
6448 if (event->pending_kill) {
6449 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6450 event->pending_kill = 0;
6454 static void perf_pending_event_disable(struct perf_event *event)
6456 int cpu = READ_ONCE(event->pending_disable);
6461 if (cpu == smp_processor_id()) {
6462 WRITE_ONCE(event->pending_disable, -1);
6463 perf_event_disable_local(event);
6470 * perf_event_disable_inatomic()
6471 * @pending_disable = CPU-A;
6475 * @pending_disable = -1;
6478 * perf_event_disable_inatomic()
6479 * @pending_disable = CPU-B;
6480 * irq_work_queue(); // FAILS
6483 * perf_pending_event()
6485 * But the event runs on CPU-B and wants disabling there.
6487 irq_work_queue_on(&event->pending, cpu);
6490 static void perf_pending_event(struct irq_work *entry)
6492 struct perf_event *event = container_of(entry, struct perf_event, pending);
6495 rctx = perf_swevent_get_recursion_context();
6497 * If we 'fail' here, that's OK, it means recursion is already disabled
6498 * and we won't recurse 'further'.
6501 perf_pending_event_disable(event);
6503 if (event->pending_wakeup) {
6504 event->pending_wakeup = 0;
6505 perf_event_wakeup(event);
6509 perf_swevent_put_recursion_context(rctx);
6513 * We assume there is only KVM supporting the callbacks.
6514 * Later on, we might change it to a list if there is
6515 * another virtualization implementation supporting the callbacks.
6517 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6519 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6521 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6524 rcu_assign_pointer(perf_guest_cbs, cbs);
6527 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6529 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6531 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6534 rcu_assign_pointer(perf_guest_cbs, NULL);
6538 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6541 perf_output_sample_regs(struct perf_output_handle *handle,
6542 struct pt_regs *regs, u64 mask)
6545 DECLARE_BITMAP(_mask, 64);
6547 bitmap_from_u64(_mask, mask);
6548 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6551 val = perf_reg_value(regs, bit);
6552 perf_output_put(handle, val);
6556 static void perf_sample_regs_user(struct perf_regs *regs_user,
6557 struct pt_regs *regs)
6559 if (user_mode(regs)) {
6560 regs_user->abi = perf_reg_abi(current);
6561 regs_user->regs = regs;
6562 } else if (!(current->flags & PF_KTHREAD)) {
6563 perf_get_regs_user(regs_user, regs);
6565 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6566 regs_user->regs = NULL;
6570 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6571 struct pt_regs *regs)
6573 regs_intr->regs = regs;
6574 regs_intr->abi = perf_reg_abi(current);
6579 * Get remaining task size from user stack pointer.
6581 * It'd be better to take stack vma map and limit this more
6582 * precisely, but there's no way to get it safely under interrupt,
6583 * so using TASK_SIZE as limit.
6585 static u64 perf_ustack_task_size(struct pt_regs *regs)
6587 unsigned long addr = perf_user_stack_pointer(regs);
6589 if (!addr || addr >= TASK_SIZE)
6592 return TASK_SIZE - addr;
6596 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6597 struct pt_regs *regs)
6601 /* No regs, no stack pointer, no dump. */
6606 * Check if we fit in with the requested stack size into the:
6608 * If we don't, we limit the size to the TASK_SIZE.
6610 * - remaining sample size
6611 * If we don't, we customize the stack size to
6612 * fit in to the remaining sample size.
6615 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6616 stack_size = min(stack_size, (u16) task_size);
6618 /* Current header size plus static size and dynamic size. */
6619 header_size += 2 * sizeof(u64);
6621 /* Do we fit in with the current stack dump size? */
6622 if ((u16) (header_size + stack_size) < header_size) {
6624 * If we overflow the maximum size for the sample,
6625 * we customize the stack dump size to fit in.
6627 stack_size = USHRT_MAX - header_size - sizeof(u64);
6628 stack_size = round_up(stack_size, sizeof(u64));
6635 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6636 struct pt_regs *regs)
6638 /* Case of a kernel thread, nothing to dump */
6641 perf_output_put(handle, size);
6651 * - the size requested by user or the best one we can fit
6652 * in to the sample max size
6654 * - user stack dump data
6656 * - the actual dumped size
6660 perf_output_put(handle, dump_size);
6663 sp = perf_user_stack_pointer(regs);
6664 fs = force_uaccess_begin();
6665 rem = __output_copy_user(handle, (void *) sp, dump_size);
6666 force_uaccess_end(fs);
6667 dyn_size = dump_size - rem;
6669 perf_output_skip(handle, rem);
6672 perf_output_put(handle, dyn_size);
6676 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6677 struct perf_sample_data *data,
6680 struct perf_event *sampler = event->aux_event;
6681 struct perf_buffer *rb;
6688 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6691 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6694 rb = ring_buffer_get(sampler);
6699 * If this is an NMI hit inside sampling code, don't take
6700 * the sample. See also perf_aux_sample_output().
6702 if (READ_ONCE(rb->aux_in_sampling)) {
6705 size = min_t(size_t, size, perf_aux_size(rb));
6706 data->aux_size = ALIGN(size, sizeof(u64));
6708 ring_buffer_put(rb);
6711 return data->aux_size;
6714 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6715 struct perf_event *event,
6716 struct perf_output_handle *handle,
6719 unsigned long flags;
6723 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6724 * paths. If we start calling them in NMI context, they may race with
6725 * the IRQ ones, that is, for example, re-starting an event that's just
6726 * been stopped, which is why we're using a separate callback that
6727 * doesn't change the event state.
6729 * IRQs need to be disabled to prevent IPIs from racing with us.
6731 local_irq_save(flags);
6733 * Guard against NMI hits inside the critical section;
6734 * see also perf_prepare_sample_aux().
6736 WRITE_ONCE(rb->aux_in_sampling, 1);
6739 ret = event->pmu->snapshot_aux(event, handle, size);
6742 WRITE_ONCE(rb->aux_in_sampling, 0);
6743 local_irq_restore(flags);
6748 static void perf_aux_sample_output(struct perf_event *event,
6749 struct perf_output_handle *handle,
6750 struct perf_sample_data *data)
6752 struct perf_event *sampler = event->aux_event;
6753 struct perf_buffer *rb;
6757 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6760 rb = ring_buffer_get(sampler);
6764 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6767 * An error here means that perf_output_copy() failed (returned a
6768 * non-zero surplus that it didn't copy), which in its current
6769 * enlightened implementation is not possible. If that changes, we'd
6772 if (WARN_ON_ONCE(size < 0))
6776 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6777 * perf_prepare_sample_aux(), so should not be more than that.
6779 pad = data->aux_size - size;
6780 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6785 perf_output_copy(handle, &zero, pad);
6789 ring_buffer_put(rb);
6792 static void __perf_event_header__init_id(struct perf_event_header *header,
6793 struct perf_sample_data *data,
6794 struct perf_event *event)
6796 u64 sample_type = event->attr.sample_type;
6798 data->type = sample_type;
6799 header->size += event->id_header_size;
6801 if (sample_type & PERF_SAMPLE_TID) {
6802 /* namespace issues */
6803 data->tid_entry.pid = perf_event_pid(event, current);
6804 data->tid_entry.tid = perf_event_tid(event, current);
6807 if (sample_type & PERF_SAMPLE_TIME)
6808 data->time = perf_event_clock(event);
6810 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6811 data->id = primary_event_id(event);
6813 if (sample_type & PERF_SAMPLE_STREAM_ID)
6814 data->stream_id = event->id;
6816 if (sample_type & PERF_SAMPLE_CPU) {
6817 data->cpu_entry.cpu = raw_smp_processor_id();
6818 data->cpu_entry.reserved = 0;
6822 void perf_event_header__init_id(struct perf_event_header *header,
6823 struct perf_sample_data *data,
6824 struct perf_event *event)
6826 if (event->attr.sample_id_all)
6827 __perf_event_header__init_id(header, data, event);
6830 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6831 struct perf_sample_data *data)
6833 u64 sample_type = data->type;
6835 if (sample_type & PERF_SAMPLE_TID)
6836 perf_output_put(handle, data->tid_entry);
6838 if (sample_type & PERF_SAMPLE_TIME)
6839 perf_output_put(handle, data->time);
6841 if (sample_type & PERF_SAMPLE_ID)
6842 perf_output_put(handle, data->id);
6844 if (sample_type & PERF_SAMPLE_STREAM_ID)
6845 perf_output_put(handle, data->stream_id);
6847 if (sample_type & PERF_SAMPLE_CPU)
6848 perf_output_put(handle, data->cpu_entry);
6850 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6851 perf_output_put(handle, data->id);
6854 void perf_event__output_id_sample(struct perf_event *event,
6855 struct perf_output_handle *handle,
6856 struct perf_sample_data *sample)
6858 if (event->attr.sample_id_all)
6859 __perf_event__output_id_sample(handle, sample);
6862 static void perf_output_read_one(struct perf_output_handle *handle,
6863 struct perf_event *event,
6864 u64 enabled, u64 running)
6866 u64 read_format = event->attr.read_format;
6870 values[n++] = perf_event_count(event);
6871 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6872 values[n++] = enabled +
6873 atomic64_read(&event->child_total_time_enabled);
6875 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6876 values[n++] = running +
6877 atomic64_read(&event->child_total_time_running);
6879 if (read_format & PERF_FORMAT_ID)
6880 values[n++] = primary_event_id(event);
6881 if (read_format & PERF_FORMAT_LOST)
6882 values[n++] = atomic64_read(&event->lost_samples);
6884 __output_copy(handle, values, n * sizeof(u64));
6887 static void perf_output_read_group(struct perf_output_handle *handle,
6888 struct perf_event *event,
6889 u64 enabled, u64 running)
6891 struct perf_event *leader = event->group_leader, *sub;
6892 u64 read_format = event->attr.read_format;
6893 unsigned long flags;
6898 * Disabling interrupts avoids all counter scheduling
6899 * (context switches, timer based rotation and IPIs).
6901 local_irq_save(flags);
6903 values[n++] = 1 + leader->nr_siblings;
6905 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6906 values[n++] = enabled;
6908 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6909 values[n++] = running;
6911 if ((leader != event) &&
6912 (leader->state == PERF_EVENT_STATE_ACTIVE))
6913 leader->pmu->read(leader);
6915 values[n++] = perf_event_count(leader);
6916 if (read_format & PERF_FORMAT_ID)
6917 values[n++] = primary_event_id(leader);
6918 if (read_format & PERF_FORMAT_LOST)
6919 values[n++] = atomic64_read(&leader->lost_samples);
6921 __output_copy(handle, values, n * sizeof(u64));
6923 for_each_sibling_event(sub, leader) {
6926 if ((sub != event) &&
6927 (sub->state == PERF_EVENT_STATE_ACTIVE))
6928 sub->pmu->read(sub);
6930 values[n++] = perf_event_count(sub);
6931 if (read_format & PERF_FORMAT_ID)
6932 values[n++] = primary_event_id(sub);
6933 if (read_format & PERF_FORMAT_LOST)
6934 values[n++] = atomic64_read(&sub->lost_samples);
6936 __output_copy(handle, values, n * sizeof(u64));
6939 local_irq_restore(flags);
6942 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6943 PERF_FORMAT_TOTAL_TIME_RUNNING)
6946 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6948 * The problem is that its both hard and excessively expensive to iterate the
6949 * child list, not to mention that its impossible to IPI the children running
6950 * on another CPU, from interrupt/NMI context.
6952 static void perf_output_read(struct perf_output_handle *handle,
6953 struct perf_event *event)
6955 u64 enabled = 0, running = 0, now;
6956 u64 read_format = event->attr.read_format;
6959 * compute total_time_enabled, total_time_running
6960 * based on snapshot values taken when the event
6961 * was last scheduled in.
6963 * we cannot simply called update_context_time()
6964 * because of locking issue as we are called in
6967 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6968 calc_timer_values(event, &now, &enabled, &running);
6970 if (event->attr.read_format & PERF_FORMAT_GROUP)
6971 perf_output_read_group(handle, event, enabled, running);
6973 perf_output_read_one(handle, event, enabled, running);
6976 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6978 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6981 void perf_output_sample(struct perf_output_handle *handle,
6982 struct perf_event_header *header,
6983 struct perf_sample_data *data,
6984 struct perf_event *event)
6986 u64 sample_type = data->type;
6988 perf_output_put(handle, *header);
6990 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6991 perf_output_put(handle, data->id);
6993 if (sample_type & PERF_SAMPLE_IP)
6994 perf_output_put(handle, data->ip);
6996 if (sample_type & PERF_SAMPLE_TID)
6997 perf_output_put(handle, data->tid_entry);
6999 if (sample_type & PERF_SAMPLE_TIME)
7000 perf_output_put(handle, data->time);
7002 if (sample_type & PERF_SAMPLE_ADDR)
7003 perf_output_put(handle, data->addr);
7005 if (sample_type & PERF_SAMPLE_ID)
7006 perf_output_put(handle, data->id);
7008 if (sample_type & PERF_SAMPLE_STREAM_ID)
7009 perf_output_put(handle, data->stream_id);
7011 if (sample_type & PERF_SAMPLE_CPU)
7012 perf_output_put(handle, data->cpu_entry);
7014 if (sample_type & PERF_SAMPLE_PERIOD)
7015 perf_output_put(handle, data->period);
7017 if (sample_type & PERF_SAMPLE_READ)
7018 perf_output_read(handle, event);
7020 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7023 size += data->callchain->nr;
7024 size *= sizeof(u64);
7025 __output_copy(handle, data->callchain, size);
7028 if (sample_type & PERF_SAMPLE_RAW) {
7029 struct perf_raw_record *raw = data->raw;
7032 struct perf_raw_frag *frag = &raw->frag;
7034 perf_output_put(handle, raw->size);
7037 __output_custom(handle, frag->copy,
7038 frag->data, frag->size);
7040 __output_copy(handle, frag->data,
7043 if (perf_raw_frag_last(frag))
7048 __output_skip(handle, NULL, frag->pad);
7054 .size = sizeof(u32),
7057 perf_output_put(handle, raw);
7061 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7062 if (data->br_stack) {
7065 size = data->br_stack->nr
7066 * sizeof(struct perf_branch_entry);
7068 perf_output_put(handle, data->br_stack->nr);
7069 if (perf_sample_save_hw_index(event))
7070 perf_output_put(handle, data->br_stack->hw_idx);
7071 perf_output_copy(handle, data->br_stack->entries, size);
7074 * we always store at least the value of nr
7077 perf_output_put(handle, nr);
7081 if (sample_type & PERF_SAMPLE_REGS_USER) {
7082 u64 abi = data->regs_user.abi;
7085 * If there are no regs to dump, notice it through
7086 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7088 perf_output_put(handle, abi);
7091 u64 mask = event->attr.sample_regs_user;
7092 perf_output_sample_regs(handle,
7093 data->regs_user.regs,
7098 if (sample_type & PERF_SAMPLE_STACK_USER) {
7099 perf_output_sample_ustack(handle,
7100 data->stack_user_size,
7101 data->regs_user.regs);
7104 if (sample_type & PERF_SAMPLE_WEIGHT)
7105 perf_output_put(handle, data->weight);
7107 if (sample_type & PERF_SAMPLE_DATA_SRC)
7108 perf_output_put(handle, data->data_src.val);
7110 if (sample_type & PERF_SAMPLE_TRANSACTION)
7111 perf_output_put(handle, data->txn);
7113 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7114 u64 abi = data->regs_intr.abi;
7116 * If there are no regs to dump, notice it through
7117 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7119 perf_output_put(handle, abi);
7122 u64 mask = event->attr.sample_regs_intr;
7124 perf_output_sample_regs(handle,
7125 data->regs_intr.regs,
7130 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7131 perf_output_put(handle, data->phys_addr);
7133 if (sample_type & PERF_SAMPLE_CGROUP)
7134 perf_output_put(handle, data->cgroup);
7136 if (sample_type & PERF_SAMPLE_AUX) {
7137 perf_output_put(handle, data->aux_size);
7140 perf_aux_sample_output(event, handle, data);
7143 if (!event->attr.watermark) {
7144 int wakeup_events = event->attr.wakeup_events;
7146 if (wakeup_events) {
7147 struct perf_buffer *rb = handle->rb;
7148 int events = local_inc_return(&rb->events);
7150 if (events >= wakeup_events) {
7151 local_sub(wakeup_events, &rb->events);
7152 local_inc(&rb->wakeup);
7158 static u64 perf_virt_to_phys(u64 virt)
7165 if (virt >= TASK_SIZE) {
7166 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7167 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7168 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7169 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7172 * Walking the pages tables for user address.
7173 * Interrupts are disabled, so it prevents any tear down
7174 * of the page tables.
7175 * Try IRQ-safe get_user_page_fast_only first.
7176 * If failed, leave phys_addr as 0.
7178 if (current->mm != NULL) {
7181 pagefault_disable();
7182 if (get_user_page_fast_only(virt, 0, &p)) {
7183 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7193 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7195 struct perf_callchain_entry *
7196 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7198 bool kernel = !event->attr.exclude_callchain_kernel;
7199 bool user = !event->attr.exclude_callchain_user;
7200 /* Disallow cross-task user callchains. */
7201 bool crosstask = event->ctx->task && event->ctx->task != current;
7202 const u32 max_stack = event->attr.sample_max_stack;
7203 struct perf_callchain_entry *callchain;
7205 if (!kernel && !user)
7206 return &__empty_callchain;
7208 callchain = get_perf_callchain(regs, 0, kernel, user,
7209 max_stack, crosstask, true);
7210 return callchain ?: &__empty_callchain;
7213 void perf_prepare_sample(struct perf_event_header *header,
7214 struct perf_sample_data *data,
7215 struct perf_event *event,
7216 struct pt_regs *regs)
7218 u64 sample_type = event->attr.sample_type;
7220 header->type = PERF_RECORD_SAMPLE;
7221 header->size = sizeof(*header) + event->header_size;
7224 header->misc |= perf_misc_flags(regs);
7226 __perf_event_header__init_id(header, data, event);
7228 if (sample_type & PERF_SAMPLE_IP)
7229 data->ip = perf_instruction_pointer(regs);
7231 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7234 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7235 data->callchain = perf_callchain(event, regs);
7237 size += data->callchain->nr;
7239 header->size += size * sizeof(u64);
7242 if (sample_type & PERF_SAMPLE_RAW) {
7243 struct perf_raw_record *raw = data->raw;
7247 struct perf_raw_frag *frag = &raw->frag;
7252 if (perf_raw_frag_last(frag))
7257 size = round_up(sum + sizeof(u32), sizeof(u64));
7258 raw->size = size - sizeof(u32);
7259 frag->pad = raw->size - sum;
7264 header->size += size;
7267 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7268 int size = sizeof(u64); /* nr */
7269 if (data->br_stack) {
7270 if (perf_sample_save_hw_index(event))
7271 size += sizeof(u64);
7273 size += data->br_stack->nr
7274 * sizeof(struct perf_branch_entry);
7276 header->size += size;
7279 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7280 perf_sample_regs_user(&data->regs_user, regs);
7282 if (sample_type & PERF_SAMPLE_REGS_USER) {
7283 /* regs dump ABI info */
7284 int size = sizeof(u64);
7286 if (data->regs_user.regs) {
7287 u64 mask = event->attr.sample_regs_user;
7288 size += hweight64(mask) * sizeof(u64);
7291 header->size += size;
7294 if (sample_type & PERF_SAMPLE_STACK_USER) {
7296 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7297 * processed as the last one or have additional check added
7298 * in case new sample type is added, because we could eat
7299 * up the rest of the sample size.
7301 u16 stack_size = event->attr.sample_stack_user;
7302 u16 size = sizeof(u64);
7304 stack_size = perf_sample_ustack_size(stack_size, header->size,
7305 data->regs_user.regs);
7308 * If there is something to dump, add space for the dump
7309 * itself and for the field that tells the dynamic size,
7310 * which is how many have been actually dumped.
7313 size += sizeof(u64) + stack_size;
7315 data->stack_user_size = stack_size;
7316 header->size += size;
7319 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7320 /* regs dump ABI info */
7321 int size = sizeof(u64);
7323 perf_sample_regs_intr(&data->regs_intr, regs);
7325 if (data->regs_intr.regs) {
7326 u64 mask = event->attr.sample_regs_intr;
7328 size += hweight64(mask) * sizeof(u64);
7331 header->size += size;
7334 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7335 data->phys_addr = perf_virt_to_phys(data->addr);
7337 #ifdef CONFIG_CGROUP_PERF
7338 if (sample_type & PERF_SAMPLE_CGROUP) {
7339 struct cgroup *cgrp;
7341 /* protected by RCU */
7342 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7343 data->cgroup = cgroup_id(cgrp);
7347 if (sample_type & PERF_SAMPLE_AUX) {
7350 header->size += sizeof(u64); /* size */
7353 * Given the 16bit nature of header::size, an AUX sample can
7354 * easily overflow it, what with all the preceding sample bits.
7355 * Make sure this doesn't happen by using up to U16_MAX bytes
7356 * per sample in total (rounded down to 8 byte boundary).
7358 size = min_t(size_t, U16_MAX - header->size,
7359 event->attr.aux_sample_size);
7360 size = rounddown(size, 8);
7361 size = perf_prepare_sample_aux(event, data, size);
7363 WARN_ON_ONCE(size + header->size > U16_MAX);
7364 header->size += size;
7367 * If you're adding more sample types here, you likely need to do
7368 * something about the overflowing header::size, like repurpose the
7369 * lowest 3 bits of size, which should be always zero at the moment.
7370 * This raises a more important question, do we really need 512k sized
7371 * samples and why, so good argumentation is in order for whatever you
7374 WARN_ON_ONCE(header->size & 7);
7377 static __always_inline int
7378 __perf_event_output(struct perf_event *event,
7379 struct perf_sample_data *data,
7380 struct pt_regs *regs,
7381 int (*output_begin)(struct perf_output_handle *,
7382 struct perf_sample_data *,
7383 struct perf_event *,
7386 struct perf_output_handle handle;
7387 struct perf_event_header header;
7390 /* protect the callchain buffers */
7393 perf_prepare_sample(&header, data, event, regs);
7395 err = output_begin(&handle, data, event, header.size);
7399 perf_output_sample(&handle, &header, data, event);
7401 perf_output_end(&handle);
7409 perf_event_output_forward(struct perf_event *event,
7410 struct perf_sample_data *data,
7411 struct pt_regs *regs)
7413 __perf_event_output(event, data, regs, perf_output_begin_forward);
7417 perf_event_output_backward(struct perf_event *event,
7418 struct perf_sample_data *data,
7419 struct pt_regs *regs)
7421 __perf_event_output(event, data, regs, perf_output_begin_backward);
7425 perf_event_output(struct perf_event *event,
7426 struct perf_sample_data *data,
7427 struct pt_regs *regs)
7429 return __perf_event_output(event, data, regs, perf_output_begin);
7436 struct perf_read_event {
7437 struct perf_event_header header;
7444 perf_event_read_event(struct perf_event *event,
7445 struct task_struct *task)
7447 struct perf_output_handle handle;
7448 struct perf_sample_data sample;
7449 struct perf_read_event read_event = {
7451 .type = PERF_RECORD_READ,
7453 .size = sizeof(read_event) + event->read_size,
7455 .pid = perf_event_pid(event, task),
7456 .tid = perf_event_tid(event, task),
7460 perf_event_header__init_id(&read_event.header, &sample, event);
7461 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7465 perf_output_put(&handle, read_event);
7466 perf_output_read(&handle, event);
7467 perf_event__output_id_sample(event, &handle, &sample);
7469 perf_output_end(&handle);
7472 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7475 perf_iterate_ctx(struct perf_event_context *ctx,
7476 perf_iterate_f output,
7477 void *data, bool all)
7479 struct perf_event *event;
7481 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7483 if (event->state < PERF_EVENT_STATE_INACTIVE)
7485 if (!event_filter_match(event))
7489 output(event, data);
7493 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7495 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7496 struct perf_event *event;
7498 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7500 * Skip events that are not fully formed yet; ensure that
7501 * if we observe event->ctx, both event and ctx will be
7502 * complete enough. See perf_install_in_context().
7504 if (!smp_load_acquire(&event->ctx))
7507 if (event->state < PERF_EVENT_STATE_INACTIVE)
7509 if (!event_filter_match(event))
7511 output(event, data);
7516 * Iterate all events that need to receive side-band events.
7518 * For new callers; ensure that account_pmu_sb_event() includes
7519 * your event, otherwise it might not get delivered.
7522 perf_iterate_sb(perf_iterate_f output, void *data,
7523 struct perf_event_context *task_ctx)
7525 struct perf_event_context *ctx;
7532 * If we have task_ctx != NULL we only notify the task context itself.
7533 * The task_ctx is set only for EXIT events before releasing task
7537 perf_iterate_ctx(task_ctx, output, data, false);
7541 perf_iterate_sb_cpu(output, data);
7543 for_each_task_context_nr(ctxn) {
7544 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7546 perf_iterate_ctx(ctx, output, data, false);
7554 * Clear all file-based filters at exec, they'll have to be
7555 * re-instated when/if these objects are mmapped again.
7557 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7559 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7560 struct perf_addr_filter *filter;
7561 unsigned int restart = 0, count = 0;
7562 unsigned long flags;
7564 if (!has_addr_filter(event))
7567 raw_spin_lock_irqsave(&ifh->lock, flags);
7568 list_for_each_entry(filter, &ifh->list, entry) {
7569 if (filter->path.dentry) {
7570 event->addr_filter_ranges[count].start = 0;
7571 event->addr_filter_ranges[count].size = 0;
7579 event->addr_filters_gen++;
7580 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7583 perf_event_stop(event, 1);
7586 void perf_event_exec(void)
7588 struct perf_event_context *ctx;
7592 for_each_task_context_nr(ctxn) {
7593 ctx = current->perf_event_ctxp[ctxn];
7597 perf_event_enable_on_exec(ctxn);
7599 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7605 struct remote_output {
7606 struct perf_buffer *rb;
7610 static void __perf_event_output_stop(struct perf_event *event, void *data)
7612 struct perf_event *parent = event->parent;
7613 struct remote_output *ro = data;
7614 struct perf_buffer *rb = ro->rb;
7615 struct stop_event_data sd = {
7619 if (!has_aux(event))
7626 * In case of inheritance, it will be the parent that links to the
7627 * ring-buffer, but it will be the child that's actually using it.
7629 * We are using event::rb to determine if the event should be stopped,
7630 * however this may race with ring_buffer_attach() (through set_output),
7631 * which will make us skip the event that actually needs to be stopped.
7632 * So ring_buffer_attach() has to stop an aux event before re-assigning
7635 if (rcu_dereference(parent->rb) == rb)
7636 ro->err = __perf_event_stop(&sd);
7639 static int __perf_pmu_output_stop(void *info)
7641 struct perf_event *event = info;
7642 struct pmu *pmu = event->ctx->pmu;
7643 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7644 struct remote_output ro = {
7649 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7650 if (cpuctx->task_ctx)
7651 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7658 static void perf_pmu_output_stop(struct perf_event *event)
7660 struct perf_event *iter;
7665 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7667 * For per-CPU events, we need to make sure that neither they
7668 * nor their children are running; for cpu==-1 events it's
7669 * sufficient to stop the event itself if it's active, since
7670 * it can't have children.
7674 cpu = READ_ONCE(iter->oncpu);
7679 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7680 if (err == -EAGAIN) {
7689 * task tracking -- fork/exit
7691 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7694 struct perf_task_event {
7695 struct task_struct *task;
7696 struct perf_event_context *task_ctx;
7699 struct perf_event_header header;
7709 static int perf_event_task_match(struct perf_event *event)
7711 return event->attr.comm || event->attr.mmap ||
7712 event->attr.mmap2 || event->attr.mmap_data ||
7716 static void perf_event_task_output(struct perf_event *event,
7719 struct perf_task_event *task_event = data;
7720 struct perf_output_handle handle;
7721 struct perf_sample_data sample;
7722 struct task_struct *task = task_event->task;
7723 int ret, size = task_event->event_id.header.size;
7725 if (!perf_event_task_match(event))
7728 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7730 ret = perf_output_begin(&handle, &sample, event,
7731 task_event->event_id.header.size);
7735 task_event->event_id.pid = perf_event_pid(event, task);
7736 task_event->event_id.tid = perf_event_tid(event, task);
7738 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7739 task_event->event_id.ppid = perf_event_pid(event,
7741 task_event->event_id.ptid = perf_event_pid(event,
7743 } else { /* PERF_RECORD_FORK */
7744 task_event->event_id.ppid = perf_event_pid(event, current);
7745 task_event->event_id.ptid = perf_event_tid(event, current);
7748 task_event->event_id.time = perf_event_clock(event);
7750 perf_output_put(&handle, task_event->event_id);
7752 perf_event__output_id_sample(event, &handle, &sample);
7754 perf_output_end(&handle);
7756 task_event->event_id.header.size = size;
7759 static void perf_event_task(struct task_struct *task,
7760 struct perf_event_context *task_ctx,
7763 struct perf_task_event task_event;
7765 if (!atomic_read(&nr_comm_events) &&
7766 !atomic_read(&nr_mmap_events) &&
7767 !atomic_read(&nr_task_events))
7770 task_event = (struct perf_task_event){
7772 .task_ctx = task_ctx,
7775 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7777 .size = sizeof(task_event.event_id),
7787 perf_iterate_sb(perf_event_task_output,
7792 void perf_event_fork(struct task_struct *task)
7794 perf_event_task(task, NULL, 1);
7795 perf_event_namespaces(task);
7802 struct perf_comm_event {
7803 struct task_struct *task;
7808 struct perf_event_header header;
7815 static int perf_event_comm_match(struct perf_event *event)
7817 return event->attr.comm;
7820 static void perf_event_comm_output(struct perf_event *event,
7823 struct perf_comm_event *comm_event = data;
7824 struct perf_output_handle handle;
7825 struct perf_sample_data sample;
7826 int size = comm_event->event_id.header.size;
7829 if (!perf_event_comm_match(event))
7832 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7833 ret = perf_output_begin(&handle, &sample, event,
7834 comm_event->event_id.header.size);
7839 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7840 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7842 perf_output_put(&handle, comm_event->event_id);
7843 __output_copy(&handle, comm_event->comm,
7844 comm_event->comm_size);
7846 perf_event__output_id_sample(event, &handle, &sample);
7848 perf_output_end(&handle);
7850 comm_event->event_id.header.size = size;
7853 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7855 char comm[TASK_COMM_LEN];
7858 memset(comm, 0, sizeof(comm));
7859 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7860 size = ALIGN(strlen(comm)+1, sizeof(u64));
7862 comm_event->comm = comm;
7863 comm_event->comm_size = size;
7865 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7867 perf_iterate_sb(perf_event_comm_output,
7872 void perf_event_comm(struct task_struct *task, bool exec)
7874 struct perf_comm_event comm_event;
7876 if (!atomic_read(&nr_comm_events))
7879 comm_event = (struct perf_comm_event){
7885 .type = PERF_RECORD_COMM,
7886 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7894 perf_event_comm_event(&comm_event);
7898 * namespaces tracking
7901 struct perf_namespaces_event {
7902 struct task_struct *task;
7905 struct perf_event_header header;
7910 struct perf_ns_link_info link_info[NR_NAMESPACES];
7914 static int perf_event_namespaces_match(struct perf_event *event)
7916 return event->attr.namespaces;
7919 static void perf_event_namespaces_output(struct perf_event *event,
7922 struct perf_namespaces_event *namespaces_event = data;
7923 struct perf_output_handle handle;
7924 struct perf_sample_data sample;
7925 u16 header_size = namespaces_event->event_id.header.size;
7928 if (!perf_event_namespaces_match(event))
7931 perf_event_header__init_id(&namespaces_event->event_id.header,
7933 ret = perf_output_begin(&handle, &sample, event,
7934 namespaces_event->event_id.header.size);
7938 namespaces_event->event_id.pid = perf_event_pid(event,
7939 namespaces_event->task);
7940 namespaces_event->event_id.tid = perf_event_tid(event,
7941 namespaces_event->task);
7943 perf_output_put(&handle, namespaces_event->event_id);
7945 perf_event__output_id_sample(event, &handle, &sample);
7947 perf_output_end(&handle);
7949 namespaces_event->event_id.header.size = header_size;
7952 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7953 struct task_struct *task,
7954 const struct proc_ns_operations *ns_ops)
7956 struct path ns_path;
7957 struct inode *ns_inode;
7960 error = ns_get_path(&ns_path, task, ns_ops);
7962 ns_inode = ns_path.dentry->d_inode;
7963 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7964 ns_link_info->ino = ns_inode->i_ino;
7969 void perf_event_namespaces(struct task_struct *task)
7971 struct perf_namespaces_event namespaces_event;
7972 struct perf_ns_link_info *ns_link_info;
7974 if (!atomic_read(&nr_namespaces_events))
7977 namespaces_event = (struct perf_namespaces_event){
7981 .type = PERF_RECORD_NAMESPACES,
7983 .size = sizeof(namespaces_event.event_id),
7987 .nr_namespaces = NR_NAMESPACES,
7988 /* .link_info[NR_NAMESPACES] */
7992 ns_link_info = namespaces_event.event_id.link_info;
7994 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7995 task, &mntns_operations);
7997 #ifdef CONFIG_USER_NS
7998 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7999 task, &userns_operations);
8001 #ifdef CONFIG_NET_NS
8002 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8003 task, &netns_operations);
8005 #ifdef CONFIG_UTS_NS
8006 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8007 task, &utsns_operations);
8009 #ifdef CONFIG_IPC_NS
8010 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8011 task, &ipcns_operations);
8013 #ifdef CONFIG_PID_NS
8014 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8015 task, &pidns_operations);
8017 #ifdef CONFIG_CGROUPS
8018 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8019 task, &cgroupns_operations);
8022 perf_iterate_sb(perf_event_namespaces_output,
8030 #ifdef CONFIG_CGROUP_PERF
8032 struct perf_cgroup_event {
8036 struct perf_event_header header;
8042 static int perf_event_cgroup_match(struct perf_event *event)
8044 return event->attr.cgroup;
8047 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8049 struct perf_cgroup_event *cgroup_event = data;
8050 struct perf_output_handle handle;
8051 struct perf_sample_data sample;
8052 u16 header_size = cgroup_event->event_id.header.size;
8055 if (!perf_event_cgroup_match(event))
8058 perf_event_header__init_id(&cgroup_event->event_id.header,
8060 ret = perf_output_begin(&handle, &sample, event,
8061 cgroup_event->event_id.header.size);
8065 perf_output_put(&handle, cgroup_event->event_id);
8066 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8068 perf_event__output_id_sample(event, &handle, &sample);
8070 perf_output_end(&handle);
8072 cgroup_event->event_id.header.size = header_size;
8075 static void perf_event_cgroup(struct cgroup *cgrp)
8077 struct perf_cgroup_event cgroup_event;
8078 char path_enomem[16] = "//enomem";
8082 if (!atomic_read(&nr_cgroup_events))
8085 cgroup_event = (struct perf_cgroup_event){
8088 .type = PERF_RECORD_CGROUP,
8090 .size = sizeof(cgroup_event.event_id),
8092 .id = cgroup_id(cgrp),
8096 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8097 if (pathname == NULL) {
8098 cgroup_event.path = path_enomem;
8100 /* just to be sure to have enough space for alignment */
8101 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8102 cgroup_event.path = pathname;
8106 * Since our buffer works in 8 byte units we need to align our string
8107 * size to a multiple of 8. However, we must guarantee the tail end is
8108 * zero'd out to avoid leaking random bits to userspace.
8110 size = strlen(cgroup_event.path) + 1;
8111 while (!IS_ALIGNED(size, sizeof(u64)))
8112 cgroup_event.path[size++] = '\0';
8114 cgroup_event.event_id.header.size += size;
8115 cgroup_event.path_size = size;
8117 perf_iterate_sb(perf_event_cgroup_output,
8130 struct perf_mmap_event {
8131 struct vm_area_struct *vma;
8133 const char *file_name;
8141 struct perf_event_header header;
8151 static int perf_event_mmap_match(struct perf_event *event,
8154 struct perf_mmap_event *mmap_event = data;
8155 struct vm_area_struct *vma = mmap_event->vma;
8156 int executable = vma->vm_flags & VM_EXEC;
8158 return (!executable && event->attr.mmap_data) ||
8159 (executable && (event->attr.mmap || event->attr.mmap2));
8162 static void perf_event_mmap_output(struct perf_event *event,
8165 struct perf_mmap_event *mmap_event = data;
8166 struct perf_output_handle handle;
8167 struct perf_sample_data sample;
8168 int size = mmap_event->event_id.header.size;
8169 u32 type = mmap_event->event_id.header.type;
8172 if (!perf_event_mmap_match(event, data))
8175 if (event->attr.mmap2) {
8176 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8177 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8178 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8179 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8180 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8181 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8182 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8185 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8186 ret = perf_output_begin(&handle, &sample, event,
8187 mmap_event->event_id.header.size);
8191 mmap_event->event_id.pid = perf_event_pid(event, current);
8192 mmap_event->event_id.tid = perf_event_tid(event, current);
8194 perf_output_put(&handle, mmap_event->event_id);
8196 if (event->attr.mmap2) {
8197 perf_output_put(&handle, mmap_event->maj);
8198 perf_output_put(&handle, mmap_event->min);
8199 perf_output_put(&handle, mmap_event->ino);
8200 perf_output_put(&handle, mmap_event->ino_generation);
8201 perf_output_put(&handle, mmap_event->prot);
8202 perf_output_put(&handle, mmap_event->flags);
8205 __output_copy(&handle, mmap_event->file_name,
8206 mmap_event->file_size);
8208 perf_event__output_id_sample(event, &handle, &sample);
8210 perf_output_end(&handle);
8212 mmap_event->event_id.header.size = size;
8213 mmap_event->event_id.header.type = type;
8216 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8218 struct vm_area_struct *vma = mmap_event->vma;
8219 struct file *file = vma->vm_file;
8220 int maj = 0, min = 0;
8221 u64 ino = 0, gen = 0;
8222 u32 prot = 0, flags = 0;
8228 if (vma->vm_flags & VM_READ)
8230 if (vma->vm_flags & VM_WRITE)
8232 if (vma->vm_flags & VM_EXEC)
8235 if (vma->vm_flags & VM_MAYSHARE)
8238 flags = MAP_PRIVATE;
8240 if (vma->vm_flags & VM_DENYWRITE)
8241 flags |= MAP_DENYWRITE;
8242 if (vma->vm_flags & VM_MAYEXEC)
8243 flags |= MAP_EXECUTABLE;
8244 if (vma->vm_flags & VM_LOCKED)
8245 flags |= MAP_LOCKED;
8246 if (is_vm_hugetlb_page(vma))
8247 flags |= MAP_HUGETLB;
8250 struct inode *inode;
8253 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8259 * d_path() works from the end of the rb backwards, so we
8260 * need to add enough zero bytes after the string to handle
8261 * the 64bit alignment we do later.
8263 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8268 inode = file_inode(vma->vm_file);
8269 dev = inode->i_sb->s_dev;
8271 gen = inode->i_generation;
8277 if (vma->vm_ops && vma->vm_ops->name) {
8278 name = (char *) vma->vm_ops->name(vma);
8283 name = (char *)arch_vma_name(vma);
8287 if (vma->vm_start <= vma->vm_mm->start_brk &&
8288 vma->vm_end >= vma->vm_mm->brk) {
8292 if (vma->vm_start <= vma->vm_mm->start_stack &&
8293 vma->vm_end >= vma->vm_mm->start_stack) {
8303 strlcpy(tmp, name, sizeof(tmp));
8307 * Since our buffer works in 8 byte units we need to align our string
8308 * size to a multiple of 8. However, we must guarantee the tail end is
8309 * zero'd out to avoid leaking random bits to userspace.
8311 size = strlen(name)+1;
8312 while (!IS_ALIGNED(size, sizeof(u64)))
8313 name[size++] = '\0';
8315 mmap_event->file_name = name;
8316 mmap_event->file_size = size;
8317 mmap_event->maj = maj;
8318 mmap_event->min = min;
8319 mmap_event->ino = ino;
8320 mmap_event->ino_generation = gen;
8321 mmap_event->prot = prot;
8322 mmap_event->flags = flags;
8324 if (!(vma->vm_flags & VM_EXEC))
8325 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8327 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8329 perf_iterate_sb(perf_event_mmap_output,
8337 * Check whether inode and address range match filter criteria.
8339 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8340 struct file *file, unsigned long offset,
8343 /* d_inode(NULL) won't be equal to any mapped user-space file */
8344 if (!filter->path.dentry)
8347 if (d_inode(filter->path.dentry) != file_inode(file))
8350 if (filter->offset > offset + size)
8353 if (filter->offset + filter->size < offset)
8359 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8360 struct vm_area_struct *vma,
8361 struct perf_addr_filter_range *fr)
8363 unsigned long vma_size = vma->vm_end - vma->vm_start;
8364 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8365 struct file *file = vma->vm_file;
8367 if (!perf_addr_filter_match(filter, file, off, vma_size))
8370 if (filter->offset < off) {
8371 fr->start = vma->vm_start;
8372 fr->size = min(vma_size, filter->size - (off - filter->offset));
8374 fr->start = vma->vm_start + filter->offset - off;
8375 fr->size = min(vma->vm_end - fr->start, filter->size);
8381 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8383 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8384 struct vm_area_struct *vma = data;
8385 struct perf_addr_filter *filter;
8386 unsigned int restart = 0, count = 0;
8387 unsigned long flags;
8389 if (!has_addr_filter(event))
8395 raw_spin_lock_irqsave(&ifh->lock, flags);
8396 list_for_each_entry(filter, &ifh->list, entry) {
8397 if (perf_addr_filter_vma_adjust(filter, vma,
8398 &event->addr_filter_ranges[count]))
8405 event->addr_filters_gen++;
8406 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8409 perf_event_stop(event, 1);
8413 * Adjust all task's events' filters to the new vma
8415 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8417 struct perf_event_context *ctx;
8421 * Data tracing isn't supported yet and as such there is no need
8422 * to keep track of anything that isn't related to executable code:
8424 if (!(vma->vm_flags & VM_EXEC))
8428 for_each_task_context_nr(ctxn) {
8429 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8433 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8438 void perf_event_mmap(struct vm_area_struct *vma)
8440 struct perf_mmap_event mmap_event;
8442 if (!atomic_read(&nr_mmap_events))
8445 mmap_event = (struct perf_mmap_event){
8451 .type = PERF_RECORD_MMAP,
8452 .misc = PERF_RECORD_MISC_USER,
8457 .start = vma->vm_start,
8458 .len = vma->vm_end - vma->vm_start,
8459 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8461 /* .maj (attr_mmap2 only) */
8462 /* .min (attr_mmap2 only) */
8463 /* .ino (attr_mmap2 only) */
8464 /* .ino_generation (attr_mmap2 only) */
8465 /* .prot (attr_mmap2 only) */
8466 /* .flags (attr_mmap2 only) */
8469 perf_addr_filters_adjust(vma);
8470 perf_event_mmap_event(&mmap_event);
8473 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8474 unsigned long size, u64 flags)
8476 struct perf_output_handle handle;
8477 struct perf_sample_data sample;
8478 struct perf_aux_event {
8479 struct perf_event_header header;
8485 .type = PERF_RECORD_AUX,
8487 .size = sizeof(rec),
8495 perf_event_header__init_id(&rec.header, &sample, event);
8496 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8501 perf_output_put(&handle, rec);
8502 perf_event__output_id_sample(event, &handle, &sample);
8504 perf_output_end(&handle);
8508 * Lost/dropped samples logging
8510 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8512 struct perf_output_handle handle;
8513 struct perf_sample_data sample;
8517 struct perf_event_header header;
8519 } lost_samples_event = {
8521 .type = PERF_RECORD_LOST_SAMPLES,
8523 .size = sizeof(lost_samples_event),
8528 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8530 ret = perf_output_begin(&handle, &sample, event,
8531 lost_samples_event.header.size);
8535 perf_output_put(&handle, lost_samples_event);
8536 perf_event__output_id_sample(event, &handle, &sample);
8537 perf_output_end(&handle);
8541 * context_switch tracking
8544 struct perf_switch_event {
8545 struct task_struct *task;
8546 struct task_struct *next_prev;
8549 struct perf_event_header header;
8555 static int perf_event_switch_match(struct perf_event *event)
8557 return event->attr.context_switch;
8560 static void perf_event_switch_output(struct perf_event *event, void *data)
8562 struct perf_switch_event *se = data;
8563 struct perf_output_handle handle;
8564 struct perf_sample_data sample;
8567 if (!perf_event_switch_match(event))
8570 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8571 if (event->ctx->task) {
8572 se->event_id.header.type = PERF_RECORD_SWITCH;
8573 se->event_id.header.size = sizeof(se->event_id.header);
8575 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8576 se->event_id.header.size = sizeof(se->event_id);
8577 se->event_id.next_prev_pid =
8578 perf_event_pid(event, se->next_prev);
8579 se->event_id.next_prev_tid =
8580 perf_event_tid(event, se->next_prev);
8583 perf_event_header__init_id(&se->event_id.header, &sample, event);
8585 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8589 if (event->ctx->task)
8590 perf_output_put(&handle, se->event_id.header);
8592 perf_output_put(&handle, se->event_id);
8594 perf_event__output_id_sample(event, &handle, &sample);
8596 perf_output_end(&handle);
8599 static void perf_event_switch(struct task_struct *task,
8600 struct task_struct *next_prev, bool sched_in)
8602 struct perf_switch_event switch_event;
8604 /* N.B. caller checks nr_switch_events != 0 */
8606 switch_event = (struct perf_switch_event){
8608 .next_prev = next_prev,
8612 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8615 /* .next_prev_pid */
8616 /* .next_prev_tid */
8620 if (!sched_in && task->state == TASK_RUNNING)
8621 switch_event.event_id.header.misc |=
8622 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8624 perf_iterate_sb(perf_event_switch_output,
8630 * IRQ throttle logging
8633 static void perf_log_throttle(struct perf_event *event, int enable)
8635 struct perf_output_handle handle;
8636 struct perf_sample_data sample;
8640 struct perf_event_header header;
8644 } throttle_event = {
8646 .type = PERF_RECORD_THROTTLE,
8648 .size = sizeof(throttle_event),
8650 .time = perf_event_clock(event),
8651 .id = primary_event_id(event),
8652 .stream_id = event->id,
8656 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8658 perf_event_header__init_id(&throttle_event.header, &sample, event);
8660 ret = perf_output_begin(&handle, &sample, event,
8661 throttle_event.header.size);
8665 perf_output_put(&handle, throttle_event);
8666 perf_event__output_id_sample(event, &handle, &sample);
8667 perf_output_end(&handle);
8671 * ksymbol register/unregister tracking
8674 struct perf_ksymbol_event {
8678 struct perf_event_header header;
8686 static int perf_event_ksymbol_match(struct perf_event *event)
8688 return event->attr.ksymbol;
8691 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8693 struct perf_ksymbol_event *ksymbol_event = data;
8694 struct perf_output_handle handle;
8695 struct perf_sample_data sample;
8698 if (!perf_event_ksymbol_match(event))
8701 perf_event_header__init_id(&ksymbol_event->event_id.header,
8703 ret = perf_output_begin(&handle, &sample, event,
8704 ksymbol_event->event_id.header.size);
8708 perf_output_put(&handle, ksymbol_event->event_id);
8709 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8710 perf_event__output_id_sample(event, &handle, &sample);
8712 perf_output_end(&handle);
8715 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8718 struct perf_ksymbol_event ksymbol_event;
8719 char name[KSYM_NAME_LEN];
8723 if (!atomic_read(&nr_ksymbol_events))
8726 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8727 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8730 strlcpy(name, sym, KSYM_NAME_LEN);
8731 name_len = strlen(name) + 1;
8732 while (!IS_ALIGNED(name_len, sizeof(u64)))
8733 name[name_len++] = '\0';
8734 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8737 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8739 ksymbol_event = (struct perf_ksymbol_event){
8741 .name_len = name_len,
8744 .type = PERF_RECORD_KSYMBOL,
8745 .size = sizeof(ksymbol_event.event_id) +
8750 .ksym_type = ksym_type,
8755 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8758 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8762 * bpf program load/unload tracking
8765 struct perf_bpf_event {
8766 struct bpf_prog *prog;
8768 struct perf_event_header header;
8772 u8 tag[BPF_TAG_SIZE];
8776 static int perf_event_bpf_match(struct perf_event *event)
8778 return event->attr.bpf_event;
8781 static void perf_event_bpf_output(struct perf_event *event, void *data)
8783 struct perf_bpf_event *bpf_event = data;
8784 struct perf_output_handle handle;
8785 struct perf_sample_data sample;
8788 if (!perf_event_bpf_match(event))
8791 perf_event_header__init_id(&bpf_event->event_id.header,
8793 ret = perf_output_begin(&handle, &sample, event,
8794 bpf_event->event_id.header.size);
8798 perf_output_put(&handle, bpf_event->event_id);
8799 perf_event__output_id_sample(event, &handle, &sample);
8801 perf_output_end(&handle);
8804 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8805 enum perf_bpf_event_type type)
8807 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8810 if (prog->aux->func_cnt == 0) {
8811 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8812 (u64)(unsigned long)prog->bpf_func,
8813 prog->jited_len, unregister,
8814 prog->aux->ksym.name);
8816 for (i = 0; i < prog->aux->func_cnt; i++) {
8817 struct bpf_prog *subprog = prog->aux->func[i];
8820 PERF_RECORD_KSYMBOL_TYPE_BPF,
8821 (u64)(unsigned long)subprog->bpf_func,
8822 subprog->jited_len, unregister,
8823 subprog->aux->ksym.name);
8828 void perf_event_bpf_event(struct bpf_prog *prog,
8829 enum perf_bpf_event_type type,
8832 struct perf_bpf_event bpf_event;
8834 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8835 type >= PERF_BPF_EVENT_MAX)
8839 case PERF_BPF_EVENT_PROG_LOAD:
8840 case PERF_BPF_EVENT_PROG_UNLOAD:
8841 if (atomic_read(&nr_ksymbol_events))
8842 perf_event_bpf_emit_ksymbols(prog, type);
8848 if (!atomic_read(&nr_bpf_events))
8851 bpf_event = (struct perf_bpf_event){
8855 .type = PERF_RECORD_BPF_EVENT,
8856 .size = sizeof(bpf_event.event_id),
8860 .id = prog->aux->id,
8864 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8866 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8867 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8870 struct perf_text_poke_event {
8871 const void *old_bytes;
8872 const void *new_bytes;
8878 struct perf_event_header header;
8884 static int perf_event_text_poke_match(struct perf_event *event)
8886 return event->attr.text_poke;
8889 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8891 struct perf_text_poke_event *text_poke_event = data;
8892 struct perf_output_handle handle;
8893 struct perf_sample_data sample;
8897 if (!perf_event_text_poke_match(event))
8900 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8902 ret = perf_output_begin(&handle, &sample, event,
8903 text_poke_event->event_id.header.size);
8907 perf_output_put(&handle, text_poke_event->event_id);
8908 perf_output_put(&handle, text_poke_event->old_len);
8909 perf_output_put(&handle, text_poke_event->new_len);
8911 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8912 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8914 if (text_poke_event->pad)
8915 __output_copy(&handle, &padding, text_poke_event->pad);
8917 perf_event__output_id_sample(event, &handle, &sample);
8919 perf_output_end(&handle);
8922 void perf_event_text_poke(const void *addr, const void *old_bytes,
8923 size_t old_len, const void *new_bytes, size_t new_len)
8925 struct perf_text_poke_event text_poke_event;
8928 if (!atomic_read(&nr_text_poke_events))
8931 tot = sizeof(text_poke_event.old_len) + old_len;
8932 tot += sizeof(text_poke_event.new_len) + new_len;
8933 pad = ALIGN(tot, sizeof(u64)) - tot;
8935 text_poke_event = (struct perf_text_poke_event){
8936 .old_bytes = old_bytes,
8937 .new_bytes = new_bytes,
8943 .type = PERF_RECORD_TEXT_POKE,
8944 .misc = PERF_RECORD_MISC_KERNEL,
8945 .size = sizeof(text_poke_event.event_id) + tot + pad,
8947 .addr = (unsigned long)addr,
8951 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8954 void perf_event_itrace_started(struct perf_event *event)
8956 event->attach_state |= PERF_ATTACH_ITRACE;
8959 static void perf_log_itrace_start(struct perf_event *event)
8961 struct perf_output_handle handle;
8962 struct perf_sample_data sample;
8963 struct perf_aux_event {
8964 struct perf_event_header header;
8971 event = event->parent;
8973 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8974 event->attach_state & PERF_ATTACH_ITRACE)
8977 rec.header.type = PERF_RECORD_ITRACE_START;
8978 rec.header.misc = 0;
8979 rec.header.size = sizeof(rec);
8980 rec.pid = perf_event_pid(event, current);
8981 rec.tid = perf_event_tid(event, current);
8983 perf_event_header__init_id(&rec.header, &sample, event);
8984 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8989 perf_output_put(&handle, rec);
8990 perf_event__output_id_sample(event, &handle, &sample);
8992 perf_output_end(&handle);
8996 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8998 struct hw_perf_event *hwc = &event->hw;
9002 seq = __this_cpu_read(perf_throttled_seq);
9003 if (seq != hwc->interrupts_seq) {
9004 hwc->interrupts_seq = seq;
9005 hwc->interrupts = 1;
9008 if (unlikely(throttle &&
9009 hwc->interrupts > max_samples_per_tick)) {
9010 __this_cpu_inc(perf_throttled_count);
9011 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9012 hwc->interrupts = MAX_INTERRUPTS;
9013 perf_log_throttle(event, 0);
9018 if (event->attr.freq) {
9019 u64 now = perf_clock();
9020 s64 delta = now - hwc->freq_time_stamp;
9022 hwc->freq_time_stamp = now;
9024 if (delta > 0 && delta < 2*TICK_NSEC)
9025 perf_adjust_period(event, delta, hwc->last_period, true);
9031 int perf_event_account_interrupt(struct perf_event *event)
9033 return __perf_event_account_interrupt(event, 1);
9037 * Generic event overflow handling, sampling.
9040 static int __perf_event_overflow(struct perf_event *event,
9041 int throttle, struct perf_sample_data *data,
9042 struct pt_regs *regs)
9044 int events = atomic_read(&event->event_limit);
9048 * Non-sampling counters might still use the PMI to fold short
9049 * hardware counters, ignore those.
9051 if (unlikely(!is_sampling_event(event)))
9054 ret = __perf_event_account_interrupt(event, throttle);
9057 * XXX event_limit might not quite work as expected on inherited
9061 event->pending_kill = POLL_IN;
9062 if (events && atomic_dec_and_test(&event->event_limit)) {
9064 event->pending_kill = POLL_HUP;
9066 perf_event_disable_inatomic(event);
9069 READ_ONCE(event->overflow_handler)(event, data, regs);
9071 if (*perf_event_fasync(event) && event->pending_kill) {
9072 event->pending_wakeup = 1;
9073 irq_work_queue(&event->pending);
9079 int perf_event_overflow(struct perf_event *event,
9080 struct perf_sample_data *data,
9081 struct pt_regs *regs)
9083 return __perf_event_overflow(event, 1, data, regs);
9087 * Generic software event infrastructure
9090 struct swevent_htable {
9091 struct swevent_hlist *swevent_hlist;
9092 struct mutex hlist_mutex;
9095 /* Recursion avoidance in each contexts */
9096 int recursion[PERF_NR_CONTEXTS];
9099 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9102 * We directly increment event->count and keep a second value in
9103 * event->hw.period_left to count intervals. This period event
9104 * is kept in the range [-sample_period, 0] so that we can use the
9108 u64 perf_swevent_set_period(struct perf_event *event)
9110 struct hw_perf_event *hwc = &event->hw;
9111 u64 period = hwc->last_period;
9115 hwc->last_period = hwc->sample_period;
9118 old = val = local64_read(&hwc->period_left);
9122 nr = div64_u64(period + val, period);
9123 offset = nr * period;
9125 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9131 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9132 struct perf_sample_data *data,
9133 struct pt_regs *regs)
9135 struct hw_perf_event *hwc = &event->hw;
9139 overflow = perf_swevent_set_period(event);
9141 if (hwc->interrupts == MAX_INTERRUPTS)
9144 for (; overflow; overflow--) {
9145 if (__perf_event_overflow(event, throttle,
9148 * We inhibit the overflow from happening when
9149 * hwc->interrupts == MAX_INTERRUPTS.
9157 static void perf_swevent_event(struct perf_event *event, u64 nr,
9158 struct perf_sample_data *data,
9159 struct pt_regs *regs)
9161 struct hw_perf_event *hwc = &event->hw;
9163 local64_add(nr, &event->count);
9168 if (!is_sampling_event(event))
9171 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9173 return perf_swevent_overflow(event, 1, data, regs);
9175 data->period = event->hw.last_period;
9177 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9178 return perf_swevent_overflow(event, 1, data, regs);
9180 if (local64_add_negative(nr, &hwc->period_left))
9183 perf_swevent_overflow(event, 0, data, regs);
9186 static int perf_exclude_event(struct perf_event *event,
9187 struct pt_regs *regs)
9189 if (event->hw.state & PERF_HES_STOPPED)
9193 if (event->attr.exclude_user && user_mode(regs))
9196 if (event->attr.exclude_kernel && !user_mode(regs))
9203 static int perf_swevent_match(struct perf_event *event,
9204 enum perf_type_id type,
9206 struct perf_sample_data *data,
9207 struct pt_regs *regs)
9209 if (event->attr.type != type)
9212 if (event->attr.config != event_id)
9215 if (perf_exclude_event(event, regs))
9221 static inline u64 swevent_hash(u64 type, u32 event_id)
9223 u64 val = event_id | (type << 32);
9225 return hash_64(val, SWEVENT_HLIST_BITS);
9228 static inline struct hlist_head *
9229 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9231 u64 hash = swevent_hash(type, event_id);
9233 return &hlist->heads[hash];
9236 /* For the read side: events when they trigger */
9237 static inline struct hlist_head *
9238 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9240 struct swevent_hlist *hlist;
9242 hlist = rcu_dereference(swhash->swevent_hlist);
9246 return __find_swevent_head(hlist, type, event_id);
9249 /* For the event head insertion and removal in the hlist */
9250 static inline struct hlist_head *
9251 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9253 struct swevent_hlist *hlist;
9254 u32 event_id = event->attr.config;
9255 u64 type = event->attr.type;
9258 * Event scheduling is always serialized against hlist allocation
9259 * and release. Which makes the protected version suitable here.
9260 * The context lock guarantees that.
9262 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9263 lockdep_is_held(&event->ctx->lock));
9267 return __find_swevent_head(hlist, type, event_id);
9270 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9272 struct perf_sample_data *data,
9273 struct pt_regs *regs)
9275 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9276 struct perf_event *event;
9277 struct hlist_head *head;
9280 head = find_swevent_head_rcu(swhash, type, event_id);
9284 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9285 if (perf_swevent_match(event, type, event_id, data, regs))
9286 perf_swevent_event(event, nr, data, regs);
9292 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9294 int perf_swevent_get_recursion_context(void)
9296 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9298 return get_recursion_context(swhash->recursion);
9300 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9302 void perf_swevent_put_recursion_context(int rctx)
9304 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9306 put_recursion_context(swhash->recursion, rctx);
9309 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9311 struct perf_sample_data data;
9313 if (WARN_ON_ONCE(!regs))
9316 perf_sample_data_init(&data, addr, 0);
9317 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9320 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9324 preempt_disable_notrace();
9325 rctx = perf_swevent_get_recursion_context();
9326 if (unlikely(rctx < 0))
9329 ___perf_sw_event(event_id, nr, regs, addr);
9331 perf_swevent_put_recursion_context(rctx);
9333 preempt_enable_notrace();
9336 static void perf_swevent_read(struct perf_event *event)
9340 static int perf_swevent_add(struct perf_event *event, int flags)
9342 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9343 struct hw_perf_event *hwc = &event->hw;
9344 struct hlist_head *head;
9346 if (is_sampling_event(event)) {
9347 hwc->last_period = hwc->sample_period;
9348 perf_swevent_set_period(event);
9351 hwc->state = !(flags & PERF_EF_START);
9353 head = find_swevent_head(swhash, event);
9354 if (WARN_ON_ONCE(!head))
9357 hlist_add_head_rcu(&event->hlist_entry, head);
9358 perf_event_update_userpage(event);
9363 static void perf_swevent_del(struct perf_event *event, int flags)
9365 hlist_del_rcu(&event->hlist_entry);
9368 static void perf_swevent_start(struct perf_event *event, int flags)
9370 event->hw.state = 0;
9373 static void perf_swevent_stop(struct perf_event *event, int flags)
9375 event->hw.state = PERF_HES_STOPPED;
9378 /* Deref the hlist from the update side */
9379 static inline struct swevent_hlist *
9380 swevent_hlist_deref(struct swevent_htable *swhash)
9382 return rcu_dereference_protected(swhash->swevent_hlist,
9383 lockdep_is_held(&swhash->hlist_mutex));
9386 static void swevent_hlist_release(struct swevent_htable *swhash)
9388 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9393 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9394 kfree_rcu(hlist, rcu_head);
9397 static void swevent_hlist_put_cpu(int cpu)
9399 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9401 mutex_lock(&swhash->hlist_mutex);
9403 if (!--swhash->hlist_refcount)
9404 swevent_hlist_release(swhash);
9406 mutex_unlock(&swhash->hlist_mutex);
9409 static void swevent_hlist_put(void)
9413 for_each_possible_cpu(cpu)
9414 swevent_hlist_put_cpu(cpu);
9417 static int swevent_hlist_get_cpu(int cpu)
9419 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9422 mutex_lock(&swhash->hlist_mutex);
9423 if (!swevent_hlist_deref(swhash) &&
9424 cpumask_test_cpu(cpu, perf_online_mask)) {
9425 struct swevent_hlist *hlist;
9427 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9432 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9434 swhash->hlist_refcount++;
9436 mutex_unlock(&swhash->hlist_mutex);
9441 static int swevent_hlist_get(void)
9443 int err, cpu, failed_cpu;
9445 mutex_lock(&pmus_lock);
9446 for_each_possible_cpu(cpu) {
9447 err = swevent_hlist_get_cpu(cpu);
9453 mutex_unlock(&pmus_lock);
9456 for_each_possible_cpu(cpu) {
9457 if (cpu == failed_cpu)
9459 swevent_hlist_put_cpu(cpu);
9461 mutex_unlock(&pmus_lock);
9465 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9467 static void sw_perf_event_destroy(struct perf_event *event)
9469 u64 event_id = event->attr.config;
9471 WARN_ON(event->parent);
9473 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9474 swevent_hlist_put();
9477 static int perf_swevent_init(struct perf_event *event)
9479 u64 event_id = event->attr.config;
9481 if (event->attr.type != PERF_TYPE_SOFTWARE)
9485 * no branch sampling for software events
9487 if (has_branch_stack(event))
9491 case PERF_COUNT_SW_CPU_CLOCK:
9492 case PERF_COUNT_SW_TASK_CLOCK:
9499 if (event_id >= PERF_COUNT_SW_MAX)
9502 if (!event->parent) {
9505 err = swevent_hlist_get();
9509 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9510 event->destroy = sw_perf_event_destroy;
9516 static struct pmu perf_swevent = {
9517 .task_ctx_nr = perf_sw_context,
9519 .capabilities = PERF_PMU_CAP_NO_NMI,
9521 .event_init = perf_swevent_init,
9522 .add = perf_swevent_add,
9523 .del = perf_swevent_del,
9524 .start = perf_swevent_start,
9525 .stop = perf_swevent_stop,
9526 .read = perf_swevent_read,
9529 #ifdef CONFIG_EVENT_TRACING
9531 static int perf_tp_filter_match(struct perf_event *event,
9532 struct perf_sample_data *data)
9534 void *record = data->raw->frag.data;
9536 /* only top level events have filters set */
9538 event = event->parent;
9540 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9545 static int perf_tp_event_match(struct perf_event *event,
9546 struct perf_sample_data *data,
9547 struct pt_regs *regs)
9549 if (event->hw.state & PERF_HES_STOPPED)
9552 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9554 if (event->attr.exclude_kernel && !user_mode(regs))
9557 if (!perf_tp_filter_match(event, data))
9563 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9564 struct trace_event_call *call, u64 count,
9565 struct pt_regs *regs, struct hlist_head *head,
9566 struct task_struct *task)
9568 if (bpf_prog_array_valid(call)) {
9569 *(struct pt_regs **)raw_data = regs;
9570 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9571 perf_swevent_put_recursion_context(rctx);
9575 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9578 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9580 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9581 struct pt_regs *regs, struct hlist_head *head, int rctx,
9582 struct task_struct *task)
9584 struct perf_sample_data data;
9585 struct perf_event *event;
9587 struct perf_raw_record raw = {
9594 perf_sample_data_init(&data, 0, 0);
9597 perf_trace_buf_update(record, event_type);
9599 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9600 if (perf_tp_event_match(event, &data, regs))
9601 perf_swevent_event(event, count, &data, regs);
9605 * If we got specified a target task, also iterate its context and
9606 * deliver this event there too.
9608 if (task && task != current) {
9609 struct perf_event_context *ctx;
9610 struct trace_entry *entry = record;
9613 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9617 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9618 if (event->cpu != smp_processor_id())
9620 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9622 if (event->attr.config != entry->type)
9624 if (perf_tp_event_match(event, &data, regs))
9625 perf_swevent_event(event, count, &data, regs);
9631 perf_swevent_put_recursion_context(rctx);
9633 EXPORT_SYMBOL_GPL(perf_tp_event);
9635 static void tp_perf_event_destroy(struct perf_event *event)
9637 perf_trace_destroy(event);
9640 static int perf_tp_event_init(struct perf_event *event)
9644 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9648 * no branch sampling for tracepoint events
9650 if (has_branch_stack(event))
9653 err = perf_trace_init(event);
9657 event->destroy = tp_perf_event_destroy;
9662 static struct pmu perf_tracepoint = {
9663 .task_ctx_nr = perf_sw_context,
9665 .event_init = perf_tp_event_init,
9666 .add = perf_trace_add,
9667 .del = perf_trace_del,
9668 .start = perf_swevent_start,
9669 .stop = perf_swevent_stop,
9670 .read = perf_swevent_read,
9673 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9675 * Flags in config, used by dynamic PMU kprobe and uprobe
9676 * The flags should match following PMU_FORMAT_ATTR().
9678 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9679 * if not set, create kprobe/uprobe
9681 * The following values specify a reference counter (or semaphore in the
9682 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9683 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9685 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9686 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9688 enum perf_probe_config {
9689 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9690 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9691 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9694 PMU_FORMAT_ATTR(retprobe, "config:0");
9697 #ifdef CONFIG_KPROBE_EVENTS
9698 static struct attribute *kprobe_attrs[] = {
9699 &format_attr_retprobe.attr,
9703 static struct attribute_group kprobe_format_group = {
9705 .attrs = kprobe_attrs,
9708 static const struct attribute_group *kprobe_attr_groups[] = {
9709 &kprobe_format_group,
9713 static int perf_kprobe_event_init(struct perf_event *event);
9714 static struct pmu perf_kprobe = {
9715 .task_ctx_nr = perf_sw_context,
9716 .event_init = perf_kprobe_event_init,
9717 .add = perf_trace_add,
9718 .del = perf_trace_del,
9719 .start = perf_swevent_start,
9720 .stop = perf_swevent_stop,
9721 .read = perf_swevent_read,
9722 .attr_groups = kprobe_attr_groups,
9725 static int perf_kprobe_event_init(struct perf_event *event)
9730 if (event->attr.type != perf_kprobe.type)
9733 if (!perfmon_capable())
9737 * no branch sampling for probe events
9739 if (has_branch_stack(event))
9742 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9743 err = perf_kprobe_init(event, is_retprobe);
9747 event->destroy = perf_kprobe_destroy;
9751 #endif /* CONFIG_KPROBE_EVENTS */
9753 #ifdef CONFIG_UPROBE_EVENTS
9754 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9756 static struct attribute *uprobe_attrs[] = {
9757 &format_attr_retprobe.attr,
9758 &format_attr_ref_ctr_offset.attr,
9762 static struct attribute_group uprobe_format_group = {
9764 .attrs = uprobe_attrs,
9767 static const struct attribute_group *uprobe_attr_groups[] = {
9768 &uprobe_format_group,
9772 static int perf_uprobe_event_init(struct perf_event *event);
9773 static struct pmu perf_uprobe = {
9774 .task_ctx_nr = perf_sw_context,
9775 .event_init = perf_uprobe_event_init,
9776 .add = perf_trace_add,
9777 .del = perf_trace_del,
9778 .start = perf_swevent_start,
9779 .stop = perf_swevent_stop,
9780 .read = perf_swevent_read,
9781 .attr_groups = uprobe_attr_groups,
9784 static int perf_uprobe_event_init(struct perf_event *event)
9787 unsigned long ref_ctr_offset;
9790 if (event->attr.type != perf_uprobe.type)
9793 if (!perfmon_capable())
9797 * no branch sampling for probe events
9799 if (has_branch_stack(event))
9802 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9803 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9804 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9808 event->destroy = perf_uprobe_destroy;
9812 #endif /* CONFIG_UPROBE_EVENTS */
9814 static inline void perf_tp_register(void)
9816 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9817 #ifdef CONFIG_KPROBE_EVENTS
9818 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9820 #ifdef CONFIG_UPROBE_EVENTS
9821 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9825 static void perf_event_free_filter(struct perf_event *event)
9827 ftrace_profile_free_filter(event);
9830 #ifdef CONFIG_BPF_SYSCALL
9831 static void bpf_overflow_handler(struct perf_event *event,
9832 struct perf_sample_data *data,
9833 struct pt_regs *regs)
9835 struct bpf_perf_event_data_kern ctx = {
9841 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9842 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9845 ret = BPF_PROG_RUN(event->prog, &ctx);
9848 __this_cpu_dec(bpf_prog_active);
9852 event->orig_overflow_handler(event, data, regs);
9855 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9857 struct bpf_prog *prog;
9859 if (event->overflow_handler_context)
9860 /* hw breakpoint or kernel counter */
9866 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9868 return PTR_ERR(prog);
9870 if (event->attr.precise_ip &&
9871 prog->call_get_stack &&
9872 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9873 event->attr.exclude_callchain_kernel ||
9874 event->attr.exclude_callchain_user)) {
9876 * On perf_event with precise_ip, calling bpf_get_stack()
9877 * may trigger unwinder warnings and occasional crashes.
9878 * bpf_get_[stack|stackid] works around this issue by using
9879 * callchain attached to perf_sample_data. If the
9880 * perf_event does not full (kernel and user) callchain
9881 * attached to perf_sample_data, do not allow attaching BPF
9882 * program that calls bpf_get_[stack|stackid].
9889 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9890 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9894 static void perf_event_free_bpf_handler(struct perf_event *event)
9896 struct bpf_prog *prog = event->prog;
9901 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9906 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9910 static void perf_event_free_bpf_handler(struct perf_event *event)
9916 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9917 * with perf_event_open()
9919 static inline bool perf_event_is_tracing(struct perf_event *event)
9921 if (event->pmu == &perf_tracepoint)
9923 #ifdef CONFIG_KPROBE_EVENTS
9924 if (event->pmu == &perf_kprobe)
9927 #ifdef CONFIG_UPROBE_EVENTS
9928 if (event->pmu == &perf_uprobe)
9934 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9936 bool is_kprobe, is_tracepoint, is_syscall_tp;
9937 struct bpf_prog *prog;
9940 if (!perf_event_is_tracing(event))
9941 return perf_event_set_bpf_handler(event, prog_fd);
9943 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9944 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9945 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9946 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9947 /* bpf programs can only be attached to u/kprobe or tracepoint */
9950 prog = bpf_prog_get(prog_fd);
9952 return PTR_ERR(prog);
9954 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9955 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9956 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9957 /* valid fd, but invalid bpf program type */
9962 /* Kprobe override only works for kprobes, not uprobes. */
9963 if (prog->kprobe_override &&
9964 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9969 if (is_tracepoint || is_syscall_tp) {
9970 int off = trace_event_get_offsets(event->tp_event);
9972 if (prog->aux->max_ctx_offset > off) {
9978 ret = perf_event_attach_bpf_prog(event, prog);
9984 static void perf_event_free_bpf_prog(struct perf_event *event)
9986 if (!perf_event_is_tracing(event)) {
9987 perf_event_free_bpf_handler(event);
9990 perf_event_detach_bpf_prog(event);
9995 static inline void perf_tp_register(void)
9999 static void perf_event_free_filter(struct perf_event *event)
10003 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
10008 static void perf_event_free_bpf_prog(struct perf_event *event)
10011 #endif /* CONFIG_EVENT_TRACING */
10013 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10014 void perf_bp_event(struct perf_event *bp, void *data)
10016 struct perf_sample_data sample;
10017 struct pt_regs *regs = data;
10019 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10021 if (!bp->hw.state && !perf_exclude_event(bp, regs))
10022 perf_swevent_event(bp, 1, &sample, regs);
10027 * Allocate a new address filter
10029 static struct perf_addr_filter *
10030 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10032 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10033 struct perf_addr_filter *filter;
10035 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10039 INIT_LIST_HEAD(&filter->entry);
10040 list_add_tail(&filter->entry, filters);
10045 static void free_filters_list(struct list_head *filters)
10047 struct perf_addr_filter *filter, *iter;
10049 list_for_each_entry_safe(filter, iter, filters, entry) {
10050 path_put(&filter->path);
10051 list_del(&filter->entry);
10057 * Free existing address filters and optionally install new ones
10059 static void perf_addr_filters_splice(struct perf_event *event,
10060 struct list_head *head)
10062 unsigned long flags;
10065 if (!has_addr_filter(event))
10068 /* don't bother with children, they don't have their own filters */
10072 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10074 list_splice_init(&event->addr_filters.list, &list);
10076 list_splice(head, &event->addr_filters.list);
10078 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10080 free_filters_list(&list);
10084 * Scan through mm's vmas and see if one of them matches the
10085 * @filter; if so, adjust filter's address range.
10086 * Called with mm::mmap_lock down for reading.
10088 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10089 struct mm_struct *mm,
10090 struct perf_addr_filter_range *fr)
10092 struct vm_area_struct *vma;
10094 for (vma = mm->mmap; vma; vma = vma->vm_next) {
10098 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10104 * Update event's address range filters based on the
10105 * task's existing mappings, if any.
10107 static void perf_event_addr_filters_apply(struct perf_event *event)
10109 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10110 struct task_struct *task = READ_ONCE(event->ctx->task);
10111 struct perf_addr_filter *filter;
10112 struct mm_struct *mm = NULL;
10113 unsigned int count = 0;
10114 unsigned long flags;
10117 * We may observe TASK_TOMBSTONE, which means that the event tear-down
10118 * will stop on the parent's child_mutex that our caller is also holding
10120 if (task == TASK_TOMBSTONE)
10123 if (ifh->nr_file_filters) {
10124 mm = get_task_mm(task);
10128 mmap_read_lock(mm);
10131 raw_spin_lock_irqsave(&ifh->lock, flags);
10132 list_for_each_entry(filter, &ifh->list, entry) {
10133 if (filter->path.dentry) {
10135 * Adjust base offset if the filter is associated to a
10136 * binary that needs to be mapped:
10138 event->addr_filter_ranges[count].start = 0;
10139 event->addr_filter_ranges[count].size = 0;
10141 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10143 event->addr_filter_ranges[count].start = filter->offset;
10144 event->addr_filter_ranges[count].size = filter->size;
10150 event->addr_filters_gen++;
10151 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10153 if (ifh->nr_file_filters) {
10154 mmap_read_unlock(mm);
10160 perf_event_stop(event, 1);
10164 * Address range filtering: limiting the data to certain
10165 * instruction address ranges. Filters are ioctl()ed to us from
10166 * userspace as ascii strings.
10168 * Filter string format:
10170 * ACTION RANGE_SPEC
10171 * where ACTION is one of the
10172 * * "filter": limit the trace to this region
10173 * * "start": start tracing from this address
10174 * * "stop": stop tracing at this address/region;
10176 * * for kernel addresses: <start address>[/<size>]
10177 * * for object files: <start address>[/<size>]@</path/to/object/file>
10179 * if <size> is not specified or is zero, the range is treated as a single
10180 * address; not valid for ACTION=="filter".
10194 IF_STATE_ACTION = 0,
10199 static const match_table_t if_tokens = {
10200 { IF_ACT_FILTER, "filter" },
10201 { IF_ACT_START, "start" },
10202 { IF_ACT_STOP, "stop" },
10203 { IF_SRC_FILE, "%u/%u@%s" },
10204 { IF_SRC_KERNEL, "%u/%u" },
10205 { IF_SRC_FILEADDR, "%u@%s" },
10206 { IF_SRC_KERNELADDR, "%u" },
10207 { IF_ACT_NONE, NULL },
10211 * Address filter string parser
10214 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10215 struct list_head *filters)
10217 struct perf_addr_filter *filter = NULL;
10218 char *start, *orig, *filename = NULL;
10219 substring_t args[MAX_OPT_ARGS];
10220 int state = IF_STATE_ACTION, token;
10221 unsigned int kernel = 0;
10224 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10228 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10229 static const enum perf_addr_filter_action_t actions[] = {
10230 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10231 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10232 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10239 /* filter definition begins */
10240 if (state == IF_STATE_ACTION) {
10241 filter = perf_addr_filter_new(event, filters);
10246 token = match_token(start, if_tokens, args);
10248 case IF_ACT_FILTER:
10251 if (state != IF_STATE_ACTION)
10254 filter->action = actions[token];
10255 state = IF_STATE_SOURCE;
10258 case IF_SRC_KERNELADDR:
10259 case IF_SRC_KERNEL:
10263 case IF_SRC_FILEADDR:
10265 if (state != IF_STATE_SOURCE)
10269 ret = kstrtoul(args[0].from, 0, &filter->offset);
10273 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10275 ret = kstrtoul(args[1].from, 0, &filter->size);
10280 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10281 int fpos = token == IF_SRC_FILE ? 2 : 1;
10284 filename = match_strdup(&args[fpos]);
10291 state = IF_STATE_END;
10299 * Filter definition is fully parsed, validate and install it.
10300 * Make sure that it doesn't contradict itself or the event's
10303 if (state == IF_STATE_END) {
10305 if (kernel && event->attr.exclude_kernel)
10309 * ACTION "filter" must have a non-zero length region
10312 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10321 * For now, we only support file-based filters
10322 * in per-task events; doing so for CPU-wide
10323 * events requires additional context switching
10324 * trickery, since same object code will be
10325 * mapped at different virtual addresses in
10326 * different processes.
10329 if (!event->ctx->task)
10332 /* look up the path and grab its inode */
10333 ret = kern_path(filename, LOOKUP_FOLLOW,
10339 if (!filter->path.dentry ||
10340 !S_ISREG(d_inode(filter->path.dentry)
10344 event->addr_filters.nr_file_filters++;
10347 /* ready to consume more filters */
10350 state = IF_STATE_ACTION;
10356 if (state != IF_STATE_ACTION)
10366 free_filters_list(filters);
10373 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10375 LIST_HEAD(filters);
10379 * Since this is called in perf_ioctl() path, we're already holding
10382 lockdep_assert_held(&event->ctx->mutex);
10384 if (WARN_ON_ONCE(event->parent))
10387 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10389 goto fail_clear_files;
10391 ret = event->pmu->addr_filters_validate(&filters);
10393 goto fail_free_filters;
10395 /* remove existing filters, if any */
10396 perf_addr_filters_splice(event, &filters);
10398 /* install new filters */
10399 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10404 free_filters_list(&filters);
10407 event->addr_filters.nr_file_filters = 0;
10412 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10417 filter_str = strndup_user(arg, PAGE_SIZE);
10418 if (IS_ERR(filter_str))
10419 return PTR_ERR(filter_str);
10421 #ifdef CONFIG_EVENT_TRACING
10422 if (perf_event_is_tracing(event)) {
10423 struct perf_event_context *ctx = event->ctx;
10426 * Beware, here be dragons!!
10428 * the tracepoint muck will deadlock against ctx->mutex, but
10429 * the tracepoint stuff does not actually need it. So
10430 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10431 * already have a reference on ctx.
10433 * This can result in event getting moved to a different ctx,
10434 * but that does not affect the tracepoint state.
10436 mutex_unlock(&ctx->mutex);
10437 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10438 mutex_lock(&ctx->mutex);
10441 if (has_addr_filter(event))
10442 ret = perf_event_set_addr_filter(event, filter_str);
10449 * hrtimer based swevent callback
10452 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10454 enum hrtimer_restart ret = HRTIMER_RESTART;
10455 struct perf_sample_data data;
10456 struct pt_regs *regs;
10457 struct perf_event *event;
10460 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10462 if (event->state != PERF_EVENT_STATE_ACTIVE)
10463 return HRTIMER_NORESTART;
10465 event->pmu->read(event);
10467 perf_sample_data_init(&data, 0, event->hw.last_period);
10468 regs = get_irq_regs();
10470 if (regs && !perf_exclude_event(event, regs)) {
10471 if (!(event->attr.exclude_idle && is_idle_task(current)))
10472 if (__perf_event_overflow(event, 1, &data, regs))
10473 ret = HRTIMER_NORESTART;
10476 period = max_t(u64, 10000, event->hw.sample_period);
10477 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10482 static void perf_swevent_start_hrtimer(struct perf_event *event)
10484 struct hw_perf_event *hwc = &event->hw;
10487 if (!is_sampling_event(event))
10490 period = local64_read(&hwc->period_left);
10495 local64_set(&hwc->period_left, 0);
10497 period = max_t(u64, 10000, hwc->sample_period);
10499 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10500 HRTIMER_MODE_REL_PINNED_HARD);
10503 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10505 struct hw_perf_event *hwc = &event->hw;
10507 if (is_sampling_event(event)) {
10508 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10509 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10511 hrtimer_cancel(&hwc->hrtimer);
10515 static void perf_swevent_init_hrtimer(struct perf_event *event)
10517 struct hw_perf_event *hwc = &event->hw;
10519 if (!is_sampling_event(event))
10522 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10523 hwc->hrtimer.function = perf_swevent_hrtimer;
10526 * Since hrtimers have a fixed rate, we can do a static freq->period
10527 * mapping and avoid the whole period adjust feedback stuff.
10529 if (event->attr.freq) {
10530 long freq = event->attr.sample_freq;
10532 event->attr.sample_period = NSEC_PER_SEC / freq;
10533 hwc->sample_period = event->attr.sample_period;
10534 local64_set(&hwc->period_left, hwc->sample_period);
10535 hwc->last_period = hwc->sample_period;
10536 event->attr.freq = 0;
10541 * Software event: cpu wall time clock
10544 static void cpu_clock_event_update(struct perf_event *event)
10549 now = local_clock();
10550 prev = local64_xchg(&event->hw.prev_count, now);
10551 local64_add(now - prev, &event->count);
10554 static void cpu_clock_event_start(struct perf_event *event, int flags)
10556 local64_set(&event->hw.prev_count, local_clock());
10557 perf_swevent_start_hrtimer(event);
10560 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10562 perf_swevent_cancel_hrtimer(event);
10563 cpu_clock_event_update(event);
10566 static int cpu_clock_event_add(struct perf_event *event, int flags)
10568 if (flags & PERF_EF_START)
10569 cpu_clock_event_start(event, flags);
10570 perf_event_update_userpage(event);
10575 static void cpu_clock_event_del(struct perf_event *event, int flags)
10577 cpu_clock_event_stop(event, flags);
10580 static void cpu_clock_event_read(struct perf_event *event)
10582 cpu_clock_event_update(event);
10585 static int cpu_clock_event_init(struct perf_event *event)
10587 if (event->attr.type != PERF_TYPE_SOFTWARE)
10590 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10594 * no branch sampling for software events
10596 if (has_branch_stack(event))
10597 return -EOPNOTSUPP;
10599 perf_swevent_init_hrtimer(event);
10604 static struct pmu perf_cpu_clock = {
10605 .task_ctx_nr = perf_sw_context,
10607 .capabilities = PERF_PMU_CAP_NO_NMI,
10609 .event_init = cpu_clock_event_init,
10610 .add = cpu_clock_event_add,
10611 .del = cpu_clock_event_del,
10612 .start = cpu_clock_event_start,
10613 .stop = cpu_clock_event_stop,
10614 .read = cpu_clock_event_read,
10618 * Software event: task time clock
10621 static void task_clock_event_update(struct perf_event *event, u64 now)
10626 prev = local64_xchg(&event->hw.prev_count, now);
10627 delta = now - prev;
10628 local64_add(delta, &event->count);
10631 static void task_clock_event_start(struct perf_event *event, int flags)
10633 local64_set(&event->hw.prev_count, event->ctx->time);
10634 perf_swevent_start_hrtimer(event);
10637 static void task_clock_event_stop(struct perf_event *event, int flags)
10639 perf_swevent_cancel_hrtimer(event);
10640 task_clock_event_update(event, event->ctx->time);
10643 static int task_clock_event_add(struct perf_event *event, int flags)
10645 if (flags & PERF_EF_START)
10646 task_clock_event_start(event, flags);
10647 perf_event_update_userpage(event);
10652 static void task_clock_event_del(struct perf_event *event, int flags)
10654 task_clock_event_stop(event, PERF_EF_UPDATE);
10657 static void task_clock_event_read(struct perf_event *event)
10659 u64 now = perf_clock();
10660 u64 delta = now - event->ctx->timestamp;
10661 u64 time = event->ctx->time + delta;
10663 task_clock_event_update(event, time);
10666 static int task_clock_event_init(struct perf_event *event)
10668 if (event->attr.type != PERF_TYPE_SOFTWARE)
10671 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10675 * no branch sampling for software events
10677 if (has_branch_stack(event))
10678 return -EOPNOTSUPP;
10680 perf_swevent_init_hrtimer(event);
10685 static struct pmu perf_task_clock = {
10686 .task_ctx_nr = perf_sw_context,
10688 .capabilities = PERF_PMU_CAP_NO_NMI,
10690 .event_init = task_clock_event_init,
10691 .add = task_clock_event_add,
10692 .del = task_clock_event_del,
10693 .start = task_clock_event_start,
10694 .stop = task_clock_event_stop,
10695 .read = task_clock_event_read,
10698 static void perf_pmu_nop_void(struct pmu *pmu)
10702 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10706 static int perf_pmu_nop_int(struct pmu *pmu)
10711 static int perf_event_nop_int(struct perf_event *event, u64 value)
10716 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10718 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10720 __this_cpu_write(nop_txn_flags, flags);
10722 if (flags & ~PERF_PMU_TXN_ADD)
10725 perf_pmu_disable(pmu);
10728 static int perf_pmu_commit_txn(struct pmu *pmu)
10730 unsigned int flags = __this_cpu_read(nop_txn_flags);
10732 __this_cpu_write(nop_txn_flags, 0);
10734 if (flags & ~PERF_PMU_TXN_ADD)
10737 perf_pmu_enable(pmu);
10741 static void perf_pmu_cancel_txn(struct pmu *pmu)
10743 unsigned int flags = __this_cpu_read(nop_txn_flags);
10745 __this_cpu_write(nop_txn_flags, 0);
10747 if (flags & ~PERF_PMU_TXN_ADD)
10750 perf_pmu_enable(pmu);
10753 static int perf_event_idx_default(struct perf_event *event)
10759 * Ensures all contexts with the same task_ctx_nr have the same
10760 * pmu_cpu_context too.
10762 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10769 list_for_each_entry(pmu, &pmus, entry) {
10770 if (pmu->task_ctx_nr == ctxn)
10771 return pmu->pmu_cpu_context;
10777 static void free_pmu_context(struct pmu *pmu)
10780 * Static contexts such as perf_sw_context have a global lifetime
10781 * and may be shared between different PMUs. Avoid freeing them
10782 * when a single PMU is going away.
10784 if (pmu->task_ctx_nr > perf_invalid_context)
10787 free_percpu(pmu->pmu_cpu_context);
10791 * Let userspace know that this PMU supports address range filtering:
10793 static ssize_t nr_addr_filters_show(struct device *dev,
10794 struct device_attribute *attr,
10797 struct pmu *pmu = dev_get_drvdata(dev);
10799 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10801 DEVICE_ATTR_RO(nr_addr_filters);
10803 static struct idr pmu_idr;
10806 type_show(struct device *dev, struct device_attribute *attr, char *page)
10808 struct pmu *pmu = dev_get_drvdata(dev);
10810 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10812 static DEVICE_ATTR_RO(type);
10815 perf_event_mux_interval_ms_show(struct device *dev,
10816 struct device_attribute *attr,
10819 struct pmu *pmu = dev_get_drvdata(dev);
10821 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10824 static DEFINE_MUTEX(mux_interval_mutex);
10827 perf_event_mux_interval_ms_store(struct device *dev,
10828 struct device_attribute *attr,
10829 const char *buf, size_t count)
10831 struct pmu *pmu = dev_get_drvdata(dev);
10832 int timer, cpu, ret;
10834 ret = kstrtoint(buf, 0, &timer);
10841 /* same value, noting to do */
10842 if (timer == pmu->hrtimer_interval_ms)
10845 mutex_lock(&mux_interval_mutex);
10846 pmu->hrtimer_interval_ms = timer;
10848 /* update all cpuctx for this PMU */
10850 for_each_online_cpu(cpu) {
10851 struct perf_cpu_context *cpuctx;
10852 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10853 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10855 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpuctx);
10857 cpus_read_unlock();
10858 mutex_unlock(&mux_interval_mutex);
10862 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10864 static struct attribute *pmu_dev_attrs[] = {
10865 &dev_attr_type.attr,
10866 &dev_attr_perf_event_mux_interval_ms.attr,
10867 &dev_attr_nr_addr_filters.attr,
10871 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
10873 struct device *dev = kobj_to_dev(kobj);
10874 struct pmu *pmu = dev_get_drvdata(dev);
10876 if (n == 2 && !pmu->nr_addr_filters)
10882 static struct attribute_group pmu_dev_attr_group = {
10883 .is_visible = pmu_dev_is_visible,
10884 .attrs = pmu_dev_attrs,
10887 static const struct attribute_group *pmu_dev_groups[] = {
10888 &pmu_dev_attr_group,
10892 static int pmu_bus_running;
10893 static struct bus_type pmu_bus = {
10894 .name = "event_source",
10895 .dev_groups = pmu_dev_groups,
10898 static void pmu_dev_release(struct device *dev)
10903 static int pmu_dev_alloc(struct pmu *pmu)
10907 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10911 pmu->dev->groups = pmu->attr_groups;
10912 device_initialize(pmu->dev);
10914 dev_set_drvdata(pmu->dev, pmu);
10915 pmu->dev->bus = &pmu_bus;
10916 pmu->dev->release = pmu_dev_release;
10918 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10922 ret = device_add(pmu->dev);
10926 if (pmu->attr_update) {
10927 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10936 device_del(pmu->dev);
10939 put_device(pmu->dev);
10943 static struct lock_class_key cpuctx_mutex;
10944 static struct lock_class_key cpuctx_lock;
10946 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10948 int cpu, ret, max = PERF_TYPE_MAX;
10950 mutex_lock(&pmus_lock);
10952 pmu->pmu_disable_count = alloc_percpu(int);
10953 if (!pmu->pmu_disable_count)
10961 if (type != PERF_TYPE_SOFTWARE) {
10965 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10969 WARN_ON(type >= 0 && ret != type);
10975 if (pmu_bus_running) {
10976 ret = pmu_dev_alloc(pmu);
10982 if (pmu->task_ctx_nr == perf_hw_context) {
10983 static int hw_context_taken = 0;
10986 * Other than systems with heterogeneous CPUs, it never makes
10987 * sense for two PMUs to share perf_hw_context. PMUs which are
10988 * uncore must use perf_invalid_context.
10990 if (WARN_ON_ONCE(hw_context_taken &&
10991 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10992 pmu->task_ctx_nr = perf_invalid_context;
10994 hw_context_taken = 1;
10997 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10998 if (pmu->pmu_cpu_context)
10999 goto got_cpu_context;
11002 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
11003 if (!pmu->pmu_cpu_context)
11006 for_each_possible_cpu(cpu) {
11007 struct perf_cpu_context *cpuctx;
11009 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
11010 __perf_event_init_context(&cpuctx->ctx);
11011 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
11012 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
11013 cpuctx->ctx.pmu = pmu;
11014 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
11016 __perf_mux_hrtimer_init(cpuctx, cpu);
11018 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
11019 cpuctx->heap = cpuctx->heap_default;
11023 if (!pmu->start_txn) {
11024 if (pmu->pmu_enable) {
11026 * If we have pmu_enable/pmu_disable calls, install
11027 * transaction stubs that use that to try and batch
11028 * hardware accesses.
11030 pmu->start_txn = perf_pmu_start_txn;
11031 pmu->commit_txn = perf_pmu_commit_txn;
11032 pmu->cancel_txn = perf_pmu_cancel_txn;
11034 pmu->start_txn = perf_pmu_nop_txn;
11035 pmu->commit_txn = perf_pmu_nop_int;
11036 pmu->cancel_txn = perf_pmu_nop_void;
11040 if (!pmu->pmu_enable) {
11041 pmu->pmu_enable = perf_pmu_nop_void;
11042 pmu->pmu_disable = perf_pmu_nop_void;
11045 if (!pmu->check_period)
11046 pmu->check_period = perf_event_nop_int;
11048 if (!pmu->event_idx)
11049 pmu->event_idx = perf_event_idx_default;
11052 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
11053 * since these cannot be in the IDR. This way the linear search
11054 * is fast, provided a valid software event is provided.
11056 if (type == PERF_TYPE_SOFTWARE || !name)
11057 list_add_rcu(&pmu->entry, &pmus);
11059 list_add_tail_rcu(&pmu->entry, &pmus);
11061 atomic_set(&pmu->exclusive_cnt, 0);
11064 mutex_unlock(&pmus_lock);
11069 device_del(pmu->dev);
11070 put_device(pmu->dev);
11073 if (pmu->type != PERF_TYPE_SOFTWARE)
11074 idr_remove(&pmu_idr, pmu->type);
11077 free_percpu(pmu->pmu_disable_count);
11080 EXPORT_SYMBOL_GPL(perf_pmu_register);
11082 void perf_pmu_unregister(struct pmu *pmu)
11084 mutex_lock(&pmus_lock);
11085 list_del_rcu(&pmu->entry);
11088 * We dereference the pmu list under both SRCU and regular RCU, so
11089 * synchronize against both of those.
11091 synchronize_srcu(&pmus_srcu);
11094 free_percpu(pmu->pmu_disable_count);
11095 if (pmu->type != PERF_TYPE_SOFTWARE)
11096 idr_remove(&pmu_idr, pmu->type);
11097 if (pmu_bus_running) {
11098 if (pmu->nr_addr_filters)
11099 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11100 device_del(pmu->dev);
11101 put_device(pmu->dev);
11103 free_pmu_context(pmu);
11104 mutex_unlock(&pmus_lock);
11106 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11108 static inline bool has_extended_regs(struct perf_event *event)
11110 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11111 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11114 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11116 struct perf_event_context *ctx = NULL;
11119 if (!try_module_get(pmu->module))
11123 * A number of pmu->event_init() methods iterate the sibling_list to,
11124 * for example, validate if the group fits on the PMU. Therefore,
11125 * if this is a sibling event, acquire the ctx->mutex to protect
11126 * the sibling_list.
11128 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11130 * This ctx->mutex can nest when we're called through
11131 * inheritance. See the perf_event_ctx_lock_nested() comment.
11133 ctx = perf_event_ctx_lock_nested(event->group_leader,
11134 SINGLE_DEPTH_NESTING);
11139 ret = pmu->event_init(event);
11142 perf_event_ctx_unlock(event->group_leader, ctx);
11145 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11146 has_extended_regs(event))
11149 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11150 event_has_any_exclude_flag(event))
11153 if (ret && event->destroy)
11154 event->destroy(event);
11158 module_put(pmu->module);
11163 static struct pmu *perf_init_event(struct perf_event *event)
11165 int idx, type, ret;
11168 idx = srcu_read_lock(&pmus_srcu);
11170 /* Try parent's PMU first: */
11171 if (event->parent && event->parent->pmu) {
11172 pmu = event->parent->pmu;
11173 ret = perf_try_init_event(pmu, event);
11179 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11180 * are often aliases for PERF_TYPE_RAW.
11182 type = event->attr.type;
11183 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11184 type = PERF_TYPE_RAW;
11188 pmu = idr_find(&pmu_idr, type);
11191 ret = perf_try_init_event(pmu, event);
11192 if (ret == -ENOENT && event->attr.type != type) {
11193 type = event->attr.type;
11198 pmu = ERR_PTR(ret);
11203 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11204 ret = perf_try_init_event(pmu, event);
11208 if (ret != -ENOENT) {
11209 pmu = ERR_PTR(ret);
11213 pmu = ERR_PTR(-ENOENT);
11215 srcu_read_unlock(&pmus_srcu, idx);
11220 static void attach_sb_event(struct perf_event *event)
11222 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11224 raw_spin_lock(&pel->lock);
11225 list_add_rcu(&event->sb_list, &pel->list);
11226 raw_spin_unlock(&pel->lock);
11230 * We keep a list of all !task (and therefore per-cpu) events
11231 * that need to receive side-band records.
11233 * This avoids having to scan all the various PMU per-cpu contexts
11234 * looking for them.
11236 static void account_pmu_sb_event(struct perf_event *event)
11238 if (is_sb_event(event))
11239 attach_sb_event(event);
11242 static void account_event_cpu(struct perf_event *event, int cpu)
11247 if (is_cgroup_event(event))
11248 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11251 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11252 static void account_freq_event_nohz(void)
11254 #ifdef CONFIG_NO_HZ_FULL
11255 /* Lock so we don't race with concurrent unaccount */
11256 spin_lock(&nr_freq_lock);
11257 if (atomic_inc_return(&nr_freq_events) == 1)
11258 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11259 spin_unlock(&nr_freq_lock);
11263 static void account_freq_event(void)
11265 if (tick_nohz_full_enabled())
11266 account_freq_event_nohz();
11268 atomic_inc(&nr_freq_events);
11272 static void account_event(struct perf_event *event)
11279 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11281 if (event->attr.mmap || event->attr.mmap_data)
11282 atomic_inc(&nr_mmap_events);
11283 if (event->attr.comm)
11284 atomic_inc(&nr_comm_events);
11285 if (event->attr.namespaces)
11286 atomic_inc(&nr_namespaces_events);
11287 if (event->attr.cgroup)
11288 atomic_inc(&nr_cgroup_events);
11289 if (event->attr.task)
11290 atomic_inc(&nr_task_events);
11291 if (event->attr.freq)
11292 account_freq_event();
11293 if (event->attr.context_switch) {
11294 atomic_inc(&nr_switch_events);
11297 if (has_branch_stack(event))
11299 if (is_cgroup_event(event))
11301 if (event->attr.ksymbol)
11302 atomic_inc(&nr_ksymbol_events);
11303 if (event->attr.bpf_event)
11304 atomic_inc(&nr_bpf_events);
11305 if (event->attr.text_poke)
11306 atomic_inc(&nr_text_poke_events);
11310 * We need the mutex here because static_branch_enable()
11311 * must complete *before* the perf_sched_count increment
11314 if (atomic_inc_not_zero(&perf_sched_count))
11317 mutex_lock(&perf_sched_mutex);
11318 if (!atomic_read(&perf_sched_count)) {
11319 static_branch_enable(&perf_sched_events);
11321 * Guarantee that all CPUs observe they key change and
11322 * call the perf scheduling hooks before proceeding to
11323 * install events that need them.
11328 * Now that we have waited for the sync_sched(), allow further
11329 * increments to by-pass the mutex.
11331 atomic_inc(&perf_sched_count);
11332 mutex_unlock(&perf_sched_mutex);
11336 account_event_cpu(event, event->cpu);
11338 account_pmu_sb_event(event);
11342 * Allocate and initialize an event structure
11344 static struct perf_event *
11345 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11346 struct task_struct *task,
11347 struct perf_event *group_leader,
11348 struct perf_event *parent_event,
11349 perf_overflow_handler_t overflow_handler,
11350 void *context, int cgroup_fd)
11353 struct perf_event *event;
11354 struct hw_perf_event *hwc;
11355 long err = -EINVAL;
11357 if ((unsigned)cpu >= nr_cpu_ids) {
11358 if (!task || cpu != -1)
11359 return ERR_PTR(-EINVAL);
11362 event = kzalloc(sizeof(*event), GFP_KERNEL);
11364 return ERR_PTR(-ENOMEM);
11367 * Single events are their own group leaders, with an
11368 * empty sibling list:
11371 group_leader = event;
11373 mutex_init(&event->child_mutex);
11374 INIT_LIST_HEAD(&event->child_list);
11376 INIT_LIST_HEAD(&event->event_entry);
11377 INIT_LIST_HEAD(&event->sibling_list);
11378 INIT_LIST_HEAD(&event->active_list);
11379 init_event_group(event);
11380 INIT_LIST_HEAD(&event->rb_entry);
11381 INIT_LIST_HEAD(&event->active_entry);
11382 INIT_LIST_HEAD(&event->addr_filters.list);
11383 INIT_HLIST_NODE(&event->hlist_entry);
11386 init_waitqueue_head(&event->waitq);
11387 event->pending_disable = -1;
11388 init_irq_work(&event->pending, perf_pending_event);
11390 mutex_init(&event->mmap_mutex);
11391 raw_spin_lock_init(&event->addr_filters.lock);
11393 atomic_long_set(&event->refcount, 1);
11395 event->attr = *attr;
11396 event->group_leader = group_leader;
11400 event->parent = parent_event;
11402 event->ns = get_pid_ns(task_active_pid_ns(current));
11403 event->id = atomic64_inc_return(&perf_event_id);
11405 event->state = PERF_EVENT_STATE_INACTIVE;
11408 event->attach_state = PERF_ATTACH_TASK;
11410 * XXX pmu::event_init needs to know what task to account to
11411 * and we cannot use the ctx information because we need the
11412 * pmu before we get a ctx.
11414 event->hw.target = get_task_struct(task);
11417 event->clock = &local_clock;
11419 event->clock = parent_event->clock;
11421 if (!overflow_handler && parent_event) {
11422 overflow_handler = parent_event->overflow_handler;
11423 context = parent_event->overflow_handler_context;
11424 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11425 if (overflow_handler == bpf_overflow_handler) {
11426 struct bpf_prog *prog = parent_event->prog;
11428 bpf_prog_inc(prog);
11429 event->prog = prog;
11430 event->orig_overflow_handler =
11431 parent_event->orig_overflow_handler;
11436 if (overflow_handler) {
11437 event->overflow_handler = overflow_handler;
11438 event->overflow_handler_context = context;
11439 } else if (is_write_backward(event)){
11440 event->overflow_handler = perf_event_output_backward;
11441 event->overflow_handler_context = NULL;
11443 event->overflow_handler = perf_event_output_forward;
11444 event->overflow_handler_context = NULL;
11447 perf_event__state_init(event);
11452 hwc->sample_period = attr->sample_period;
11453 if (attr->freq && attr->sample_freq)
11454 hwc->sample_period = 1;
11455 hwc->last_period = hwc->sample_period;
11457 local64_set(&hwc->period_left, hwc->sample_period);
11460 * We currently do not support PERF_SAMPLE_READ on inherited events.
11461 * See perf_output_read().
11463 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11466 if (!has_branch_stack(event))
11467 event->attr.branch_sample_type = 0;
11469 pmu = perf_init_event(event);
11471 err = PTR_ERR(pmu);
11476 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11477 * be different on other CPUs in the uncore mask.
11479 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11484 if (event->attr.aux_output &&
11485 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11490 if (cgroup_fd != -1) {
11491 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11496 err = exclusive_event_init(event);
11500 if (has_addr_filter(event)) {
11501 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11502 sizeof(struct perf_addr_filter_range),
11504 if (!event->addr_filter_ranges) {
11510 * Clone the parent's vma offsets: they are valid until exec()
11511 * even if the mm is not shared with the parent.
11513 if (event->parent) {
11514 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11516 raw_spin_lock_irq(&ifh->lock);
11517 memcpy(event->addr_filter_ranges,
11518 event->parent->addr_filter_ranges,
11519 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11520 raw_spin_unlock_irq(&ifh->lock);
11523 /* force hw sync on the address filters */
11524 event->addr_filters_gen = 1;
11527 if (!event->parent) {
11528 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11529 err = get_callchain_buffers(attr->sample_max_stack);
11531 goto err_addr_filters;
11535 err = security_perf_event_alloc(event);
11537 goto err_callchain_buffer;
11539 /* symmetric to unaccount_event() in _free_event() */
11540 account_event(event);
11544 err_callchain_buffer:
11545 if (!event->parent) {
11546 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11547 put_callchain_buffers();
11550 kfree(event->addr_filter_ranges);
11553 exclusive_event_destroy(event);
11556 if (is_cgroup_event(event))
11557 perf_detach_cgroup(event);
11558 if (event->destroy)
11559 event->destroy(event);
11560 module_put(pmu->module);
11563 put_pid_ns(event->ns);
11564 if (event->hw.target)
11565 put_task_struct(event->hw.target);
11568 return ERR_PTR(err);
11571 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11572 struct perf_event_attr *attr)
11577 /* Zero the full structure, so that a short copy will be nice. */
11578 memset(attr, 0, sizeof(*attr));
11580 ret = get_user(size, &uattr->size);
11584 /* ABI compatibility quirk: */
11586 size = PERF_ATTR_SIZE_VER0;
11587 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11590 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11599 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11602 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11605 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11608 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11609 u64 mask = attr->branch_sample_type;
11611 /* only using defined bits */
11612 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11615 /* at least one branch bit must be set */
11616 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11619 /* propagate priv level, when not set for branch */
11620 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11622 /* exclude_kernel checked on syscall entry */
11623 if (!attr->exclude_kernel)
11624 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11626 if (!attr->exclude_user)
11627 mask |= PERF_SAMPLE_BRANCH_USER;
11629 if (!attr->exclude_hv)
11630 mask |= PERF_SAMPLE_BRANCH_HV;
11632 * adjust user setting (for HW filter setup)
11634 attr->branch_sample_type = mask;
11636 /* privileged levels capture (kernel, hv): check permissions */
11637 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11638 ret = perf_allow_kernel(attr);
11644 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11645 ret = perf_reg_validate(attr->sample_regs_user);
11650 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11651 if (!arch_perf_have_user_stack_dump())
11655 * We have __u32 type for the size, but so far
11656 * we can only use __u16 as maximum due to the
11657 * __u16 sample size limit.
11659 if (attr->sample_stack_user >= USHRT_MAX)
11661 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11665 if (!attr->sample_max_stack)
11666 attr->sample_max_stack = sysctl_perf_event_max_stack;
11668 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11669 ret = perf_reg_validate(attr->sample_regs_intr);
11671 #ifndef CONFIG_CGROUP_PERF
11672 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11680 put_user(sizeof(*attr), &uattr->size);
11685 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11691 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11695 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11697 struct perf_buffer *rb = NULL;
11700 if (!output_event) {
11701 mutex_lock(&event->mmap_mutex);
11705 /* don't allow circular references */
11706 if (event == output_event)
11710 * Don't allow cross-cpu buffers
11712 if (output_event->cpu != event->cpu)
11716 * If its not a per-cpu rb, it must be the same task.
11718 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
11722 * Mixing clocks in the same buffer is trouble you don't need.
11724 if (output_event->clock != event->clock)
11728 * Either writing ring buffer from beginning or from end.
11729 * Mixing is not allowed.
11731 if (is_write_backward(output_event) != is_write_backward(event))
11735 * If both events generate aux data, they must be on the same PMU
11737 if (has_aux(event) && has_aux(output_event) &&
11738 event->pmu != output_event->pmu)
11742 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
11743 * output_event is already on rb->event_list, and the list iteration
11744 * restarts after every removal, it is guaranteed this new event is
11745 * observed *OR* if output_event is already removed, it's guaranteed we
11746 * observe !rb->mmap_count.
11748 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
11750 /* Can't redirect output if we've got an active mmap() */
11751 if (atomic_read(&event->mmap_count))
11754 if (output_event) {
11755 /* get the rb we want to redirect to */
11756 rb = ring_buffer_get(output_event);
11760 /* did we race against perf_mmap_close() */
11761 if (!atomic_read(&rb->mmap_count)) {
11762 ring_buffer_put(rb);
11767 ring_buffer_attach(event, rb);
11771 mutex_unlock(&event->mmap_mutex);
11773 mutex_unlock(&output_event->mmap_mutex);
11779 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11781 bool nmi_safe = false;
11784 case CLOCK_MONOTONIC:
11785 event->clock = &ktime_get_mono_fast_ns;
11789 case CLOCK_MONOTONIC_RAW:
11790 event->clock = &ktime_get_raw_fast_ns;
11794 case CLOCK_REALTIME:
11795 event->clock = &ktime_get_real_ns;
11798 case CLOCK_BOOTTIME:
11799 event->clock = &ktime_get_boottime_ns;
11803 event->clock = &ktime_get_clocktai_ns;
11810 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11817 * Variation on perf_event_ctx_lock_nested(), except we take two context
11820 static struct perf_event_context *
11821 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11822 struct perf_event_context *ctx)
11824 struct perf_event_context *gctx;
11828 gctx = READ_ONCE(group_leader->ctx);
11829 if (!refcount_inc_not_zero(&gctx->refcount)) {
11835 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11837 if (group_leader->ctx != gctx) {
11838 mutex_unlock(&ctx->mutex);
11839 mutex_unlock(&gctx->mutex);
11848 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11850 * @attr_uptr: event_id type attributes for monitoring/sampling
11853 * @group_fd: group leader event fd
11855 SYSCALL_DEFINE5(perf_event_open,
11856 struct perf_event_attr __user *, attr_uptr,
11857 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11859 struct perf_event *group_leader = NULL, *output_event = NULL;
11860 struct perf_event *event, *sibling;
11861 struct perf_event_attr attr;
11862 struct perf_event_context *ctx, *gctx;
11863 struct file *event_file = NULL;
11864 struct fd group = {NULL, 0};
11865 struct task_struct *task = NULL;
11868 int move_group = 0;
11870 int f_flags = O_RDWR;
11871 int cgroup_fd = -1;
11873 /* for future expandability... */
11874 if (flags & ~PERF_FLAG_ALL)
11877 err = perf_copy_attr(attr_uptr, &attr);
11881 /* Do we allow access to perf_event_open(2) ? */
11882 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11886 if (!attr.exclude_kernel) {
11887 err = perf_allow_kernel(&attr);
11892 if (attr.namespaces) {
11893 if (!perfmon_capable())
11898 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11901 if (attr.sample_period & (1ULL << 63))
11905 /* Only privileged users can get physical addresses */
11906 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11907 err = perf_allow_kernel(&attr);
11912 /* REGS_INTR can leak data, lockdown must prevent this */
11913 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
11914 err = security_locked_down(LOCKDOWN_PERF);
11920 * In cgroup mode, the pid argument is used to pass the fd
11921 * opened to the cgroup directory in cgroupfs. The cpu argument
11922 * designates the cpu on which to monitor threads from that
11925 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11928 if (flags & PERF_FLAG_FD_CLOEXEC)
11929 f_flags |= O_CLOEXEC;
11931 event_fd = get_unused_fd_flags(f_flags);
11935 if (group_fd != -1) {
11936 err = perf_fget_light(group_fd, &group);
11939 group_leader = group.file->private_data;
11940 if (flags & PERF_FLAG_FD_OUTPUT)
11941 output_event = group_leader;
11942 if (flags & PERF_FLAG_FD_NO_GROUP)
11943 group_leader = NULL;
11946 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11947 task = find_lively_task_by_vpid(pid);
11948 if (IS_ERR(task)) {
11949 err = PTR_ERR(task);
11954 if (task && group_leader &&
11955 group_leader->attr.inherit != attr.inherit) {
11960 if (flags & PERF_FLAG_PID_CGROUP)
11963 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11964 NULL, NULL, cgroup_fd);
11965 if (IS_ERR(event)) {
11966 err = PTR_ERR(event);
11970 if (is_sampling_event(event)) {
11971 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11978 * Special case software events and allow them to be part of
11979 * any hardware group.
11983 if (attr.use_clockid) {
11984 err = perf_event_set_clock(event, attr.clockid);
11989 if (pmu->task_ctx_nr == perf_sw_context)
11990 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11992 if (group_leader) {
11993 if (is_software_event(event) &&
11994 !in_software_context(group_leader)) {
11996 * If the event is a sw event, but the group_leader
11997 * is on hw context.
11999 * Allow the addition of software events to hw
12000 * groups, this is safe because software events
12001 * never fail to schedule.
12003 pmu = group_leader->ctx->pmu;
12004 } else if (!is_software_event(event) &&
12005 is_software_event(group_leader) &&
12006 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12008 * In case the group is a pure software group, and we
12009 * try to add a hardware event, move the whole group to
12010 * the hardware context.
12017 * Get the target context (task or percpu):
12019 ctx = find_get_context(pmu, task, event);
12021 err = PTR_ERR(ctx);
12026 * Look up the group leader (we will attach this event to it):
12028 if (group_leader) {
12032 * Do not allow a recursive hierarchy (this new sibling
12033 * becoming part of another group-sibling):
12035 if (group_leader->group_leader != group_leader)
12038 /* All events in a group should have the same clock */
12039 if (group_leader->clock != event->clock)
12043 * Make sure we're both events for the same CPU;
12044 * grouping events for different CPUs is broken; since
12045 * you can never concurrently schedule them anyhow.
12047 if (group_leader->cpu != event->cpu)
12051 * Make sure we're both on the same task, or both
12054 if (group_leader->ctx->task != ctx->task)
12058 * Do not allow to attach to a group in a different task
12059 * or CPU context. If we're moving SW events, we'll fix
12060 * this up later, so allow that.
12062 * Racy, not holding group_leader->ctx->mutex, see comment with
12063 * perf_event_ctx_lock().
12065 if (!move_group && group_leader->ctx != ctx)
12069 * Only a group leader can be exclusive or pinned
12071 if (attr.exclusive || attr.pinned)
12075 if (output_event) {
12076 err = perf_event_set_output(event, output_event);
12081 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
12083 if (IS_ERR(event_file)) {
12084 err = PTR_ERR(event_file);
12090 err = down_read_interruptible(&task->signal->exec_update_lock);
12095 * Preserve ptrace permission check for backwards compatibility.
12097 * We must hold exec_update_lock across this and any potential
12098 * perf_install_in_context() call for this new event to
12099 * serialize against exec() altering our credentials (and the
12100 * perf_event_exit_task() that could imply).
12103 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
12108 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
12110 if (gctx->task == TASK_TOMBSTONE) {
12116 * Check if we raced against another sys_perf_event_open() call
12117 * moving the software group underneath us.
12119 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12121 * If someone moved the group out from under us, check
12122 * if this new event wound up on the same ctx, if so
12123 * its the regular !move_group case, otherwise fail.
12129 perf_event_ctx_unlock(group_leader, gctx);
12131 goto not_move_group;
12136 * Failure to create exclusive events returns -EBUSY.
12139 if (!exclusive_event_installable(group_leader, ctx))
12142 for_each_sibling_event(sibling, group_leader) {
12143 if (!exclusive_event_installable(sibling, ctx))
12147 mutex_lock(&ctx->mutex);
12150 * Now that we hold ctx->lock, (re)validate group_leader->ctx == ctx,
12151 * see the group_leader && !move_group test earlier.
12153 if (group_leader && group_leader->ctx != ctx) {
12160 if (ctx->task == TASK_TOMBSTONE) {
12165 if (!perf_event_validate_size(event)) {
12172 * Check if the @cpu we're creating an event for is online.
12174 * We use the perf_cpu_context::ctx::mutex to serialize against
12175 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12177 struct perf_cpu_context *cpuctx =
12178 container_of(ctx, struct perf_cpu_context, ctx);
12180 if (!cpuctx->online) {
12186 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12192 * Must be under the same ctx::mutex as perf_install_in_context(),
12193 * because we need to serialize with concurrent event creation.
12195 if (!exclusive_event_installable(event, ctx)) {
12200 WARN_ON_ONCE(ctx->parent_ctx);
12203 * This is the point on no return; we cannot fail hereafter. This is
12204 * where we start modifying current state.
12209 * See perf_event_ctx_lock() for comments on the details
12210 * of swizzling perf_event::ctx.
12212 perf_remove_from_context(group_leader, 0);
12215 for_each_sibling_event(sibling, group_leader) {
12216 perf_remove_from_context(sibling, 0);
12221 * Wait for everybody to stop referencing the events through
12222 * the old lists, before installing it on new lists.
12227 * Install the group siblings before the group leader.
12229 * Because a group leader will try and install the entire group
12230 * (through the sibling list, which is still in-tact), we can
12231 * end up with siblings installed in the wrong context.
12233 * By installing siblings first we NO-OP because they're not
12234 * reachable through the group lists.
12236 for_each_sibling_event(sibling, group_leader) {
12237 perf_event__state_init(sibling);
12238 perf_install_in_context(ctx, sibling, sibling->cpu);
12243 * Removing from the context ends up with disabled
12244 * event. What we want here is event in the initial
12245 * startup state, ready to be add into new context.
12247 perf_event__state_init(group_leader);
12248 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12253 * Precalculate sample_data sizes; do while holding ctx::mutex such
12254 * that we're serialized against further additions and before
12255 * perf_install_in_context() which is the point the event is active and
12256 * can use these values.
12258 perf_event__header_size(event);
12259 perf_event__id_header_size(event);
12261 event->owner = current;
12263 perf_install_in_context(ctx, event, event->cpu);
12264 perf_unpin_context(ctx);
12267 perf_event_ctx_unlock(group_leader, gctx);
12268 mutex_unlock(&ctx->mutex);
12271 up_read(&task->signal->exec_update_lock);
12272 put_task_struct(task);
12275 mutex_lock(¤t->perf_event_mutex);
12276 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12277 mutex_unlock(¤t->perf_event_mutex);
12280 * Drop the reference on the group_event after placing the
12281 * new event on the sibling_list. This ensures destruction
12282 * of the group leader will find the pointer to itself in
12283 * perf_group_detach().
12286 fd_install(event_fd, event_file);
12291 perf_event_ctx_unlock(group_leader, gctx);
12292 mutex_unlock(&ctx->mutex);
12295 up_read(&task->signal->exec_update_lock);
12299 perf_unpin_context(ctx);
12303 * If event_file is set, the fput() above will have called ->release()
12304 * and that will take care of freeing the event.
12310 put_task_struct(task);
12314 put_unused_fd(event_fd);
12319 * perf_event_create_kernel_counter
12321 * @attr: attributes of the counter to create
12322 * @cpu: cpu in which the counter is bound
12323 * @task: task to profile (NULL for percpu)
12325 struct perf_event *
12326 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12327 struct task_struct *task,
12328 perf_overflow_handler_t overflow_handler,
12331 struct perf_event_context *ctx;
12332 struct perf_event *event;
12336 * Grouping is not supported for kernel events, neither is 'AUX',
12337 * make sure the caller's intentions are adjusted.
12339 if (attr->aux_output)
12340 return ERR_PTR(-EINVAL);
12342 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12343 overflow_handler, context, -1);
12344 if (IS_ERR(event)) {
12345 err = PTR_ERR(event);
12349 /* Mark owner so we could distinguish it from user events. */
12350 event->owner = TASK_TOMBSTONE;
12353 * Get the target context (task or percpu):
12355 ctx = find_get_context(event->pmu, task, event);
12357 err = PTR_ERR(ctx);
12361 WARN_ON_ONCE(ctx->parent_ctx);
12362 mutex_lock(&ctx->mutex);
12363 if (ctx->task == TASK_TOMBSTONE) {
12370 * Check if the @cpu we're creating an event for is online.
12372 * We use the perf_cpu_context::ctx::mutex to serialize against
12373 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12375 struct perf_cpu_context *cpuctx =
12376 container_of(ctx, struct perf_cpu_context, ctx);
12377 if (!cpuctx->online) {
12383 if (!exclusive_event_installable(event, ctx)) {
12388 perf_install_in_context(ctx, event, event->cpu);
12389 perf_unpin_context(ctx);
12390 mutex_unlock(&ctx->mutex);
12395 mutex_unlock(&ctx->mutex);
12396 perf_unpin_context(ctx);
12401 return ERR_PTR(err);
12403 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12405 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12407 struct perf_event_context *src_ctx;
12408 struct perf_event_context *dst_ctx;
12409 struct perf_event *event, *tmp;
12412 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12413 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12416 * See perf_event_ctx_lock() for comments on the details
12417 * of swizzling perf_event::ctx.
12419 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12420 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12422 perf_remove_from_context(event, 0);
12423 unaccount_event_cpu(event, src_cpu);
12425 list_add(&event->migrate_entry, &events);
12429 * Wait for the events to quiesce before re-instating them.
12434 * Re-instate events in 2 passes.
12436 * Skip over group leaders and only install siblings on this first
12437 * pass, siblings will not get enabled without a leader, however a
12438 * leader will enable its siblings, even if those are still on the old
12441 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12442 if (event->group_leader == event)
12445 list_del(&event->migrate_entry);
12446 if (event->state >= PERF_EVENT_STATE_OFF)
12447 event->state = PERF_EVENT_STATE_INACTIVE;
12448 account_event_cpu(event, dst_cpu);
12449 perf_install_in_context(dst_ctx, event, dst_cpu);
12454 * Once all the siblings are setup properly, install the group leaders
12457 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12458 list_del(&event->migrate_entry);
12459 if (event->state >= PERF_EVENT_STATE_OFF)
12460 event->state = PERF_EVENT_STATE_INACTIVE;
12461 account_event_cpu(event, dst_cpu);
12462 perf_install_in_context(dst_ctx, event, dst_cpu);
12465 mutex_unlock(&dst_ctx->mutex);
12466 mutex_unlock(&src_ctx->mutex);
12468 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12470 static void sync_child_event(struct perf_event *child_event,
12471 struct task_struct *child)
12473 struct perf_event *parent_event = child_event->parent;
12476 if (child_event->attr.inherit_stat)
12477 perf_event_read_event(child_event, child);
12479 child_val = perf_event_count(child_event);
12482 * Add back the child's count to the parent's count:
12484 atomic64_add(child_val, &parent_event->child_count);
12485 atomic64_add(child_event->total_time_enabled,
12486 &parent_event->child_total_time_enabled);
12487 atomic64_add(child_event->total_time_running,
12488 &parent_event->child_total_time_running);
12492 perf_event_exit_event(struct perf_event *child_event,
12493 struct perf_event_context *child_ctx,
12494 struct task_struct *child)
12496 struct perf_event *parent_event = child_event->parent;
12499 * Do not destroy the 'original' grouping; because of the context
12500 * switch optimization the original events could've ended up in a
12501 * random child task.
12503 * If we were to destroy the original group, all group related
12504 * operations would cease to function properly after this random
12507 * Do destroy all inherited groups, we don't care about those
12508 * and being thorough is better.
12510 raw_spin_lock_irq(&child_ctx->lock);
12511 WARN_ON_ONCE(child_ctx->is_active);
12514 perf_group_detach(child_event);
12515 list_del_event(child_event, child_ctx);
12516 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12517 raw_spin_unlock_irq(&child_ctx->lock);
12520 * Parent events are governed by their filedesc, retain them.
12522 if (!parent_event) {
12523 perf_event_wakeup(child_event);
12527 * Child events can be cleaned up.
12530 sync_child_event(child_event, child);
12533 * Remove this event from the parent's list
12535 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12536 mutex_lock(&parent_event->child_mutex);
12537 list_del_init(&child_event->child_list);
12538 mutex_unlock(&parent_event->child_mutex);
12541 * Kick perf_poll() for is_event_hup().
12543 perf_event_wakeup(parent_event);
12544 free_event(child_event);
12545 put_event(parent_event);
12548 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12550 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12551 struct perf_event *child_event, *next;
12553 WARN_ON_ONCE(child != current);
12555 child_ctx = perf_pin_task_context(child, ctxn);
12560 * In order to reduce the amount of tricky in ctx tear-down, we hold
12561 * ctx::mutex over the entire thing. This serializes against almost
12562 * everything that wants to access the ctx.
12564 * The exception is sys_perf_event_open() /
12565 * perf_event_create_kernel_count() which does find_get_context()
12566 * without ctx::mutex (it cannot because of the move_group double mutex
12567 * lock thing). See the comments in perf_install_in_context().
12569 mutex_lock(&child_ctx->mutex);
12572 * In a single ctx::lock section, de-schedule the events and detach the
12573 * context from the task such that we cannot ever get it scheduled back
12576 raw_spin_lock_irq(&child_ctx->lock);
12577 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12580 * Now that the context is inactive, destroy the task <-> ctx relation
12581 * and mark the context dead.
12583 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12584 put_ctx(child_ctx); /* cannot be last */
12585 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12586 put_task_struct(current); /* cannot be last */
12588 clone_ctx = unclone_ctx(child_ctx);
12589 raw_spin_unlock_irq(&child_ctx->lock);
12592 put_ctx(clone_ctx);
12595 * Report the task dead after unscheduling the events so that we
12596 * won't get any samples after PERF_RECORD_EXIT. We can however still
12597 * get a few PERF_RECORD_READ events.
12599 perf_event_task(child, child_ctx, 0);
12601 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12602 perf_event_exit_event(child_event, child_ctx, child);
12604 mutex_unlock(&child_ctx->mutex);
12606 put_ctx(child_ctx);
12610 * When a child task exits, feed back event values to parent events.
12612 * Can be called with exec_update_lock held when called from
12613 * setup_new_exec().
12615 void perf_event_exit_task(struct task_struct *child)
12617 struct perf_event *event, *tmp;
12620 mutex_lock(&child->perf_event_mutex);
12621 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12623 list_del_init(&event->owner_entry);
12626 * Ensure the list deletion is visible before we clear
12627 * the owner, closes a race against perf_release() where
12628 * we need to serialize on the owner->perf_event_mutex.
12630 smp_store_release(&event->owner, NULL);
12632 mutex_unlock(&child->perf_event_mutex);
12634 for_each_task_context_nr(ctxn)
12635 perf_event_exit_task_context(child, ctxn);
12638 * The perf_event_exit_task_context calls perf_event_task
12639 * with child's task_ctx, which generates EXIT events for
12640 * child contexts and sets child->perf_event_ctxp[] to NULL.
12641 * At this point we need to send EXIT events to cpu contexts.
12643 perf_event_task(child, NULL, 0);
12646 static void perf_free_event(struct perf_event *event,
12647 struct perf_event_context *ctx)
12649 struct perf_event *parent = event->parent;
12651 if (WARN_ON_ONCE(!parent))
12654 mutex_lock(&parent->child_mutex);
12655 list_del_init(&event->child_list);
12656 mutex_unlock(&parent->child_mutex);
12660 raw_spin_lock_irq(&ctx->lock);
12661 perf_group_detach(event);
12662 list_del_event(event, ctx);
12663 raw_spin_unlock_irq(&ctx->lock);
12668 * Free a context as created by inheritance by perf_event_init_task() below,
12669 * used by fork() in case of fail.
12671 * Even though the task has never lived, the context and events have been
12672 * exposed through the child_list, so we must take care tearing it all down.
12674 void perf_event_free_task(struct task_struct *task)
12676 struct perf_event_context *ctx;
12677 struct perf_event *event, *tmp;
12680 for_each_task_context_nr(ctxn) {
12681 ctx = task->perf_event_ctxp[ctxn];
12685 mutex_lock(&ctx->mutex);
12686 raw_spin_lock_irq(&ctx->lock);
12688 * Destroy the task <-> ctx relation and mark the context dead.
12690 * This is important because even though the task hasn't been
12691 * exposed yet the context has been (through child_list).
12693 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12694 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12695 put_task_struct(task); /* cannot be last */
12696 raw_spin_unlock_irq(&ctx->lock);
12698 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12699 perf_free_event(event, ctx);
12701 mutex_unlock(&ctx->mutex);
12704 * perf_event_release_kernel() could've stolen some of our
12705 * child events and still have them on its free_list. In that
12706 * case we must wait for these events to have been freed (in
12707 * particular all their references to this task must've been
12710 * Without this copy_process() will unconditionally free this
12711 * task (irrespective of its reference count) and
12712 * _free_event()'s put_task_struct(event->hw.target) will be a
12715 * Wait for all events to drop their context reference.
12717 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12718 put_ctx(ctx); /* must be last */
12722 void perf_event_delayed_put(struct task_struct *task)
12726 for_each_task_context_nr(ctxn)
12727 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12730 struct file *perf_event_get(unsigned int fd)
12732 struct file *file = fget(fd);
12734 return ERR_PTR(-EBADF);
12736 if (file->f_op != &perf_fops) {
12738 return ERR_PTR(-EBADF);
12744 const struct perf_event *perf_get_event(struct file *file)
12746 if (file->f_op != &perf_fops)
12747 return ERR_PTR(-EINVAL);
12749 return file->private_data;
12752 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12755 return ERR_PTR(-EINVAL);
12757 return &event->attr;
12761 * Inherit an event from parent task to child task.
12764 * - valid pointer on success
12765 * - NULL for orphaned events
12766 * - IS_ERR() on error
12768 static struct perf_event *
12769 inherit_event(struct perf_event *parent_event,
12770 struct task_struct *parent,
12771 struct perf_event_context *parent_ctx,
12772 struct task_struct *child,
12773 struct perf_event *group_leader,
12774 struct perf_event_context *child_ctx)
12776 enum perf_event_state parent_state = parent_event->state;
12777 struct perf_event *child_event;
12778 unsigned long flags;
12781 * Instead of creating recursive hierarchies of events,
12782 * we link inherited events back to the original parent,
12783 * which has a filp for sure, which we use as the reference
12786 if (parent_event->parent)
12787 parent_event = parent_event->parent;
12789 child_event = perf_event_alloc(&parent_event->attr,
12792 group_leader, parent_event,
12794 if (IS_ERR(child_event))
12795 return child_event;
12798 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12799 !child_ctx->task_ctx_data) {
12800 struct pmu *pmu = child_event->pmu;
12802 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12803 if (!child_ctx->task_ctx_data) {
12804 free_event(child_event);
12805 return ERR_PTR(-ENOMEM);
12810 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12811 * must be under the same lock in order to serialize against
12812 * perf_event_release_kernel(), such that either we must observe
12813 * is_orphaned_event() or they will observe us on the child_list.
12815 mutex_lock(&parent_event->child_mutex);
12816 if (is_orphaned_event(parent_event) ||
12817 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12818 mutex_unlock(&parent_event->child_mutex);
12819 /* task_ctx_data is freed with child_ctx */
12820 free_event(child_event);
12824 get_ctx(child_ctx);
12827 * Make the child state follow the state of the parent event,
12828 * not its attr.disabled bit. We hold the parent's mutex,
12829 * so we won't race with perf_event_{en, dis}able_family.
12831 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12832 child_event->state = PERF_EVENT_STATE_INACTIVE;
12834 child_event->state = PERF_EVENT_STATE_OFF;
12836 if (parent_event->attr.freq) {
12837 u64 sample_period = parent_event->hw.sample_period;
12838 struct hw_perf_event *hwc = &child_event->hw;
12840 hwc->sample_period = sample_period;
12841 hwc->last_period = sample_period;
12843 local64_set(&hwc->period_left, sample_period);
12846 child_event->ctx = child_ctx;
12847 child_event->overflow_handler = parent_event->overflow_handler;
12848 child_event->overflow_handler_context
12849 = parent_event->overflow_handler_context;
12852 * Precalculate sample_data sizes
12854 perf_event__header_size(child_event);
12855 perf_event__id_header_size(child_event);
12858 * Link it up in the child's context:
12860 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12861 add_event_to_ctx(child_event, child_ctx);
12862 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12865 * Link this into the parent event's child list
12867 list_add_tail(&child_event->child_list, &parent_event->child_list);
12868 mutex_unlock(&parent_event->child_mutex);
12870 return child_event;
12874 * Inherits an event group.
12876 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12877 * This matches with perf_event_release_kernel() removing all child events.
12883 static int inherit_group(struct perf_event *parent_event,
12884 struct task_struct *parent,
12885 struct perf_event_context *parent_ctx,
12886 struct task_struct *child,
12887 struct perf_event_context *child_ctx)
12889 struct perf_event *leader;
12890 struct perf_event *sub;
12891 struct perf_event *child_ctr;
12893 leader = inherit_event(parent_event, parent, parent_ctx,
12894 child, NULL, child_ctx);
12895 if (IS_ERR(leader))
12896 return PTR_ERR(leader);
12898 * @leader can be NULL here because of is_orphaned_event(). In this
12899 * case inherit_event() will create individual events, similar to what
12900 * perf_group_detach() would do anyway.
12902 for_each_sibling_event(sub, parent_event) {
12903 child_ctr = inherit_event(sub, parent, parent_ctx,
12904 child, leader, child_ctx);
12905 if (IS_ERR(child_ctr))
12906 return PTR_ERR(child_ctr);
12908 if (sub->aux_event == parent_event && child_ctr &&
12909 !perf_get_aux_event(child_ctr, leader))
12913 leader->group_generation = parent_event->group_generation;
12918 * Creates the child task context and tries to inherit the event-group.
12920 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12921 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12922 * consistent with perf_event_release_kernel() removing all child events.
12929 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12930 struct perf_event_context *parent_ctx,
12931 struct task_struct *child, int ctxn,
12932 int *inherited_all)
12935 struct perf_event_context *child_ctx;
12937 if (!event->attr.inherit) {
12938 *inherited_all = 0;
12942 child_ctx = child->perf_event_ctxp[ctxn];
12945 * This is executed from the parent task context, so
12946 * inherit events that have been marked for cloning.
12947 * First allocate and initialize a context for the
12950 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12954 child->perf_event_ctxp[ctxn] = child_ctx;
12957 ret = inherit_group(event, parent, parent_ctx,
12961 *inherited_all = 0;
12967 * Initialize the perf_event context in task_struct
12969 static int perf_event_init_context(struct task_struct *child, int ctxn)
12971 struct perf_event_context *child_ctx, *parent_ctx;
12972 struct perf_event_context *cloned_ctx;
12973 struct perf_event *event;
12974 struct task_struct *parent = current;
12975 int inherited_all = 1;
12976 unsigned long flags;
12979 if (likely(!parent->perf_event_ctxp[ctxn]))
12983 * If the parent's context is a clone, pin it so it won't get
12984 * swapped under us.
12986 parent_ctx = perf_pin_task_context(parent, ctxn);
12991 * No need to check if parent_ctx != NULL here; since we saw
12992 * it non-NULL earlier, the only reason for it to become NULL
12993 * is if we exit, and since we're currently in the middle of
12994 * a fork we can't be exiting at the same time.
12998 * Lock the parent list. No need to lock the child - not PID
12999 * hashed yet and not running, so nobody can access it.
13001 mutex_lock(&parent_ctx->mutex);
13004 * We dont have to disable NMIs - we are only looking at
13005 * the list, not manipulating it:
13007 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13008 ret = inherit_task_group(event, parent, parent_ctx,
13009 child, ctxn, &inherited_all);
13015 * We can't hold ctx->lock when iterating the ->flexible_group list due
13016 * to allocations, but we need to prevent rotation because
13017 * rotate_ctx() will change the list from interrupt context.
13019 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13020 parent_ctx->rotate_disable = 1;
13021 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13023 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13024 ret = inherit_task_group(event, parent, parent_ctx,
13025 child, ctxn, &inherited_all);
13030 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13031 parent_ctx->rotate_disable = 0;
13033 child_ctx = child->perf_event_ctxp[ctxn];
13035 if (child_ctx && inherited_all) {
13037 * Mark the child context as a clone of the parent
13038 * context, or of whatever the parent is a clone of.
13040 * Note that if the parent is a clone, the holding of
13041 * parent_ctx->lock avoids it from being uncloned.
13043 cloned_ctx = parent_ctx->parent_ctx;
13045 child_ctx->parent_ctx = cloned_ctx;
13046 child_ctx->parent_gen = parent_ctx->parent_gen;
13048 child_ctx->parent_ctx = parent_ctx;
13049 child_ctx->parent_gen = parent_ctx->generation;
13051 get_ctx(child_ctx->parent_ctx);
13054 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13056 mutex_unlock(&parent_ctx->mutex);
13058 perf_unpin_context(parent_ctx);
13059 put_ctx(parent_ctx);
13065 * Initialize the perf_event context in task_struct
13067 int perf_event_init_task(struct task_struct *child)
13071 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
13072 mutex_init(&child->perf_event_mutex);
13073 INIT_LIST_HEAD(&child->perf_event_list);
13075 for_each_task_context_nr(ctxn) {
13076 ret = perf_event_init_context(child, ctxn);
13078 perf_event_free_task(child);
13086 static void __init perf_event_init_all_cpus(void)
13088 struct swevent_htable *swhash;
13091 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13093 for_each_possible_cpu(cpu) {
13094 swhash = &per_cpu(swevent_htable, cpu);
13095 mutex_init(&swhash->hlist_mutex);
13096 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
13098 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13099 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13101 #ifdef CONFIG_CGROUP_PERF
13102 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
13104 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13108 static void perf_swevent_init_cpu(unsigned int cpu)
13110 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13112 mutex_lock(&swhash->hlist_mutex);
13113 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13114 struct swevent_hlist *hlist;
13116 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13118 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13120 mutex_unlock(&swhash->hlist_mutex);
13123 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13124 static void __perf_event_exit_context(void *__info)
13126 struct perf_event_context *ctx = __info;
13127 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
13128 struct perf_event *event;
13130 raw_spin_lock(&ctx->lock);
13131 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
13132 list_for_each_entry(event, &ctx->event_list, event_entry)
13133 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13134 raw_spin_unlock(&ctx->lock);
13137 static void perf_event_exit_cpu_context(int cpu)
13139 struct perf_cpu_context *cpuctx;
13140 struct perf_event_context *ctx;
13143 mutex_lock(&pmus_lock);
13144 list_for_each_entry(pmu, &pmus, entry) {
13145 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13146 ctx = &cpuctx->ctx;
13148 mutex_lock(&ctx->mutex);
13149 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13150 cpuctx->online = 0;
13151 mutex_unlock(&ctx->mutex);
13153 cpumask_clear_cpu(cpu, perf_online_mask);
13154 mutex_unlock(&pmus_lock);
13158 static void perf_event_exit_cpu_context(int cpu) { }
13162 int perf_event_init_cpu(unsigned int cpu)
13164 struct perf_cpu_context *cpuctx;
13165 struct perf_event_context *ctx;
13168 perf_swevent_init_cpu(cpu);
13170 mutex_lock(&pmus_lock);
13171 cpumask_set_cpu(cpu, perf_online_mask);
13172 list_for_each_entry(pmu, &pmus, entry) {
13173 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
13174 ctx = &cpuctx->ctx;
13176 mutex_lock(&ctx->mutex);
13177 cpuctx->online = 1;
13178 mutex_unlock(&ctx->mutex);
13180 mutex_unlock(&pmus_lock);
13185 int perf_event_exit_cpu(unsigned int cpu)
13187 perf_event_exit_cpu_context(cpu);
13192 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13196 for_each_online_cpu(cpu)
13197 perf_event_exit_cpu(cpu);
13203 * Run the perf reboot notifier at the very last possible moment so that
13204 * the generic watchdog code runs as long as possible.
13206 static struct notifier_block perf_reboot_notifier = {
13207 .notifier_call = perf_reboot,
13208 .priority = INT_MIN,
13211 void __init perf_event_init(void)
13215 idr_init(&pmu_idr);
13217 perf_event_init_all_cpus();
13218 init_srcu_struct(&pmus_srcu);
13219 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13220 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13221 perf_pmu_register(&perf_task_clock, NULL, -1);
13222 perf_tp_register();
13223 perf_event_init_cpu(smp_processor_id());
13224 register_reboot_notifier(&perf_reboot_notifier);
13226 ret = init_hw_breakpoint();
13227 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13230 * Build time assertion that we keep the data_head at the intended
13231 * location. IOW, validation we got the __reserved[] size right.
13233 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13237 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13240 struct perf_pmu_events_attr *pmu_attr =
13241 container_of(attr, struct perf_pmu_events_attr, attr);
13243 if (pmu_attr->event_str)
13244 return sprintf(page, "%s\n", pmu_attr->event_str);
13248 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13250 static int __init perf_event_sysfs_init(void)
13255 mutex_lock(&pmus_lock);
13257 ret = bus_register(&pmu_bus);
13261 list_for_each_entry(pmu, &pmus, entry) {
13262 if (!pmu->name || pmu->type < 0)
13265 ret = pmu_dev_alloc(pmu);
13266 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13268 pmu_bus_running = 1;
13272 mutex_unlock(&pmus_lock);
13276 device_initcall(perf_event_sysfs_init);
13278 #ifdef CONFIG_CGROUP_PERF
13279 static struct cgroup_subsys_state *
13280 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13282 struct perf_cgroup *jc;
13284 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13286 return ERR_PTR(-ENOMEM);
13288 jc->info = alloc_percpu(struct perf_cgroup_info);
13291 return ERR_PTR(-ENOMEM);
13297 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13299 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13301 free_percpu(jc->info);
13305 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13307 perf_event_cgroup(css->cgroup);
13311 static int __perf_cgroup_move(void *info)
13313 struct task_struct *task = info;
13315 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13320 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13322 struct task_struct *task;
13323 struct cgroup_subsys_state *css;
13325 cgroup_taskset_for_each(task, css, tset)
13326 task_function_call(task, __perf_cgroup_move, task);
13329 struct cgroup_subsys perf_event_cgrp_subsys = {
13330 .css_alloc = perf_cgroup_css_alloc,
13331 .css_free = perf_cgroup_css_free,
13332 .css_online = perf_cgroup_css_online,
13333 .attach = perf_cgroup_attach,
13335 * Implicitly enable on dfl hierarchy so that perf events can
13336 * always be filtered by cgroup2 path as long as perf_event
13337 * controller is not mounted on a legacy hierarchy.
13339 .implicit_on_dfl = true,
13342 #endif /* CONFIG_CGROUP_PERF */