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 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(struct pmu_event_list, pmu_sb_events);
388 static atomic_t nr_mmap_events __read_mostly;
389 static atomic_t nr_comm_events __read_mostly;
390 static atomic_t nr_namespaces_events __read_mostly;
391 static atomic_t nr_task_events __read_mostly;
392 static atomic_t nr_freq_events __read_mostly;
393 static atomic_t nr_switch_events __read_mostly;
394 static atomic_t nr_ksymbol_events __read_mostly;
395 static atomic_t nr_bpf_events __read_mostly;
396 static atomic_t nr_cgroup_events __read_mostly;
397 static atomic_t nr_text_poke_events __read_mostly;
399 static LIST_HEAD(pmus);
400 static DEFINE_MUTEX(pmus_lock);
401 static struct srcu_struct pmus_srcu;
402 static cpumask_var_t perf_online_mask;
405 * perf event paranoia level:
406 * -1 - not paranoid at all
407 * 0 - disallow raw tracepoint access for unpriv
408 * 1 - disallow cpu events for unpriv
409 * 2 - disallow kernel profiling for unpriv
411 int sysctl_perf_event_paranoid __read_mostly = 2;
413 /* Minimum for 512 kiB + 1 user control page */
414 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
417 * max perf event sample rate
419 #define DEFAULT_MAX_SAMPLE_RATE 100000
420 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
421 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
423 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
425 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
426 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
428 static int perf_sample_allowed_ns __read_mostly =
429 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
431 static void update_perf_cpu_limits(void)
433 u64 tmp = perf_sample_period_ns;
435 tmp *= sysctl_perf_cpu_time_max_percent;
436 tmp = div_u64(tmp, 100);
440 WRITE_ONCE(perf_sample_allowed_ns, tmp);
443 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
445 int perf_proc_update_handler(struct ctl_table *table, int write,
446 void *buffer, size_t *lenp, loff_t *ppos)
449 int perf_cpu = sysctl_perf_cpu_time_max_percent;
451 * If throttling is disabled don't allow the write:
453 if (write && (perf_cpu == 100 || perf_cpu == 0))
456 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
460 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
461 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
462 update_perf_cpu_limits();
467 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
469 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
470 void *buffer, size_t *lenp, loff_t *ppos)
472 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
477 if (sysctl_perf_cpu_time_max_percent == 100 ||
478 sysctl_perf_cpu_time_max_percent == 0) {
480 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
481 WRITE_ONCE(perf_sample_allowed_ns, 0);
483 update_perf_cpu_limits();
490 * perf samples are done in some very critical code paths (NMIs).
491 * If they take too much CPU time, the system can lock up and not
492 * get any real work done. This will drop the sample rate when
493 * we detect that events are taking too long.
495 #define NR_ACCUMULATED_SAMPLES 128
496 static DEFINE_PER_CPU(u64, running_sample_length);
498 static u64 __report_avg;
499 static u64 __report_allowed;
501 static void perf_duration_warn(struct irq_work *w)
503 printk_ratelimited(KERN_INFO
504 "perf: interrupt took too long (%lld > %lld), lowering "
505 "kernel.perf_event_max_sample_rate to %d\n",
506 __report_avg, __report_allowed,
507 sysctl_perf_event_sample_rate);
510 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
512 void perf_sample_event_took(u64 sample_len_ns)
514 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
522 /* Decay the counter by 1 average sample. */
523 running_len = __this_cpu_read(running_sample_length);
524 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
525 running_len += sample_len_ns;
526 __this_cpu_write(running_sample_length, running_len);
529 * Note: this will be biased artifically low until we have
530 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
531 * from having to maintain a count.
533 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
534 if (avg_len <= max_len)
537 __report_avg = avg_len;
538 __report_allowed = max_len;
541 * Compute a throttle threshold 25% below the current duration.
543 avg_len += avg_len / 4;
544 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
550 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
551 WRITE_ONCE(max_samples_per_tick, max);
553 sysctl_perf_event_sample_rate = max * HZ;
554 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
556 if (!irq_work_queue(&perf_duration_work)) {
557 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
558 "kernel.perf_event_max_sample_rate to %d\n",
559 __report_avg, __report_allowed,
560 sysctl_perf_event_sample_rate);
564 static atomic64_t perf_event_id;
566 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
567 enum event_type_t event_type);
569 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
570 enum event_type_t event_type,
571 struct task_struct *task);
573 static void update_context_time(struct perf_event_context *ctx);
574 static u64 perf_event_time(struct perf_event *event);
576 void __weak perf_event_print_debug(void) { }
578 extern __weak const char *perf_pmu_name(void)
583 static inline u64 perf_clock(void)
585 return local_clock();
588 static inline u64 perf_event_clock(struct perf_event *event)
590 return event->clock();
594 * State based event timekeeping...
596 * The basic idea is to use event->state to determine which (if any) time
597 * fields to increment with the current delta. This means we only need to
598 * update timestamps when we change state or when they are explicitly requested
601 * Event groups make things a little more complicated, but not terribly so. The
602 * rules for a group are that if the group leader is OFF the entire group is
603 * OFF, irrespecive of what the group member states are. This results in
604 * __perf_effective_state().
606 * A futher ramification is that when a group leader flips between OFF and
607 * !OFF, we need to update all group member times.
610 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
611 * need to make sure the relevant context time is updated before we try and
612 * update our timestamps.
615 static __always_inline enum perf_event_state
616 __perf_effective_state(struct perf_event *event)
618 struct perf_event *leader = event->group_leader;
620 if (leader->state <= PERF_EVENT_STATE_OFF)
621 return leader->state;
626 static __always_inline void
627 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
629 enum perf_event_state state = __perf_effective_state(event);
630 u64 delta = now - event->tstamp;
632 *enabled = event->total_time_enabled;
633 if (state >= PERF_EVENT_STATE_INACTIVE)
636 *running = event->total_time_running;
637 if (state >= PERF_EVENT_STATE_ACTIVE)
641 static void perf_event_update_time(struct perf_event *event)
643 u64 now = perf_event_time(event);
645 __perf_update_times(event, now, &event->total_time_enabled,
646 &event->total_time_running);
650 static void perf_event_update_sibling_time(struct perf_event *leader)
652 struct perf_event *sibling;
654 for_each_sibling_event(sibling, leader)
655 perf_event_update_time(sibling);
659 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
661 if (event->state == state)
664 perf_event_update_time(event);
666 * If a group leader gets enabled/disabled all its siblings
669 if ((event->state < 0) ^ (state < 0))
670 perf_event_update_sibling_time(event);
672 WRITE_ONCE(event->state, state);
675 #ifdef CONFIG_CGROUP_PERF
678 perf_cgroup_match(struct perf_event *event)
680 struct perf_event_context *ctx = event->ctx;
681 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
683 /* @event doesn't care about cgroup */
687 /* wants specific cgroup scope but @cpuctx isn't associated with any */
692 * Cgroup scoping is recursive. An event enabled for a cgroup is
693 * also enabled for all its descendant cgroups. If @cpuctx's
694 * cgroup is a descendant of @event's (the test covers identity
695 * case), it's a match.
697 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
698 event->cgrp->css.cgroup);
701 static inline void perf_detach_cgroup(struct perf_event *event)
703 css_put(&event->cgrp->css);
707 static inline int is_cgroup_event(struct perf_event *event)
709 return event->cgrp != NULL;
712 static inline u64 perf_cgroup_event_time(struct perf_event *event)
714 struct perf_cgroup_info *t;
716 t = per_cpu_ptr(event->cgrp->info, event->cpu);
720 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
722 struct perf_cgroup_info *info;
727 info = this_cpu_ptr(cgrp->info);
729 info->time += now - info->timestamp;
730 info->timestamp = now;
733 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
735 struct perf_cgroup *cgrp = cpuctx->cgrp;
736 struct cgroup_subsys_state *css;
739 for (css = &cgrp->css; css; css = css->parent) {
740 cgrp = container_of(css, struct perf_cgroup, css);
741 __update_cgrp_time(cgrp);
746 static inline void update_cgrp_time_from_event(struct perf_event *event)
748 struct perf_cgroup *cgrp;
751 * ensure we access cgroup data only when needed and
752 * when we know the cgroup is pinned (css_get)
754 if (!is_cgroup_event(event))
757 cgrp = perf_cgroup_from_task(current, event->ctx);
759 * Do not update time when cgroup is not active
761 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
762 __update_cgrp_time(event->cgrp);
766 perf_cgroup_set_timestamp(struct task_struct *task,
767 struct perf_event_context *ctx)
769 struct perf_cgroup *cgrp;
770 struct perf_cgroup_info *info;
771 struct cgroup_subsys_state *css;
774 * ctx->lock held by caller
775 * ensure we do not access cgroup data
776 * unless we have the cgroup pinned (css_get)
778 if (!task || !ctx->nr_cgroups)
781 cgrp = perf_cgroup_from_task(task, ctx);
783 for (css = &cgrp->css; css; css = css->parent) {
784 cgrp = container_of(css, struct perf_cgroup, css);
785 info = this_cpu_ptr(cgrp->info);
786 info->timestamp = ctx->timestamp;
790 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
792 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
793 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
796 * reschedule events based on the cgroup constraint of task.
798 * mode SWOUT : schedule out everything
799 * mode SWIN : schedule in based on cgroup for next
801 static void perf_cgroup_switch(struct task_struct *task, int mode)
803 struct perf_cpu_context *cpuctx;
804 struct list_head *list;
808 * Disable interrupts and preemption to avoid this CPU's
809 * cgrp_cpuctx_entry to change under us.
811 local_irq_save(flags);
813 list = this_cpu_ptr(&cgrp_cpuctx_list);
814 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
815 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
817 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
818 perf_pmu_disable(cpuctx->ctx.pmu);
820 if (mode & PERF_CGROUP_SWOUT) {
821 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
823 * must not be done before ctxswout due
824 * to event_filter_match() in event_sched_out()
829 if (mode & PERF_CGROUP_SWIN) {
830 WARN_ON_ONCE(cpuctx->cgrp);
832 * set cgrp before ctxsw in to allow
833 * event_filter_match() to not have to pass
835 * we pass the cpuctx->ctx to perf_cgroup_from_task()
836 * because cgorup events are only per-cpu
838 cpuctx->cgrp = perf_cgroup_from_task(task,
840 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
842 perf_pmu_enable(cpuctx->ctx.pmu);
843 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
846 local_irq_restore(flags);
849 static inline void perf_cgroup_sched_out(struct task_struct *task,
850 struct task_struct *next)
852 struct perf_cgroup *cgrp1;
853 struct perf_cgroup *cgrp2 = NULL;
857 * we come here when we know perf_cgroup_events > 0
858 * we do not need to pass the ctx here because we know
859 * we are holding the rcu lock
861 cgrp1 = perf_cgroup_from_task(task, NULL);
862 cgrp2 = perf_cgroup_from_task(next, NULL);
865 * only schedule out current cgroup events if we know
866 * that we are switching to a different cgroup. Otherwise,
867 * do no touch the cgroup events.
870 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
875 static inline void perf_cgroup_sched_in(struct task_struct *prev,
876 struct task_struct *task)
878 struct perf_cgroup *cgrp1;
879 struct perf_cgroup *cgrp2 = NULL;
883 * we come here when we know perf_cgroup_events > 0
884 * we do not need to pass the ctx here because we know
885 * we are holding the rcu lock
887 cgrp1 = perf_cgroup_from_task(task, NULL);
888 cgrp2 = perf_cgroup_from_task(prev, NULL);
891 * only need to schedule in cgroup events if we are changing
892 * cgroup during ctxsw. Cgroup events were not scheduled
893 * out of ctxsw out if that was not the case.
896 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
901 static int perf_cgroup_ensure_storage(struct perf_event *event,
902 struct cgroup_subsys_state *css)
904 struct perf_cpu_context *cpuctx;
905 struct perf_event **storage;
906 int cpu, heap_size, ret = 0;
909 * Allow storage to have sufficent space for an iterator for each
910 * possibly nested cgroup plus an iterator for events with no cgroup.
912 for (heap_size = 1; css; css = css->parent)
915 for_each_possible_cpu(cpu) {
916 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
917 if (heap_size <= cpuctx->heap_size)
920 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
921 GFP_KERNEL, cpu_to_node(cpu));
927 raw_spin_lock_irq(&cpuctx->ctx.lock);
928 if (cpuctx->heap_size < heap_size) {
929 swap(cpuctx->heap, storage);
930 if (storage == cpuctx->heap_default)
932 cpuctx->heap_size = heap_size;
934 raw_spin_unlock_irq(&cpuctx->ctx.lock);
942 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
943 struct perf_event_attr *attr,
944 struct perf_event *group_leader)
946 struct perf_cgroup *cgrp;
947 struct cgroup_subsys_state *css;
948 struct fd f = fdget(fd);
954 css = css_tryget_online_from_dir(f.file->f_path.dentry,
955 &perf_event_cgrp_subsys);
961 ret = perf_cgroup_ensure_storage(event, css);
965 cgrp = container_of(css, struct perf_cgroup, css);
969 * all events in a group must monitor
970 * the same cgroup because a task belongs
971 * to only one perf cgroup at a time
973 if (group_leader && group_leader->cgrp != cgrp) {
974 perf_detach_cgroup(event);
983 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
985 struct perf_cgroup_info *t;
986 t = per_cpu_ptr(event->cgrp->info, event->cpu);
987 event->shadow_ctx_time = now - t->timestamp;
991 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
993 struct perf_cpu_context *cpuctx;
995 if (!is_cgroup_event(event))
999 * Because cgroup events are always per-cpu events,
1000 * @ctx == &cpuctx->ctx.
1002 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1005 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1006 * matching the event's cgroup, we must do this for every new event,
1007 * because if the first would mismatch, the second would not try again
1008 * and we would leave cpuctx->cgrp unset.
1010 if (ctx->is_active && !cpuctx->cgrp) {
1011 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1013 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1014 cpuctx->cgrp = cgrp;
1017 if (ctx->nr_cgroups++)
1020 list_add(&cpuctx->cgrp_cpuctx_entry,
1021 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1025 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1027 struct perf_cpu_context *cpuctx;
1029 if (!is_cgroup_event(event))
1033 * Because cgroup events are always per-cpu events,
1034 * @ctx == &cpuctx->ctx.
1036 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1038 if (--ctx->nr_cgroups)
1041 if (ctx->is_active && cpuctx->cgrp)
1042 cpuctx->cgrp = NULL;
1044 list_del(&cpuctx->cgrp_cpuctx_entry);
1047 #else /* !CONFIG_CGROUP_PERF */
1050 perf_cgroup_match(struct perf_event *event)
1055 static inline void perf_detach_cgroup(struct perf_event *event)
1058 static inline int is_cgroup_event(struct perf_event *event)
1063 static inline void update_cgrp_time_from_event(struct perf_event *event)
1067 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1071 static inline void perf_cgroup_sched_out(struct task_struct *task,
1072 struct task_struct *next)
1076 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1077 struct task_struct *task)
1081 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1082 struct perf_event_attr *attr,
1083 struct perf_event *group_leader)
1089 perf_cgroup_set_timestamp(struct task_struct *task,
1090 struct perf_event_context *ctx)
1095 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1100 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1104 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1110 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1115 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1121 * set default to be dependent on timer tick just
1122 * like original code
1124 #define PERF_CPU_HRTIMER (1000 / HZ)
1126 * function must be called with interrupts disabled
1128 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1130 struct perf_cpu_context *cpuctx;
1133 lockdep_assert_irqs_disabled();
1135 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1136 rotations = perf_rotate_context(cpuctx);
1138 raw_spin_lock(&cpuctx->hrtimer_lock);
1140 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1142 cpuctx->hrtimer_active = 0;
1143 raw_spin_unlock(&cpuctx->hrtimer_lock);
1145 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1148 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1150 struct hrtimer *timer = &cpuctx->hrtimer;
1151 struct pmu *pmu = cpuctx->ctx.pmu;
1154 /* no multiplexing needed for SW PMU */
1155 if (pmu->task_ctx_nr == perf_sw_context)
1159 * check default is sane, if not set then force to
1160 * default interval (1/tick)
1162 interval = pmu->hrtimer_interval_ms;
1164 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1166 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1168 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1169 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1170 timer->function = perf_mux_hrtimer_handler;
1173 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1175 struct hrtimer *timer = &cpuctx->hrtimer;
1176 struct pmu *pmu = cpuctx->ctx.pmu;
1177 unsigned long flags;
1179 /* not for SW PMU */
1180 if (pmu->task_ctx_nr == perf_sw_context)
1183 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1184 if (!cpuctx->hrtimer_active) {
1185 cpuctx->hrtimer_active = 1;
1186 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1187 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1189 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1194 void perf_pmu_disable(struct pmu *pmu)
1196 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1198 pmu->pmu_disable(pmu);
1201 void perf_pmu_enable(struct pmu *pmu)
1203 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1205 pmu->pmu_enable(pmu);
1208 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1211 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1212 * perf_event_task_tick() are fully serialized because they're strictly cpu
1213 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1214 * disabled, while perf_event_task_tick is called from IRQ context.
1216 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1218 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1220 lockdep_assert_irqs_disabled();
1222 WARN_ON(!list_empty(&ctx->active_ctx_list));
1224 list_add(&ctx->active_ctx_list, head);
1227 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1229 lockdep_assert_irqs_disabled();
1231 WARN_ON(list_empty(&ctx->active_ctx_list));
1233 list_del_init(&ctx->active_ctx_list);
1236 static void get_ctx(struct perf_event_context *ctx)
1238 refcount_inc(&ctx->refcount);
1241 static void *alloc_task_ctx_data(struct pmu *pmu)
1243 if (pmu->task_ctx_cache)
1244 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1249 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1251 if (pmu->task_ctx_cache && task_ctx_data)
1252 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1255 static void free_ctx(struct rcu_head *head)
1257 struct perf_event_context *ctx;
1259 ctx = container_of(head, struct perf_event_context, rcu_head);
1260 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1264 static void put_ctx(struct perf_event_context *ctx)
1266 if (refcount_dec_and_test(&ctx->refcount)) {
1267 if (ctx->parent_ctx)
1268 put_ctx(ctx->parent_ctx);
1269 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1270 put_task_struct(ctx->task);
1271 call_rcu(&ctx->rcu_head, free_ctx);
1276 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1277 * perf_pmu_migrate_context() we need some magic.
1279 * Those places that change perf_event::ctx will hold both
1280 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1282 * Lock ordering is by mutex address. There are two other sites where
1283 * perf_event_context::mutex nests and those are:
1285 * - perf_event_exit_task_context() [ child , 0 ]
1286 * perf_event_exit_event()
1287 * put_event() [ parent, 1 ]
1289 * - perf_event_init_context() [ parent, 0 ]
1290 * inherit_task_group()
1293 * perf_event_alloc()
1295 * perf_try_init_event() [ child , 1 ]
1297 * While it appears there is an obvious deadlock here -- the parent and child
1298 * nesting levels are inverted between the two. This is in fact safe because
1299 * life-time rules separate them. That is an exiting task cannot fork, and a
1300 * spawning task cannot (yet) exit.
1302 * But remember that that these are parent<->child context relations, and
1303 * migration does not affect children, therefore these two orderings should not
1306 * The change in perf_event::ctx does not affect children (as claimed above)
1307 * because the sys_perf_event_open() case will install a new event and break
1308 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1309 * concerned with cpuctx and that doesn't have children.
1311 * The places that change perf_event::ctx will issue:
1313 * perf_remove_from_context();
1314 * synchronize_rcu();
1315 * perf_install_in_context();
1317 * to affect the change. The remove_from_context() + synchronize_rcu() should
1318 * quiesce the event, after which we can install it in the new location. This
1319 * means that only external vectors (perf_fops, prctl) can perturb the event
1320 * while in transit. Therefore all such accessors should also acquire
1321 * perf_event_context::mutex to serialize against this.
1323 * However; because event->ctx can change while we're waiting to acquire
1324 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1329 * task_struct::perf_event_mutex
1330 * perf_event_context::mutex
1331 * perf_event::child_mutex;
1332 * perf_event_context::lock
1333 * perf_event::mmap_mutex
1335 * perf_addr_filters_head::lock
1339 * cpuctx->mutex / perf_event_context::mutex
1341 static struct perf_event_context *
1342 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1344 struct perf_event_context *ctx;
1348 ctx = READ_ONCE(event->ctx);
1349 if (!refcount_inc_not_zero(&ctx->refcount)) {
1355 mutex_lock_nested(&ctx->mutex, nesting);
1356 if (event->ctx != ctx) {
1357 mutex_unlock(&ctx->mutex);
1365 static inline struct perf_event_context *
1366 perf_event_ctx_lock(struct perf_event *event)
1368 return perf_event_ctx_lock_nested(event, 0);
1371 static void perf_event_ctx_unlock(struct perf_event *event,
1372 struct perf_event_context *ctx)
1374 mutex_unlock(&ctx->mutex);
1379 * This must be done under the ctx->lock, such as to serialize against
1380 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1381 * calling scheduler related locks and ctx->lock nests inside those.
1383 static __must_check struct perf_event_context *
1384 unclone_ctx(struct perf_event_context *ctx)
1386 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1388 lockdep_assert_held(&ctx->lock);
1391 ctx->parent_ctx = NULL;
1397 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1402 * only top level events have the pid namespace they were created in
1405 event = event->parent;
1407 nr = __task_pid_nr_ns(p, type, event->ns);
1408 /* avoid -1 if it is idle thread or runs in another ns */
1409 if (!nr && !pid_alive(p))
1414 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1416 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1419 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1421 return perf_event_pid_type(event, p, PIDTYPE_PID);
1425 * If we inherit events we want to return the parent event id
1428 static u64 primary_event_id(struct perf_event *event)
1433 id = event->parent->id;
1439 * Get the perf_event_context for a task and lock it.
1441 * This has to cope with with the fact that until it is locked,
1442 * the context could get moved to another task.
1444 static struct perf_event_context *
1445 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1447 struct perf_event_context *ctx;
1451 * One of the few rules of preemptible RCU is that one cannot do
1452 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1453 * part of the read side critical section was irqs-enabled -- see
1454 * rcu_read_unlock_special().
1456 * Since ctx->lock nests under rq->lock we must ensure the entire read
1457 * side critical section has interrupts disabled.
1459 local_irq_save(*flags);
1461 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1464 * If this context is a clone of another, it might
1465 * get swapped for another underneath us by
1466 * perf_event_task_sched_out, though the
1467 * rcu_read_lock() protects us from any context
1468 * getting freed. Lock the context and check if it
1469 * got swapped before we could get the lock, and retry
1470 * if so. If we locked the right context, then it
1471 * can't get swapped on us any more.
1473 raw_spin_lock(&ctx->lock);
1474 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1475 raw_spin_unlock(&ctx->lock);
1477 local_irq_restore(*flags);
1481 if (ctx->task == TASK_TOMBSTONE ||
1482 !refcount_inc_not_zero(&ctx->refcount)) {
1483 raw_spin_unlock(&ctx->lock);
1486 WARN_ON_ONCE(ctx->task != task);
1491 local_irq_restore(*flags);
1496 * Get the context for a task and increment its pin_count so it
1497 * can't get swapped to another task. This also increments its
1498 * reference count so that the context can't get freed.
1500 static struct perf_event_context *
1501 perf_pin_task_context(struct task_struct *task, int ctxn)
1503 struct perf_event_context *ctx;
1504 unsigned long flags;
1506 ctx = perf_lock_task_context(task, ctxn, &flags);
1509 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1514 static void perf_unpin_context(struct perf_event_context *ctx)
1516 unsigned long flags;
1518 raw_spin_lock_irqsave(&ctx->lock, flags);
1520 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1524 * Update the record of the current time in a context.
1526 static void update_context_time(struct perf_event_context *ctx)
1528 u64 now = perf_clock();
1530 ctx->time += now - ctx->timestamp;
1531 ctx->timestamp = now;
1534 static u64 perf_event_time(struct perf_event *event)
1536 struct perf_event_context *ctx = event->ctx;
1538 if (is_cgroup_event(event))
1539 return perf_cgroup_event_time(event);
1541 return ctx ? ctx->time : 0;
1544 static enum event_type_t get_event_type(struct perf_event *event)
1546 struct perf_event_context *ctx = event->ctx;
1547 enum event_type_t event_type;
1549 lockdep_assert_held(&ctx->lock);
1552 * It's 'group type', really, because if our group leader is
1553 * pinned, so are we.
1555 if (event->group_leader != event)
1556 event = event->group_leader;
1558 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1560 event_type |= EVENT_CPU;
1566 * Helper function to initialize event group nodes.
1568 static void init_event_group(struct perf_event *event)
1570 RB_CLEAR_NODE(&event->group_node);
1571 event->group_index = 0;
1575 * Extract pinned or flexible groups from the context
1576 * based on event attrs bits.
1578 static struct perf_event_groups *
1579 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1581 if (event->attr.pinned)
1582 return &ctx->pinned_groups;
1584 return &ctx->flexible_groups;
1588 * Helper function to initializes perf_event_group trees.
1590 static void perf_event_groups_init(struct perf_event_groups *groups)
1592 groups->tree = RB_ROOT;
1597 * Compare function for event groups;
1599 * Implements complex key that first sorts by CPU and then by virtual index
1600 * which provides ordering when rotating groups for the same CPU.
1603 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1605 if (left->cpu < right->cpu)
1607 if (left->cpu > right->cpu)
1610 #ifdef CONFIG_CGROUP_PERF
1611 if (left->cgrp != right->cgrp) {
1612 if (!left->cgrp || !left->cgrp->css.cgroup) {
1614 * Left has no cgroup but right does, no cgroups come
1619 if (!right->cgrp || !right->cgrp->css.cgroup) {
1621 * Right has no cgroup but left does, no cgroups come
1626 /* Two dissimilar cgroups, order by id. */
1627 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1634 if (left->group_index < right->group_index)
1636 if (left->group_index > right->group_index)
1643 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1644 * key (see perf_event_groups_less). This places it last inside the CPU
1648 perf_event_groups_insert(struct perf_event_groups *groups,
1649 struct perf_event *event)
1651 struct perf_event *node_event;
1652 struct rb_node *parent;
1653 struct rb_node **node;
1655 event->group_index = ++groups->index;
1657 node = &groups->tree.rb_node;
1662 node_event = container_of(*node, struct perf_event, group_node);
1664 if (perf_event_groups_less(event, node_event))
1665 node = &parent->rb_left;
1667 node = &parent->rb_right;
1670 rb_link_node(&event->group_node, parent, node);
1671 rb_insert_color(&event->group_node, &groups->tree);
1675 * Helper function to insert event into the pinned or flexible groups.
1678 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1680 struct perf_event_groups *groups;
1682 groups = get_event_groups(event, ctx);
1683 perf_event_groups_insert(groups, event);
1687 * Delete a group from a tree.
1690 perf_event_groups_delete(struct perf_event_groups *groups,
1691 struct perf_event *event)
1693 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1694 RB_EMPTY_ROOT(&groups->tree));
1696 rb_erase(&event->group_node, &groups->tree);
1697 init_event_group(event);
1701 * Helper function to delete event from its groups.
1704 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1706 struct perf_event_groups *groups;
1708 groups = get_event_groups(event, ctx);
1709 perf_event_groups_delete(groups, event);
1713 * Get the leftmost event in the cpu/cgroup subtree.
1715 static struct perf_event *
1716 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1717 struct cgroup *cgrp)
1719 struct perf_event *node_event = NULL, *match = NULL;
1720 struct rb_node *node = groups->tree.rb_node;
1721 #ifdef CONFIG_CGROUP_PERF
1722 u64 node_cgrp_id, cgrp_id = 0;
1725 cgrp_id = cgrp->kn->id;
1729 node_event = container_of(node, struct perf_event, group_node);
1731 if (cpu < node_event->cpu) {
1732 node = node->rb_left;
1735 if (cpu > node_event->cpu) {
1736 node = node->rb_right;
1739 #ifdef CONFIG_CGROUP_PERF
1741 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1742 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1744 if (cgrp_id < node_cgrp_id) {
1745 node = node->rb_left;
1748 if (cgrp_id > node_cgrp_id) {
1749 node = node->rb_right;
1754 node = node->rb_left;
1761 * Like rb_entry_next_safe() for the @cpu subtree.
1763 static struct perf_event *
1764 perf_event_groups_next(struct perf_event *event)
1766 struct perf_event *next;
1767 #ifdef CONFIG_CGROUP_PERF
1768 u64 curr_cgrp_id = 0;
1769 u64 next_cgrp_id = 0;
1772 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1773 if (next == NULL || next->cpu != event->cpu)
1776 #ifdef CONFIG_CGROUP_PERF
1777 if (event->cgrp && event->cgrp->css.cgroup)
1778 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1780 if (next->cgrp && next->cgrp->css.cgroup)
1781 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1783 if (curr_cgrp_id != next_cgrp_id)
1790 * Iterate through the whole groups tree.
1792 #define perf_event_groups_for_each(event, groups) \
1793 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1794 typeof(*event), group_node); event; \
1795 event = rb_entry_safe(rb_next(&event->group_node), \
1796 typeof(*event), group_node))
1799 * Add an event from the lists for its context.
1800 * Must be called with ctx->mutex and ctx->lock held.
1803 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1805 lockdep_assert_held(&ctx->lock);
1807 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1808 event->attach_state |= PERF_ATTACH_CONTEXT;
1810 event->tstamp = perf_event_time(event);
1813 * If we're a stand alone event or group leader, we go to the context
1814 * list, group events are kept attached to the group so that
1815 * perf_group_detach can, at all times, locate all siblings.
1817 if (event->group_leader == event) {
1818 event->group_caps = event->event_caps;
1819 add_event_to_groups(event, ctx);
1822 list_add_rcu(&event->event_entry, &ctx->event_list);
1824 if (event->attr.inherit_stat)
1827 if (event->state > PERF_EVENT_STATE_OFF)
1828 perf_cgroup_event_enable(event, ctx);
1834 * Initialize event state based on the perf_event_attr::disabled.
1836 static inline void perf_event__state_init(struct perf_event *event)
1838 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1839 PERF_EVENT_STATE_INACTIVE;
1842 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1844 int entry = sizeof(u64); /* value */
1848 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1849 size += sizeof(u64);
1851 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1852 size += sizeof(u64);
1854 if (event->attr.read_format & PERF_FORMAT_ID)
1855 entry += sizeof(u64);
1857 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1859 size += sizeof(u64);
1863 event->read_size = size;
1866 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1868 struct perf_sample_data *data;
1871 if (sample_type & PERF_SAMPLE_IP)
1872 size += sizeof(data->ip);
1874 if (sample_type & PERF_SAMPLE_ADDR)
1875 size += sizeof(data->addr);
1877 if (sample_type & PERF_SAMPLE_PERIOD)
1878 size += sizeof(data->period);
1880 if (sample_type & PERF_SAMPLE_WEIGHT)
1881 size += sizeof(data->weight);
1883 if (sample_type & PERF_SAMPLE_READ)
1884 size += event->read_size;
1886 if (sample_type & PERF_SAMPLE_DATA_SRC)
1887 size += sizeof(data->data_src.val);
1889 if (sample_type & PERF_SAMPLE_TRANSACTION)
1890 size += sizeof(data->txn);
1892 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1893 size += sizeof(data->phys_addr);
1895 if (sample_type & PERF_SAMPLE_CGROUP)
1896 size += sizeof(data->cgroup);
1898 event->header_size = size;
1902 * Called at perf_event creation and when events are attached/detached from a
1905 static void perf_event__header_size(struct perf_event *event)
1907 __perf_event_read_size(event,
1908 event->group_leader->nr_siblings);
1909 __perf_event_header_size(event, event->attr.sample_type);
1912 static void perf_event__id_header_size(struct perf_event *event)
1914 struct perf_sample_data *data;
1915 u64 sample_type = event->attr.sample_type;
1918 if (sample_type & PERF_SAMPLE_TID)
1919 size += sizeof(data->tid_entry);
1921 if (sample_type & PERF_SAMPLE_TIME)
1922 size += sizeof(data->time);
1924 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1925 size += sizeof(data->id);
1927 if (sample_type & PERF_SAMPLE_ID)
1928 size += sizeof(data->id);
1930 if (sample_type & PERF_SAMPLE_STREAM_ID)
1931 size += sizeof(data->stream_id);
1933 if (sample_type & PERF_SAMPLE_CPU)
1934 size += sizeof(data->cpu_entry);
1936 event->id_header_size = size;
1939 static bool perf_event_validate_size(struct perf_event *event)
1942 * The values computed here will be over-written when we actually
1945 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1946 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1947 perf_event__id_header_size(event);
1950 * Sum the lot; should not exceed the 64k limit we have on records.
1951 * Conservative limit to allow for callchains and other variable fields.
1953 if (event->read_size + event->header_size +
1954 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1960 static void perf_group_attach(struct perf_event *event)
1962 struct perf_event *group_leader = event->group_leader, *pos;
1964 lockdep_assert_held(&event->ctx->lock);
1967 * We can have double attach due to group movement in perf_event_open.
1969 if (event->attach_state & PERF_ATTACH_GROUP)
1972 event->attach_state |= PERF_ATTACH_GROUP;
1974 if (group_leader == event)
1977 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1979 group_leader->group_caps &= event->event_caps;
1981 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1982 group_leader->nr_siblings++;
1984 perf_event__header_size(group_leader);
1986 for_each_sibling_event(pos, group_leader)
1987 perf_event__header_size(pos);
1991 * Remove an event from the lists for its context.
1992 * Must be called with ctx->mutex and ctx->lock held.
1995 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1997 WARN_ON_ONCE(event->ctx != ctx);
1998 lockdep_assert_held(&ctx->lock);
2001 * We can have double detach due to exit/hot-unplug + close.
2003 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2006 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2009 if (event->attr.inherit_stat)
2012 list_del_rcu(&event->event_entry);
2014 if (event->group_leader == event)
2015 del_event_from_groups(event, ctx);
2018 * If event was in error state, then keep it
2019 * that way, otherwise bogus counts will be
2020 * returned on read(). The only way to get out
2021 * of error state is by explicit re-enabling
2024 if (event->state > PERF_EVENT_STATE_OFF) {
2025 perf_cgroup_event_disable(event, ctx);
2026 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2033 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2035 if (!has_aux(aux_event))
2038 if (!event->pmu->aux_output_match)
2041 return event->pmu->aux_output_match(aux_event);
2044 static void put_event(struct perf_event *event);
2045 static void event_sched_out(struct perf_event *event,
2046 struct perf_cpu_context *cpuctx,
2047 struct perf_event_context *ctx);
2049 static void perf_put_aux_event(struct perf_event *event)
2051 struct perf_event_context *ctx = event->ctx;
2052 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2053 struct perf_event *iter;
2056 * If event uses aux_event tear down the link
2058 if (event->aux_event) {
2059 iter = event->aux_event;
2060 event->aux_event = NULL;
2066 * If the event is an aux_event, tear down all links to
2067 * it from other events.
2069 for_each_sibling_event(iter, event->group_leader) {
2070 if (iter->aux_event != event)
2073 iter->aux_event = NULL;
2077 * If it's ACTIVE, schedule it out and put it into ERROR
2078 * state so that we don't try to schedule it again. Note
2079 * that perf_event_enable() will clear the ERROR status.
2081 event_sched_out(iter, cpuctx, ctx);
2082 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2086 static bool perf_need_aux_event(struct perf_event *event)
2088 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2091 static int perf_get_aux_event(struct perf_event *event,
2092 struct perf_event *group_leader)
2095 * Our group leader must be an aux event if we want to be
2096 * an aux_output. This way, the aux event will precede its
2097 * aux_output events in the group, and therefore will always
2104 * aux_output and aux_sample_size are mutually exclusive.
2106 if (event->attr.aux_output && event->attr.aux_sample_size)
2109 if (event->attr.aux_output &&
2110 !perf_aux_output_match(event, group_leader))
2113 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2116 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2120 * Link aux_outputs to their aux event; this is undone in
2121 * perf_group_detach() by perf_put_aux_event(). When the
2122 * group in torn down, the aux_output events loose their
2123 * link to the aux_event and can't schedule any more.
2125 event->aux_event = group_leader;
2130 static inline struct list_head *get_event_list(struct perf_event *event)
2132 struct perf_event_context *ctx = event->ctx;
2133 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2137 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2138 * cannot exist on their own, schedule them out and move them into the ERROR
2139 * state. Also see _perf_event_enable(), it will not be able to recover
2142 static inline void perf_remove_sibling_event(struct perf_event *event)
2144 struct perf_event_context *ctx = event->ctx;
2145 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2147 event_sched_out(event, cpuctx, ctx);
2148 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2151 static void perf_group_detach(struct perf_event *event)
2153 struct perf_event *leader = event->group_leader;
2154 struct perf_event *sibling, *tmp;
2155 struct perf_event_context *ctx = event->ctx;
2157 lockdep_assert_held(&ctx->lock);
2160 * We can have double detach due to exit/hot-unplug + close.
2162 if (!(event->attach_state & PERF_ATTACH_GROUP))
2165 event->attach_state &= ~PERF_ATTACH_GROUP;
2167 perf_put_aux_event(event);
2170 * If this is a sibling, remove it from its group.
2172 if (leader != event) {
2173 list_del_init(&event->sibling_list);
2174 event->group_leader->nr_siblings--;
2179 * If this was a group event with sibling events then
2180 * upgrade the siblings to singleton events by adding them
2181 * to whatever list we are on.
2183 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2185 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2186 perf_remove_sibling_event(sibling);
2188 sibling->group_leader = sibling;
2189 list_del_init(&sibling->sibling_list);
2191 /* Inherit group flags from the previous leader */
2192 sibling->group_caps = event->group_caps;
2194 if (!RB_EMPTY_NODE(&event->group_node)) {
2195 add_event_to_groups(sibling, event->ctx);
2197 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2198 list_add_tail(&sibling->active_list, get_event_list(sibling));
2201 WARN_ON_ONCE(sibling->ctx != event->ctx);
2205 for_each_sibling_event(tmp, leader)
2206 perf_event__header_size(tmp);
2208 perf_event__header_size(leader);
2211 static bool is_orphaned_event(struct perf_event *event)
2213 return event->state == PERF_EVENT_STATE_DEAD;
2216 static inline int __pmu_filter_match(struct perf_event *event)
2218 struct pmu *pmu = event->pmu;
2219 return pmu->filter_match ? pmu->filter_match(event) : 1;
2223 * Check whether we should attempt to schedule an event group based on
2224 * PMU-specific filtering. An event group can consist of HW and SW events,
2225 * potentially with a SW leader, so we must check all the filters, to
2226 * determine whether a group is schedulable:
2228 static inline int pmu_filter_match(struct perf_event *event)
2230 struct perf_event *sibling;
2232 if (!__pmu_filter_match(event))
2235 for_each_sibling_event(sibling, event) {
2236 if (!__pmu_filter_match(sibling))
2244 event_filter_match(struct perf_event *event)
2246 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2247 perf_cgroup_match(event) && pmu_filter_match(event);
2251 event_sched_out(struct perf_event *event,
2252 struct perf_cpu_context *cpuctx,
2253 struct perf_event_context *ctx)
2255 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2257 WARN_ON_ONCE(event->ctx != ctx);
2258 lockdep_assert_held(&ctx->lock);
2260 if (event->state != PERF_EVENT_STATE_ACTIVE)
2264 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2265 * we can schedule events _OUT_ individually through things like
2266 * __perf_remove_from_context().
2268 list_del_init(&event->active_list);
2270 perf_pmu_disable(event->pmu);
2272 event->pmu->del(event, 0);
2275 if (READ_ONCE(event->pending_disable) >= 0) {
2276 WRITE_ONCE(event->pending_disable, -1);
2277 perf_cgroup_event_disable(event, ctx);
2278 state = PERF_EVENT_STATE_OFF;
2280 perf_event_set_state(event, state);
2282 if (!is_software_event(event))
2283 cpuctx->active_oncpu--;
2284 if (!--ctx->nr_active)
2285 perf_event_ctx_deactivate(ctx);
2286 if (event->attr.freq && event->attr.sample_freq)
2288 if (event->attr.exclusive || !cpuctx->active_oncpu)
2289 cpuctx->exclusive = 0;
2291 perf_pmu_enable(event->pmu);
2295 group_sched_out(struct perf_event *group_event,
2296 struct perf_cpu_context *cpuctx,
2297 struct perf_event_context *ctx)
2299 struct perf_event *event;
2301 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2304 perf_pmu_disable(ctx->pmu);
2306 event_sched_out(group_event, cpuctx, ctx);
2309 * Schedule out siblings (if any):
2311 for_each_sibling_event(event, group_event)
2312 event_sched_out(event, cpuctx, ctx);
2314 perf_pmu_enable(ctx->pmu);
2316 if (group_event->attr.exclusive)
2317 cpuctx->exclusive = 0;
2320 #define DETACH_GROUP 0x01UL
2323 * Cross CPU call to remove a performance event
2325 * We disable the event on the hardware level first. After that we
2326 * remove it from the context list.
2329 __perf_remove_from_context(struct perf_event *event,
2330 struct perf_cpu_context *cpuctx,
2331 struct perf_event_context *ctx,
2334 unsigned long flags = (unsigned long)info;
2336 if (ctx->is_active & EVENT_TIME) {
2337 update_context_time(ctx);
2338 update_cgrp_time_from_cpuctx(cpuctx);
2341 event_sched_out(event, cpuctx, ctx);
2342 if (flags & DETACH_GROUP)
2343 perf_group_detach(event);
2344 list_del_event(event, ctx);
2346 if (!ctx->nr_events && ctx->is_active) {
2348 ctx->rotate_necessary = 0;
2350 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2351 cpuctx->task_ctx = NULL;
2357 * Remove the event from a task's (or a CPU's) list of events.
2359 * If event->ctx is a cloned context, callers must make sure that
2360 * every task struct that event->ctx->task could possibly point to
2361 * remains valid. This is OK when called from perf_release since
2362 * that only calls us on the top-level context, which can't be a clone.
2363 * When called from perf_event_exit_task, it's OK because the
2364 * context has been detached from its task.
2366 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2368 struct perf_event_context *ctx = event->ctx;
2370 lockdep_assert_held(&ctx->mutex);
2372 event_function_call(event, __perf_remove_from_context, (void *)flags);
2375 * The above event_function_call() can NO-OP when it hits
2376 * TASK_TOMBSTONE. In that case we must already have been detached
2377 * from the context (by perf_event_exit_event()) but the grouping
2378 * might still be in-tact.
2380 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2381 if ((flags & DETACH_GROUP) &&
2382 (event->attach_state & PERF_ATTACH_GROUP)) {
2384 * Since in that case we cannot possibly be scheduled, simply
2387 raw_spin_lock_irq(&ctx->lock);
2388 perf_group_detach(event);
2389 raw_spin_unlock_irq(&ctx->lock);
2394 * Cross CPU call to disable a performance event
2396 static void __perf_event_disable(struct perf_event *event,
2397 struct perf_cpu_context *cpuctx,
2398 struct perf_event_context *ctx,
2401 if (event->state < PERF_EVENT_STATE_INACTIVE)
2404 if (ctx->is_active & EVENT_TIME) {
2405 update_context_time(ctx);
2406 update_cgrp_time_from_event(event);
2409 if (event == event->group_leader)
2410 group_sched_out(event, cpuctx, ctx);
2412 event_sched_out(event, cpuctx, ctx);
2414 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2415 perf_cgroup_event_disable(event, ctx);
2421 * If event->ctx is a cloned context, callers must make sure that
2422 * every task struct that event->ctx->task could possibly point to
2423 * remains valid. This condition is satisfied when called through
2424 * perf_event_for_each_child or perf_event_for_each because they
2425 * hold the top-level event's child_mutex, so any descendant that
2426 * goes to exit will block in perf_event_exit_event().
2428 * When called from perf_pending_event it's OK because event->ctx
2429 * is the current context on this CPU and preemption is disabled,
2430 * hence we can't get into perf_event_task_sched_out for this context.
2432 static void _perf_event_disable(struct perf_event *event)
2434 struct perf_event_context *ctx = event->ctx;
2436 raw_spin_lock_irq(&ctx->lock);
2437 if (event->state <= PERF_EVENT_STATE_OFF) {
2438 raw_spin_unlock_irq(&ctx->lock);
2441 raw_spin_unlock_irq(&ctx->lock);
2443 event_function_call(event, __perf_event_disable, NULL);
2446 void perf_event_disable_local(struct perf_event *event)
2448 event_function_local(event, __perf_event_disable, NULL);
2452 * Strictly speaking kernel users cannot create groups and therefore this
2453 * interface does not need the perf_event_ctx_lock() magic.
2455 void perf_event_disable(struct perf_event *event)
2457 struct perf_event_context *ctx;
2459 ctx = perf_event_ctx_lock(event);
2460 _perf_event_disable(event);
2461 perf_event_ctx_unlock(event, ctx);
2463 EXPORT_SYMBOL_GPL(perf_event_disable);
2465 void perf_event_disable_inatomic(struct perf_event *event)
2467 WRITE_ONCE(event->pending_disable, smp_processor_id());
2468 /* can fail, see perf_pending_event_disable() */
2469 irq_work_queue(&event->pending);
2472 static void perf_set_shadow_time(struct perf_event *event,
2473 struct perf_event_context *ctx)
2476 * use the correct time source for the time snapshot
2478 * We could get by without this by leveraging the
2479 * fact that to get to this function, the caller
2480 * has most likely already called update_context_time()
2481 * and update_cgrp_time_xx() and thus both timestamp
2482 * are identical (or very close). Given that tstamp is,
2483 * already adjusted for cgroup, we could say that:
2484 * tstamp - ctx->timestamp
2486 * tstamp - cgrp->timestamp.
2488 * Then, in perf_output_read(), the calculation would
2489 * work with no changes because:
2490 * - event is guaranteed scheduled in
2491 * - no scheduled out in between
2492 * - thus the timestamp would be the same
2494 * But this is a bit hairy.
2496 * So instead, we have an explicit cgroup call to remain
2497 * within the time time source all along. We believe it
2498 * is cleaner and simpler to understand.
2500 if (is_cgroup_event(event))
2501 perf_cgroup_set_shadow_time(event, event->tstamp);
2503 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2506 #define MAX_INTERRUPTS (~0ULL)
2508 static void perf_log_throttle(struct perf_event *event, int enable);
2509 static void perf_log_itrace_start(struct perf_event *event);
2512 event_sched_in(struct perf_event *event,
2513 struct perf_cpu_context *cpuctx,
2514 struct perf_event_context *ctx)
2518 WARN_ON_ONCE(event->ctx != ctx);
2520 lockdep_assert_held(&ctx->lock);
2522 if (event->state <= PERF_EVENT_STATE_OFF)
2525 WRITE_ONCE(event->oncpu, smp_processor_id());
2527 * Order event::oncpu write to happen before the ACTIVE state is
2528 * visible. This allows perf_event_{stop,read}() to observe the correct
2529 * ->oncpu if it sees ACTIVE.
2532 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2535 * Unthrottle events, since we scheduled we might have missed several
2536 * ticks already, also for a heavily scheduling task there is little
2537 * guarantee it'll get a tick in a timely manner.
2539 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2540 perf_log_throttle(event, 1);
2541 event->hw.interrupts = 0;
2544 perf_pmu_disable(event->pmu);
2546 perf_set_shadow_time(event, ctx);
2548 perf_log_itrace_start(event);
2550 if (event->pmu->add(event, PERF_EF_START)) {
2551 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2557 if (!is_software_event(event))
2558 cpuctx->active_oncpu++;
2559 if (!ctx->nr_active++)
2560 perf_event_ctx_activate(ctx);
2561 if (event->attr.freq && event->attr.sample_freq)
2564 if (event->attr.exclusive)
2565 cpuctx->exclusive = 1;
2568 perf_pmu_enable(event->pmu);
2574 group_sched_in(struct perf_event *group_event,
2575 struct perf_cpu_context *cpuctx,
2576 struct perf_event_context *ctx)
2578 struct perf_event *event, *partial_group = NULL;
2579 struct pmu *pmu = ctx->pmu;
2581 if (group_event->state == PERF_EVENT_STATE_OFF)
2584 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2586 if (event_sched_in(group_event, cpuctx, ctx)) {
2587 pmu->cancel_txn(pmu);
2588 perf_mux_hrtimer_restart(cpuctx);
2593 * Schedule in siblings as one group (if any):
2595 for_each_sibling_event(event, group_event) {
2596 if (event_sched_in(event, cpuctx, ctx)) {
2597 partial_group = event;
2602 if (!pmu->commit_txn(pmu))
2607 * Groups can be scheduled in as one unit only, so undo any
2608 * partial group before returning:
2609 * The events up to the failed event are scheduled out normally.
2611 for_each_sibling_event(event, group_event) {
2612 if (event == partial_group)
2615 event_sched_out(event, cpuctx, ctx);
2617 event_sched_out(group_event, cpuctx, ctx);
2619 pmu->cancel_txn(pmu);
2621 perf_mux_hrtimer_restart(cpuctx);
2627 * Work out whether we can put this event group on the CPU now.
2629 static int group_can_go_on(struct perf_event *event,
2630 struct perf_cpu_context *cpuctx,
2634 * Groups consisting entirely of software events can always go on.
2636 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2639 * If an exclusive group is already on, no other hardware
2642 if (cpuctx->exclusive)
2645 * If this group is exclusive and there are already
2646 * events on the CPU, it can't go on.
2648 if (event->attr.exclusive && cpuctx->active_oncpu)
2651 * Otherwise, try to add it if all previous groups were able
2657 static void add_event_to_ctx(struct perf_event *event,
2658 struct perf_event_context *ctx)
2660 list_add_event(event, ctx);
2661 perf_group_attach(event);
2664 static void ctx_sched_out(struct perf_event_context *ctx,
2665 struct perf_cpu_context *cpuctx,
2666 enum event_type_t event_type);
2668 ctx_sched_in(struct perf_event_context *ctx,
2669 struct perf_cpu_context *cpuctx,
2670 enum event_type_t event_type,
2671 struct task_struct *task);
2673 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2674 struct perf_event_context *ctx,
2675 enum event_type_t event_type)
2677 if (!cpuctx->task_ctx)
2680 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2683 ctx_sched_out(ctx, cpuctx, event_type);
2686 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2687 struct perf_event_context *ctx,
2688 struct task_struct *task)
2690 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2692 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2693 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2695 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2699 * We want to maintain the following priority of scheduling:
2700 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2701 * - task pinned (EVENT_PINNED)
2702 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2703 * - task flexible (EVENT_FLEXIBLE).
2705 * In order to avoid unscheduling and scheduling back in everything every
2706 * time an event is added, only do it for the groups of equal priority and
2709 * This can be called after a batch operation on task events, in which case
2710 * event_type is a bit mask of the types of events involved. For CPU events,
2711 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2713 static void ctx_resched(struct perf_cpu_context *cpuctx,
2714 struct perf_event_context *task_ctx,
2715 enum event_type_t event_type)
2717 enum event_type_t ctx_event_type;
2718 bool cpu_event = !!(event_type & EVENT_CPU);
2721 * If pinned groups are involved, flexible groups also need to be
2724 if (event_type & EVENT_PINNED)
2725 event_type |= EVENT_FLEXIBLE;
2727 ctx_event_type = event_type & EVENT_ALL;
2729 perf_pmu_disable(cpuctx->ctx.pmu);
2731 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2734 * Decide which cpu ctx groups to schedule out based on the types
2735 * of events that caused rescheduling:
2736 * - EVENT_CPU: schedule out corresponding groups;
2737 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2738 * - otherwise, do nothing more.
2741 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2742 else if (ctx_event_type & EVENT_PINNED)
2743 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2745 perf_event_sched_in(cpuctx, task_ctx, current);
2746 perf_pmu_enable(cpuctx->ctx.pmu);
2749 void perf_pmu_resched(struct pmu *pmu)
2751 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2752 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2754 perf_ctx_lock(cpuctx, task_ctx);
2755 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2756 perf_ctx_unlock(cpuctx, task_ctx);
2760 * Cross CPU call to install and enable a performance event
2762 * Very similar to remote_function() + event_function() but cannot assume that
2763 * things like ctx->is_active and cpuctx->task_ctx are set.
2765 static int __perf_install_in_context(void *info)
2767 struct perf_event *event = info;
2768 struct perf_event_context *ctx = event->ctx;
2769 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2770 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2771 bool reprogram = true;
2774 raw_spin_lock(&cpuctx->ctx.lock);
2776 raw_spin_lock(&ctx->lock);
2779 reprogram = (ctx->task == current);
2782 * If the task is running, it must be running on this CPU,
2783 * otherwise we cannot reprogram things.
2785 * If its not running, we don't care, ctx->lock will
2786 * serialize against it becoming runnable.
2788 if (task_curr(ctx->task) && !reprogram) {
2793 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2794 } else if (task_ctx) {
2795 raw_spin_lock(&task_ctx->lock);
2798 #ifdef CONFIG_CGROUP_PERF
2799 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2801 * If the current cgroup doesn't match the event's
2802 * cgroup, we should not try to schedule it.
2804 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2805 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2806 event->cgrp->css.cgroup);
2811 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2812 add_event_to_ctx(event, ctx);
2813 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2815 add_event_to_ctx(event, ctx);
2819 perf_ctx_unlock(cpuctx, task_ctx);
2824 static bool exclusive_event_installable(struct perf_event *event,
2825 struct perf_event_context *ctx);
2828 * Attach a performance event to a context.
2830 * Very similar to event_function_call, see comment there.
2833 perf_install_in_context(struct perf_event_context *ctx,
2834 struct perf_event *event,
2837 struct task_struct *task = READ_ONCE(ctx->task);
2839 lockdep_assert_held(&ctx->mutex);
2841 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2843 if (event->cpu != -1)
2847 * Ensures that if we can observe event->ctx, both the event and ctx
2848 * will be 'complete'. See perf_iterate_sb_cpu().
2850 smp_store_release(&event->ctx, ctx);
2853 * perf_event_attr::disabled events will not run and can be initialized
2854 * without IPI. Except when this is the first event for the context, in
2855 * that case we need the magic of the IPI to set ctx->is_active.
2857 * The IOC_ENABLE that is sure to follow the creation of a disabled
2858 * event will issue the IPI and reprogram the hardware.
2860 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2861 raw_spin_lock_irq(&ctx->lock);
2862 if (ctx->task == TASK_TOMBSTONE) {
2863 raw_spin_unlock_irq(&ctx->lock);
2866 add_event_to_ctx(event, ctx);
2867 raw_spin_unlock_irq(&ctx->lock);
2872 cpu_function_call(cpu, __perf_install_in_context, event);
2877 * Should not happen, we validate the ctx is still alive before calling.
2879 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2883 * Installing events is tricky because we cannot rely on ctx->is_active
2884 * to be set in case this is the nr_events 0 -> 1 transition.
2886 * Instead we use task_curr(), which tells us if the task is running.
2887 * However, since we use task_curr() outside of rq::lock, we can race
2888 * against the actual state. This means the result can be wrong.
2890 * If we get a false positive, we retry, this is harmless.
2892 * If we get a false negative, things are complicated. If we are after
2893 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2894 * value must be correct. If we're before, it doesn't matter since
2895 * perf_event_context_sched_in() will program the counter.
2897 * However, this hinges on the remote context switch having observed
2898 * our task->perf_event_ctxp[] store, such that it will in fact take
2899 * ctx::lock in perf_event_context_sched_in().
2901 * We do this by task_function_call(), if the IPI fails to hit the task
2902 * we know any future context switch of task must see the
2903 * perf_event_ctpx[] store.
2907 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2908 * task_cpu() load, such that if the IPI then does not find the task
2909 * running, a future context switch of that task must observe the
2914 if (!task_function_call(task, __perf_install_in_context, event))
2917 raw_spin_lock_irq(&ctx->lock);
2919 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2921 * Cannot happen because we already checked above (which also
2922 * cannot happen), and we hold ctx->mutex, which serializes us
2923 * against perf_event_exit_task_context().
2925 raw_spin_unlock_irq(&ctx->lock);
2929 * If the task is not running, ctx->lock will avoid it becoming so,
2930 * thus we can safely install the event.
2932 if (task_curr(task)) {
2933 raw_spin_unlock_irq(&ctx->lock);
2936 add_event_to_ctx(event, ctx);
2937 raw_spin_unlock_irq(&ctx->lock);
2941 * Cross CPU call to enable a performance event
2943 static void __perf_event_enable(struct perf_event *event,
2944 struct perf_cpu_context *cpuctx,
2945 struct perf_event_context *ctx,
2948 struct perf_event *leader = event->group_leader;
2949 struct perf_event_context *task_ctx;
2951 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2952 event->state <= PERF_EVENT_STATE_ERROR)
2956 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2958 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2959 perf_cgroup_event_enable(event, ctx);
2961 if (!ctx->is_active)
2964 if (!event_filter_match(event)) {
2965 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2970 * If the event is in a group and isn't the group leader,
2971 * then don't put it on unless the group is on.
2973 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2974 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2978 task_ctx = cpuctx->task_ctx;
2980 WARN_ON_ONCE(task_ctx != ctx);
2982 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2988 * If event->ctx is a cloned context, callers must make sure that
2989 * every task struct that event->ctx->task could possibly point to
2990 * remains valid. This condition is satisfied when called through
2991 * perf_event_for_each_child or perf_event_for_each as described
2992 * for perf_event_disable.
2994 static void _perf_event_enable(struct perf_event *event)
2996 struct perf_event_context *ctx = event->ctx;
2998 raw_spin_lock_irq(&ctx->lock);
2999 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3000 event->state < PERF_EVENT_STATE_ERROR) {
3002 raw_spin_unlock_irq(&ctx->lock);
3007 * If the event is in error state, clear that first.
3009 * That way, if we see the event in error state below, we know that it
3010 * has gone back into error state, as distinct from the task having
3011 * been scheduled away before the cross-call arrived.
3013 if (event->state == PERF_EVENT_STATE_ERROR) {
3015 * Detached SIBLING events cannot leave ERROR state.
3017 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3018 event->group_leader == event)
3021 event->state = PERF_EVENT_STATE_OFF;
3023 raw_spin_unlock_irq(&ctx->lock);
3025 event_function_call(event, __perf_event_enable, NULL);
3029 * See perf_event_disable();
3031 void perf_event_enable(struct perf_event *event)
3033 struct perf_event_context *ctx;
3035 ctx = perf_event_ctx_lock(event);
3036 _perf_event_enable(event);
3037 perf_event_ctx_unlock(event, ctx);
3039 EXPORT_SYMBOL_GPL(perf_event_enable);
3041 struct stop_event_data {
3042 struct perf_event *event;
3043 unsigned int restart;
3046 static int __perf_event_stop(void *info)
3048 struct stop_event_data *sd = info;
3049 struct perf_event *event = sd->event;
3051 /* if it's already INACTIVE, do nothing */
3052 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3055 /* matches smp_wmb() in event_sched_in() */
3059 * There is a window with interrupts enabled before we get here,
3060 * so we need to check again lest we try to stop another CPU's event.
3062 if (READ_ONCE(event->oncpu) != smp_processor_id())
3065 event->pmu->stop(event, PERF_EF_UPDATE);
3068 * May race with the actual stop (through perf_pmu_output_stop()),
3069 * but it is only used for events with AUX ring buffer, and such
3070 * events will refuse to restart because of rb::aux_mmap_count==0,
3071 * see comments in perf_aux_output_begin().
3073 * Since this is happening on an event-local CPU, no trace is lost
3077 event->pmu->start(event, 0);
3082 static int perf_event_stop(struct perf_event *event, int restart)
3084 struct stop_event_data sd = {
3091 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3094 /* matches smp_wmb() in event_sched_in() */
3098 * We only want to restart ACTIVE events, so if the event goes
3099 * inactive here (event->oncpu==-1), there's nothing more to do;
3100 * fall through with ret==-ENXIO.
3102 ret = cpu_function_call(READ_ONCE(event->oncpu),
3103 __perf_event_stop, &sd);
3104 } while (ret == -EAGAIN);
3110 * In order to contain the amount of racy and tricky in the address filter
3111 * configuration management, it is a two part process:
3113 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3114 * we update the addresses of corresponding vmas in
3115 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3116 * (p2) when an event is scheduled in (pmu::add), it calls
3117 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3118 * if the generation has changed since the previous call.
3120 * If (p1) happens while the event is active, we restart it to force (p2).
3122 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3123 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3125 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3126 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3128 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3131 void perf_event_addr_filters_sync(struct perf_event *event)
3133 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3135 if (!has_addr_filter(event))
3138 raw_spin_lock(&ifh->lock);
3139 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3140 event->pmu->addr_filters_sync(event);
3141 event->hw.addr_filters_gen = event->addr_filters_gen;
3143 raw_spin_unlock(&ifh->lock);
3145 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3147 static int _perf_event_refresh(struct perf_event *event, int refresh)
3150 * not supported on inherited events
3152 if (event->attr.inherit || !is_sampling_event(event))
3155 atomic_add(refresh, &event->event_limit);
3156 _perf_event_enable(event);
3162 * See perf_event_disable()
3164 int perf_event_refresh(struct perf_event *event, int refresh)
3166 struct perf_event_context *ctx;
3169 ctx = perf_event_ctx_lock(event);
3170 ret = _perf_event_refresh(event, refresh);
3171 perf_event_ctx_unlock(event, ctx);
3175 EXPORT_SYMBOL_GPL(perf_event_refresh);
3177 static int perf_event_modify_breakpoint(struct perf_event *bp,
3178 struct perf_event_attr *attr)
3182 _perf_event_disable(bp);
3184 err = modify_user_hw_breakpoint_check(bp, attr, true);
3186 if (!bp->attr.disabled)
3187 _perf_event_enable(bp);
3192 static int perf_event_modify_attr(struct perf_event *event,
3193 struct perf_event_attr *attr)
3195 if (event->attr.type != attr->type)
3198 switch (event->attr.type) {
3199 case PERF_TYPE_BREAKPOINT:
3200 return perf_event_modify_breakpoint(event, attr);
3202 /* Place holder for future additions. */
3207 static void ctx_sched_out(struct perf_event_context *ctx,
3208 struct perf_cpu_context *cpuctx,
3209 enum event_type_t event_type)
3211 struct perf_event *event, *tmp;
3212 int is_active = ctx->is_active;
3214 lockdep_assert_held(&ctx->lock);
3216 if (likely(!ctx->nr_events)) {
3218 * See __perf_remove_from_context().
3220 WARN_ON_ONCE(ctx->is_active);
3222 WARN_ON_ONCE(cpuctx->task_ctx);
3226 ctx->is_active &= ~event_type;
3227 if (!(ctx->is_active & EVENT_ALL))
3231 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3232 if (!ctx->is_active)
3233 cpuctx->task_ctx = NULL;
3237 * Always update time if it was set; not only when it changes.
3238 * Otherwise we can 'forget' to update time for any but the last
3239 * context we sched out. For example:
3241 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3242 * ctx_sched_out(.event_type = EVENT_PINNED)
3244 * would only update time for the pinned events.
3246 if (is_active & EVENT_TIME) {
3247 /* update (and stop) ctx time */
3248 update_context_time(ctx);
3249 update_cgrp_time_from_cpuctx(cpuctx);
3252 is_active ^= ctx->is_active; /* changed bits */
3254 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3257 perf_pmu_disable(ctx->pmu);
3258 if (is_active & EVENT_PINNED) {
3259 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3260 group_sched_out(event, cpuctx, ctx);
3263 if (is_active & EVENT_FLEXIBLE) {
3264 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3265 group_sched_out(event, cpuctx, ctx);
3268 * Since we cleared EVENT_FLEXIBLE, also clear
3269 * rotate_necessary, is will be reset by
3270 * ctx_flexible_sched_in() when needed.
3272 ctx->rotate_necessary = 0;
3274 perf_pmu_enable(ctx->pmu);
3278 * Test whether two contexts are equivalent, i.e. whether they have both been
3279 * cloned from the same version of the same context.
3281 * Equivalence is measured using a generation number in the context that is
3282 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3283 * and list_del_event().
3285 static int context_equiv(struct perf_event_context *ctx1,
3286 struct perf_event_context *ctx2)
3288 lockdep_assert_held(&ctx1->lock);
3289 lockdep_assert_held(&ctx2->lock);
3291 /* Pinning disables the swap optimization */
3292 if (ctx1->pin_count || ctx2->pin_count)
3295 /* If ctx1 is the parent of ctx2 */
3296 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3299 /* If ctx2 is the parent of ctx1 */
3300 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3304 * If ctx1 and ctx2 have the same parent; we flatten the parent
3305 * hierarchy, see perf_event_init_context().
3307 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3308 ctx1->parent_gen == ctx2->parent_gen)
3315 static void __perf_event_sync_stat(struct perf_event *event,
3316 struct perf_event *next_event)
3320 if (!event->attr.inherit_stat)
3324 * Update the event value, we cannot use perf_event_read()
3325 * because we're in the middle of a context switch and have IRQs
3326 * disabled, which upsets smp_call_function_single(), however
3327 * we know the event must be on the current CPU, therefore we
3328 * don't need to use it.
3330 if (event->state == PERF_EVENT_STATE_ACTIVE)
3331 event->pmu->read(event);
3333 perf_event_update_time(event);
3336 * In order to keep per-task stats reliable we need to flip the event
3337 * values when we flip the contexts.
3339 value = local64_read(&next_event->count);
3340 value = local64_xchg(&event->count, value);
3341 local64_set(&next_event->count, value);
3343 swap(event->total_time_enabled, next_event->total_time_enabled);
3344 swap(event->total_time_running, next_event->total_time_running);
3347 * Since we swizzled the values, update the user visible data too.
3349 perf_event_update_userpage(event);
3350 perf_event_update_userpage(next_event);
3353 static void perf_event_sync_stat(struct perf_event_context *ctx,
3354 struct perf_event_context *next_ctx)
3356 struct perf_event *event, *next_event;
3361 update_context_time(ctx);
3363 event = list_first_entry(&ctx->event_list,
3364 struct perf_event, event_entry);
3366 next_event = list_first_entry(&next_ctx->event_list,
3367 struct perf_event, event_entry);
3369 while (&event->event_entry != &ctx->event_list &&
3370 &next_event->event_entry != &next_ctx->event_list) {
3372 __perf_event_sync_stat(event, next_event);
3374 event = list_next_entry(event, event_entry);
3375 next_event = list_next_entry(next_event, event_entry);
3379 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3380 struct task_struct *next)
3382 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3383 struct perf_event_context *next_ctx;
3384 struct perf_event_context *parent, *next_parent;
3385 struct perf_cpu_context *cpuctx;
3393 cpuctx = __get_cpu_context(ctx);
3394 if (!cpuctx->task_ctx)
3398 next_ctx = next->perf_event_ctxp[ctxn];
3402 parent = rcu_dereference(ctx->parent_ctx);
3403 next_parent = rcu_dereference(next_ctx->parent_ctx);
3405 /* If neither context have a parent context; they cannot be clones. */
3406 if (!parent && !next_parent)
3409 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3411 * Looks like the two contexts are clones, so we might be
3412 * able to optimize the context switch. We lock both
3413 * contexts and check that they are clones under the
3414 * lock (including re-checking that neither has been
3415 * uncloned in the meantime). It doesn't matter which
3416 * order we take the locks because no other cpu could
3417 * be trying to lock both of these tasks.
3419 raw_spin_lock(&ctx->lock);
3420 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3421 if (context_equiv(ctx, next_ctx)) {
3423 WRITE_ONCE(ctx->task, next);
3424 WRITE_ONCE(next_ctx->task, task);
3426 perf_pmu_disable(pmu);
3428 if (cpuctx->sched_cb_usage && pmu->sched_task)
3429 pmu->sched_task(ctx, false);
3432 * PMU specific parts of task perf context can require
3433 * additional synchronization. As an example of such
3434 * synchronization see implementation details of Intel
3435 * LBR call stack data profiling;
3437 if (pmu->swap_task_ctx)
3438 pmu->swap_task_ctx(ctx, next_ctx);
3440 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3442 perf_pmu_enable(pmu);
3445 * RCU_INIT_POINTER here is safe because we've not
3446 * modified the ctx and the above modification of
3447 * ctx->task and ctx->task_ctx_data are immaterial
3448 * since those values are always verified under
3449 * ctx->lock which we're now holding.
3451 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3452 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3456 perf_event_sync_stat(ctx, next_ctx);
3458 raw_spin_unlock(&next_ctx->lock);
3459 raw_spin_unlock(&ctx->lock);
3465 raw_spin_lock(&ctx->lock);
3466 perf_pmu_disable(pmu);
3468 if (cpuctx->sched_cb_usage && pmu->sched_task)
3469 pmu->sched_task(ctx, false);
3470 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3472 perf_pmu_enable(pmu);
3473 raw_spin_unlock(&ctx->lock);
3477 void perf_sched_cb_dec(struct pmu *pmu)
3479 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3481 --cpuctx->sched_cb_usage;
3485 void perf_sched_cb_inc(struct pmu *pmu)
3487 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3489 cpuctx->sched_cb_usage++;
3493 * This function provides the context switch callback to the lower code
3494 * layer. It is invoked ONLY when the context switch callback is enabled.
3496 * This callback is relevant even to per-cpu events; for example multi event
3497 * PEBS requires this to provide PID/TID information. This requires we flush
3498 * all queued PEBS records before we context switch to a new task.
3500 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3504 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3506 if (WARN_ON_ONCE(!pmu->sched_task))
3509 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3510 perf_pmu_disable(pmu);
3512 pmu->sched_task(cpuctx->task_ctx, sched_in);
3514 perf_pmu_enable(pmu);
3515 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3518 static void perf_event_switch(struct task_struct *task,
3519 struct task_struct *next_prev, bool sched_in);
3521 #define for_each_task_context_nr(ctxn) \
3522 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3525 * Called from scheduler to remove the events of the current task,
3526 * with interrupts disabled.
3528 * We stop each event and update the event value in event->count.
3530 * This does not protect us against NMI, but disable()
3531 * sets the disabled bit in the control field of event _before_
3532 * accessing the event control register. If a NMI hits, then it will
3533 * not restart the event.
3535 void __perf_event_task_sched_out(struct task_struct *task,
3536 struct task_struct *next)
3540 if (atomic_read(&nr_switch_events))
3541 perf_event_switch(task, next, false);
3543 for_each_task_context_nr(ctxn)
3544 perf_event_context_sched_out(task, ctxn, next);
3547 * if cgroup events exist on this CPU, then we need
3548 * to check if we have to switch out PMU state.
3549 * cgroup event are system-wide mode only
3551 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3552 perf_cgroup_sched_out(task, next);
3556 * Called with IRQs disabled
3558 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3559 enum event_type_t event_type)
3561 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3564 static bool perf_less_group_idx(const void *l, const void *r)
3566 const struct perf_event *le = *(const struct perf_event **)l;
3567 const struct perf_event *re = *(const struct perf_event **)r;
3569 return le->group_index < re->group_index;
3572 static void swap_ptr(void *l, void *r)
3574 void **lp = l, **rp = r;
3579 static const struct min_heap_callbacks perf_min_heap = {
3580 .elem_size = sizeof(struct perf_event *),
3581 .less = perf_less_group_idx,
3585 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3587 struct perf_event **itrs = heap->data;
3590 itrs[heap->nr] = event;
3595 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3596 struct perf_event_groups *groups, int cpu,
3597 int (*func)(struct perf_event *, void *),
3600 #ifdef CONFIG_CGROUP_PERF
3601 struct cgroup_subsys_state *css = NULL;
3603 /* Space for per CPU and/or any CPU event iterators. */
3604 struct perf_event *itrs[2];
3605 struct min_heap event_heap;
3606 struct perf_event **evt;
3610 event_heap = (struct min_heap){
3611 .data = cpuctx->heap,
3613 .size = cpuctx->heap_size,
3616 lockdep_assert_held(&cpuctx->ctx.lock);
3618 #ifdef CONFIG_CGROUP_PERF
3620 css = &cpuctx->cgrp->css;
3623 event_heap = (struct min_heap){
3626 .size = ARRAY_SIZE(itrs),
3628 /* Events not within a CPU context may be on any CPU. */
3629 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3631 evt = event_heap.data;
3633 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3635 #ifdef CONFIG_CGROUP_PERF
3636 for (; css; css = css->parent)
3637 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3640 min_heapify_all(&event_heap, &perf_min_heap);
3642 while (event_heap.nr) {
3643 ret = func(*evt, data);
3647 *evt = perf_event_groups_next(*evt);
3649 min_heapify(&event_heap, 0, &perf_min_heap);
3651 min_heap_pop(&event_heap, &perf_min_heap);
3657 static int merge_sched_in(struct perf_event *event, void *data)
3659 struct perf_event_context *ctx = event->ctx;
3660 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3661 int *can_add_hw = data;
3663 if (event->state <= PERF_EVENT_STATE_OFF)
3666 if (!event_filter_match(event))
3669 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3670 if (!group_sched_in(event, cpuctx, ctx))
3671 list_add_tail(&event->active_list, get_event_list(event));
3674 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3675 if (event->attr.pinned) {
3676 perf_cgroup_event_disable(event, ctx);
3677 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3681 ctx->rotate_necessary = 1;
3688 ctx_pinned_sched_in(struct perf_event_context *ctx,
3689 struct perf_cpu_context *cpuctx)
3693 if (ctx != &cpuctx->ctx)
3696 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3698 merge_sched_in, &can_add_hw);
3702 ctx_flexible_sched_in(struct perf_event_context *ctx,
3703 struct perf_cpu_context *cpuctx)
3707 if (ctx != &cpuctx->ctx)
3710 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3712 merge_sched_in, &can_add_hw);
3716 ctx_sched_in(struct perf_event_context *ctx,
3717 struct perf_cpu_context *cpuctx,
3718 enum event_type_t event_type,
3719 struct task_struct *task)
3721 int is_active = ctx->is_active;
3724 lockdep_assert_held(&ctx->lock);
3726 if (likely(!ctx->nr_events))
3729 ctx->is_active |= (event_type | EVENT_TIME);
3732 cpuctx->task_ctx = ctx;
3734 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3737 is_active ^= ctx->is_active; /* changed bits */
3739 if (is_active & EVENT_TIME) {
3740 /* start ctx time */
3742 ctx->timestamp = now;
3743 perf_cgroup_set_timestamp(task, ctx);
3747 * First go through the list and put on any pinned groups
3748 * in order to give them the best chance of going on.
3750 if (is_active & EVENT_PINNED)
3751 ctx_pinned_sched_in(ctx, cpuctx);
3753 /* Then walk through the lower prio flexible groups */
3754 if (is_active & EVENT_FLEXIBLE)
3755 ctx_flexible_sched_in(ctx, cpuctx);
3758 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3759 enum event_type_t event_type,
3760 struct task_struct *task)
3762 struct perf_event_context *ctx = &cpuctx->ctx;
3764 ctx_sched_in(ctx, cpuctx, event_type, task);
3767 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3768 struct task_struct *task)
3770 struct perf_cpu_context *cpuctx;
3771 struct pmu *pmu = ctx->pmu;
3773 cpuctx = __get_cpu_context(ctx);
3774 if (cpuctx->task_ctx == ctx) {
3775 if (cpuctx->sched_cb_usage)
3776 __perf_pmu_sched_task(cpuctx, true);
3780 perf_ctx_lock(cpuctx, ctx);
3782 * We must check ctx->nr_events while holding ctx->lock, such
3783 * that we serialize against perf_install_in_context().
3785 if (!ctx->nr_events)
3788 perf_pmu_disable(pmu);
3790 * We want to keep the following priority order:
3791 * cpu pinned (that don't need to move), task pinned,
3792 * cpu flexible, task flexible.
3794 * However, if task's ctx is not carrying any pinned
3795 * events, no need to flip the cpuctx's events around.
3797 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3798 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3799 perf_event_sched_in(cpuctx, ctx, task);
3801 if (cpuctx->sched_cb_usage && pmu->sched_task)
3802 pmu->sched_task(cpuctx->task_ctx, true);
3804 perf_pmu_enable(pmu);
3807 perf_ctx_unlock(cpuctx, ctx);
3811 * Called from scheduler to add the events of the current task
3812 * with interrupts disabled.
3814 * We restore the event value and then enable it.
3816 * This does not protect us against NMI, but enable()
3817 * sets the enabled bit in the control field of event _before_
3818 * accessing the event control register. If a NMI hits, then it will
3819 * keep the event running.
3821 void __perf_event_task_sched_in(struct task_struct *prev,
3822 struct task_struct *task)
3824 struct perf_event_context *ctx;
3828 * If cgroup events exist on this CPU, then we need to check if we have
3829 * to switch in PMU state; cgroup event are system-wide mode only.
3831 * Since cgroup events are CPU events, we must schedule these in before
3832 * we schedule in the task events.
3834 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3835 perf_cgroup_sched_in(prev, task);
3837 for_each_task_context_nr(ctxn) {
3838 ctx = task->perf_event_ctxp[ctxn];
3842 perf_event_context_sched_in(ctx, task);
3845 if (atomic_read(&nr_switch_events))
3846 perf_event_switch(task, prev, true);
3849 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3851 u64 frequency = event->attr.sample_freq;
3852 u64 sec = NSEC_PER_SEC;
3853 u64 divisor, dividend;
3855 int count_fls, nsec_fls, frequency_fls, sec_fls;
3857 count_fls = fls64(count);
3858 nsec_fls = fls64(nsec);
3859 frequency_fls = fls64(frequency);
3863 * We got @count in @nsec, with a target of sample_freq HZ
3864 * the target period becomes:
3867 * period = -------------------
3868 * @nsec * sample_freq
3873 * Reduce accuracy by one bit such that @a and @b converge
3874 * to a similar magnitude.
3876 #define REDUCE_FLS(a, b) \
3878 if (a##_fls > b##_fls) { \
3888 * Reduce accuracy until either term fits in a u64, then proceed with
3889 * the other, so that finally we can do a u64/u64 division.
3891 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3892 REDUCE_FLS(nsec, frequency);
3893 REDUCE_FLS(sec, count);
3896 if (count_fls + sec_fls > 64) {
3897 divisor = nsec * frequency;
3899 while (count_fls + sec_fls > 64) {
3900 REDUCE_FLS(count, sec);
3904 dividend = count * sec;
3906 dividend = count * sec;
3908 while (nsec_fls + frequency_fls > 64) {
3909 REDUCE_FLS(nsec, frequency);
3913 divisor = nsec * frequency;
3919 return div64_u64(dividend, divisor);
3922 static DEFINE_PER_CPU(int, perf_throttled_count);
3923 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3925 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3927 struct hw_perf_event *hwc = &event->hw;
3928 s64 period, sample_period;
3931 period = perf_calculate_period(event, nsec, count);
3933 delta = (s64)(period - hwc->sample_period);
3934 delta = (delta + 7) / 8; /* low pass filter */
3936 sample_period = hwc->sample_period + delta;
3941 hwc->sample_period = sample_period;
3943 if (local64_read(&hwc->period_left) > 8*sample_period) {
3945 event->pmu->stop(event, PERF_EF_UPDATE);
3947 local64_set(&hwc->period_left, 0);
3950 event->pmu->start(event, PERF_EF_RELOAD);
3955 * combine freq adjustment with unthrottling to avoid two passes over the
3956 * events. At the same time, make sure, having freq events does not change
3957 * the rate of unthrottling as that would introduce bias.
3959 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3962 struct perf_event *event;
3963 struct hw_perf_event *hwc;
3964 u64 now, period = TICK_NSEC;
3968 * only need to iterate over all events iff:
3969 * - context have events in frequency mode (needs freq adjust)
3970 * - there are events to unthrottle on this cpu
3972 if (!(ctx->nr_freq || needs_unthr))
3975 raw_spin_lock(&ctx->lock);
3976 perf_pmu_disable(ctx->pmu);
3978 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3979 if (event->state != PERF_EVENT_STATE_ACTIVE)
3982 if (!event_filter_match(event))
3985 perf_pmu_disable(event->pmu);
3989 if (hwc->interrupts == MAX_INTERRUPTS) {
3990 hwc->interrupts = 0;
3991 perf_log_throttle(event, 1);
3992 event->pmu->start(event, 0);
3995 if (!event->attr.freq || !event->attr.sample_freq)
3999 * stop the event and update event->count
4001 event->pmu->stop(event, PERF_EF_UPDATE);
4003 now = local64_read(&event->count);
4004 delta = now - hwc->freq_count_stamp;
4005 hwc->freq_count_stamp = now;
4009 * reload only if value has changed
4010 * we have stopped the event so tell that
4011 * to perf_adjust_period() to avoid stopping it
4015 perf_adjust_period(event, period, delta, false);
4017 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4019 perf_pmu_enable(event->pmu);
4022 perf_pmu_enable(ctx->pmu);
4023 raw_spin_unlock(&ctx->lock);
4027 * Move @event to the tail of the @ctx's elegible events.
4029 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4032 * Rotate the first entry last of non-pinned groups. Rotation might be
4033 * disabled by the inheritance code.
4035 if (ctx->rotate_disable)
4038 perf_event_groups_delete(&ctx->flexible_groups, event);
4039 perf_event_groups_insert(&ctx->flexible_groups, event);
4042 /* pick an event from the flexible_groups to rotate */
4043 static inline struct perf_event *
4044 ctx_event_to_rotate(struct perf_event_context *ctx)
4046 struct perf_event *event;
4048 /* pick the first active flexible event */
4049 event = list_first_entry_or_null(&ctx->flexible_active,
4050 struct perf_event, active_list);
4052 /* if no active flexible event, pick the first event */
4054 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4055 typeof(*event), group_node);
4059 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4060 * finds there are unschedulable events, it will set it again.
4062 ctx->rotate_necessary = 0;
4067 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4069 struct perf_event *cpu_event = NULL, *task_event = NULL;
4070 struct perf_event_context *task_ctx = NULL;
4071 int cpu_rotate, task_rotate;
4074 * Since we run this from IRQ context, nobody can install new
4075 * events, thus the event count values are stable.
4078 cpu_rotate = cpuctx->ctx.rotate_necessary;
4079 task_ctx = cpuctx->task_ctx;
4080 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4082 if (!(cpu_rotate || task_rotate))
4085 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4086 perf_pmu_disable(cpuctx->ctx.pmu);
4089 task_event = ctx_event_to_rotate(task_ctx);
4091 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4094 * As per the order given at ctx_resched() first 'pop' task flexible
4095 * and then, if needed CPU flexible.
4097 if (task_event || (task_ctx && cpu_event))
4098 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4100 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4103 rotate_ctx(task_ctx, task_event);
4105 rotate_ctx(&cpuctx->ctx, cpu_event);
4107 perf_event_sched_in(cpuctx, task_ctx, current);
4109 perf_pmu_enable(cpuctx->ctx.pmu);
4110 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4115 void perf_event_task_tick(void)
4117 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4118 struct perf_event_context *ctx, *tmp;
4121 lockdep_assert_irqs_disabled();
4123 __this_cpu_inc(perf_throttled_seq);
4124 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4125 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4127 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4128 perf_adjust_freq_unthr_context(ctx, throttled);
4131 static int event_enable_on_exec(struct perf_event *event,
4132 struct perf_event_context *ctx)
4134 if (!event->attr.enable_on_exec)
4137 event->attr.enable_on_exec = 0;
4138 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4141 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4147 * Enable all of a task's events that have been marked enable-on-exec.
4148 * This expects task == current.
4150 static void perf_event_enable_on_exec(int ctxn)
4152 struct perf_event_context *ctx, *clone_ctx = NULL;
4153 enum event_type_t event_type = 0;
4154 struct perf_cpu_context *cpuctx;
4155 struct perf_event *event;
4156 unsigned long flags;
4159 local_irq_save(flags);
4160 ctx = current->perf_event_ctxp[ctxn];
4161 if (!ctx || !ctx->nr_events)
4164 cpuctx = __get_cpu_context(ctx);
4165 perf_ctx_lock(cpuctx, ctx);
4166 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4167 list_for_each_entry(event, &ctx->event_list, event_entry) {
4168 enabled |= event_enable_on_exec(event, ctx);
4169 event_type |= get_event_type(event);
4173 * Unclone and reschedule this context if we enabled any event.
4176 clone_ctx = unclone_ctx(ctx);
4177 ctx_resched(cpuctx, ctx, event_type);
4179 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4181 perf_ctx_unlock(cpuctx, ctx);
4184 local_irq_restore(flags);
4190 struct perf_read_data {
4191 struct perf_event *event;
4196 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4198 u16 local_pkg, event_pkg;
4200 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4201 int local_cpu = smp_processor_id();
4203 event_pkg = topology_physical_package_id(event_cpu);
4204 local_pkg = topology_physical_package_id(local_cpu);
4206 if (event_pkg == local_pkg)
4214 * Cross CPU call to read the hardware event
4216 static void __perf_event_read(void *info)
4218 struct perf_read_data *data = info;
4219 struct perf_event *sub, *event = data->event;
4220 struct perf_event_context *ctx = event->ctx;
4221 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4222 struct pmu *pmu = event->pmu;
4225 * If this is a task context, we need to check whether it is
4226 * the current task context of this cpu. If not it has been
4227 * scheduled out before the smp call arrived. In that case
4228 * event->count would have been updated to a recent sample
4229 * when the event was scheduled out.
4231 if (ctx->task && cpuctx->task_ctx != ctx)
4234 raw_spin_lock(&ctx->lock);
4235 if (ctx->is_active & EVENT_TIME) {
4236 update_context_time(ctx);
4237 update_cgrp_time_from_event(event);
4240 perf_event_update_time(event);
4242 perf_event_update_sibling_time(event);
4244 if (event->state != PERF_EVENT_STATE_ACTIVE)
4253 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4257 for_each_sibling_event(sub, event) {
4258 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4260 * Use sibling's PMU rather than @event's since
4261 * sibling could be on different (eg: software) PMU.
4263 sub->pmu->read(sub);
4267 data->ret = pmu->commit_txn(pmu);
4270 raw_spin_unlock(&ctx->lock);
4273 static inline u64 perf_event_count(struct perf_event *event)
4275 return local64_read(&event->count) + atomic64_read(&event->child_count);
4279 * NMI-safe method to read a local event, that is an event that
4281 * - either for the current task, or for this CPU
4282 * - does not have inherit set, for inherited task events
4283 * will not be local and we cannot read them atomically
4284 * - must not have a pmu::count method
4286 int perf_event_read_local(struct perf_event *event, u64 *value,
4287 u64 *enabled, u64 *running)
4289 unsigned long flags;
4293 * Disabling interrupts avoids all counter scheduling (context
4294 * switches, timer based rotation and IPIs).
4296 local_irq_save(flags);
4299 * It must not be an event with inherit set, we cannot read
4300 * all child counters from atomic context.
4302 if (event->attr.inherit) {
4307 /* If this is a per-task event, it must be for current */
4308 if ((event->attach_state & PERF_ATTACH_TASK) &&
4309 event->hw.target != current) {
4314 /* If this is a per-CPU event, it must be for this CPU */
4315 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4316 event->cpu != smp_processor_id()) {
4321 /* If this is a pinned event it must be running on this CPU */
4322 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4328 * If the event is currently on this CPU, its either a per-task event,
4329 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4332 if (event->oncpu == smp_processor_id())
4333 event->pmu->read(event);
4335 *value = local64_read(&event->count);
4336 if (enabled || running) {
4337 u64 now = event->shadow_ctx_time + perf_clock();
4338 u64 __enabled, __running;
4340 __perf_update_times(event, now, &__enabled, &__running);
4342 *enabled = __enabled;
4344 *running = __running;
4347 local_irq_restore(flags);
4352 static int perf_event_read(struct perf_event *event, bool group)
4354 enum perf_event_state state = READ_ONCE(event->state);
4355 int event_cpu, ret = 0;
4358 * If event is enabled and currently active on a CPU, update the
4359 * value in the event structure:
4362 if (state == PERF_EVENT_STATE_ACTIVE) {
4363 struct perf_read_data data;
4366 * Orders the ->state and ->oncpu loads such that if we see
4367 * ACTIVE we must also see the right ->oncpu.
4369 * Matches the smp_wmb() from event_sched_in().
4373 event_cpu = READ_ONCE(event->oncpu);
4374 if ((unsigned)event_cpu >= nr_cpu_ids)
4377 data = (struct perf_read_data){
4384 event_cpu = __perf_event_read_cpu(event, event_cpu);
4387 * Purposely ignore the smp_call_function_single() return
4390 * If event_cpu isn't a valid CPU it means the event got
4391 * scheduled out and that will have updated the event count.
4393 * Therefore, either way, we'll have an up-to-date event count
4396 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4400 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4401 struct perf_event_context *ctx = event->ctx;
4402 unsigned long flags;
4404 raw_spin_lock_irqsave(&ctx->lock, flags);
4405 state = event->state;
4406 if (state != PERF_EVENT_STATE_INACTIVE) {
4407 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4412 * May read while context is not active (e.g., thread is
4413 * blocked), in that case we cannot update context time
4415 if (ctx->is_active & EVENT_TIME) {
4416 update_context_time(ctx);
4417 update_cgrp_time_from_event(event);
4420 perf_event_update_time(event);
4422 perf_event_update_sibling_time(event);
4423 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4430 * Initialize the perf_event context in a task_struct:
4432 static void __perf_event_init_context(struct perf_event_context *ctx)
4434 raw_spin_lock_init(&ctx->lock);
4435 mutex_init(&ctx->mutex);
4436 INIT_LIST_HEAD(&ctx->active_ctx_list);
4437 perf_event_groups_init(&ctx->pinned_groups);
4438 perf_event_groups_init(&ctx->flexible_groups);
4439 INIT_LIST_HEAD(&ctx->event_list);
4440 INIT_LIST_HEAD(&ctx->pinned_active);
4441 INIT_LIST_HEAD(&ctx->flexible_active);
4442 refcount_set(&ctx->refcount, 1);
4445 static struct perf_event_context *
4446 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4448 struct perf_event_context *ctx;
4450 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4454 __perf_event_init_context(ctx);
4456 ctx->task = get_task_struct(task);
4462 static struct task_struct *
4463 find_lively_task_by_vpid(pid_t vpid)
4465 struct task_struct *task;
4471 task = find_task_by_vpid(vpid);
4473 get_task_struct(task);
4477 return ERR_PTR(-ESRCH);
4483 * Returns a matching context with refcount and pincount.
4485 static struct perf_event_context *
4486 find_get_context(struct pmu *pmu, struct task_struct *task,
4487 struct perf_event *event)
4489 struct perf_event_context *ctx, *clone_ctx = NULL;
4490 struct perf_cpu_context *cpuctx;
4491 void *task_ctx_data = NULL;
4492 unsigned long flags;
4494 int cpu = event->cpu;
4497 /* Must be root to operate on a CPU event: */
4498 err = perf_allow_cpu(&event->attr);
4500 return ERR_PTR(err);
4502 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4511 ctxn = pmu->task_ctx_nr;
4515 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4516 task_ctx_data = alloc_task_ctx_data(pmu);
4517 if (!task_ctx_data) {
4524 ctx = perf_lock_task_context(task, ctxn, &flags);
4526 clone_ctx = unclone_ctx(ctx);
4529 if (task_ctx_data && !ctx->task_ctx_data) {
4530 ctx->task_ctx_data = task_ctx_data;
4531 task_ctx_data = NULL;
4533 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4538 ctx = alloc_perf_context(pmu, task);
4543 if (task_ctx_data) {
4544 ctx->task_ctx_data = task_ctx_data;
4545 task_ctx_data = NULL;
4549 mutex_lock(&task->perf_event_mutex);
4551 * If it has already passed perf_event_exit_task().
4552 * we must see PF_EXITING, it takes this mutex too.
4554 if (task->flags & PF_EXITING)
4556 else if (task->perf_event_ctxp[ctxn])
4561 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4563 mutex_unlock(&task->perf_event_mutex);
4565 if (unlikely(err)) {
4574 free_task_ctx_data(pmu, task_ctx_data);
4578 free_task_ctx_data(pmu, task_ctx_data);
4579 return ERR_PTR(err);
4582 static void perf_event_free_filter(struct perf_event *event);
4583 static void perf_event_free_bpf_prog(struct perf_event *event);
4585 static void free_event_rcu(struct rcu_head *head)
4587 struct perf_event *event;
4589 event = container_of(head, struct perf_event, rcu_head);
4591 put_pid_ns(event->ns);
4592 perf_event_free_filter(event);
4596 static void ring_buffer_attach(struct perf_event *event,
4597 struct perf_buffer *rb);
4599 static void detach_sb_event(struct perf_event *event)
4601 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4603 raw_spin_lock(&pel->lock);
4604 list_del_rcu(&event->sb_list);
4605 raw_spin_unlock(&pel->lock);
4608 static bool is_sb_event(struct perf_event *event)
4610 struct perf_event_attr *attr = &event->attr;
4615 if (event->attach_state & PERF_ATTACH_TASK)
4618 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4619 attr->comm || attr->comm_exec ||
4620 attr->task || attr->ksymbol ||
4621 attr->context_switch || attr->text_poke ||
4627 static void unaccount_pmu_sb_event(struct perf_event *event)
4629 if (is_sb_event(event))
4630 detach_sb_event(event);
4633 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4638 if (is_cgroup_event(event))
4639 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4642 #ifdef CONFIG_NO_HZ_FULL
4643 static DEFINE_SPINLOCK(nr_freq_lock);
4646 static void unaccount_freq_event_nohz(void)
4648 #ifdef CONFIG_NO_HZ_FULL
4649 spin_lock(&nr_freq_lock);
4650 if (atomic_dec_and_test(&nr_freq_events))
4651 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4652 spin_unlock(&nr_freq_lock);
4656 static void unaccount_freq_event(void)
4658 if (tick_nohz_full_enabled())
4659 unaccount_freq_event_nohz();
4661 atomic_dec(&nr_freq_events);
4664 static void unaccount_event(struct perf_event *event)
4671 if (event->attach_state & PERF_ATTACH_TASK)
4673 if (event->attr.mmap || event->attr.mmap_data)
4674 atomic_dec(&nr_mmap_events);
4675 if (event->attr.comm)
4676 atomic_dec(&nr_comm_events);
4677 if (event->attr.namespaces)
4678 atomic_dec(&nr_namespaces_events);
4679 if (event->attr.cgroup)
4680 atomic_dec(&nr_cgroup_events);
4681 if (event->attr.task)
4682 atomic_dec(&nr_task_events);
4683 if (event->attr.freq)
4684 unaccount_freq_event();
4685 if (event->attr.context_switch) {
4687 atomic_dec(&nr_switch_events);
4689 if (is_cgroup_event(event))
4691 if (has_branch_stack(event))
4693 if (event->attr.ksymbol)
4694 atomic_dec(&nr_ksymbol_events);
4695 if (event->attr.bpf_event)
4696 atomic_dec(&nr_bpf_events);
4697 if (event->attr.text_poke)
4698 atomic_dec(&nr_text_poke_events);
4701 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4702 schedule_delayed_work(&perf_sched_work, HZ);
4705 unaccount_event_cpu(event, event->cpu);
4707 unaccount_pmu_sb_event(event);
4710 static void perf_sched_delayed(struct work_struct *work)
4712 mutex_lock(&perf_sched_mutex);
4713 if (atomic_dec_and_test(&perf_sched_count))
4714 static_branch_disable(&perf_sched_events);
4715 mutex_unlock(&perf_sched_mutex);
4719 * The following implement mutual exclusion of events on "exclusive" pmus
4720 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4721 * at a time, so we disallow creating events that might conflict, namely:
4723 * 1) cpu-wide events in the presence of per-task events,
4724 * 2) per-task events in the presence of cpu-wide events,
4725 * 3) two matching events on the same context.
4727 * The former two cases are handled in the allocation path (perf_event_alloc(),
4728 * _free_event()), the latter -- before the first perf_install_in_context().
4730 static int exclusive_event_init(struct perf_event *event)
4732 struct pmu *pmu = event->pmu;
4734 if (!is_exclusive_pmu(pmu))
4738 * Prevent co-existence of per-task and cpu-wide events on the
4739 * same exclusive pmu.
4741 * Negative pmu::exclusive_cnt means there are cpu-wide
4742 * events on this "exclusive" pmu, positive means there are
4745 * Since this is called in perf_event_alloc() path, event::ctx
4746 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4747 * to mean "per-task event", because unlike other attach states it
4748 * never gets cleared.
4750 if (event->attach_state & PERF_ATTACH_TASK) {
4751 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4754 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4761 static void exclusive_event_destroy(struct perf_event *event)
4763 struct pmu *pmu = event->pmu;
4765 if (!is_exclusive_pmu(pmu))
4768 /* see comment in exclusive_event_init() */
4769 if (event->attach_state & PERF_ATTACH_TASK)
4770 atomic_dec(&pmu->exclusive_cnt);
4772 atomic_inc(&pmu->exclusive_cnt);
4775 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4777 if ((e1->pmu == e2->pmu) &&
4778 (e1->cpu == e2->cpu ||
4785 static bool exclusive_event_installable(struct perf_event *event,
4786 struct perf_event_context *ctx)
4788 struct perf_event *iter_event;
4789 struct pmu *pmu = event->pmu;
4791 lockdep_assert_held(&ctx->mutex);
4793 if (!is_exclusive_pmu(pmu))
4796 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4797 if (exclusive_event_match(iter_event, event))
4804 static void perf_addr_filters_splice(struct perf_event *event,
4805 struct list_head *head);
4807 static void _free_event(struct perf_event *event)
4809 irq_work_sync(&event->pending);
4811 unaccount_event(event);
4813 security_perf_event_free(event);
4817 * Can happen when we close an event with re-directed output.
4819 * Since we have a 0 refcount, perf_mmap_close() will skip
4820 * over us; possibly making our ring_buffer_put() the last.
4822 mutex_lock(&event->mmap_mutex);
4823 ring_buffer_attach(event, NULL);
4824 mutex_unlock(&event->mmap_mutex);
4827 if (is_cgroup_event(event))
4828 perf_detach_cgroup(event);
4830 if (!event->parent) {
4831 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4832 put_callchain_buffers();
4835 perf_event_free_bpf_prog(event);
4836 perf_addr_filters_splice(event, NULL);
4837 kfree(event->addr_filter_ranges);
4840 event->destroy(event);
4843 * Must be after ->destroy(), due to uprobe_perf_close() using
4846 if (event->hw.target)
4847 put_task_struct(event->hw.target);
4850 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4851 * all task references must be cleaned up.
4854 put_ctx(event->ctx);
4856 exclusive_event_destroy(event);
4857 module_put(event->pmu->module);
4859 call_rcu(&event->rcu_head, free_event_rcu);
4863 * Used to free events which have a known refcount of 1, such as in error paths
4864 * where the event isn't exposed yet and inherited events.
4866 static void free_event(struct perf_event *event)
4868 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4869 "unexpected event refcount: %ld; ptr=%p\n",
4870 atomic_long_read(&event->refcount), event)) {
4871 /* leak to avoid use-after-free */
4879 * Remove user event from the owner task.
4881 static void perf_remove_from_owner(struct perf_event *event)
4883 struct task_struct *owner;
4887 * Matches the smp_store_release() in perf_event_exit_task(). If we
4888 * observe !owner it means the list deletion is complete and we can
4889 * indeed free this event, otherwise we need to serialize on
4890 * owner->perf_event_mutex.
4892 owner = READ_ONCE(event->owner);
4895 * Since delayed_put_task_struct() also drops the last
4896 * task reference we can safely take a new reference
4897 * while holding the rcu_read_lock().
4899 get_task_struct(owner);
4905 * If we're here through perf_event_exit_task() we're already
4906 * holding ctx->mutex which would be an inversion wrt. the
4907 * normal lock order.
4909 * However we can safely take this lock because its the child
4912 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4915 * We have to re-check the event->owner field, if it is cleared
4916 * we raced with perf_event_exit_task(), acquiring the mutex
4917 * ensured they're done, and we can proceed with freeing the
4921 list_del_init(&event->owner_entry);
4922 smp_store_release(&event->owner, NULL);
4924 mutex_unlock(&owner->perf_event_mutex);
4925 put_task_struct(owner);
4929 static void put_event(struct perf_event *event)
4931 if (!atomic_long_dec_and_test(&event->refcount))
4938 * Kill an event dead; while event:refcount will preserve the event
4939 * object, it will not preserve its functionality. Once the last 'user'
4940 * gives up the object, we'll destroy the thing.
4942 int perf_event_release_kernel(struct perf_event *event)
4944 struct perf_event_context *ctx = event->ctx;
4945 struct perf_event *child, *tmp;
4946 LIST_HEAD(free_list);
4949 * If we got here through err_file: fput(event_file); we will not have
4950 * attached to a context yet.
4953 WARN_ON_ONCE(event->attach_state &
4954 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4958 if (!is_kernel_event(event))
4959 perf_remove_from_owner(event);
4961 ctx = perf_event_ctx_lock(event);
4962 WARN_ON_ONCE(ctx->parent_ctx);
4963 perf_remove_from_context(event, DETACH_GROUP);
4965 raw_spin_lock_irq(&ctx->lock);
4967 * Mark this event as STATE_DEAD, there is no external reference to it
4970 * Anybody acquiring event->child_mutex after the below loop _must_
4971 * also see this, most importantly inherit_event() which will avoid
4972 * placing more children on the list.
4974 * Thus this guarantees that we will in fact observe and kill _ALL_
4977 event->state = PERF_EVENT_STATE_DEAD;
4978 raw_spin_unlock_irq(&ctx->lock);
4980 perf_event_ctx_unlock(event, ctx);
4983 mutex_lock(&event->child_mutex);
4984 list_for_each_entry(child, &event->child_list, child_list) {
4987 * Cannot change, child events are not migrated, see the
4988 * comment with perf_event_ctx_lock_nested().
4990 ctx = READ_ONCE(child->ctx);
4992 * Since child_mutex nests inside ctx::mutex, we must jump
4993 * through hoops. We start by grabbing a reference on the ctx.
4995 * Since the event cannot get freed while we hold the
4996 * child_mutex, the context must also exist and have a !0
5002 * Now that we have a ctx ref, we can drop child_mutex, and
5003 * acquire ctx::mutex without fear of it going away. Then we
5004 * can re-acquire child_mutex.
5006 mutex_unlock(&event->child_mutex);
5007 mutex_lock(&ctx->mutex);
5008 mutex_lock(&event->child_mutex);
5011 * Now that we hold ctx::mutex and child_mutex, revalidate our
5012 * state, if child is still the first entry, it didn't get freed
5013 * and we can continue doing so.
5015 tmp = list_first_entry_or_null(&event->child_list,
5016 struct perf_event, child_list);
5018 perf_remove_from_context(child, DETACH_GROUP);
5019 list_move(&child->child_list, &free_list);
5021 * This matches the refcount bump in inherit_event();
5022 * this can't be the last reference.
5027 mutex_unlock(&event->child_mutex);
5028 mutex_unlock(&ctx->mutex);
5032 mutex_unlock(&event->child_mutex);
5034 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5035 void *var = &child->ctx->refcount;
5037 list_del(&child->child_list);
5041 * Wake any perf_event_free_task() waiting for this event to be
5044 smp_mb(); /* pairs with wait_var_event() */
5049 put_event(event); /* Must be the 'last' reference */
5052 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5055 * Called when the last reference to the file is gone.
5057 static int perf_release(struct inode *inode, struct file *file)
5059 perf_event_release_kernel(file->private_data);
5063 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5065 struct perf_event *child;
5071 mutex_lock(&event->child_mutex);
5073 (void)perf_event_read(event, false);
5074 total += perf_event_count(event);
5076 *enabled += event->total_time_enabled +
5077 atomic64_read(&event->child_total_time_enabled);
5078 *running += event->total_time_running +
5079 atomic64_read(&event->child_total_time_running);
5081 list_for_each_entry(child, &event->child_list, child_list) {
5082 (void)perf_event_read(child, false);
5083 total += perf_event_count(child);
5084 *enabled += child->total_time_enabled;
5085 *running += child->total_time_running;
5087 mutex_unlock(&event->child_mutex);
5092 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5094 struct perf_event_context *ctx;
5097 ctx = perf_event_ctx_lock(event);
5098 count = __perf_event_read_value(event, enabled, running);
5099 perf_event_ctx_unlock(event, ctx);
5103 EXPORT_SYMBOL_GPL(perf_event_read_value);
5105 static int __perf_read_group_add(struct perf_event *leader,
5106 u64 read_format, u64 *values)
5108 struct perf_event_context *ctx = leader->ctx;
5109 struct perf_event *sub;
5110 unsigned long flags;
5111 int n = 1; /* skip @nr */
5114 ret = perf_event_read(leader, true);
5118 raw_spin_lock_irqsave(&ctx->lock, flags);
5121 * Since we co-schedule groups, {enabled,running} times of siblings
5122 * will be identical to those of the leader, so we only publish one
5125 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5126 values[n++] += leader->total_time_enabled +
5127 atomic64_read(&leader->child_total_time_enabled);
5130 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5131 values[n++] += leader->total_time_running +
5132 atomic64_read(&leader->child_total_time_running);
5136 * Write {count,id} tuples for every sibling.
5138 values[n++] += perf_event_count(leader);
5139 if (read_format & PERF_FORMAT_ID)
5140 values[n++] = primary_event_id(leader);
5142 for_each_sibling_event(sub, leader) {
5143 values[n++] += perf_event_count(sub);
5144 if (read_format & PERF_FORMAT_ID)
5145 values[n++] = primary_event_id(sub);
5148 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5152 static int perf_read_group(struct perf_event *event,
5153 u64 read_format, char __user *buf)
5155 struct perf_event *leader = event->group_leader, *child;
5156 struct perf_event_context *ctx = leader->ctx;
5160 lockdep_assert_held(&ctx->mutex);
5162 values = kzalloc(event->read_size, GFP_KERNEL);
5166 values[0] = 1 + leader->nr_siblings;
5169 * By locking the child_mutex of the leader we effectively
5170 * lock the child list of all siblings.. XXX explain how.
5172 mutex_lock(&leader->child_mutex);
5174 ret = __perf_read_group_add(leader, read_format, values);
5178 list_for_each_entry(child, &leader->child_list, child_list) {
5179 ret = __perf_read_group_add(child, read_format, values);
5184 mutex_unlock(&leader->child_mutex);
5186 ret = event->read_size;
5187 if (copy_to_user(buf, values, event->read_size))
5192 mutex_unlock(&leader->child_mutex);
5198 static int perf_read_one(struct perf_event *event,
5199 u64 read_format, char __user *buf)
5201 u64 enabled, running;
5205 values[n++] = __perf_event_read_value(event, &enabled, &running);
5206 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5207 values[n++] = enabled;
5208 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5209 values[n++] = running;
5210 if (read_format & PERF_FORMAT_ID)
5211 values[n++] = primary_event_id(event);
5213 if (copy_to_user(buf, values, n * sizeof(u64)))
5216 return n * sizeof(u64);
5219 static bool is_event_hup(struct perf_event *event)
5223 if (event->state > PERF_EVENT_STATE_EXIT)
5226 mutex_lock(&event->child_mutex);
5227 no_children = list_empty(&event->child_list);
5228 mutex_unlock(&event->child_mutex);
5233 * Read the performance event - simple non blocking version for now
5236 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5238 u64 read_format = event->attr.read_format;
5242 * Return end-of-file for a read on an event that is in
5243 * error state (i.e. because it was pinned but it couldn't be
5244 * scheduled on to the CPU at some point).
5246 if (event->state == PERF_EVENT_STATE_ERROR)
5249 if (count < event->read_size)
5252 WARN_ON_ONCE(event->ctx->parent_ctx);
5253 if (read_format & PERF_FORMAT_GROUP)
5254 ret = perf_read_group(event, read_format, buf);
5256 ret = perf_read_one(event, read_format, buf);
5262 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5264 struct perf_event *event = file->private_data;
5265 struct perf_event_context *ctx;
5268 ret = security_perf_event_read(event);
5272 ctx = perf_event_ctx_lock(event);
5273 ret = __perf_read(event, buf, count);
5274 perf_event_ctx_unlock(event, ctx);
5279 static __poll_t perf_poll(struct file *file, poll_table *wait)
5281 struct perf_event *event = file->private_data;
5282 struct perf_buffer *rb;
5283 __poll_t events = EPOLLHUP;
5285 poll_wait(file, &event->waitq, wait);
5287 if (is_event_hup(event))
5291 * Pin the event->rb by taking event->mmap_mutex; otherwise
5292 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5294 mutex_lock(&event->mmap_mutex);
5297 events = atomic_xchg(&rb->poll, 0);
5298 mutex_unlock(&event->mmap_mutex);
5302 static void _perf_event_reset(struct perf_event *event)
5304 (void)perf_event_read(event, false);
5305 local64_set(&event->count, 0);
5306 perf_event_update_userpage(event);
5309 /* Assume it's not an event with inherit set. */
5310 u64 perf_event_pause(struct perf_event *event, bool reset)
5312 struct perf_event_context *ctx;
5315 ctx = perf_event_ctx_lock(event);
5316 WARN_ON_ONCE(event->attr.inherit);
5317 _perf_event_disable(event);
5318 count = local64_read(&event->count);
5320 local64_set(&event->count, 0);
5321 perf_event_ctx_unlock(event, ctx);
5325 EXPORT_SYMBOL_GPL(perf_event_pause);
5328 * Holding the top-level event's child_mutex means that any
5329 * descendant process that has inherited this event will block
5330 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5331 * task existence requirements of perf_event_enable/disable.
5333 static void perf_event_for_each_child(struct perf_event *event,
5334 void (*func)(struct perf_event *))
5336 struct perf_event *child;
5338 WARN_ON_ONCE(event->ctx->parent_ctx);
5340 mutex_lock(&event->child_mutex);
5342 list_for_each_entry(child, &event->child_list, child_list)
5344 mutex_unlock(&event->child_mutex);
5347 static void perf_event_for_each(struct perf_event *event,
5348 void (*func)(struct perf_event *))
5350 struct perf_event_context *ctx = event->ctx;
5351 struct perf_event *sibling;
5353 lockdep_assert_held(&ctx->mutex);
5355 event = event->group_leader;
5357 perf_event_for_each_child(event, func);
5358 for_each_sibling_event(sibling, event)
5359 perf_event_for_each_child(sibling, func);
5362 static void __perf_event_period(struct perf_event *event,
5363 struct perf_cpu_context *cpuctx,
5364 struct perf_event_context *ctx,
5367 u64 value = *((u64 *)info);
5370 if (event->attr.freq) {
5371 event->attr.sample_freq = value;
5373 event->attr.sample_period = value;
5374 event->hw.sample_period = value;
5377 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5379 perf_pmu_disable(ctx->pmu);
5381 * We could be throttled; unthrottle now to avoid the tick
5382 * trying to unthrottle while we already re-started the event.
5384 if (event->hw.interrupts == MAX_INTERRUPTS) {
5385 event->hw.interrupts = 0;
5386 perf_log_throttle(event, 1);
5388 event->pmu->stop(event, PERF_EF_UPDATE);
5391 local64_set(&event->hw.period_left, 0);
5394 event->pmu->start(event, PERF_EF_RELOAD);
5395 perf_pmu_enable(ctx->pmu);
5399 static int perf_event_check_period(struct perf_event *event, u64 value)
5401 return event->pmu->check_period(event, value);
5404 static int _perf_event_period(struct perf_event *event, u64 value)
5406 if (!is_sampling_event(event))
5412 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5415 if (perf_event_check_period(event, value))
5418 if (!event->attr.freq && (value & (1ULL << 63)))
5421 event_function_call(event, __perf_event_period, &value);
5426 int perf_event_period(struct perf_event *event, u64 value)
5428 struct perf_event_context *ctx;
5431 ctx = perf_event_ctx_lock(event);
5432 ret = _perf_event_period(event, value);
5433 perf_event_ctx_unlock(event, ctx);
5437 EXPORT_SYMBOL_GPL(perf_event_period);
5439 static const struct file_operations perf_fops;
5441 static inline int perf_fget_light(int fd, struct fd *p)
5443 struct fd f = fdget(fd);
5447 if (f.file->f_op != &perf_fops) {
5455 static int perf_event_set_output(struct perf_event *event,
5456 struct perf_event *output_event);
5457 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5458 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5459 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5460 struct perf_event_attr *attr);
5462 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5464 void (*func)(struct perf_event *);
5468 case PERF_EVENT_IOC_ENABLE:
5469 func = _perf_event_enable;
5471 case PERF_EVENT_IOC_DISABLE:
5472 func = _perf_event_disable;
5474 case PERF_EVENT_IOC_RESET:
5475 func = _perf_event_reset;
5478 case PERF_EVENT_IOC_REFRESH:
5479 return _perf_event_refresh(event, arg);
5481 case PERF_EVENT_IOC_PERIOD:
5485 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5488 return _perf_event_period(event, value);
5490 case PERF_EVENT_IOC_ID:
5492 u64 id = primary_event_id(event);
5494 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5499 case PERF_EVENT_IOC_SET_OUTPUT:
5503 struct perf_event *output_event;
5505 ret = perf_fget_light(arg, &output);
5508 output_event = output.file->private_data;
5509 ret = perf_event_set_output(event, output_event);
5512 ret = perf_event_set_output(event, NULL);
5517 case PERF_EVENT_IOC_SET_FILTER:
5518 return perf_event_set_filter(event, (void __user *)arg);
5520 case PERF_EVENT_IOC_SET_BPF:
5521 return perf_event_set_bpf_prog(event, arg);
5523 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5524 struct perf_buffer *rb;
5527 rb = rcu_dereference(event->rb);
5528 if (!rb || !rb->nr_pages) {
5532 rb_toggle_paused(rb, !!arg);
5537 case PERF_EVENT_IOC_QUERY_BPF:
5538 return perf_event_query_prog_array(event, (void __user *)arg);
5540 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5541 struct perf_event_attr new_attr;
5542 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5548 return perf_event_modify_attr(event, &new_attr);
5554 if (flags & PERF_IOC_FLAG_GROUP)
5555 perf_event_for_each(event, func);
5557 perf_event_for_each_child(event, func);
5562 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5564 struct perf_event *event = file->private_data;
5565 struct perf_event_context *ctx;
5568 /* Treat ioctl like writes as it is likely a mutating operation. */
5569 ret = security_perf_event_write(event);
5573 ctx = perf_event_ctx_lock(event);
5574 ret = _perf_ioctl(event, cmd, arg);
5575 perf_event_ctx_unlock(event, ctx);
5580 #ifdef CONFIG_COMPAT
5581 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5584 switch (_IOC_NR(cmd)) {
5585 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5586 case _IOC_NR(PERF_EVENT_IOC_ID):
5587 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5588 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5589 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5590 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5591 cmd &= ~IOCSIZE_MASK;
5592 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5596 return perf_ioctl(file, cmd, arg);
5599 # define perf_compat_ioctl NULL
5602 int perf_event_task_enable(void)
5604 struct perf_event_context *ctx;
5605 struct perf_event *event;
5607 mutex_lock(¤t->perf_event_mutex);
5608 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5609 ctx = perf_event_ctx_lock(event);
5610 perf_event_for_each_child(event, _perf_event_enable);
5611 perf_event_ctx_unlock(event, ctx);
5613 mutex_unlock(¤t->perf_event_mutex);
5618 int perf_event_task_disable(void)
5620 struct perf_event_context *ctx;
5621 struct perf_event *event;
5623 mutex_lock(¤t->perf_event_mutex);
5624 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5625 ctx = perf_event_ctx_lock(event);
5626 perf_event_for_each_child(event, _perf_event_disable);
5627 perf_event_ctx_unlock(event, ctx);
5629 mutex_unlock(¤t->perf_event_mutex);
5634 static int perf_event_index(struct perf_event *event)
5636 if (event->hw.state & PERF_HES_STOPPED)
5639 if (event->state != PERF_EVENT_STATE_ACTIVE)
5642 return event->pmu->event_idx(event);
5645 static void calc_timer_values(struct perf_event *event,
5652 *now = perf_clock();
5653 ctx_time = event->shadow_ctx_time + *now;
5654 __perf_update_times(event, ctx_time, enabled, running);
5657 static void perf_event_init_userpage(struct perf_event *event)
5659 struct perf_event_mmap_page *userpg;
5660 struct perf_buffer *rb;
5663 rb = rcu_dereference(event->rb);
5667 userpg = rb->user_page;
5669 /* Allow new userspace to detect that bit 0 is deprecated */
5670 userpg->cap_bit0_is_deprecated = 1;
5671 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5672 userpg->data_offset = PAGE_SIZE;
5673 userpg->data_size = perf_data_size(rb);
5679 void __weak arch_perf_update_userpage(
5680 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5685 * Callers need to ensure there can be no nesting of this function, otherwise
5686 * the seqlock logic goes bad. We can not serialize this because the arch
5687 * code calls this from NMI context.
5689 void perf_event_update_userpage(struct perf_event *event)
5691 struct perf_event_mmap_page *userpg;
5692 struct perf_buffer *rb;
5693 u64 enabled, running, now;
5696 rb = rcu_dereference(event->rb);
5701 * compute total_time_enabled, total_time_running
5702 * based on snapshot values taken when the event
5703 * was last scheduled in.
5705 * we cannot simply called update_context_time()
5706 * because of locking issue as we can be called in
5709 calc_timer_values(event, &now, &enabled, &running);
5711 userpg = rb->user_page;
5713 * Disable preemption to guarantee consistent time stamps are stored to
5719 userpg->index = perf_event_index(event);
5720 userpg->offset = perf_event_count(event);
5722 userpg->offset -= local64_read(&event->hw.prev_count);
5724 userpg->time_enabled = enabled +
5725 atomic64_read(&event->child_total_time_enabled);
5727 userpg->time_running = running +
5728 atomic64_read(&event->child_total_time_running);
5730 arch_perf_update_userpage(event, userpg, now);
5738 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5740 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5742 struct perf_event *event = vmf->vma->vm_file->private_data;
5743 struct perf_buffer *rb;
5744 vm_fault_t ret = VM_FAULT_SIGBUS;
5746 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5747 if (vmf->pgoff == 0)
5753 rb = rcu_dereference(event->rb);
5757 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5760 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5764 get_page(vmf->page);
5765 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5766 vmf->page->index = vmf->pgoff;
5775 static void ring_buffer_attach(struct perf_event *event,
5776 struct perf_buffer *rb)
5778 struct perf_buffer *old_rb = NULL;
5779 unsigned long flags;
5783 * Should be impossible, we set this when removing
5784 * event->rb_entry and wait/clear when adding event->rb_entry.
5786 WARN_ON_ONCE(event->rcu_pending);
5789 spin_lock_irqsave(&old_rb->event_lock, flags);
5790 list_del_rcu(&event->rb_entry);
5791 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5793 event->rcu_batches = get_state_synchronize_rcu();
5794 event->rcu_pending = 1;
5798 if (event->rcu_pending) {
5799 cond_synchronize_rcu(event->rcu_batches);
5800 event->rcu_pending = 0;
5803 spin_lock_irqsave(&rb->event_lock, flags);
5804 list_add_rcu(&event->rb_entry, &rb->event_list);
5805 spin_unlock_irqrestore(&rb->event_lock, flags);
5809 * Avoid racing with perf_mmap_close(AUX): stop the event
5810 * before swizzling the event::rb pointer; if it's getting
5811 * unmapped, its aux_mmap_count will be 0 and it won't
5812 * restart. See the comment in __perf_pmu_output_stop().
5814 * Data will inevitably be lost when set_output is done in
5815 * mid-air, but then again, whoever does it like this is
5816 * not in for the data anyway.
5819 perf_event_stop(event, 0);
5821 rcu_assign_pointer(event->rb, rb);
5824 ring_buffer_put(old_rb);
5826 * Since we detached before setting the new rb, so that we
5827 * could attach the new rb, we could have missed a wakeup.
5830 wake_up_all(&event->waitq);
5834 static void ring_buffer_wakeup(struct perf_event *event)
5836 struct perf_buffer *rb;
5839 rb = rcu_dereference(event->rb);
5841 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5842 wake_up_all(&event->waitq);
5847 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5849 struct perf_buffer *rb;
5852 rb = rcu_dereference(event->rb);
5854 if (!refcount_inc_not_zero(&rb->refcount))
5862 void ring_buffer_put(struct perf_buffer *rb)
5864 if (!refcount_dec_and_test(&rb->refcount))
5867 WARN_ON_ONCE(!list_empty(&rb->event_list));
5869 call_rcu(&rb->rcu_head, rb_free_rcu);
5872 static void perf_mmap_open(struct vm_area_struct *vma)
5874 struct perf_event *event = vma->vm_file->private_data;
5876 atomic_inc(&event->mmap_count);
5877 atomic_inc(&event->rb->mmap_count);
5880 atomic_inc(&event->rb->aux_mmap_count);
5882 if (event->pmu->event_mapped)
5883 event->pmu->event_mapped(event, vma->vm_mm);
5886 static void perf_pmu_output_stop(struct perf_event *event);
5889 * A buffer can be mmap()ed multiple times; either directly through the same
5890 * event, or through other events by use of perf_event_set_output().
5892 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5893 * the buffer here, where we still have a VM context. This means we need
5894 * to detach all events redirecting to us.
5896 static void perf_mmap_close(struct vm_area_struct *vma)
5898 struct perf_event *event = vma->vm_file->private_data;
5899 struct perf_buffer *rb = ring_buffer_get(event);
5900 struct user_struct *mmap_user = rb->mmap_user;
5901 int mmap_locked = rb->mmap_locked;
5902 unsigned long size = perf_data_size(rb);
5903 bool detach_rest = false;
5905 if (event->pmu->event_unmapped)
5906 event->pmu->event_unmapped(event, vma->vm_mm);
5909 * rb->aux_mmap_count will always drop before rb->mmap_count and
5910 * event->mmap_count, so it is ok to use event->mmap_mutex to
5911 * serialize with perf_mmap here.
5913 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5914 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5916 * Stop all AUX events that are writing to this buffer,
5917 * so that we can free its AUX pages and corresponding PMU
5918 * data. Note that after rb::aux_mmap_count dropped to zero,
5919 * they won't start any more (see perf_aux_output_begin()).
5921 perf_pmu_output_stop(event);
5923 /* now it's safe to free the pages */
5924 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5925 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5927 /* this has to be the last one */
5929 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5931 mutex_unlock(&event->mmap_mutex);
5934 if (atomic_dec_and_test(&rb->mmap_count))
5937 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5940 ring_buffer_attach(event, NULL);
5941 mutex_unlock(&event->mmap_mutex);
5943 /* If there's still other mmap()s of this buffer, we're done. */
5948 * No other mmap()s, detach from all other events that might redirect
5949 * into the now unreachable buffer. Somewhat complicated by the
5950 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5954 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5955 if (!atomic_long_inc_not_zero(&event->refcount)) {
5957 * This event is en-route to free_event() which will
5958 * detach it and remove it from the list.
5964 mutex_lock(&event->mmap_mutex);
5966 * Check we didn't race with perf_event_set_output() which can
5967 * swizzle the rb from under us while we were waiting to
5968 * acquire mmap_mutex.
5970 * If we find a different rb; ignore this event, a next
5971 * iteration will no longer find it on the list. We have to
5972 * still restart the iteration to make sure we're not now
5973 * iterating the wrong list.
5975 if (event->rb == rb)
5976 ring_buffer_attach(event, NULL);
5978 mutex_unlock(&event->mmap_mutex);
5982 * Restart the iteration; either we're on the wrong list or
5983 * destroyed its integrity by doing a deletion.
5990 * It could be there's still a few 0-ref events on the list; they'll
5991 * get cleaned up by free_event() -- they'll also still have their
5992 * ref on the rb and will free it whenever they are done with it.
5994 * Aside from that, this buffer is 'fully' detached and unmapped,
5995 * undo the VM accounting.
5998 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5999 &mmap_user->locked_vm);
6000 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6001 free_uid(mmap_user);
6004 ring_buffer_put(rb); /* could be last */
6007 static const struct vm_operations_struct perf_mmap_vmops = {
6008 .open = perf_mmap_open,
6009 .close = perf_mmap_close, /* non mergeable */
6010 .fault = perf_mmap_fault,
6011 .page_mkwrite = perf_mmap_fault,
6014 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6016 struct perf_event *event = file->private_data;
6017 unsigned long user_locked, user_lock_limit;
6018 struct user_struct *user = current_user();
6019 struct perf_buffer *rb = NULL;
6020 unsigned long locked, lock_limit;
6021 unsigned long vma_size;
6022 unsigned long nr_pages;
6023 long user_extra = 0, extra = 0;
6024 int ret = 0, flags = 0;
6027 * Don't allow mmap() of inherited per-task counters. This would
6028 * create a performance issue due to all children writing to the
6031 if (event->cpu == -1 && event->attr.inherit)
6034 if (!(vma->vm_flags & VM_SHARED))
6037 ret = security_perf_event_read(event);
6041 vma_size = vma->vm_end - vma->vm_start;
6043 if (vma->vm_pgoff == 0) {
6044 nr_pages = (vma_size / PAGE_SIZE) - 1;
6047 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6048 * mapped, all subsequent mappings should have the same size
6049 * and offset. Must be above the normal perf buffer.
6051 u64 aux_offset, aux_size;
6056 nr_pages = vma_size / PAGE_SIZE;
6058 mutex_lock(&event->mmap_mutex);
6065 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6066 aux_size = READ_ONCE(rb->user_page->aux_size);
6068 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6071 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6074 /* already mapped with a different offset */
6075 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6078 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6081 /* already mapped with a different size */
6082 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6085 if (!is_power_of_2(nr_pages))
6088 if (!atomic_inc_not_zero(&rb->mmap_count))
6091 if (rb_has_aux(rb)) {
6092 atomic_inc(&rb->aux_mmap_count);
6097 atomic_set(&rb->aux_mmap_count, 1);
6098 user_extra = nr_pages;
6104 * If we have rb pages ensure they're a power-of-two number, so we
6105 * can do bitmasks instead of modulo.
6107 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6110 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6113 WARN_ON_ONCE(event->ctx->parent_ctx);
6115 mutex_lock(&event->mmap_mutex);
6117 if (event->rb->nr_pages != nr_pages) {
6122 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6124 * Raced against perf_mmap_close() through
6125 * perf_event_set_output(). Try again, hope for better
6128 mutex_unlock(&event->mmap_mutex);
6135 user_extra = nr_pages + 1;
6138 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6141 * Increase the limit linearly with more CPUs:
6143 user_lock_limit *= num_online_cpus();
6145 user_locked = atomic_long_read(&user->locked_vm);
6148 * sysctl_perf_event_mlock may have changed, so that
6149 * user->locked_vm > user_lock_limit
6151 if (user_locked > user_lock_limit)
6152 user_locked = user_lock_limit;
6153 user_locked += user_extra;
6155 if (user_locked > user_lock_limit) {
6157 * charge locked_vm until it hits user_lock_limit;
6158 * charge the rest from pinned_vm
6160 extra = user_locked - user_lock_limit;
6161 user_extra -= extra;
6164 lock_limit = rlimit(RLIMIT_MEMLOCK);
6165 lock_limit >>= PAGE_SHIFT;
6166 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6168 if ((locked > lock_limit) && perf_is_paranoid() &&
6169 !capable(CAP_IPC_LOCK)) {
6174 WARN_ON(!rb && event->rb);
6176 if (vma->vm_flags & VM_WRITE)
6177 flags |= RING_BUFFER_WRITABLE;
6180 rb = rb_alloc(nr_pages,
6181 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6189 atomic_set(&rb->mmap_count, 1);
6190 rb->mmap_user = get_current_user();
6191 rb->mmap_locked = extra;
6193 ring_buffer_attach(event, rb);
6195 perf_event_init_userpage(event);
6196 perf_event_update_userpage(event);
6198 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6199 event->attr.aux_watermark, flags);
6201 rb->aux_mmap_locked = extra;
6206 atomic_long_add(user_extra, &user->locked_vm);
6207 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6209 atomic_inc(&event->mmap_count);
6211 atomic_dec(&rb->mmap_count);
6214 mutex_unlock(&event->mmap_mutex);
6217 * Since pinned accounting is per vm we cannot allow fork() to copy our
6220 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6221 vma->vm_ops = &perf_mmap_vmops;
6223 if (event->pmu->event_mapped)
6224 event->pmu->event_mapped(event, vma->vm_mm);
6229 static int perf_fasync(int fd, struct file *filp, int on)
6231 struct inode *inode = file_inode(filp);
6232 struct perf_event *event = filp->private_data;
6236 retval = fasync_helper(fd, filp, on, &event->fasync);
6237 inode_unlock(inode);
6245 static const struct file_operations perf_fops = {
6246 .llseek = no_llseek,
6247 .release = perf_release,
6250 .unlocked_ioctl = perf_ioctl,
6251 .compat_ioctl = perf_compat_ioctl,
6253 .fasync = perf_fasync,
6259 * If there's data, ensure we set the poll() state and publish everything
6260 * to user-space before waking everybody up.
6263 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6265 /* only the parent has fasync state */
6267 event = event->parent;
6268 return &event->fasync;
6271 void perf_event_wakeup(struct perf_event *event)
6273 ring_buffer_wakeup(event);
6275 if (event->pending_kill) {
6276 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6277 event->pending_kill = 0;
6281 static void perf_pending_event_disable(struct perf_event *event)
6283 int cpu = READ_ONCE(event->pending_disable);
6288 if (cpu == smp_processor_id()) {
6289 WRITE_ONCE(event->pending_disable, -1);
6290 perf_event_disable_local(event);
6297 * perf_event_disable_inatomic()
6298 * @pending_disable = CPU-A;
6302 * @pending_disable = -1;
6305 * perf_event_disable_inatomic()
6306 * @pending_disable = CPU-B;
6307 * irq_work_queue(); // FAILS
6310 * perf_pending_event()
6312 * But the event runs on CPU-B and wants disabling there.
6314 irq_work_queue_on(&event->pending, cpu);
6317 static void perf_pending_event(struct irq_work *entry)
6319 struct perf_event *event = container_of(entry, struct perf_event, pending);
6322 rctx = perf_swevent_get_recursion_context();
6324 * If we 'fail' here, that's OK, it means recursion is already disabled
6325 * and we won't recurse 'further'.
6328 perf_pending_event_disable(event);
6330 if (event->pending_wakeup) {
6331 event->pending_wakeup = 0;
6332 perf_event_wakeup(event);
6336 perf_swevent_put_recursion_context(rctx);
6340 * We assume there is only KVM supporting the callbacks.
6341 * Later on, we might change it to a list if there is
6342 * another virtualization implementation supporting the callbacks.
6344 struct perf_guest_info_callbacks *perf_guest_cbs;
6346 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6348 perf_guest_cbs = cbs;
6351 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6353 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6355 perf_guest_cbs = NULL;
6358 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6361 perf_output_sample_regs(struct perf_output_handle *handle,
6362 struct pt_regs *regs, u64 mask)
6365 DECLARE_BITMAP(_mask, 64);
6367 bitmap_from_u64(_mask, mask);
6368 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6371 val = perf_reg_value(regs, bit);
6372 perf_output_put(handle, val);
6376 static void perf_sample_regs_user(struct perf_regs *regs_user,
6377 struct pt_regs *regs,
6378 struct pt_regs *regs_user_copy)
6380 if (user_mode(regs)) {
6381 regs_user->abi = perf_reg_abi(current);
6382 regs_user->regs = regs;
6383 } else if (!(current->flags & PF_KTHREAD)) {
6384 perf_get_regs_user(regs_user, regs, regs_user_copy);
6386 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6387 regs_user->regs = NULL;
6391 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6392 struct pt_regs *regs)
6394 regs_intr->regs = regs;
6395 regs_intr->abi = perf_reg_abi(current);
6400 * Get remaining task size from user stack pointer.
6402 * It'd be better to take stack vma map and limit this more
6403 * precisely, but there's no way to get it safely under interrupt,
6404 * so using TASK_SIZE as limit.
6406 static u64 perf_ustack_task_size(struct pt_regs *regs)
6408 unsigned long addr = perf_user_stack_pointer(regs);
6410 if (!addr || addr >= TASK_SIZE)
6413 return TASK_SIZE - addr;
6417 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6418 struct pt_regs *regs)
6422 /* No regs, no stack pointer, no dump. */
6427 * Check if we fit in with the requested stack size into the:
6429 * If we don't, we limit the size to the TASK_SIZE.
6431 * - remaining sample size
6432 * If we don't, we customize the stack size to
6433 * fit in to the remaining sample size.
6436 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6437 stack_size = min(stack_size, (u16) task_size);
6439 /* Current header size plus static size and dynamic size. */
6440 header_size += 2 * sizeof(u64);
6442 /* Do we fit in with the current stack dump size? */
6443 if ((u16) (header_size + stack_size) < header_size) {
6445 * If we overflow the maximum size for the sample,
6446 * we customize the stack dump size to fit in.
6448 stack_size = USHRT_MAX - header_size - sizeof(u64);
6449 stack_size = round_up(stack_size, sizeof(u64));
6456 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6457 struct pt_regs *regs)
6459 /* Case of a kernel thread, nothing to dump */
6462 perf_output_put(handle, size);
6472 * - the size requested by user or the best one we can fit
6473 * in to the sample max size
6475 * - user stack dump data
6477 * - the actual dumped size
6481 perf_output_put(handle, dump_size);
6484 sp = perf_user_stack_pointer(regs);
6485 fs = force_uaccess_begin();
6486 rem = __output_copy_user(handle, (void *) sp, dump_size);
6487 force_uaccess_end(fs);
6488 dyn_size = dump_size - rem;
6490 perf_output_skip(handle, rem);
6493 perf_output_put(handle, dyn_size);
6497 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6498 struct perf_sample_data *data,
6501 struct perf_event *sampler = event->aux_event;
6502 struct perf_buffer *rb;
6509 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6512 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6515 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6520 * If this is an NMI hit inside sampling code, don't take
6521 * the sample. See also perf_aux_sample_output().
6523 if (READ_ONCE(rb->aux_in_sampling)) {
6526 size = min_t(size_t, size, perf_aux_size(rb));
6527 data->aux_size = ALIGN(size, sizeof(u64));
6529 ring_buffer_put(rb);
6532 return data->aux_size;
6535 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6536 struct perf_event *event,
6537 struct perf_output_handle *handle,
6540 unsigned long flags;
6544 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6545 * paths. If we start calling them in NMI context, they may race with
6546 * the IRQ ones, that is, for example, re-starting an event that's just
6547 * been stopped, which is why we're using a separate callback that
6548 * doesn't change the event state.
6550 * IRQs need to be disabled to prevent IPIs from racing with us.
6552 local_irq_save(flags);
6554 * Guard against NMI hits inside the critical section;
6555 * see also perf_prepare_sample_aux().
6557 WRITE_ONCE(rb->aux_in_sampling, 1);
6560 ret = event->pmu->snapshot_aux(event, handle, size);
6563 WRITE_ONCE(rb->aux_in_sampling, 0);
6564 local_irq_restore(flags);
6569 static void perf_aux_sample_output(struct perf_event *event,
6570 struct perf_output_handle *handle,
6571 struct perf_sample_data *data)
6573 struct perf_event *sampler = event->aux_event;
6574 struct perf_buffer *rb;
6578 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6581 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6585 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6588 * An error here means that perf_output_copy() failed (returned a
6589 * non-zero surplus that it didn't copy), which in its current
6590 * enlightened implementation is not possible. If that changes, we'd
6593 if (WARN_ON_ONCE(size < 0))
6597 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6598 * perf_prepare_sample_aux(), so should not be more than that.
6600 pad = data->aux_size - size;
6601 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6606 perf_output_copy(handle, &zero, pad);
6610 ring_buffer_put(rb);
6613 static void __perf_event_header__init_id(struct perf_event_header *header,
6614 struct perf_sample_data *data,
6615 struct perf_event *event)
6617 u64 sample_type = event->attr.sample_type;
6619 data->type = sample_type;
6620 header->size += event->id_header_size;
6622 if (sample_type & PERF_SAMPLE_TID) {
6623 /* namespace issues */
6624 data->tid_entry.pid = perf_event_pid(event, current);
6625 data->tid_entry.tid = perf_event_tid(event, current);
6628 if (sample_type & PERF_SAMPLE_TIME)
6629 data->time = perf_event_clock(event);
6631 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6632 data->id = primary_event_id(event);
6634 if (sample_type & PERF_SAMPLE_STREAM_ID)
6635 data->stream_id = event->id;
6637 if (sample_type & PERF_SAMPLE_CPU) {
6638 data->cpu_entry.cpu = raw_smp_processor_id();
6639 data->cpu_entry.reserved = 0;
6643 void perf_event_header__init_id(struct perf_event_header *header,
6644 struct perf_sample_data *data,
6645 struct perf_event *event)
6647 if (event->attr.sample_id_all)
6648 __perf_event_header__init_id(header, data, event);
6651 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6652 struct perf_sample_data *data)
6654 u64 sample_type = data->type;
6656 if (sample_type & PERF_SAMPLE_TID)
6657 perf_output_put(handle, data->tid_entry);
6659 if (sample_type & PERF_SAMPLE_TIME)
6660 perf_output_put(handle, data->time);
6662 if (sample_type & PERF_SAMPLE_ID)
6663 perf_output_put(handle, data->id);
6665 if (sample_type & PERF_SAMPLE_STREAM_ID)
6666 perf_output_put(handle, data->stream_id);
6668 if (sample_type & PERF_SAMPLE_CPU)
6669 perf_output_put(handle, data->cpu_entry);
6671 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6672 perf_output_put(handle, data->id);
6675 void perf_event__output_id_sample(struct perf_event *event,
6676 struct perf_output_handle *handle,
6677 struct perf_sample_data *sample)
6679 if (event->attr.sample_id_all)
6680 __perf_event__output_id_sample(handle, sample);
6683 static void perf_output_read_one(struct perf_output_handle *handle,
6684 struct perf_event *event,
6685 u64 enabled, u64 running)
6687 u64 read_format = event->attr.read_format;
6691 values[n++] = perf_event_count(event);
6692 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6693 values[n++] = enabled +
6694 atomic64_read(&event->child_total_time_enabled);
6696 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6697 values[n++] = running +
6698 atomic64_read(&event->child_total_time_running);
6700 if (read_format & PERF_FORMAT_ID)
6701 values[n++] = primary_event_id(event);
6703 __output_copy(handle, values, n * sizeof(u64));
6706 static void perf_output_read_group(struct perf_output_handle *handle,
6707 struct perf_event *event,
6708 u64 enabled, u64 running)
6710 struct perf_event *leader = event->group_leader, *sub;
6711 u64 read_format = event->attr.read_format;
6715 values[n++] = 1 + leader->nr_siblings;
6717 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6718 values[n++] = enabled;
6720 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6721 values[n++] = running;
6723 if ((leader != event) &&
6724 (leader->state == PERF_EVENT_STATE_ACTIVE))
6725 leader->pmu->read(leader);
6727 values[n++] = perf_event_count(leader);
6728 if (read_format & PERF_FORMAT_ID)
6729 values[n++] = primary_event_id(leader);
6731 __output_copy(handle, values, n * sizeof(u64));
6733 for_each_sibling_event(sub, leader) {
6736 if ((sub != event) &&
6737 (sub->state == PERF_EVENT_STATE_ACTIVE))
6738 sub->pmu->read(sub);
6740 values[n++] = perf_event_count(sub);
6741 if (read_format & PERF_FORMAT_ID)
6742 values[n++] = primary_event_id(sub);
6744 __output_copy(handle, values, n * sizeof(u64));
6748 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6749 PERF_FORMAT_TOTAL_TIME_RUNNING)
6752 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6754 * The problem is that its both hard and excessively expensive to iterate the
6755 * child list, not to mention that its impossible to IPI the children running
6756 * on another CPU, from interrupt/NMI context.
6758 static void perf_output_read(struct perf_output_handle *handle,
6759 struct perf_event *event)
6761 u64 enabled = 0, running = 0, now;
6762 u64 read_format = event->attr.read_format;
6765 * compute total_time_enabled, total_time_running
6766 * based on snapshot values taken when the event
6767 * was last scheduled in.
6769 * we cannot simply called update_context_time()
6770 * because of locking issue as we are called in
6773 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6774 calc_timer_values(event, &now, &enabled, &running);
6776 if (event->attr.read_format & PERF_FORMAT_GROUP)
6777 perf_output_read_group(handle, event, enabled, running);
6779 perf_output_read_one(handle, event, enabled, running);
6782 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6784 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6787 void perf_output_sample(struct perf_output_handle *handle,
6788 struct perf_event_header *header,
6789 struct perf_sample_data *data,
6790 struct perf_event *event)
6792 u64 sample_type = data->type;
6794 perf_output_put(handle, *header);
6796 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6797 perf_output_put(handle, data->id);
6799 if (sample_type & PERF_SAMPLE_IP)
6800 perf_output_put(handle, data->ip);
6802 if (sample_type & PERF_SAMPLE_TID)
6803 perf_output_put(handle, data->tid_entry);
6805 if (sample_type & PERF_SAMPLE_TIME)
6806 perf_output_put(handle, data->time);
6808 if (sample_type & PERF_SAMPLE_ADDR)
6809 perf_output_put(handle, data->addr);
6811 if (sample_type & PERF_SAMPLE_ID)
6812 perf_output_put(handle, data->id);
6814 if (sample_type & PERF_SAMPLE_STREAM_ID)
6815 perf_output_put(handle, data->stream_id);
6817 if (sample_type & PERF_SAMPLE_CPU)
6818 perf_output_put(handle, data->cpu_entry);
6820 if (sample_type & PERF_SAMPLE_PERIOD)
6821 perf_output_put(handle, data->period);
6823 if (sample_type & PERF_SAMPLE_READ)
6824 perf_output_read(handle, event);
6826 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6829 size += data->callchain->nr;
6830 size *= sizeof(u64);
6831 __output_copy(handle, data->callchain, size);
6834 if (sample_type & PERF_SAMPLE_RAW) {
6835 struct perf_raw_record *raw = data->raw;
6838 struct perf_raw_frag *frag = &raw->frag;
6840 perf_output_put(handle, raw->size);
6843 __output_custom(handle, frag->copy,
6844 frag->data, frag->size);
6846 __output_copy(handle, frag->data,
6849 if (perf_raw_frag_last(frag))
6854 __output_skip(handle, NULL, frag->pad);
6860 .size = sizeof(u32),
6863 perf_output_put(handle, raw);
6867 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6868 if (data->br_stack) {
6871 size = data->br_stack->nr
6872 * sizeof(struct perf_branch_entry);
6874 perf_output_put(handle, data->br_stack->nr);
6875 if (perf_sample_save_hw_index(event))
6876 perf_output_put(handle, data->br_stack->hw_idx);
6877 perf_output_copy(handle, data->br_stack->entries, size);
6880 * we always store at least the value of nr
6883 perf_output_put(handle, nr);
6887 if (sample_type & PERF_SAMPLE_REGS_USER) {
6888 u64 abi = data->regs_user.abi;
6891 * If there are no regs to dump, notice it through
6892 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6894 perf_output_put(handle, abi);
6897 u64 mask = event->attr.sample_regs_user;
6898 perf_output_sample_regs(handle,
6899 data->regs_user.regs,
6904 if (sample_type & PERF_SAMPLE_STACK_USER) {
6905 perf_output_sample_ustack(handle,
6906 data->stack_user_size,
6907 data->regs_user.regs);
6910 if (sample_type & PERF_SAMPLE_WEIGHT)
6911 perf_output_put(handle, data->weight);
6913 if (sample_type & PERF_SAMPLE_DATA_SRC)
6914 perf_output_put(handle, data->data_src.val);
6916 if (sample_type & PERF_SAMPLE_TRANSACTION)
6917 perf_output_put(handle, data->txn);
6919 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6920 u64 abi = data->regs_intr.abi;
6922 * If there are no regs to dump, notice it through
6923 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6925 perf_output_put(handle, abi);
6928 u64 mask = event->attr.sample_regs_intr;
6930 perf_output_sample_regs(handle,
6931 data->regs_intr.regs,
6936 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6937 perf_output_put(handle, data->phys_addr);
6939 if (sample_type & PERF_SAMPLE_CGROUP)
6940 perf_output_put(handle, data->cgroup);
6942 if (sample_type & PERF_SAMPLE_AUX) {
6943 perf_output_put(handle, data->aux_size);
6946 perf_aux_sample_output(event, handle, data);
6949 if (!event->attr.watermark) {
6950 int wakeup_events = event->attr.wakeup_events;
6952 if (wakeup_events) {
6953 struct perf_buffer *rb = handle->rb;
6954 int events = local_inc_return(&rb->events);
6956 if (events >= wakeup_events) {
6957 local_sub(wakeup_events, &rb->events);
6958 local_inc(&rb->wakeup);
6964 static u64 perf_virt_to_phys(u64 virt)
6967 struct page *p = NULL;
6972 if (virt >= TASK_SIZE) {
6973 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6974 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6975 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6976 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6979 * Walking the pages tables for user address.
6980 * Interrupts are disabled, so it prevents any tear down
6981 * of the page tables.
6982 * Try IRQ-safe get_user_page_fast_only first.
6983 * If failed, leave phys_addr as 0.
6985 if (current->mm != NULL) {
6986 pagefault_disable();
6987 if (get_user_page_fast_only(virt, 0, &p))
6988 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6999 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7001 struct perf_callchain_entry *
7002 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7004 bool kernel = !event->attr.exclude_callchain_kernel;
7005 bool user = !event->attr.exclude_callchain_user;
7006 /* Disallow cross-task user callchains. */
7007 bool crosstask = event->ctx->task && event->ctx->task != current;
7008 const u32 max_stack = event->attr.sample_max_stack;
7009 struct perf_callchain_entry *callchain;
7011 if (!kernel && !user)
7012 return &__empty_callchain;
7014 callchain = get_perf_callchain(regs, 0, kernel, user,
7015 max_stack, crosstask, true);
7016 return callchain ?: &__empty_callchain;
7019 void perf_prepare_sample(struct perf_event_header *header,
7020 struct perf_sample_data *data,
7021 struct perf_event *event,
7022 struct pt_regs *regs)
7024 u64 sample_type = event->attr.sample_type;
7026 header->type = PERF_RECORD_SAMPLE;
7027 header->size = sizeof(*header) + event->header_size;
7030 header->misc |= perf_misc_flags(regs);
7032 __perf_event_header__init_id(header, data, event);
7034 if (sample_type & PERF_SAMPLE_IP)
7035 data->ip = perf_instruction_pointer(regs);
7037 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7040 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7041 data->callchain = perf_callchain(event, regs);
7043 size += data->callchain->nr;
7045 header->size += size * sizeof(u64);
7048 if (sample_type & PERF_SAMPLE_RAW) {
7049 struct perf_raw_record *raw = data->raw;
7053 struct perf_raw_frag *frag = &raw->frag;
7058 if (perf_raw_frag_last(frag))
7063 size = round_up(sum + sizeof(u32), sizeof(u64));
7064 raw->size = size - sizeof(u32);
7065 frag->pad = raw->size - sum;
7070 header->size += size;
7073 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7074 int size = sizeof(u64); /* nr */
7075 if (data->br_stack) {
7076 if (perf_sample_save_hw_index(event))
7077 size += sizeof(u64);
7079 size += data->br_stack->nr
7080 * sizeof(struct perf_branch_entry);
7082 header->size += size;
7085 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7086 perf_sample_regs_user(&data->regs_user, regs,
7087 &data->regs_user_copy);
7089 if (sample_type & PERF_SAMPLE_REGS_USER) {
7090 /* regs dump ABI info */
7091 int size = sizeof(u64);
7093 if (data->regs_user.regs) {
7094 u64 mask = event->attr.sample_regs_user;
7095 size += hweight64(mask) * sizeof(u64);
7098 header->size += size;
7101 if (sample_type & PERF_SAMPLE_STACK_USER) {
7103 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7104 * processed as the last one or have additional check added
7105 * in case new sample type is added, because we could eat
7106 * up the rest of the sample size.
7108 u16 stack_size = event->attr.sample_stack_user;
7109 u16 size = sizeof(u64);
7111 stack_size = perf_sample_ustack_size(stack_size, header->size,
7112 data->regs_user.regs);
7115 * If there is something to dump, add space for the dump
7116 * itself and for the field that tells the dynamic size,
7117 * which is how many have been actually dumped.
7120 size += sizeof(u64) + stack_size;
7122 data->stack_user_size = stack_size;
7123 header->size += size;
7126 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7127 /* regs dump ABI info */
7128 int size = sizeof(u64);
7130 perf_sample_regs_intr(&data->regs_intr, regs);
7132 if (data->regs_intr.regs) {
7133 u64 mask = event->attr.sample_regs_intr;
7135 size += hweight64(mask) * sizeof(u64);
7138 header->size += size;
7141 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7142 data->phys_addr = perf_virt_to_phys(data->addr);
7144 #ifdef CONFIG_CGROUP_PERF
7145 if (sample_type & PERF_SAMPLE_CGROUP) {
7146 struct cgroup *cgrp;
7148 /* protected by RCU */
7149 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7150 data->cgroup = cgroup_id(cgrp);
7154 if (sample_type & PERF_SAMPLE_AUX) {
7157 header->size += sizeof(u64); /* size */
7160 * Given the 16bit nature of header::size, an AUX sample can
7161 * easily overflow it, what with all the preceding sample bits.
7162 * Make sure this doesn't happen by using up to U16_MAX bytes
7163 * per sample in total (rounded down to 8 byte boundary).
7165 size = min_t(size_t, U16_MAX - header->size,
7166 event->attr.aux_sample_size);
7167 size = rounddown(size, 8);
7168 size = perf_prepare_sample_aux(event, data, size);
7170 WARN_ON_ONCE(size + header->size > U16_MAX);
7171 header->size += size;
7174 * If you're adding more sample types here, you likely need to do
7175 * something about the overflowing header::size, like repurpose the
7176 * lowest 3 bits of size, which should be always zero at the moment.
7177 * This raises a more important question, do we really need 512k sized
7178 * samples and why, so good argumentation is in order for whatever you
7181 WARN_ON_ONCE(header->size & 7);
7184 static __always_inline int
7185 __perf_event_output(struct perf_event *event,
7186 struct perf_sample_data *data,
7187 struct pt_regs *regs,
7188 int (*output_begin)(struct perf_output_handle *,
7189 struct perf_event *,
7192 struct perf_output_handle handle;
7193 struct perf_event_header header;
7196 /* protect the callchain buffers */
7199 perf_prepare_sample(&header, data, event, regs);
7201 err = output_begin(&handle, event, header.size);
7205 perf_output_sample(&handle, &header, data, event);
7207 perf_output_end(&handle);
7215 perf_event_output_forward(struct perf_event *event,
7216 struct perf_sample_data *data,
7217 struct pt_regs *regs)
7219 __perf_event_output(event, data, regs, perf_output_begin_forward);
7223 perf_event_output_backward(struct perf_event *event,
7224 struct perf_sample_data *data,
7225 struct pt_regs *regs)
7227 __perf_event_output(event, data, regs, perf_output_begin_backward);
7231 perf_event_output(struct perf_event *event,
7232 struct perf_sample_data *data,
7233 struct pt_regs *regs)
7235 return __perf_event_output(event, data, regs, perf_output_begin);
7242 struct perf_read_event {
7243 struct perf_event_header header;
7250 perf_event_read_event(struct perf_event *event,
7251 struct task_struct *task)
7253 struct perf_output_handle handle;
7254 struct perf_sample_data sample;
7255 struct perf_read_event read_event = {
7257 .type = PERF_RECORD_READ,
7259 .size = sizeof(read_event) + event->read_size,
7261 .pid = perf_event_pid(event, task),
7262 .tid = perf_event_tid(event, task),
7266 perf_event_header__init_id(&read_event.header, &sample, event);
7267 ret = perf_output_begin(&handle, event, read_event.header.size);
7271 perf_output_put(&handle, read_event);
7272 perf_output_read(&handle, event);
7273 perf_event__output_id_sample(event, &handle, &sample);
7275 perf_output_end(&handle);
7278 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7281 perf_iterate_ctx(struct perf_event_context *ctx,
7282 perf_iterate_f output,
7283 void *data, bool all)
7285 struct perf_event *event;
7287 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7289 if (event->state < PERF_EVENT_STATE_INACTIVE)
7291 if (!event_filter_match(event))
7295 output(event, data);
7299 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7301 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7302 struct perf_event *event;
7304 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7306 * Skip events that are not fully formed yet; ensure that
7307 * if we observe event->ctx, both event and ctx will be
7308 * complete enough. See perf_install_in_context().
7310 if (!smp_load_acquire(&event->ctx))
7313 if (event->state < PERF_EVENT_STATE_INACTIVE)
7315 if (!event_filter_match(event))
7317 output(event, data);
7322 * Iterate all events that need to receive side-band events.
7324 * For new callers; ensure that account_pmu_sb_event() includes
7325 * your event, otherwise it might not get delivered.
7328 perf_iterate_sb(perf_iterate_f output, void *data,
7329 struct perf_event_context *task_ctx)
7331 struct perf_event_context *ctx;
7338 * If we have task_ctx != NULL we only notify the task context itself.
7339 * The task_ctx is set only for EXIT events before releasing task
7343 perf_iterate_ctx(task_ctx, output, data, false);
7347 perf_iterate_sb_cpu(output, data);
7349 for_each_task_context_nr(ctxn) {
7350 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7352 perf_iterate_ctx(ctx, output, data, false);
7360 * Clear all file-based filters at exec, they'll have to be
7361 * re-instated when/if these objects are mmapped again.
7363 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7365 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7366 struct perf_addr_filter *filter;
7367 unsigned int restart = 0, count = 0;
7368 unsigned long flags;
7370 if (!has_addr_filter(event))
7373 raw_spin_lock_irqsave(&ifh->lock, flags);
7374 list_for_each_entry(filter, &ifh->list, entry) {
7375 if (filter->path.dentry) {
7376 event->addr_filter_ranges[count].start = 0;
7377 event->addr_filter_ranges[count].size = 0;
7385 event->addr_filters_gen++;
7386 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7389 perf_event_stop(event, 1);
7392 void perf_event_exec(void)
7394 struct perf_event_context *ctx;
7398 for_each_task_context_nr(ctxn) {
7399 ctx = current->perf_event_ctxp[ctxn];
7403 perf_event_enable_on_exec(ctxn);
7405 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7411 struct remote_output {
7412 struct perf_buffer *rb;
7416 static void __perf_event_output_stop(struct perf_event *event, void *data)
7418 struct perf_event *parent = event->parent;
7419 struct remote_output *ro = data;
7420 struct perf_buffer *rb = ro->rb;
7421 struct stop_event_data sd = {
7425 if (!has_aux(event))
7432 * In case of inheritance, it will be the parent that links to the
7433 * ring-buffer, but it will be the child that's actually using it.
7435 * We are using event::rb to determine if the event should be stopped,
7436 * however this may race with ring_buffer_attach() (through set_output),
7437 * which will make us skip the event that actually needs to be stopped.
7438 * So ring_buffer_attach() has to stop an aux event before re-assigning
7441 if (rcu_dereference(parent->rb) == rb)
7442 ro->err = __perf_event_stop(&sd);
7445 static int __perf_pmu_output_stop(void *info)
7447 struct perf_event *event = info;
7448 struct pmu *pmu = event->ctx->pmu;
7449 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7450 struct remote_output ro = {
7455 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7456 if (cpuctx->task_ctx)
7457 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7464 static void perf_pmu_output_stop(struct perf_event *event)
7466 struct perf_event *iter;
7471 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7473 * For per-CPU events, we need to make sure that neither they
7474 * nor their children are running; for cpu==-1 events it's
7475 * sufficient to stop the event itself if it's active, since
7476 * it can't have children.
7480 cpu = READ_ONCE(iter->oncpu);
7485 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7486 if (err == -EAGAIN) {
7495 * task tracking -- fork/exit
7497 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7500 struct perf_task_event {
7501 struct task_struct *task;
7502 struct perf_event_context *task_ctx;
7505 struct perf_event_header header;
7515 static int perf_event_task_match(struct perf_event *event)
7517 return event->attr.comm || event->attr.mmap ||
7518 event->attr.mmap2 || event->attr.mmap_data ||
7522 static void perf_event_task_output(struct perf_event *event,
7525 struct perf_task_event *task_event = data;
7526 struct perf_output_handle handle;
7527 struct perf_sample_data sample;
7528 struct task_struct *task = task_event->task;
7529 int ret, size = task_event->event_id.header.size;
7531 if (!perf_event_task_match(event))
7534 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7536 ret = perf_output_begin(&handle, event,
7537 task_event->event_id.header.size);
7541 task_event->event_id.pid = perf_event_pid(event, task);
7542 task_event->event_id.tid = perf_event_tid(event, task);
7544 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7545 task_event->event_id.ppid = perf_event_pid(event,
7547 task_event->event_id.ptid = perf_event_pid(event,
7549 } else { /* PERF_RECORD_FORK */
7550 task_event->event_id.ppid = perf_event_pid(event, current);
7551 task_event->event_id.ptid = perf_event_tid(event, current);
7554 task_event->event_id.time = perf_event_clock(event);
7556 perf_output_put(&handle, task_event->event_id);
7558 perf_event__output_id_sample(event, &handle, &sample);
7560 perf_output_end(&handle);
7562 task_event->event_id.header.size = size;
7565 static void perf_event_task(struct task_struct *task,
7566 struct perf_event_context *task_ctx,
7569 struct perf_task_event task_event;
7571 if (!atomic_read(&nr_comm_events) &&
7572 !atomic_read(&nr_mmap_events) &&
7573 !atomic_read(&nr_task_events))
7576 task_event = (struct perf_task_event){
7578 .task_ctx = task_ctx,
7581 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7583 .size = sizeof(task_event.event_id),
7593 perf_iterate_sb(perf_event_task_output,
7598 void perf_event_fork(struct task_struct *task)
7600 perf_event_task(task, NULL, 1);
7601 perf_event_namespaces(task);
7608 struct perf_comm_event {
7609 struct task_struct *task;
7614 struct perf_event_header header;
7621 static int perf_event_comm_match(struct perf_event *event)
7623 return event->attr.comm;
7626 static void perf_event_comm_output(struct perf_event *event,
7629 struct perf_comm_event *comm_event = data;
7630 struct perf_output_handle handle;
7631 struct perf_sample_data sample;
7632 int size = comm_event->event_id.header.size;
7635 if (!perf_event_comm_match(event))
7638 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7639 ret = perf_output_begin(&handle, event,
7640 comm_event->event_id.header.size);
7645 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7646 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7648 perf_output_put(&handle, comm_event->event_id);
7649 __output_copy(&handle, comm_event->comm,
7650 comm_event->comm_size);
7652 perf_event__output_id_sample(event, &handle, &sample);
7654 perf_output_end(&handle);
7656 comm_event->event_id.header.size = size;
7659 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7661 char comm[TASK_COMM_LEN];
7664 memset(comm, 0, sizeof(comm));
7665 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7666 size = ALIGN(strlen(comm)+1, sizeof(u64));
7668 comm_event->comm = comm;
7669 comm_event->comm_size = size;
7671 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7673 perf_iterate_sb(perf_event_comm_output,
7678 void perf_event_comm(struct task_struct *task, bool exec)
7680 struct perf_comm_event comm_event;
7682 if (!atomic_read(&nr_comm_events))
7685 comm_event = (struct perf_comm_event){
7691 .type = PERF_RECORD_COMM,
7692 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7700 perf_event_comm_event(&comm_event);
7704 * namespaces tracking
7707 struct perf_namespaces_event {
7708 struct task_struct *task;
7711 struct perf_event_header header;
7716 struct perf_ns_link_info link_info[NR_NAMESPACES];
7720 static int perf_event_namespaces_match(struct perf_event *event)
7722 return event->attr.namespaces;
7725 static void perf_event_namespaces_output(struct perf_event *event,
7728 struct perf_namespaces_event *namespaces_event = data;
7729 struct perf_output_handle handle;
7730 struct perf_sample_data sample;
7731 u16 header_size = namespaces_event->event_id.header.size;
7734 if (!perf_event_namespaces_match(event))
7737 perf_event_header__init_id(&namespaces_event->event_id.header,
7739 ret = perf_output_begin(&handle, event,
7740 namespaces_event->event_id.header.size);
7744 namespaces_event->event_id.pid = perf_event_pid(event,
7745 namespaces_event->task);
7746 namespaces_event->event_id.tid = perf_event_tid(event,
7747 namespaces_event->task);
7749 perf_output_put(&handle, namespaces_event->event_id);
7751 perf_event__output_id_sample(event, &handle, &sample);
7753 perf_output_end(&handle);
7755 namespaces_event->event_id.header.size = header_size;
7758 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7759 struct task_struct *task,
7760 const struct proc_ns_operations *ns_ops)
7762 struct path ns_path;
7763 struct inode *ns_inode;
7766 error = ns_get_path(&ns_path, task, ns_ops);
7768 ns_inode = ns_path.dentry->d_inode;
7769 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7770 ns_link_info->ino = ns_inode->i_ino;
7775 void perf_event_namespaces(struct task_struct *task)
7777 struct perf_namespaces_event namespaces_event;
7778 struct perf_ns_link_info *ns_link_info;
7780 if (!atomic_read(&nr_namespaces_events))
7783 namespaces_event = (struct perf_namespaces_event){
7787 .type = PERF_RECORD_NAMESPACES,
7789 .size = sizeof(namespaces_event.event_id),
7793 .nr_namespaces = NR_NAMESPACES,
7794 /* .link_info[NR_NAMESPACES] */
7798 ns_link_info = namespaces_event.event_id.link_info;
7800 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7801 task, &mntns_operations);
7803 #ifdef CONFIG_USER_NS
7804 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7805 task, &userns_operations);
7807 #ifdef CONFIG_NET_NS
7808 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7809 task, &netns_operations);
7811 #ifdef CONFIG_UTS_NS
7812 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7813 task, &utsns_operations);
7815 #ifdef CONFIG_IPC_NS
7816 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7817 task, &ipcns_operations);
7819 #ifdef CONFIG_PID_NS
7820 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7821 task, &pidns_operations);
7823 #ifdef CONFIG_CGROUPS
7824 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7825 task, &cgroupns_operations);
7828 perf_iterate_sb(perf_event_namespaces_output,
7836 #ifdef CONFIG_CGROUP_PERF
7838 struct perf_cgroup_event {
7842 struct perf_event_header header;
7848 static int perf_event_cgroup_match(struct perf_event *event)
7850 return event->attr.cgroup;
7853 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7855 struct perf_cgroup_event *cgroup_event = data;
7856 struct perf_output_handle handle;
7857 struct perf_sample_data sample;
7858 u16 header_size = cgroup_event->event_id.header.size;
7861 if (!perf_event_cgroup_match(event))
7864 perf_event_header__init_id(&cgroup_event->event_id.header,
7866 ret = perf_output_begin(&handle, event,
7867 cgroup_event->event_id.header.size);
7871 perf_output_put(&handle, cgroup_event->event_id);
7872 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7874 perf_event__output_id_sample(event, &handle, &sample);
7876 perf_output_end(&handle);
7878 cgroup_event->event_id.header.size = header_size;
7881 static void perf_event_cgroup(struct cgroup *cgrp)
7883 struct perf_cgroup_event cgroup_event;
7884 char path_enomem[16] = "//enomem";
7888 if (!atomic_read(&nr_cgroup_events))
7891 cgroup_event = (struct perf_cgroup_event){
7894 .type = PERF_RECORD_CGROUP,
7896 .size = sizeof(cgroup_event.event_id),
7898 .id = cgroup_id(cgrp),
7902 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7903 if (pathname == NULL) {
7904 cgroup_event.path = path_enomem;
7906 /* just to be sure to have enough space for alignment */
7907 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7908 cgroup_event.path = pathname;
7912 * Since our buffer works in 8 byte units we need to align our string
7913 * size to a multiple of 8. However, we must guarantee the tail end is
7914 * zero'd out to avoid leaking random bits to userspace.
7916 size = strlen(cgroup_event.path) + 1;
7917 while (!IS_ALIGNED(size, sizeof(u64)))
7918 cgroup_event.path[size++] = '\0';
7920 cgroup_event.event_id.header.size += size;
7921 cgroup_event.path_size = size;
7923 perf_iterate_sb(perf_event_cgroup_output,
7936 struct perf_mmap_event {
7937 struct vm_area_struct *vma;
7939 const char *file_name;
7947 struct perf_event_header header;
7957 static int perf_event_mmap_match(struct perf_event *event,
7960 struct perf_mmap_event *mmap_event = data;
7961 struct vm_area_struct *vma = mmap_event->vma;
7962 int executable = vma->vm_flags & VM_EXEC;
7964 return (!executable && event->attr.mmap_data) ||
7965 (executable && (event->attr.mmap || event->attr.mmap2));
7968 static void perf_event_mmap_output(struct perf_event *event,
7971 struct perf_mmap_event *mmap_event = data;
7972 struct perf_output_handle handle;
7973 struct perf_sample_data sample;
7974 int size = mmap_event->event_id.header.size;
7975 u32 type = mmap_event->event_id.header.type;
7978 if (!perf_event_mmap_match(event, data))
7981 if (event->attr.mmap2) {
7982 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7983 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7984 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7985 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7986 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7987 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7988 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7991 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7992 ret = perf_output_begin(&handle, event,
7993 mmap_event->event_id.header.size);
7997 mmap_event->event_id.pid = perf_event_pid(event, current);
7998 mmap_event->event_id.tid = perf_event_tid(event, current);
8000 perf_output_put(&handle, mmap_event->event_id);
8002 if (event->attr.mmap2) {
8003 perf_output_put(&handle, mmap_event->maj);
8004 perf_output_put(&handle, mmap_event->min);
8005 perf_output_put(&handle, mmap_event->ino);
8006 perf_output_put(&handle, mmap_event->ino_generation);
8007 perf_output_put(&handle, mmap_event->prot);
8008 perf_output_put(&handle, mmap_event->flags);
8011 __output_copy(&handle, mmap_event->file_name,
8012 mmap_event->file_size);
8014 perf_event__output_id_sample(event, &handle, &sample);
8016 perf_output_end(&handle);
8018 mmap_event->event_id.header.size = size;
8019 mmap_event->event_id.header.type = type;
8022 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8024 struct vm_area_struct *vma = mmap_event->vma;
8025 struct file *file = vma->vm_file;
8026 int maj = 0, min = 0;
8027 u64 ino = 0, gen = 0;
8028 u32 prot = 0, flags = 0;
8034 if (vma->vm_flags & VM_READ)
8036 if (vma->vm_flags & VM_WRITE)
8038 if (vma->vm_flags & VM_EXEC)
8041 if (vma->vm_flags & VM_MAYSHARE)
8044 flags = MAP_PRIVATE;
8046 if (vma->vm_flags & VM_DENYWRITE)
8047 flags |= MAP_DENYWRITE;
8048 if (vma->vm_flags & VM_MAYEXEC)
8049 flags |= MAP_EXECUTABLE;
8050 if (vma->vm_flags & VM_LOCKED)
8051 flags |= MAP_LOCKED;
8052 if (is_vm_hugetlb_page(vma))
8053 flags |= MAP_HUGETLB;
8056 struct inode *inode;
8059 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8065 * d_path() works from the end of the rb backwards, so we
8066 * need to add enough zero bytes after the string to handle
8067 * the 64bit alignment we do later.
8069 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8074 inode = file_inode(vma->vm_file);
8075 dev = inode->i_sb->s_dev;
8077 gen = inode->i_generation;
8083 if (vma->vm_ops && vma->vm_ops->name) {
8084 name = (char *) vma->vm_ops->name(vma);
8089 name = (char *)arch_vma_name(vma);
8093 if (vma->vm_start <= vma->vm_mm->start_brk &&
8094 vma->vm_end >= vma->vm_mm->brk) {
8098 if (vma->vm_start <= vma->vm_mm->start_stack &&
8099 vma->vm_end >= vma->vm_mm->start_stack) {
8109 strlcpy(tmp, name, sizeof(tmp));
8113 * Since our buffer works in 8 byte units we need to align our string
8114 * size to a multiple of 8. However, we must guarantee the tail end is
8115 * zero'd out to avoid leaking random bits to userspace.
8117 size = strlen(name)+1;
8118 while (!IS_ALIGNED(size, sizeof(u64)))
8119 name[size++] = '\0';
8121 mmap_event->file_name = name;
8122 mmap_event->file_size = size;
8123 mmap_event->maj = maj;
8124 mmap_event->min = min;
8125 mmap_event->ino = ino;
8126 mmap_event->ino_generation = gen;
8127 mmap_event->prot = prot;
8128 mmap_event->flags = flags;
8130 if (!(vma->vm_flags & VM_EXEC))
8131 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8133 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8135 perf_iterate_sb(perf_event_mmap_output,
8143 * Check whether inode and address range match filter criteria.
8145 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8146 struct file *file, unsigned long offset,
8149 /* d_inode(NULL) won't be equal to any mapped user-space file */
8150 if (!filter->path.dentry)
8153 if (d_inode(filter->path.dentry) != file_inode(file))
8156 if (filter->offset > offset + size)
8159 if (filter->offset + filter->size < offset)
8165 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8166 struct vm_area_struct *vma,
8167 struct perf_addr_filter_range *fr)
8169 unsigned long vma_size = vma->vm_end - vma->vm_start;
8170 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8171 struct file *file = vma->vm_file;
8173 if (!perf_addr_filter_match(filter, file, off, vma_size))
8176 if (filter->offset < off) {
8177 fr->start = vma->vm_start;
8178 fr->size = min(vma_size, filter->size - (off - filter->offset));
8180 fr->start = vma->vm_start + filter->offset - off;
8181 fr->size = min(vma->vm_end - fr->start, filter->size);
8187 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8189 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8190 struct vm_area_struct *vma = data;
8191 struct perf_addr_filter *filter;
8192 unsigned int restart = 0, count = 0;
8193 unsigned long flags;
8195 if (!has_addr_filter(event))
8201 raw_spin_lock_irqsave(&ifh->lock, flags);
8202 list_for_each_entry(filter, &ifh->list, entry) {
8203 if (perf_addr_filter_vma_adjust(filter, vma,
8204 &event->addr_filter_ranges[count]))
8211 event->addr_filters_gen++;
8212 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8215 perf_event_stop(event, 1);
8219 * Adjust all task's events' filters to the new vma
8221 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8223 struct perf_event_context *ctx;
8227 * Data tracing isn't supported yet and as such there is no need
8228 * to keep track of anything that isn't related to executable code:
8230 if (!(vma->vm_flags & VM_EXEC))
8234 for_each_task_context_nr(ctxn) {
8235 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8239 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8244 void perf_event_mmap(struct vm_area_struct *vma)
8246 struct perf_mmap_event mmap_event;
8248 if (!atomic_read(&nr_mmap_events))
8251 mmap_event = (struct perf_mmap_event){
8257 .type = PERF_RECORD_MMAP,
8258 .misc = PERF_RECORD_MISC_USER,
8263 .start = vma->vm_start,
8264 .len = vma->vm_end - vma->vm_start,
8265 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8267 /* .maj (attr_mmap2 only) */
8268 /* .min (attr_mmap2 only) */
8269 /* .ino (attr_mmap2 only) */
8270 /* .ino_generation (attr_mmap2 only) */
8271 /* .prot (attr_mmap2 only) */
8272 /* .flags (attr_mmap2 only) */
8275 perf_addr_filters_adjust(vma);
8276 perf_event_mmap_event(&mmap_event);
8279 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8280 unsigned long size, u64 flags)
8282 struct perf_output_handle handle;
8283 struct perf_sample_data sample;
8284 struct perf_aux_event {
8285 struct perf_event_header header;
8291 .type = PERF_RECORD_AUX,
8293 .size = sizeof(rec),
8301 perf_event_header__init_id(&rec.header, &sample, event);
8302 ret = perf_output_begin(&handle, event, rec.header.size);
8307 perf_output_put(&handle, rec);
8308 perf_event__output_id_sample(event, &handle, &sample);
8310 perf_output_end(&handle);
8314 * Lost/dropped samples logging
8316 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8318 struct perf_output_handle handle;
8319 struct perf_sample_data sample;
8323 struct perf_event_header header;
8325 } lost_samples_event = {
8327 .type = PERF_RECORD_LOST_SAMPLES,
8329 .size = sizeof(lost_samples_event),
8334 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8336 ret = perf_output_begin(&handle, event,
8337 lost_samples_event.header.size);
8341 perf_output_put(&handle, lost_samples_event);
8342 perf_event__output_id_sample(event, &handle, &sample);
8343 perf_output_end(&handle);
8347 * context_switch tracking
8350 struct perf_switch_event {
8351 struct task_struct *task;
8352 struct task_struct *next_prev;
8355 struct perf_event_header header;
8361 static int perf_event_switch_match(struct perf_event *event)
8363 return event->attr.context_switch;
8366 static void perf_event_switch_output(struct perf_event *event, void *data)
8368 struct perf_switch_event *se = data;
8369 struct perf_output_handle handle;
8370 struct perf_sample_data sample;
8373 if (!perf_event_switch_match(event))
8376 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8377 if (event->ctx->task) {
8378 se->event_id.header.type = PERF_RECORD_SWITCH;
8379 se->event_id.header.size = sizeof(se->event_id.header);
8381 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8382 se->event_id.header.size = sizeof(se->event_id);
8383 se->event_id.next_prev_pid =
8384 perf_event_pid(event, se->next_prev);
8385 se->event_id.next_prev_tid =
8386 perf_event_tid(event, se->next_prev);
8389 perf_event_header__init_id(&se->event_id.header, &sample, event);
8391 ret = perf_output_begin(&handle, event, se->event_id.header.size);
8395 if (event->ctx->task)
8396 perf_output_put(&handle, se->event_id.header);
8398 perf_output_put(&handle, se->event_id);
8400 perf_event__output_id_sample(event, &handle, &sample);
8402 perf_output_end(&handle);
8405 static void perf_event_switch(struct task_struct *task,
8406 struct task_struct *next_prev, bool sched_in)
8408 struct perf_switch_event switch_event;
8410 /* N.B. caller checks nr_switch_events != 0 */
8412 switch_event = (struct perf_switch_event){
8414 .next_prev = next_prev,
8418 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8421 /* .next_prev_pid */
8422 /* .next_prev_tid */
8426 if (!sched_in && task->state == TASK_RUNNING)
8427 switch_event.event_id.header.misc |=
8428 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8430 perf_iterate_sb(perf_event_switch_output,
8436 * IRQ throttle logging
8439 static void perf_log_throttle(struct perf_event *event, int enable)
8441 struct perf_output_handle handle;
8442 struct perf_sample_data sample;
8446 struct perf_event_header header;
8450 } throttle_event = {
8452 .type = PERF_RECORD_THROTTLE,
8454 .size = sizeof(throttle_event),
8456 .time = perf_event_clock(event),
8457 .id = primary_event_id(event),
8458 .stream_id = event->id,
8462 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8464 perf_event_header__init_id(&throttle_event.header, &sample, event);
8466 ret = perf_output_begin(&handle, event,
8467 throttle_event.header.size);
8471 perf_output_put(&handle, throttle_event);
8472 perf_event__output_id_sample(event, &handle, &sample);
8473 perf_output_end(&handle);
8477 * ksymbol register/unregister tracking
8480 struct perf_ksymbol_event {
8484 struct perf_event_header header;
8492 static int perf_event_ksymbol_match(struct perf_event *event)
8494 return event->attr.ksymbol;
8497 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8499 struct perf_ksymbol_event *ksymbol_event = data;
8500 struct perf_output_handle handle;
8501 struct perf_sample_data sample;
8504 if (!perf_event_ksymbol_match(event))
8507 perf_event_header__init_id(&ksymbol_event->event_id.header,
8509 ret = perf_output_begin(&handle, event,
8510 ksymbol_event->event_id.header.size);
8514 perf_output_put(&handle, ksymbol_event->event_id);
8515 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8516 perf_event__output_id_sample(event, &handle, &sample);
8518 perf_output_end(&handle);
8521 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8524 struct perf_ksymbol_event ksymbol_event;
8525 char name[KSYM_NAME_LEN];
8529 if (!atomic_read(&nr_ksymbol_events))
8532 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8533 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8536 strlcpy(name, sym, KSYM_NAME_LEN);
8537 name_len = strlen(name) + 1;
8538 while (!IS_ALIGNED(name_len, sizeof(u64)))
8539 name[name_len++] = '\0';
8540 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8543 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8545 ksymbol_event = (struct perf_ksymbol_event){
8547 .name_len = name_len,
8550 .type = PERF_RECORD_KSYMBOL,
8551 .size = sizeof(ksymbol_event.event_id) +
8556 .ksym_type = ksym_type,
8561 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8564 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8568 * bpf program load/unload tracking
8571 struct perf_bpf_event {
8572 struct bpf_prog *prog;
8574 struct perf_event_header header;
8578 u8 tag[BPF_TAG_SIZE];
8582 static int perf_event_bpf_match(struct perf_event *event)
8584 return event->attr.bpf_event;
8587 static void perf_event_bpf_output(struct perf_event *event, void *data)
8589 struct perf_bpf_event *bpf_event = data;
8590 struct perf_output_handle handle;
8591 struct perf_sample_data sample;
8594 if (!perf_event_bpf_match(event))
8597 perf_event_header__init_id(&bpf_event->event_id.header,
8599 ret = perf_output_begin(&handle, event,
8600 bpf_event->event_id.header.size);
8604 perf_output_put(&handle, bpf_event->event_id);
8605 perf_event__output_id_sample(event, &handle, &sample);
8607 perf_output_end(&handle);
8610 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8611 enum perf_bpf_event_type type)
8613 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8616 if (prog->aux->func_cnt == 0) {
8617 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8618 (u64)(unsigned long)prog->bpf_func,
8619 prog->jited_len, unregister,
8620 prog->aux->ksym.name);
8622 for (i = 0; i < prog->aux->func_cnt; i++) {
8623 struct bpf_prog *subprog = prog->aux->func[i];
8626 PERF_RECORD_KSYMBOL_TYPE_BPF,
8627 (u64)(unsigned long)subprog->bpf_func,
8628 subprog->jited_len, unregister,
8629 prog->aux->ksym.name);
8634 void perf_event_bpf_event(struct bpf_prog *prog,
8635 enum perf_bpf_event_type type,
8638 struct perf_bpf_event bpf_event;
8640 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8641 type >= PERF_BPF_EVENT_MAX)
8645 case PERF_BPF_EVENT_PROG_LOAD:
8646 case PERF_BPF_EVENT_PROG_UNLOAD:
8647 if (atomic_read(&nr_ksymbol_events))
8648 perf_event_bpf_emit_ksymbols(prog, type);
8654 if (!atomic_read(&nr_bpf_events))
8657 bpf_event = (struct perf_bpf_event){
8661 .type = PERF_RECORD_BPF_EVENT,
8662 .size = sizeof(bpf_event.event_id),
8666 .id = prog->aux->id,
8670 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8672 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8673 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8676 struct perf_text_poke_event {
8677 const void *old_bytes;
8678 const void *new_bytes;
8684 struct perf_event_header header;
8690 static int perf_event_text_poke_match(struct perf_event *event)
8692 return event->attr.text_poke;
8695 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8697 struct perf_text_poke_event *text_poke_event = data;
8698 struct perf_output_handle handle;
8699 struct perf_sample_data sample;
8703 if (!perf_event_text_poke_match(event))
8706 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8708 ret = perf_output_begin(&handle, event, text_poke_event->event_id.header.size);
8712 perf_output_put(&handle, text_poke_event->event_id);
8713 perf_output_put(&handle, text_poke_event->old_len);
8714 perf_output_put(&handle, text_poke_event->new_len);
8716 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8717 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8719 if (text_poke_event->pad)
8720 __output_copy(&handle, &padding, text_poke_event->pad);
8722 perf_event__output_id_sample(event, &handle, &sample);
8724 perf_output_end(&handle);
8727 void perf_event_text_poke(const void *addr, const void *old_bytes,
8728 size_t old_len, const void *new_bytes, size_t new_len)
8730 struct perf_text_poke_event text_poke_event;
8733 if (!atomic_read(&nr_text_poke_events))
8736 tot = sizeof(text_poke_event.old_len) + old_len;
8737 tot += sizeof(text_poke_event.new_len) + new_len;
8738 pad = ALIGN(tot, sizeof(u64)) - tot;
8740 text_poke_event = (struct perf_text_poke_event){
8741 .old_bytes = old_bytes,
8742 .new_bytes = new_bytes,
8748 .type = PERF_RECORD_TEXT_POKE,
8749 .misc = PERF_RECORD_MISC_KERNEL,
8750 .size = sizeof(text_poke_event.event_id) + tot + pad,
8752 .addr = (unsigned long)addr,
8756 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8759 void perf_event_itrace_started(struct perf_event *event)
8761 event->attach_state |= PERF_ATTACH_ITRACE;
8764 static void perf_log_itrace_start(struct perf_event *event)
8766 struct perf_output_handle handle;
8767 struct perf_sample_data sample;
8768 struct perf_aux_event {
8769 struct perf_event_header header;
8776 event = event->parent;
8778 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8779 event->attach_state & PERF_ATTACH_ITRACE)
8782 rec.header.type = PERF_RECORD_ITRACE_START;
8783 rec.header.misc = 0;
8784 rec.header.size = sizeof(rec);
8785 rec.pid = perf_event_pid(event, current);
8786 rec.tid = perf_event_tid(event, current);
8788 perf_event_header__init_id(&rec.header, &sample, event);
8789 ret = perf_output_begin(&handle, event, rec.header.size);
8794 perf_output_put(&handle, rec);
8795 perf_event__output_id_sample(event, &handle, &sample);
8797 perf_output_end(&handle);
8801 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8803 struct hw_perf_event *hwc = &event->hw;
8807 seq = __this_cpu_read(perf_throttled_seq);
8808 if (seq != hwc->interrupts_seq) {
8809 hwc->interrupts_seq = seq;
8810 hwc->interrupts = 1;
8813 if (unlikely(throttle
8814 && hwc->interrupts >= max_samples_per_tick)) {
8815 __this_cpu_inc(perf_throttled_count);
8816 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8817 hwc->interrupts = MAX_INTERRUPTS;
8818 perf_log_throttle(event, 0);
8823 if (event->attr.freq) {
8824 u64 now = perf_clock();
8825 s64 delta = now - hwc->freq_time_stamp;
8827 hwc->freq_time_stamp = now;
8829 if (delta > 0 && delta < 2*TICK_NSEC)
8830 perf_adjust_period(event, delta, hwc->last_period, true);
8836 int perf_event_account_interrupt(struct perf_event *event)
8838 return __perf_event_account_interrupt(event, 1);
8842 * Generic event overflow handling, sampling.
8845 static int __perf_event_overflow(struct perf_event *event,
8846 int throttle, struct perf_sample_data *data,
8847 struct pt_regs *regs)
8849 int events = atomic_read(&event->event_limit);
8853 * Non-sampling counters might still use the PMI to fold short
8854 * hardware counters, ignore those.
8856 if (unlikely(!is_sampling_event(event)))
8859 ret = __perf_event_account_interrupt(event, throttle);
8862 * XXX event_limit might not quite work as expected on inherited
8866 event->pending_kill = POLL_IN;
8867 if (events && atomic_dec_and_test(&event->event_limit)) {
8869 event->pending_kill = POLL_HUP;
8871 perf_event_disable_inatomic(event);
8874 READ_ONCE(event->overflow_handler)(event, data, regs);
8876 if (*perf_event_fasync(event) && event->pending_kill) {
8877 event->pending_wakeup = 1;
8878 irq_work_queue(&event->pending);
8884 int perf_event_overflow(struct perf_event *event,
8885 struct perf_sample_data *data,
8886 struct pt_regs *regs)
8888 return __perf_event_overflow(event, 1, data, regs);
8892 * Generic software event infrastructure
8895 struct swevent_htable {
8896 struct swevent_hlist *swevent_hlist;
8897 struct mutex hlist_mutex;
8900 /* Recursion avoidance in each contexts */
8901 int recursion[PERF_NR_CONTEXTS];
8904 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8907 * We directly increment event->count and keep a second value in
8908 * event->hw.period_left to count intervals. This period event
8909 * is kept in the range [-sample_period, 0] so that we can use the
8913 u64 perf_swevent_set_period(struct perf_event *event)
8915 struct hw_perf_event *hwc = &event->hw;
8916 u64 period = hwc->last_period;
8920 hwc->last_period = hwc->sample_period;
8923 old = val = local64_read(&hwc->period_left);
8927 nr = div64_u64(period + val, period);
8928 offset = nr * period;
8930 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8936 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8937 struct perf_sample_data *data,
8938 struct pt_regs *regs)
8940 struct hw_perf_event *hwc = &event->hw;
8944 overflow = perf_swevent_set_period(event);
8946 if (hwc->interrupts == MAX_INTERRUPTS)
8949 for (; overflow; overflow--) {
8950 if (__perf_event_overflow(event, throttle,
8953 * We inhibit the overflow from happening when
8954 * hwc->interrupts == MAX_INTERRUPTS.
8962 static void perf_swevent_event(struct perf_event *event, u64 nr,
8963 struct perf_sample_data *data,
8964 struct pt_regs *regs)
8966 struct hw_perf_event *hwc = &event->hw;
8968 local64_add(nr, &event->count);
8973 if (!is_sampling_event(event))
8976 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8978 return perf_swevent_overflow(event, 1, data, regs);
8980 data->period = event->hw.last_period;
8982 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8983 return perf_swevent_overflow(event, 1, data, regs);
8985 if (local64_add_negative(nr, &hwc->period_left))
8988 perf_swevent_overflow(event, 0, data, regs);
8991 static int perf_exclude_event(struct perf_event *event,
8992 struct pt_regs *regs)
8994 if (event->hw.state & PERF_HES_STOPPED)
8998 if (event->attr.exclude_user && user_mode(regs))
9001 if (event->attr.exclude_kernel && !user_mode(regs))
9008 static int perf_swevent_match(struct perf_event *event,
9009 enum perf_type_id type,
9011 struct perf_sample_data *data,
9012 struct pt_regs *regs)
9014 if (event->attr.type != type)
9017 if (event->attr.config != event_id)
9020 if (perf_exclude_event(event, regs))
9026 static inline u64 swevent_hash(u64 type, u32 event_id)
9028 u64 val = event_id | (type << 32);
9030 return hash_64(val, SWEVENT_HLIST_BITS);
9033 static inline struct hlist_head *
9034 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9036 u64 hash = swevent_hash(type, event_id);
9038 return &hlist->heads[hash];
9041 /* For the read side: events when they trigger */
9042 static inline struct hlist_head *
9043 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9045 struct swevent_hlist *hlist;
9047 hlist = rcu_dereference(swhash->swevent_hlist);
9051 return __find_swevent_head(hlist, type, event_id);
9054 /* For the event head insertion and removal in the hlist */
9055 static inline struct hlist_head *
9056 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9058 struct swevent_hlist *hlist;
9059 u32 event_id = event->attr.config;
9060 u64 type = event->attr.type;
9063 * Event scheduling is always serialized against hlist allocation
9064 * and release. Which makes the protected version suitable here.
9065 * The context lock guarantees that.
9067 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9068 lockdep_is_held(&event->ctx->lock));
9072 return __find_swevent_head(hlist, type, event_id);
9075 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9077 struct perf_sample_data *data,
9078 struct pt_regs *regs)
9080 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9081 struct perf_event *event;
9082 struct hlist_head *head;
9085 head = find_swevent_head_rcu(swhash, type, event_id);
9089 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9090 if (perf_swevent_match(event, type, event_id, data, regs))
9091 perf_swevent_event(event, nr, data, regs);
9097 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9099 int perf_swevent_get_recursion_context(void)
9101 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9103 return get_recursion_context(swhash->recursion);
9105 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9107 void perf_swevent_put_recursion_context(int rctx)
9109 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9111 put_recursion_context(swhash->recursion, rctx);
9114 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9116 struct perf_sample_data data;
9118 if (WARN_ON_ONCE(!regs))
9121 perf_sample_data_init(&data, addr, 0);
9122 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9125 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9129 preempt_disable_notrace();
9130 rctx = perf_swevent_get_recursion_context();
9131 if (unlikely(rctx < 0))
9134 ___perf_sw_event(event_id, nr, regs, addr);
9136 perf_swevent_put_recursion_context(rctx);
9138 preempt_enable_notrace();
9141 static void perf_swevent_read(struct perf_event *event)
9145 static int perf_swevent_add(struct perf_event *event, int flags)
9147 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9148 struct hw_perf_event *hwc = &event->hw;
9149 struct hlist_head *head;
9151 if (is_sampling_event(event)) {
9152 hwc->last_period = hwc->sample_period;
9153 perf_swevent_set_period(event);
9156 hwc->state = !(flags & PERF_EF_START);
9158 head = find_swevent_head(swhash, event);
9159 if (WARN_ON_ONCE(!head))
9162 hlist_add_head_rcu(&event->hlist_entry, head);
9163 perf_event_update_userpage(event);
9168 static void perf_swevent_del(struct perf_event *event, int flags)
9170 hlist_del_rcu(&event->hlist_entry);
9173 static void perf_swevent_start(struct perf_event *event, int flags)
9175 event->hw.state = 0;
9178 static void perf_swevent_stop(struct perf_event *event, int flags)
9180 event->hw.state = PERF_HES_STOPPED;
9183 /* Deref the hlist from the update side */
9184 static inline struct swevent_hlist *
9185 swevent_hlist_deref(struct swevent_htable *swhash)
9187 return rcu_dereference_protected(swhash->swevent_hlist,
9188 lockdep_is_held(&swhash->hlist_mutex));
9191 static void swevent_hlist_release(struct swevent_htable *swhash)
9193 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9198 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9199 kfree_rcu(hlist, rcu_head);
9202 static void swevent_hlist_put_cpu(int cpu)
9204 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9206 mutex_lock(&swhash->hlist_mutex);
9208 if (!--swhash->hlist_refcount)
9209 swevent_hlist_release(swhash);
9211 mutex_unlock(&swhash->hlist_mutex);
9214 static void swevent_hlist_put(void)
9218 for_each_possible_cpu(cpu)
9219 swevent_hlist_put_cpu(cpu);
9222 static int swevent_hlist_get_cpu(int cpu)
9224 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9227 mutex_lock(&swhash->hlist_mutex);
9228 if (!swevent_hlist_deref(swhash) &&
9229 cpumask_test_cpu(cpu, perf_online_mask)) {
9230 struct swevent_hlist *hlist;
9232 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9237 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9239 swhash->hlist_refcount++;
9241 mutex_unlock(&swhash->hlist_mutex);
9246 static int swevent_hlist_get(void)
9248 int err, cpu, failed_cpu;
9250 mutex_lock(&pmus_lock);
9251 for_each_possible_cpu(cpu) {
9252 err = swevent_hlist_get_cpu(cpu);
9258 mutex_unlock(&pmus_lock);
9261 for_each_possible_cpu(cpu) {
9262 if (cpu == failed_cpu)
9264 swevent_hlist_put_cpu(cpu);
9266 mutex_unlock(&pmus_lock);
9270 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9272 static void sw_perf_event_destroy(struct perf_event *event)
9274 u64 event_id = event->attr.config;
9276 WARN_ON(event->parent);
9278 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9279 swevent_hlist_put();
9282 static int perf_swevent_init(struct perf_event *event)
9284 u64 event_id = event->attr.config;
9286 if (event->attr.type != PERF_TYPE_SOFTWARE)
9290 * no branch sampling for software events
9292 if (has_branch_stack(event))
9296 case PERF_COUNT_SW_CPU_CLOCK:
9297 case PERF_COUNT_SW_TASK_CLOCK:
9304 if (event_id >= PERF_COUNT_SW_MAX)
9307 if (!event->parent) {
9310 err = swevent_hlist_get();
9314 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9315 event->destroy = sw_perf_event_destroy;
9321 static struct pmu perf_swevent = {
9322 .task_ctx_nr = perf_sw_context,
9324 .capabilities = PERF_PMU_CAP_NO_NMI,
9326 .event_init = perf_swevent_init,
9327 .add = perf_swevent_add,
9328 .del = perf_swevent_del,
9329 .start = perf_swevent_start,
9330 .stop = perf_swevent_stop,
9331 .read = perf_swevent_read,
9334 #ifdef CONFIG_EVENT_TRACING
9336 static int perf_tp_filter_match(struct perf_event *event,
9337 struct perf_sample_data *data)
9339 void *record = data->raw->frag.data;
9341 /* only top level events have filters set */
9343 event = event->parent;
9345 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9350 static int perf_tp_event_match(struct perf_event *event,
9351 struct perf_sample_data *data,
9352 struct pt_regs *regs)
9354 if (event->hw.state & PERF_HES_STOPPED)
9357 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9359 if (event->attr.exclude_kernel && !user_mode(regs))
9362 if (!perf_tp_filter_match(event, data))
9368 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9369 struct trace_event_call *call, u64 count,
9370 struct pt_regs *regs, struct hlist_head *head,
9371 struct task_struct *task)
9373 if (bpf_prog_array_valid(call)) {
9374 *(struct pt_regs **)raw_data = regs;
9375 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9376 perf_swevent_put_recursion_context(rctx);
9380 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9383 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9385 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9386 struct pt_regs *regs, struct hlist_head *head, int rctx,
9387 struct task_struct *task)
9389 struct perf_sample_data data;
9390 struct perf_event *event;
9392 struct perf_raw_record raw = {
9399 perf_sample_data_init(&data, 0, 0);
9402 perf_trace_buf_update(record, event_type);
9404 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9405 if (perf_tp_event_match(event, &data, regs))
9406 perf_swevent_event(event, count, &data, regs);
9410 * If we got specified a target task, also iterate its context and
9411 * deliver this event there too.
9413 if (task && task != current) {
9414 struct perf_event_context *ctx;
9415 struct trace_entry *entry = record;
9418 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9422 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9423 if (event->cpu != smp_processor_id())
9425 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9427 if (event->attr.config != entry->type)
9429 if (perf_tp_event_match(event, &data, regs))
9430 perf_swevent_event(event, count, &data, regs);
9436 perf_swevent_put_recursion_context(rctx);
9438 EXPORT_SYMBOL_GPL(perf_tp_event);
9440 static void tp_perf_event_destroy(struct perf_event *event)
9442 perf_trace_destroy(event);
9445 static int perf_tp_event_init(struct perf_event *event)
9449 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9453 * no branch sampling for tracepoint events
9455 if (has_branch_stack(event))
9458 err = perf_trace_init(event);
9462 event->destroy = tp_perf_event_destroy;
9467 static struct pmu perf_tracepoint = {
9468 .task_ctx_nr = perf_sw_context,
9470 .event_init = perf_tp_event_init,
9471 .add = perf_trace_add,
9472 .del = perf_trace_del,
9473 .start = perf_swevent_start,
9474 .stop = perf_swevent_stop,
9475 .read = perf_swevent_read,
9478 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9480 * Flags in config, used by dynamic PMU kprobe and uprobe
9481 * The flags should match following PMU_FORMAT_ATTR().
9483 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9484 * if not set, create kprobe/uprobe
9486 * The following values specify a reference counter (or semaphore in the
9487 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9488 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9490 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9491 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9493 enum perf_probe_config {
9494 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9495 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9496 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9499 PMU_FORMAT_ATTR(retprobe, "config:0");
9502 #ifdef CONFIG_KPROBE_EVENTS
9503 static struct attribute *kprobe_attrs[] = {
9504 &format_attr_retprobe.attr,
9508 static struct attribute_group kprobe_format_group = {
9510 .attrs = kprobe_attrs,
9513 static const struct attribute_group *kprobe_attr_groups[] = {
9514 &kprobe_format_group,
9518 static int perf_kprobe_event_init(struct perf_event *event);
9519 static struct pmu perf_kprobe = {
9520 .task_ctx_nr = perf_sw_context,
9521 .event_init = perf_kprobe_event_init,
9522 .add = perf_trace_add,
9523 .del = perf_trace_del,
9524 .start = perf_swevent_start,
9525 .stop = perf_swevent_stop,
9526 .read = perf_swevent_read,
9527 .attr_groups = kprobe_attr_groups,
9530 static int perf_kprobe_event_init(struct perf_event *event)
9535 if (event->attr.type != perf_kprobe.type)
9538 if (!perfmon_capable())
9542 * no branch sampling for probe events
9544 if (has_branch_stack(event))
9547 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9548 err = perf_kprobe_init(event, is_retprobe);
9552 event->destroy = perf_kprobe_destroy;
9556 #endif /* CONFIG_KPROBE_EVENTS */
9558 #ifdef CONFIG_UPROBE_EVENTS
9559 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9561 static struct attribute *uprobe_attrs[] = {
9562 &format_attr_retprobe.attr,
9563 &format_attr_ref_ctr_offset.attr,
9567 static struct attribute_group uprobe_format_group = {
9569 .attrs = uprobe_attrs,
9572 static const struct attribute_group *uprobe_attr_groups[] = {
9573 &uprobe_format_group,
9577 static int perf_uprobe_event_init(struct perf_event *event);
9578 static struct pmu perf_uprobe = {
9579 .task_ctx_nr = perf_sw_context,
9580 .event_init = perf_uprobe_event_init,
9581 .add = perf_trace_add,
9582 .del = perf_trace_del,
9583 .start = perf_swevent_start,
9584 .stop = perf_swevent_stop,
9585 .read = perf_swevent_read,
9586 .attr_groups = uprobe_attr_groups,
9589 static int perf_uprobe_event_init(struct perf_event *event)
9592 unsigned long ref_ctr_offset;
9595 if (event->attr.type != perf_uprobe.type)
9598 if (!perfmon_capable())
9602 * no branch sampling for probe events
9604 if (has_branch_stack(event))
9607 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9608 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9609 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9613 event->destroy = perf_uprobe_destroy;
9617 #endif /* CONFIG_UPROBE_EVENTS */
9619 static inline void perf_tp_register(void)
9621 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9622 #ifdef CONFIG_KPROBE_EVENTS
9623 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9625 #ifdef CONFIG_UPROBE_EVENTS
9626 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9630 static void perf_event_free_filter(struct perf_event *event)
9632 ftrace_profile_free_filter(event);
9635 #ifdef CONFIG_BPF_SYSCALL
9636 static void bpf_overflow_handler(struct perf_event *event,
9637 struct perf_sample_data *data,
9638 struct pt_regs *regs)
9640 struct bpf_perf_event_data_kern ctx = {
9646 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9647 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9650 ret = BPF_PROG_RUN(event->prog, &ctx);
9653 __this_cpu_dec(bpf_prog_active);
9657 event->orig_overflow_handler(event, data, regs);
9660 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9662 struct bpf_prog *prog;
9664 if (event->overflow_handler_context)
9665 /* hw breakpoint or kernel counter */
9671 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9673 return PTR_ERR(prog);
9675 if (event->attr.precise_ip &&
9676 prog->call_get_stack &&
9677 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9678 event->attr.exclude_callchain_kernel ||
9679 event->attr.exclude_callchain_user)) {
9681 * On perf_event with precise_ip, calling bpf_get_stack()
9682 * may trigger unwinder warnings and occasional crashes.
9683 * bpf_get_[stack|stackid] works around this issue by using
9684 * callchain attached to perf_sample_data. If the
9685 * perf_event does not full (kernel and user) callchain
9686 * attached to perf_sample_data, do not allow attaching BPF
9687 * program that calls bpf_get_[stack|stackid].
9694 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9695 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9699 static void perf_event_free_bpf_handler(struct perf_event *event)
9701 struct bpf_prog *prog = event->prog;
9706 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9711 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9715 static void perf_event_free_bpf_handler(struct perf_event *event)
9721 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9722 * with perf_event_open()
9724 static inline bool perf_event_is_tracing(struct perf_event *event)
9726 if (event->pmu == &perf_tracepoint)
9728 #ifdef CONFIG_KPROBE_EVENTS
9729 if (event->pmu == &perf_kprobe)
9732 #ifdef CONFIG_UPROBE_EVENTS
9733 if (event->pmu == &perf_uprobe)
9739 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9741 bool is_kprobe, is_tracepoint, is_syscall_tp;
9742 struct bpf_prog *prog;
9745 if (!perf_event_is_tracing(event))
9746 return perf_event_set_bpf_handler(event, prog_fd);
9748 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9749 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9750 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9751 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9752 /* bpf programs can only be attached to u/kprobe or tracepoint */
9755 prog = bpf_prog_get(prog_fd);
9757 return PTR_ERR(prog);
9759 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9760 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9761 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9762 /* valid fd, but invalid bpf program type */
9767 /* Kprobe override only works for kprobes, not uprobes. */
9768 if (prog->kprobe_override &&
9769 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9774 if (is_tracepoint || is_syscall_tp) {
9775 int off = trace_event_get_offsets(event->tp_event);
9777 if (prog->aux->max_ctx_offset > off) {
9783 ret = perf_event_attach_bpf_prog(event, prog);
9789 static void perf_event_free_bpf_prog(struct perf_event *event)
9791 if (!perf_event_is_tracing(event)) {
9792 perf_event_free_bpf_handler(event);
9795 perf_event_detach_bpf_prog(event);
9800 static inline void perf_tp_register(void)
9804 static void perf_event_free_filter(struct perf_event *event)
9808 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9813 static void perf_event_free_bpf_prog(struct perf_event *event)
9816 #endif /* CONFIG_EVENT_TRACING */
9818 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9819 void perf_bp_event(struct perf_event *bp, void *data)
9821 struct perf_sample_data sample;
9822 struct pt_regs *regs = data;
9824 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9826 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9827 perf_swevent_event(bp, 1, &sample, regs);
9832 * Allocate a new address filter
9834 static struct perf_addr_filter *
9835 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9837 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9838 struct perf_addr_filter *filter;
9840 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9844 INIT_LIST_HEAD(&filter->entry);
9845 list_add_tail(&filter->entry, filters);
9850 static void free_filters_list(struct list_head *filters)
9852 struct perf_addr_filter *filter, *iter;
9854 list_for_each_entry_safe(filter, iter, filters, entry) {
9855 path_put(&filter->path);
9856 list_del(&filter->entry);
9862 * Free existing address filters and optionally install new ones
9864 static void perf_addr_filters_splice(struct perf_event *event,
9865 struct list_head *head)
9867 unsigned long flags;
9870 if (!has_addr_filter(event))
9873 /* don't bother with children, they don't have their own filters */
9877 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9879 list_splice_init(&event->addr_filters.list, &list);
9881 list_splice(head, &event->addr_filters.list);
9883 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9885 free_filters_list(&list);
9889 * Scan through mm's vmas and see if one of them matches the
9890 * @filter; if so, adjust filter's address range.
9891 * Called with mm::mmap_lock down for reading.
9893 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9894 struct mm_struct *mm,
9895 struct perf_addr_filter_range *fr)
9897 struct vm_area_struct *vma;
9899 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9903 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9909 * Update event's address range filters based on the
9910 * task's existing mappings, if any.
9912 static void perf_event_addr_filters_apply(struct perf_event *event)
9914 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9915 struct task_struct *task = READ_ONCE(event->ctx->task);
9916 struct perf_addr_filter *filter;
9917 struct mm_struct *mm = NULL;
9918 unsigned int count = 0;
9919 unsigned long flags;
9922 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9923 * will stop on the parent's child_mutex that our caller is also holding
9925 if (task == TASK_TOMBSTONE)
9928 if (ifh->nr_file_filters) {
9929 mm = get_task_mm(event->ctx->task);
9936 raw_spin_lock_irqsave(&ifh->lock, flags);
9937 list_for_each_entry(filter, &ifh->list, entry) {
9938 if (filter->path.dentry) {
9940 * Adjust base offset if the filter is associated to a
9941 * binary that needs to be mapped:
9943 event->addr_filter_ranges[count].start = 0;
9944 event->addr_filter_ranges[count].size = 0;
9946 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9948 event->addr_filter_ranges[count].start = filter->offset;
9949 event->addr_filter_ranges[count].size = filter->size;
9955 event->addr_filters_gen++;
9956 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9958 if (ifh->nr_file_filters) {
9959 mmap_read_unlock(mm);
9965 perf_event_stop(event, 1);
9969 * Address range filtering: limiting the data to certain
9970 * instruction address ranges. Filters are ioctl()ed to us from
9971 * userspace as ascii strings.
9973 * Filter string format:
9976 * where ACTION is one of the
9977 * * "filter": limit the trace to this region
9978 * * "start": start tracing from this address
9979 * * "stop": stop tracing at this address/region;
9981 * * for kernel addresses: <start address>[/<size>]
9982 * * for object files: <start address>[/<size>]@</path/to/object/file>
9984 * if <size> is not specified or is zero, the range is treated as a single
9985 * address; not valid for ACTION=="filter".
9999 IF_STATE_ACTION = 0,
10004 static const match_table_t if_tokens = {
10005 { IF_ACT_FILTER, "filter" },
10006 { IF_ACT_START, "start" },
10007 { IF_ACT_STOP, "stop" },
10008 { IF_SRC_FILE, "%u/%u@%s" },
10009 { IF_SRC_KERNEL, "%u/%u" },
10010 { IF_SRC_FILEADDR, "%u@%s" },
10011 { IF_SRC_KERNELADDR, "%u" },
10012 { IF_ACT_NONE, NULL },
10016 * Address filter string parser
10019 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10020 struct list_head *filters)
10022 struct perf_addr_filter *filter = NULL;
10023 char *start, *orig, *filename = NULL;
10024 substring_t args[MAX_OPT_ARGS];
10025 int state = IF_STATE_ACTION, token;
10026 unsigned int kernel = 0;
10029 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10033 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10034 static const enum perf_addr_filter_action_t actions[] = {
10035 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10036 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10037 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10044 /* filter definition begins */
10045 if (state == IF_STATE_ACTION) {
10046 filter = perf_addr_filter_new(event, filters);
10051 token = match_token(start, if_tokens, args);
10053 case IF_ACT_FILTER:
10056 if (state != IF_STATE_ACTION)
10059 filter->action = actions[token];
10060 state = IF_STATE_SOURCE;
10063 case IF_SRC_KERNELADDR:
10064 case IF_SRC_KERNEL:
10068 case IF_SRC_FILEADDR:
10070 if (state != IF_STATE_SOURCE)
10074 ret = kstrtoul(args[0].from, 0, &filter->offset);
10078 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10080 ret = kstrtoul(args[1].from, 0, &filter->size);
10085 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10086 int fpos = token == IF_SRC_FILE ? 2 : 1;
10088 filename = match_strdup(&args[fpos]);
10095 state = IF_STATE_END;
10103 * Filter definition is fully parsed, validate and install it.
10104 * Make sure that it doesn't contradict itself or the event's
10107 if (state == IF_STATE_END) {
10109 if (kernel && event->attr.exclude_kernel)
10113 * ACTION "filter" must have a non-zero length region
10116 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10125 * For now, we only support file-based filters
10126 * in per-task events; doing so for CPU-wide
10127 * events requires additional context switching
10128 * trickery, since same object code will be
10129 * mapped at different virtual addresses in
10130 * different processes.
10133 if (!event->ctx->task)
10134 goto fail_free_name;
10136 /* look up the path and grab its inode */
10137 ret = kern_path(filename, LOOKUP_FOLLOW,
10140 goto fail_free_name;
10146 if (!filter->path.dentry ||
10147 !S_ISREG(d_inode(filter->path.dentry)
10151 event->addr_filters.nr_file_filters++;
10154 /* ready to consume more filters */
10155 state = IF_STATE_ACTION;
10160 if (state != IF_STATE_ACTION)
10170 free_filters_list(filters);
10177 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10179 LIST_HEAD(filters);
10183 * Since this is called in perf_ioctl() path, we're already holding
10186 lockdep_assert_held(&event->ctx->mutex);
10188 if (WARN_ON_ONCE(event->parent))
10191 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10193 goto fail_clear_files;
10195 ret = event->pmu->addr_filters_validate(&filters);
10197 goto fail_free_filters;
10199 /* remove existing filters, if any */
10200 perf_addr_filters_splice(event, &filters);
10202 /* install new filters */
10203 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10208 free_filters_list(&filters);
10211 event->addr_filters.nr_file_filters = 0;
10216 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10221 filter_str = strndup_user(arg, PAGE_SIZE);
10222 if (IS_ERR(filter_str))
10223 return PTR_ERR(filter_str);
10225 #ifdef CONFIG_EVENT_TRACING
10226 if (perf_event_is_tracing(event)) {
10227 struct perf_event_context *ctx = event->ctx;
10230 * Beware, here be dragons!!
10232 * the tracepoint muck will deadlock against ctx->mutex, but
10233 * the tracepoint stuff does not actually need it. So
10234 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10235 * already have a reference on ctx.
10237 * This can result in event getting moved to a different ctx,
10238 * but that does not affect the tracepoint state.
10240 mutex_unlock(&ctx->mutex);
10241 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10242 mutex_lock(&ctx->mutex);
10245 if (has_addr_filter(event))
10246 ret = perf_event_set_addr_filter(event, filter_str);
10253 * hrtimer based swevent callback
10256 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10258 enum hrtimer_restart ret = HRTIMER_RESTART;
10259 struct perf_sample_data data;
10260 struct pt_regs *regs;
10261 struct perf_event *event;
10264 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10266 if (event->state != PERF_EVENT_STATE_ACTIVE)
10267 return HRTIMER_NORESTART;
10269 event->pmu->read(event);
10271 perf_sample_data_init(&data, 0, event->hw.last_period);
10272 regs = get_irq_regs();
10274 if (regs && !perf_exclude_event(event, regs)) {
10275 if (!(event->attr.exclude_idle && is_idle_task(current)))
10276 if (__perf_event_overflow(event, 1, &data, regs))
10277 ret = HRTIMER_NORESTART;
10280 period = max_t(u64, 10000, event->hw.sample_period);
10281 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10286 static void perf_swevent_start_hrtimer(struct perf_event *event)
10288 struct hw_perf_event *hwc = &event->hw;
10291 if (!is_sampling_event(event))
10294 period = local64_read(&hwc->period_left);
10299 local64_set(&hwc->period_left, 0);
10301 period = max_t(u64, 10000, hwc->sample_period);
10303 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10304 HRTIMER_MODE_REL_PINNED_HARD);
10307 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10309 struct hw_perf_event *hwc = &event->hw;
10311 if (is_sampling_event(event)) {
10312 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10313 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10315 hrtimer_cancel(&hwc->hrtimer);
10319 static void perf_swevent_init_hrtimer(struct perf_event *event)
10321 struct hw_perf_event *hwc = &event->hw;
10323 if (!is_sampling_event(event))
10326 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10327 hwc->hrtimer.function = perf_swevent_hrtimer;
10330 * Since hrtimers have a fixed rate, we can do a static freq->period
10331 * mapping and avoid the whole period adjust feedback stuff.
10333 if (event->attr.freq) {
10334 long freq = event->attr.sample_freq;
10336 event->attr.sample_period = NSEC_PER_SEC / freq;
10337 hwc->sample_period = event->attr.sample_period;
10338 local64_set(&hwc->period_left, hwc->sample_period);
10339 hwc->last_period = hwc->sample_period;
10340 event->attr.freq = 0;
10345 * Software event: cpu wall time clock
10348 static void cpu_clock_event_update(struct perf_event *event)
10353 now = local_clock();
10354 prev = local64_xchg(&event->hw.prev_count, now);
10355 local64_add(now - prev, &event->count);
10358 static void cpu_clock_event_start(struct perf_event *event, int flags)
10360 local64_set(&event->hw.prev_count, local_clock());
10361 perf_swevent_start_hrtimer(event);
10364 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10366 perf_swevent_cancel_hrtimer(event);
10367 cpu_clock_event_update(event);
10370 static int cpu_clock_event_add(struct perf_event *event, int flags)
10372 if (flags & PERF_EF_START)
10373 cpu_clock_event_start(event, flags);
10374 perf_event_update_userpage(event);
10379 static void cpu_clock_event_del(struct perf_event *event, int flags)
10381 cpu_clock_event_stop(event, flags);
10384 static void cpu_clock_event_read(struct perf_event *event)
10386 cpu_clock_event_update(event);
10389 static int cpu_clock_event_init(struct perf_event *event)
10391 if (event->attr.type != PERF_TYPE_SOFTWARE)
10394 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10398 * no branch sampling for software events
10400 if (has_branch_stack(event))
10401 return -EOPNOTSUPP;
10403 perf_swevent_init_hrtimer(event);
10408 static struct pmu perf_cpu_clock = {
10409 .task_ctx_nr = perf_sw_context,
10411 .capabilities = PERF_PMU_CAP_NO_NMI,
10413 .event_init = cpu_clock_event_init,
10414 .add = cpu_clock_event_add,
10415 .del = cpu_clock_event_del,
10416 .start = cpu_clock_event_start,
10417 .stop = cpu_clock_event_stop,
10418 .read = cpu_clock_event_read,
10422 * Software event: task time clock
10425 static void task_clock_event_update(struct perf_event *event, u64 now)
10430 prev = local64_xchg(&event->hw.prev_count, now);
10431 delta = now - prev;
10432 local64_add(delta, &event->count);
10435 static void task_clock_event_start(struct perf_event *event, int flags)
10437 local64_set(&event->hw.prev_count, event->ctx->time);
10438 perf_swevent_start_hrtimer(event);
10441 static void task_clock_event_stop(struct perf_event *event, int flags)
10443 perf_swevent_cancel_hrtimer(event);
10444 task_clock_event_update(event, event->ctx->time);
10447 static int task_clock_event_add(struct perf_event *event, int flags)
10449 if (flags & PERF_EF_START)
10450 task_clock_event_start(event, flags);
10451 perf_event_update_userpage(event);
10456 static void task_clock_event_del(struct perf_event *event, int flags)
10458 task_clock_event_stop(event, PERF_EF_UPDATE);
10461 static void task_clock_event_read(struct perf_event *event)
10463 u64 now = perf_clock();
10464 u64 delta = now - event->ctx->timestamp;
10465 u64 time = event->ctx->time + delta;
10467 task_clock_event_update(event, time);
10470 static int task_clock_event_init(struct perf_event *event)
10472 if (event->attr.type != PERF_TYPE_SOFTWARE)
10475 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10479 * no branch sampling for software events
10481 if (has_branch_stack(event))
10482 return -EOPNOTSUPP;
10484 perf_swevent_init_hrtimer(event);
10489 static struct pmu perf_task_clock = {
10490 .task_ctx_nr = perf_sw_context,
10492 .capabilities = PERF_PMU_CAP_NO_NMI,
10494 .event_init = task_clock_event_init,
10495 .add = task_clock_event_add,
10496 .del = task_clock_event_del,
10497 .start = task_clock_event_start,
10498 .stop = task_clock_event_stop,
10499 .read = task_clock_event_read,
10502 static void perf_pmu_nop_void(struct pmu *pmu)
10506 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10510 static int perf_pmu_nop_int(struct pmu *pmu)
10515 static int perf_event_nop_int(struct perf_event *event, u64 value)
10520 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10522 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10524 __this_cpu_write(nop_txn_flags, flags);
10526 if (flags & ~PERF_PMU_TXN_ADD)
10529 perf_pmu_disable(pmu);
10532 static int perf_pmu_commit_txn(struct pmu *pmu)
10534 unsigned int flags = __this_cpu_read(nop_txn_flags);
10536 __this_cpu_write(nop_txn_flags, 0);
10538 if (flags & ~PERF_PMU_TXN_ADD)
10541 perf_pmu_enable(pmu);
10545 static void perf_pmu_cancel_txn(struct pmu *pmu)
10547 unsigned int flags = __this_cpu_read(nop_txn_flags);
10549 __this_cpu_write(nop_txn_flags, 0);
10551 if (flags & ~PERF_PMU_TXN_ADD)
10554 perf_pmu_enable(pmu);
10557 static int perf_event_idx_default(struct perf_event *event)
10563 * Ensures all contexts with the same task_ctx_nr have the same
10564 * pmu_cpu_context too.
10566 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10573 list_for_each_entry(pmu, &pmus, entry) {
10574 if (pmu->task_ctx_nr == ctxn)
10575 return pmu->pmu_cpu_context;
10581 static void free_pmu_context(struct pmu *pmu)
10584 * Static contexts such as perf_sw_context have a global lifetime
10585 * and may be shared between different PMUs. Avoid freeing them
10586 * when a single PMU is going away.
10588 if (pmu->task_ctx_nr > perf_invalid_context)
10591 free_percpu(pmu->pmu_cpu_context);
10595 * Let userspace know that this PMU supports address range filtering:
10597 static ssize_t nr_addr_filters_show(struct device *dev,
10598 struct device_attribute *attr,
10601 struct pmu *pmu = dev_get_drvdata(dev);
10603 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10605 DEVICE_ATTR_RO(nr_addr_filters);
10607 static struct idr pmu_idr;
10610 type_show(struct device *dev, struct device_attribute *attr, char *page)
10612 struct pmu *pmu = dev_get_drvdata(dev);
10614 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10616 static DEVICE_ATTR_RO(type);
10619 perf_event_mux_interval_ms_show(struct device *dev,
10620 struct device_attribute *attr,
10623 struct pmu *pmu = dev_get_drvdata(dev);
10625 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10628 static DEFINE_MUTEX(mux_interval_mutex);
10631 perf_event_mux_interval_ms_store(struct device *dev,
10632 struct device_attribute *attr,
10633 const char *buf, size_t count)
10635 struct pmu *pmu = dev_get_drvdata(dev);
10636 int timer, cpu, ret;
10638 ret = kstrtoint(buf, 0, &timer);
10645 /* same value, noting to do */
10646 if (timer == pmu->hrtimer_interval_ms)
10649 mutex_lock(&mux_interval_mutex);
10650 pmu->hrtimer_interval_ms = timer;
10652 /* update all cpuctx for this PMU */
10654 for_each_online_cpu(cpu) {
10655 struct perf_cpu_context *cpuctx;
10656 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10657 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10659 cpu_function_call(cpu,
10660 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10662 cpus_read_unlock();
10663 mutex_unlock(&mux_interval_mutex);
10667 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10669 static struct attribute *pmu_dev_attrs[] = {
10670 &dev_attr_type.attr,
10671 &dev_attr_perf_event_mux_interval_ms.attr,
10674 ATTRIBUTE_GROUPS(pmu_dev);
10676 static int pmu_bus_running;
10677 static struct bus_type pmu_bus = {
10678 .name = "event_source",
10679 .dev_groups = pmu_dev_groups,
10682 static void pmu_dev_release(struct device *dev)
10687 static int pmu_dev_alloc(struct pmu *pmu)
10691 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10695 pmu->dev->groups = pmu->attr_groups;
10696 device_initialize(pmu->dev);
10697 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10701 dev_set_drvdata(pmu->dev, pmu);
10702 pmu->dev->bus = &pmu_bus;
10703 pmu->dev->release = pmu_dev_release;
10704 ret = device_add(pmu->dev);
10708 /* For PMUs with address filters, throw in an extra attribute: */
10709 if (pmu->nr_addr_filters)
10710 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10715 if (pmu->attr_update)
10716 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10725 device_del(pmu->dev);
10728 put_device(pmu->dev);
10732 static struct lock_class_key cpuctx_mutex;
10733 static struct lock_class_key cpuctx_lock;
10735 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10737 int cpu, ret, max = PERF_TYPE_MAX;
10739 mutex_lock(&pmus_lock);
10741 pmu->pmu_disable_count = alloc_percpu(int);
10742 if (!pmu->pmu_disable_count)
10750 if (type != PERF_TYPE_SOFTWARE) {
10754 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10758 WARN_ON(type >= 0 && ret != type);
10764 if (pmu_bus_running) {
10765 ret = pmu_dev_alloc(pmu);
10771 if (pmu->task_ctx_nr == perf_hw_context) {
10772 static int hw_context_taken = 0;
10775 * Other than systems with heterogeneous CPUs, it never makes
10776 * sense for two PMUs to share perf_hw_context. PMUs which are
10777 * uncore must use perf_invalid_context.
10779 if (WARN_ON_ONCE(hw_context_taken &&
10780 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10781 pmu->task_ctx_nr = perf_invalid_context;
10783 hw_context_taken = 1;
10786 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10787 if (pmu->pmu_cpu_context)
10788 goto got_cpu_context;
10791 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10792 if (!pmu->pmu_cpu_context)
10795 for_each_possible_cpu(cpu) {
10796 struct perf_cpu_context *cpuctx;
10798 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10799 __perf_event_init_context(&cpuctx->ctx);
10800 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10801 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10802 cpuctx->ctx.pmu = pmu;
10803 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10805 __perf_mux_hrtimer_init(cpuctx, cpu);
10807 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10808 cpuctx->heap = cpuctx->heap_default;
10812 if (!pmu->start_txn) {
10813 if (pmu->pmu_enable) {
10815 * If we have pmu_enable/pmu_disable calls, install
10816 * transaction stubs that use that to try and batch
10817 * hardware accesses.
10819 pmu->start_txn = perf_pmu_start_txn;
10820 pmu->commit_txn = perf_pmu_commit_txn;
10821 pmu->cancel_txn = perf_pmu_cancel_txn;
10823 pmu->start_txn = perf_pmu_nop_txn;
10824 pmu->commit_txn = perf_pmu_nop_int;
10825 pmu->cancel_txn = perf_pmu_nop_void;
10829 if (!pmu->pmu_enable) {
10830 pmu->pmu_enable = perf_pmu_nop_void;
10831 pmu->pmu_disable = perf_pmu_nop_void;
10834 if (!pmu->check_period)
10835 pmu->check_period = perf_event_nop_int;
10837 if (!pmu->event_idx)
10838 pmu->event_idx = perf_event_idx_default;
10841 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10842 * since these cannot be in the IDR. This way the linear search
10843 * is fast, provided a valid software event is provided.
10845 if (type == PERF_TYPE_SOFTWARE || !name)
10846 list_add_rcu(&pmu->entry, &pmus);
10848 list_add_tail_rcu(&pmu->entry, &pmus);
10850 atomic_set(&pmu->exclusive_cnt, 0);
10853 mutex_unlock(&pmus_lock);
10858 device_del(pmu->dev);
10859 put_device(pmu->dev);
10862 if (pmu->type != PERF_TYPE_SOFTWARE)
10863 idr_remove(&pmu_idr, pmu->type);
10866 free_percpu(pmu->pmu_disable_count);
10869 EXPORT_SYMBOL_GPL(perf_pmu_register);
10871 void perf_pmu_unregister(struct pmu *pmu)
10873 mutex_lock(&pmus_lock);
10874 list_del_rcu(&pmu->entry);
10877 * We dereference the pmu list under both SRCU and regular RCU, so
10878 * synchronize against both of those.
10880 synchronize_srcu(&pmus_srcu);
10883 free_percpu(pmu->pmu_disable_count);
10884 if (pmu->type != PERF_TYPE_SOFTWARE)
10885 idr_remove(&pmu_idr, pmu->type);
10886 if (pmu_bus_running) {
10887 if (pmu->nr_addr_filters)
10888 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10889 device_del(pmu->dev);
10890 put_device(pmu->dev);
10892 free_pmu_context(pmu);
10893 mutex_unlock(&pmus_lock);
10895 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10897 static inline bool has_extended_regs(struct perf_event *event)
10899 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10900 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10903 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10905 struct perf_event_context *ctx = NULL;
10908 if (!try_module_get(pmu->module))
10912 * A number of pmu->event_init() methods iterate the sibling_list to,
10913 * for example, validate if the group fits on the PMU. Therefore,
10914 * if this is a sibling event, acquire the ctx->mutex to protect
10915 * the sibling_list.
10917 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10919 * This ctx->mutex can nest when we're called through
10920 * inheritance. See the perf_event_ctx_lock_nested() comment.
10922 ctx = perf_event_ctx_lock_nested(event->group_leader,
10923 SINGLE_DEPTH_NESTING);
10928 ret = pmu->event_init(event);
10931 perf_event_ctx_unlock(event->group_leader, ctx);
10934 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10935 has_extended_regs(event))
10938 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10939 event_has_any_exclude_flag(event))
10942 if (ret && event->destroy)
10943 event->destroy(event);
10947 module_put(pmu->module);
10952 static struct pmu *perf_init_event(struct perf_event *event)
10954 int idx, type, ret;
10957 idx = srcu_read_lock(&pmus_srcu);
10959 /* Try parent's PMU first: */
10960 if (event->parent && event->parent->pmu) {
10961 pmu = event->parent->pmu;
10962 ret = perf_try_init_event(pmu, event);
10968 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
10969 * are often aliases for PERF_TYPE_RAW.
10971 type = event->attr.type;
10972 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
10973 type = PERF_TYPE_RAW;
10977 pmu = idr_find(&pmu_idr, type);
10980 ret = perf_try_init_event(pmu, event);
10981 if (ret == -ENOENT && event->attr.type != type) {
10982 type = event->attr.type;
10987 pmu = ERR_PTR(ret);
10992 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
10993 ret = perf_try_init_event(pmu, event);
10997 if (ret != -ENOENT) {
10998 pmu = ERR_PTR(ret);
11002 pmu = ERR_PTR(-ENOENT);
11004 srcu_read_unlock(&pmus_srcu, idx);
11009 static void attach_sb_event(struct perf_event *event)
11011 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11013 raw_spin_lock(&pel->lock);
11014 list_add_rcu(&event->sb_list, &pel->list);
11015 raw_spin_unlock(&pel->lock);
11019 * We keep a list of all !task (and therefore per-cpu) events
11020 * that need to receive side-band records.
11022 * This avoids having to scan all the various PMU per-cpu contexts
11023 * looking for them.
11025 static void account_pmu_sb_event(struct perf_event *event)
11027 if (is_sb_event(event))
11028 attach_sb_event(event);
11031 static void account_event_cpu(struct perf_event *event, int cpu)
11036 if (is_cgroup_event(event))
11037 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11040 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11041 static void account_freq_event_nohz(void)
11043 #ifdef CONFIG_NO_HZ_FULL
11044 /* Lock so we don't race with concurrent unaccount */
11045 spin_lock(&nr_freq_lock);
11046 if (atomic_inc_return(&nr_freq_events) == 1)
11047 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11048 spin_unlock(&nr_freq_lock);
11052 static void account_freq_event(void)
11054 if (tick_nohz_full_enabled())
11055 account_freq_event_nohz();
11057 atomic_inc(&nr_freq_events);
11061 static void account_event(struct perf_event *event)
11068 if (event->attach_state & PERF_ATTACH_TASK)
11070 if (event->attr.mmap || event->attr.mmap_data)
11071 atomic_inc(&nr_mmap_events);
11072 if (event->attr.comm)
11073 atomic_inc(&nr_comm_events);
11074 if (event->attr.namespaces)
11075 atomic_inc(&nr_namespaces_events);
11076 if (event->attr.cgroup)
11077 atomic_inc(&nr_cgroup_events);
11078 if (event->attr.task)
11079 atomic_inc(&nr_task_events);
11080 if (event->attr.freq)
11081 account_freq_event();
11082 if (event->attr.context_switch) {
11083 atomic_inc(&nr_switch_events);
11086 if (has_branch_stack(event))
11088 if (is_cgroup_event(event))
11090 if (event->attr.ksymbol)
11091 atomic_inc(&nr_ksymbol_events);
11092 if (event->attr.bpf_event)
11093 atomic_inc(&nr_bpf_events);
11094 if (event->attr.text_poke)
11095 atomic_inc(&nr_text_poke_events);
11099 * We need the mutex here because static_branch_enable()
11100 * must complete *before* the perf_sched_count increment
11103 if (atomic_inc_not_zero(&perf_sched_count))
11106 mutex_lock(&perf_sched_mutex);
11107 if (!atomic_read(&perf_sched_count)) {
11108 static_branch_enable(&perf_sched_events);
11110 * Guarantee that all CPUs observe they key change and
11111 * call the perf scheduling hooks before proceeding to
11112 * install events that need them.
11117 * Now that we have waited for the sync_sched(), allow further
11118 * increments to by-pass the mutex.
11120 atomic_inc(&perf_sched_count);
11121 mutex_unlock(&perf_sched_mutex);
11125 account_event_cpu(event, event->cpu);
11127 account_pmu_sb_event(event);
11131 * Allocate and initialize an event structure
11133 static struct perf_event *
11134 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11135 struct task_struct *task,
11136 struct perf_event *group_leader,
11137 struct perf_event *parent_event,
11138 perf_overflow_handler_t overflow_handler,
11139 void *context, int cgroup_fd)
11142 struct perf_event *event;
11143 struct hw_perf_event *hwc;
11144 long err = -EINVAL;
11146 if ((unsigned)cpu >= nr_cpu_ids) {
11147 if (!task || cpu != -1)
11148 return ERR_PTR(-EINVAL);
11151 event = kzalloc(sizeof(*event), GFP_KERNEL);
11153 return ERR_PTR(-ENOMEM);
11156 * Single events are their own group leaders, with an
11157 * empty sibling list:
11160 group_leader = event;
11162 mutex_init(&event->child_mutex);
11163 INIT_LIST_HEAD(&event->child_list);
11165 INIT_LIST_HEAD(&event->event_entry);
11166 INIT_LIST_HEAD(&event->sibling_list);
11167 INIT_LIST_HEAD(&event->active_list);
11168 init_event_group(event);
11169 INIT_LIST_HEAD(&event->rb_entry);
11170 INIT_LIST_HEAD(&event->active_entry);
11171 INIT_LIST_HEAD(&event->addr_filters.list);
11172 INIT_HLIST_NODE(&event->hlist_entry);
11175 init_waitqueue_head(&event->waitq);
11176 event->pending_disable = -1;
11177 init_irq_work(&event->pending, perf_pending_event);
11179 mutex_init(&event->mmap_mutex);
11180 raw_spin_lock_init(&event->addr_filters.lock);
11182 atomic_long_set(&event->refcount, 1);
11184 event->attr = *attr;
11185 event->group_leader = group_leader;
11189 event->parent = parent_event;
11191 event->ns = get_pid_ns(task_active_pid_ns(current));
11192 event->id = atomic64_inc_return(&perf_event_id);
11194 event->state = PERF_EVENT_STATE_INACTIVE;
11197 event->attach_state = PERF_ATTACH_TASK;
11199 * XXX pmu::event_init needs to know what task to account to
11200 * and we cannot use the ctx information because we need the
11201 * pmu before we get a ctx.
11203 event->hw.target = get_task_struct(task);
11206 event->clock = &local_clock;
11208 event->clock = parent_event->clock;
11210 if (!overflow_handler && parent_event) {
11211 overflow_handler = parent_event->overflow_handler;
11212 context = parent_event->overflow_handler_context;
11213 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11214 if (overflow_handler == bpf_overflow_handler) {
11215 struct bpf_prog *prog = parent_event->prog;
11217 bpf_prog_inc(prog);
11218 event->prog = prog;
11219 event->orig_overflow_handler =
11220 parent_event->orig_overflow_handler;
11225 if (overflow_handler) {
11226 event->overflow_handler = overflow_handler;
11227 event->overflow_handler_context = context;
11228 } else if (is_write_backward(event)){
11229 event->overflow_handler = perf_event_output_backward;
11230 event->overflow_handler_context = NULL;
11232 event->overflow_handler = perf_event_output_forward;
11233 event->overflow_handler_context = NULL;
11236 perf_event__state_init(event);
11241 hwc->sample_period = attr->sample_period;
11242 if (attr->freq && attr->sample_freq)
11243 hwc->sample_period = 1;
11244 hwc->last_period = hwc->sample_period;
11246 local64_set(&hwc->period_left, hwc->sample_period);
11249 * We currently do not support PERF_SAMPLE_READ on inherited events.
11250 * See perf_output_read().
11252 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11255 if (!has_branch_stack(event))
11256 event->attr.branch_sample_type = 0;
11258 pmu = perf_init_event(event);
11260 err = PTR_ERR(pmu);
11265 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11266 * be different on other CPUs in the uncore mask.
11268 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11273 if (event->attr.aux_output &&
11274 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11279 if (cgroup_fd != -1) {
11280 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11285 err = exclusive_event_init(event);
11289 if (has_addr_filter(event)) {
11290 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11291 sizeof(struct perf_addr_filter_range),
11293 if (!event->addr_filter_ranges) {
11299 * Clone the parent's vma offsets: they are valid until exec()
11300 * even if the mm is not shared with the parent.
11302 if (event->parent) {
11303 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11305 raw_spin_lock_irq(&ifh->lock);
11306 memcpy(event->addr_filter_ranges,
11307 event->parent->addr_filter_ranges,
11308 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11309 raw_spin_unlock_irq(&ifh->lock);
11312 /* force hw sync on the address filters */
11313 event->addr_filters_gen = 1;
11316 if (!event->parent) {
11317 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11318 err = get_callchain_buffers(attr->sample_max_stack);
11320 goto err_addr_filters;
11324 err = security_perf_event_alloc(event);
11326 goto err_callchain_buffer;
11328 /* symmetric to unaccount_event() in _free_event() */
11329 account_event(event);
11333 err_callchain_buffer:
11334 if (!event->parent) {
11335 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11336 put_callchain_buffers();
11339 kfree(event->addr_filter_ranges);
11342 exclusive_event_destroy(event);
11345 if (is_cgroup_event(event))
11346 perf_detach_cgroup(event);
11347 if (event->destroy)
11348 event->destroy(event);
11349 module_put(pmu->module);
11352 put_pid_ns(event->ns);
11353 if (event->hw.target)
11354 put_task_struct(event->hw.target);
11357 return ERR_PTR(err);
11360 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11361 struct perf_event_attr *attr)
11366 /* Zero the full structure, so that a short copy will be nice. */
11367 memset(attr, 0, sizeof(*attr));
11369 ret = get_user(size, &uattr->size);
11373 /* ABI compatibility quirk: */
11375 size = PERF_ATTR_SIZE_VER0;
11376 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11379 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11388 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11391 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11394 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11397 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11398 u64 mask = attr->branch_sample_type;
11400 /* only using defined bits */
11401 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11404 /* at least one branch bit must be set */
11405 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11408 /* propagate priv level, when not set for branch */
11409 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11411 /* exclude_kernel checked on syscall entry */
11412 if (!attr->exclude_kernel)
11413 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11415 if (!attr->exclude_user)
11416 mask |= PERF_SAMPLE_BRANCH_USER;
11418 if (!attr->exclude_hv)
11419 mask |= PERF_SAMPLE_BRANCH_HV;
11421 * adjust user setting (for HW filter setup)
11423 attr->branch_sample_type = mask;
11425 /* privileged levels capture (kernel, hv): check permissions */
11426 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11427 ret = perf_allow_kernel(attr);
11433 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11434 ret = perf_reg_validate(attr->sample_regs_user);
11439 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11440 if (!arch_perf_have_user_stack_dump())
11444 * We have __u32 type for the size, but so far
11445 * we can only use __u16 as maximum due to the
11446 * __u16 sample size limit.
11448 if (attr->sample_stack_user >= USHRT_MAX)
11450 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11454 if (!attr->sample_max_stack)
11455 attr->sample_max_stack = sysctl_perf_event_max_stack;
11457 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11458 ret = perf_reg_validate(attr->sample_regs_intr);
11460 #ifndef CONFIG_CGROUP_PERF
11461 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11469 put_user(sizeof(*attr), &uattr->size);
11475 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11477 struct perf_buffer *rb = NULL;
11483 /* don't allow circular references */
11484 if (event == output_event)
11488 * Don't allow cross-cpu buffers
11490 if (output_event->cpu != event->cpu)
11494 * If its not a per-cpu rb, it must be the same task.
11496 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11500 * Mixing clocks in the same buffer is trouble you don't need.
11502 if (output_event->clock != event->clock)
11506 * Either writing ring buffer from beginning or from end.
11507 * Mixing is not allowed.
11509 if (is_write_backward(output_event) != is_write_backward(event))
11513 * If both events generate aux data, they must be on the same PMU
11515 if (has_aux(event) && has_aux(output_event) &&
11516 event->pmu != output_event->pmu)
11520 mutex_lock(&event->mmap_mutex);
11521 /* Can't redirect output if we've got an active mmap() */
11522 if (atomic_read(&event->mmap_count))
11525 if (output_event) {
11526 /* get the rb we want to redirect to */
11527 rb = ring_buffer_get(output_event);
11532 ring_buffer_attach(event, rb);
11536 mutex_unlock(&event->mmap_mutex);
11542 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11548 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11551 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11553 bool nmi_safe = false;
11556 case CLOCK_MONOTONIC:
11557 event->clock = &ktime_get_mono_fast_ns;
11561 case CLOCK_MONOTONIC_RAW:
11562 event->clock = &ktime_get_raw_fast_ns;
11566 case CLOCK_REALTIME:
11567 event->clock = &ktime_get_real_ns;
11570 case CLOCK_BOOTTIME:
11571 event->clock = &ktime_get_boottime_ns;
11575 event->clock = &ktime_get_clocktai_ns;
11582 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11589 * Variation on perf_event_ctx_lock_nested(), except we take two context
11592 static struct perf_event_context *
11593 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11594 struct perf_event_context *ctx)
11596 struct perf_event_context *gctx;
11600 gctx = READ_ONCE(group_leader->ctx);
11601 if (!refcount_inc_not_zero(&gctx->refcount)) {
11607 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11609 if (group_leader->ctx != gctx) {
11610 mutex_unlock(&ctx->mutex);
11611 mutex_unlock(&gctx->mutex);
11620 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11622 * @attr_uptr: event_id type attributes for monitoring/sampling
11625 * @group_fd: group leader event fd
11627 SYSCALL_DEFINE5(perf_event_open,
11628 struct perf_event_attr __user *, attr_uptr,
11629 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11631 struct perf_event *group_leader = NULL, *output_event = NULL;
11632 struct perf_event *event, *sibling;
11633 struct perf_event_attr attr;
11634 struct perf_event_context *ctx, *gctx;
11635 struct file *event_file = NULL;
11636 struct fd group = {NULL, 0};
11637 struct task_struct *task = NULL;
11640 int move_group = 0;
11642 int f_flags = O_RDWR;
11643 int cgroup_fd = -1;
11645 /* for future expandability... */
11646 if (flags & ~PERF_FLAG_ALL)
11649 /* Do we allow access to perf_event_open(2) ? */
11650 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11654 err = perf_copy_attr(attr_uptr, &attr);
11658 if (!attr.exclude_kernel) {
11659 err = perf_allow_kernel(&attr);
11664 if (attr.namespaces) {
11665 if (!perfmon_capable())
11670 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11673 if (attr.sample_period & (1ULL << 63))
11677 /* Only privileged users can get physical addresses */
11678 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11679 err = perf_allow_kernel(&attr);
11684 err = security_locked_down(LOCKDOWN_PERF);
11685 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11686 /* REGS_INTR can leak data, lockdown must prevent this */
11692 * In cgroup mode, the pid argument is used to pass the fd
11693 * opened to the cgroup directory in cgroupfs. The cpu argument
11694 * designates the cpu on which to monitor threads from that
11697 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11700 if (flags & PERF_FLAG_FD_CLOEXEC)
11701 f_flags |= O_CLOEXEC;
11703 event_fd = get_unused_fd_flags(f_flags);
11707 if (group_fd != -1) {
11708 err = perf_fget_light(group_fd, &group);
11711 group_leader = group.file->private_data;
11712 if (flags & PERF_FLAG_FD_OUTPUT)
11713 output_event = group_leader;
11714 if (flags & PERF_FLAG_FD_NO_GROUP)
11715 group_leader = NULL;
11718 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11719 task = find_lively_task_by_vpid(pid);
11720 if (IS_ERR(task)) {
11721 err = PTR_ERR(task);
11726 if (task && group_leader &&
11727 group_leader->attr.inherit != attr.inherit) {
11733 err = mutex_lock_interruptible(&task->signal->exec_update_mutex);
11738 * Preserve ptrace permission check for backwards compatibility.
11740 * We must hold exec_update_mutex across this and any potential
11741 * perf_install_in_context() call for this new event to
11742 * serialize against exec() altering our credentials (and the
11743 * perf_event_exit_task() that could imply).
11746 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11750 if (flags & PERF_FLAG_PID_CGROUP)
11753 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11754 NULL, NULL, cgroup_fd);
11755 if (IS_ERR(event)) {
11756 err = PTR_ERR(event);
11760 if (is_sampling_event(event)) {
11761 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11768 * Special case software events and allow them to be part of
11769 * any hardware group.
11773 if (attr.use_clockid) {
11774 err = perf_event_set_clock(event, attr.clockid);
11779 if (pmu->task_ctx_nr == perf_sw_context)
11780 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11782 if (group_leader) {
11783 if (is_software_event(event) &&
11784 !in_software_context(group_leader)) {
11786 * If the event is a sw event, but the group_leader
11787 * is on hw context.
11789 * Allow the addition of software events to hw
11790 * groups, this is safe because software events
11791 * never fail to schedule.
11793 pmu = group_leader->ctx->pmu;
11794 } else if (!is_software_event(event) &&
11795 is_software_event(group_leader) &&
11796 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11798 * In case the group is a pure software group, and we
11799 * try to add a hardware event, move the whole group to
11800 * the hardware context.
11807 * Get the target context (task or percpu):
11809 ctx = find_get_context(pmu, task, event);
11811 err = PTR_ERR(ctx);
11816 * Look up the group leader (we will attach this event to it):
11818 if (group_leader) {
11822 * Do not allow a recursive hierarchy (this new sibling
11823 * becoming part of another group-sibling):
11825 if (group_leader->group_leader != group_leader)
11828 /* All events in a group should have the same clock */
11829 if (group_leader->clock != event->clock)
11833 * Make sure we're both events for the same CPU;
11834 * grouping events for different CPUs is broken; since
11835 * you can never concurrently schedule them anyhow.
11837 if (group_leader->cpu != event->cpu)
11841 * Make sure we're both on the same task, or both
11844 if (group_leader->ctx->task != ctx->task)
11848 * Do not allow to attach to a group in a different task
11849 * or CPU context. If we're moving SW events, we'll fix
11850 * this up later, so allow that.
11852 if (!move_group && group_leader->ctx != ctx)
11856 * Only a group leader can be exclusive or pinned
11858 if (attr.exclusive || attr.pinned)
11862 if (output_event) {
11863 err = perf_event_set_output(event, output_event);
11868 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11870 if (IS_ERR(event_file)) {
11871 err = PTR_ERR(event_file);
11877 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11879 if (gctx->task == TASK_TOMBSTONE) {
11885 * Check if we raced against another sys_perf_event_open() call
11886 * moving the software group underneath us.
11888 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11890 * If someone moved the group out from under us, check
11891 * if this new event wound up on the same ctx, if so
11892 * its the regular !move_group case, otherwise fail.
11898 perf_event_ctx_unlock(group_leader, gctx);
11904 * Failure to create exclusive events returns -EBUSY.
11907 if (!exclusive_event_installable(group_leader, ctx))
11910 for_each_sibling_event(sibling, group_leader) {
11911 if (!exclusive_event_installable(sibling, ctx))
11915 mutex_lock(&ctx->mutex);
11918 if (ctx->task == TASK_TOMBSTONE) {
11923 if (!perf_event_validate_size(event)) {
11930 * Check if the @cpu we're creating an event for is online.
11932 * We use the perf_cpu_context::ctx::mutex to serialize against
11933 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11935 struct perf_cpu_context *cpuctx =
11936 container_of(ctx, struct perf_cpu_context, ctx);
11938 if (!cpuctx->online) {
11944 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
11950 * Must be under the same ctx::mutex as perf_install_in_context(),
11951 * because we need to serialize with concurrent event creation.
11953 if (!exclusive_event_installable(event, ctx)) {
11958 WARN_ON_ONCE(ctx->parent_ctx);
11961 * This is the point on no return; we cannot fail hereafter. This is
11962 * where we start modifying current state.
11967 * See perf_event_ctx_lock() for comments on the details
11968 * of swizzling perf_event::ctx.
11970 perf_remove_from_context(group_leader, 0);
11973 for_each_sibling_event(sibling, group_leader) {
11974 perf_remove_from_context(sibling, 0);
11979 * Wait for everybody to stop referencing the events through
11980 * the old lists, before installing it on new lists.
11985 * Install the group siblings before the group leader.
11987 * Because a group leader will try and install the entire group
11988 * (through the sibling list, which is still in-tact), we can
11989 * end up with siblings installed in the wrong context.
11991 * By installing siblings first we NO-OP because they're not
11992 * reachable through the group lists.
11994 for_each_sibling_event(sibling, group_leader) {
11995 perf_event__state_init(sibling);
11996 perf_install_in_context(ctx, sibling, sibling->cpu);
12001 * Removing from the context ends up with disabled
12002 * event. What we want here is event in the initial
12003 * startup state, ready to be add into new context.
12005 perf_event__state_init(group_leader);
12006 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12011 * Precalculate sample_data sizes; do while holding ctx::mutex such
12012 * that we're serialized against further additions and before
12013 * perf_install_in_context() which is the point the event is active and
12014 * can use these values.
12016 perf_event__header_size(event);
12017 perf_event__id_header_size(event);
12019 event->owner = current;
12021 perf_install_in_context(ctx, event, event->cpu);
12022 perf_unpin_context(ctx);
12025 perf_event_ctx_unlock(group_leader, gctx);
12026 mutex_unlock(&ctx->mutex);
12029 mutex_unlock(&task->signal->exec_update_mutex);
12030 put_task_struct(task);
12033 mutex_lock(¤t->perf_event_mutex);
12034 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12035 mutex_unlock(¤t->perf_event_mutex);
12038 * Drop the reference on the group_event after placing the
12039 * new event on the sibling_list. This ensures destruction
12040 * of the group leader will find the pointer to itself in
12041 * perf_group_detach().
12044 fd_install(event_fd, event_file);
12049 perf_event_ctx_unlock(group_leader, gctx);
12050 mutex_unlock(&ctx->mutex);
12054 perf_unpin_context(ctx);
12058 * If event_file is set, the fput() above will have called ->release()
12059 * and that will take care of freeing the event.
12065 mutex_unlock(&task->signal->exec_update_mutex);
12068 put_task_struct(task);
12072 put_unused_fd(event_fd);
12077 * perf_event_create_kernel_counter
12079 * @attr: attributes of the counter to create
12080 * @cpu: cpu in which the counter is bound
12081 * @task: task to profile (NULL for percpu)
12083 struct perf_event *
12084 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12085 struct task_struct *task,
12086 perf_overflow_handler_t overflow_handler,
12089 struct perf_event_context *ctx;
12090 struct perf_event *event;
12094 * Grouping is not supported for kernel events, neither is 'AUX',
12095 * make sure the caller's intentions are adjusted.
12097 if (attr->aux_output)
12098 return ERR_PTR(-EINVAL);
12100 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12101 overflow_handler, context, -1);
12102 if (IS_ERR(event)) {
12103 err = PTR_ERR(event);
12107 /* Mark owner so we could distinguish it from user events. */
12108 event->owner = TASK_TOMBSTONE;
12111 * Get the target context (task or percpu):
12113 ctx = find_get_context(event->pmu, task, event);
12115 err = PTR_ERR(ctx);
12119 WARN_ON_ONCE(ctx->parent_ctx);
12120 mutex_lock(&ctx->mutex);
12121 if (ctx->task == TASK_TOMBSTONE) {
12128 * Check if the @cpu we're creating an event for is online.
12130 * We use the perf_cpu_context::ctx::mutex to serialize against
12131 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12133 struct perf_cpu_context *cpuctx =
12134 container_of(ctx, struct perf_cpu_context, ctx);
12135 if (!cpuctx->online) {
12141 if (!exclusive_event_installable(event, ctx)) {
12146 perf_install_in_context(ctx, event, event->cpu);
12147 perf_unpin_context(ctx);
12148 mutex_unlock(&ctx->mutex);
12153 mutex_unlock(&ctx->mutex);
12154 perf_unpin_context(ctx);
12159 return ERR_PTR(err);
12161 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12163 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12165 struct perf_event_context *src_ctx;
12166 struct perf_event_context *dst_ctx;
12167 struct perf_event *event, *tmp;
12170 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12171 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12174 * See perf_event_ctx_lock() for comments on the details
12175 * of swizzling perf_event::ctx.
12177 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12178 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12180 perf_remove_from_context(event, 0);
12181 unaccount_event_cpu(event, src_cpu);
12183 list_add(&event->migrate_entry, &events);
12187 * Wait for the events to quiesce before re-instating them.
12192 * Re-instate events in 2 passes.
12194 * Skip over group leaders and only install siblings on this first
12195 * pass, siblings will not get enabled without a leader, however a
12196 * leader will enable its siblings, even if those are still on the old
12199 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12200 if (event->group_leader == event)
12203 list_del(&event->migrate_entry);
12204 if (event->state >= PERF_EVENT_STATE_OFF)
12205 event->state = PERF_EVENT_STATE_INACTIVE;
12206 account_event_cpu(event, dst_cpu);
12207 perf_install_in_context(dst_ctx, event, dst_cpu);
12212 * Once all the siblings are setup properly, install the group leaders
12215 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12216 list_del(&event->migrate_entry);
12217 if (event->state >= PERF_EVENT_STATE_OFF)
12218 event->state = PERF_EVENT_STATE_INACTIVE;
12219 account_event_cpu(event, dst_cpu);
12220 perf_install_in_context(dst_ctx, event, dst_cpu);
12223 mutex_unlock(&dst_ctx->mutex);
12224 mutex_unlock(&src_ctx->mutex);
12226 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12228 static void sync_child_event(struct perf_event *child_event,
12229 struct task_struct *child)
12231 struct perf_event *parent_event = child_event->parent;
12234 if (child_event->attr.inherit_stat)
12235 perf_event_read_event(child_event, child);
12237 child_val = perf_event_count(child_event);
12240 * Add back the child's count to the parent's count:
12242 atomic64_add(child_val, &parent_event->child_count);
12243 atomic64_add(child_event->total_time_enabled,
12244 &parent_event->child_total_time_enabled);
12245 atomic64_add(child_event->total_time_running,
12246 &parent_event->child_total_time_running);
12250 perf_event_exit_event(struct perf_event *child_event,
12251 struct perf_event_context *child_ctx,
12252 struct task_struct *child)
12254 struct perf_event *parent_event = child_event->parent;
12257 * Do not destroy the 'original' grouping; because of the context
12258 * switch optimization the original events could've ended up in a
12259 * random child task.
12261 * If we were to destroy the original group, all group related
12262 * operations would cease to function properly after this random
12265 * Do destroy all inherited groups, we don't care about those
12266 * and being thorough is better.
12268 raw_spin_lock_irq(&child_ctx->lock);
12269 WARN_ON_ONCE(child_ctx->is_active);
12272 perf_group_detach(child_event);
12273 list_del_event(child_event, child_ctx);
12274 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12275 raw_spin_unlock_irq(&child_ctx->lock);
12278 * Parent events are governed by their filedesc, retain them.
12280 if (!parent_event) {
12281 perf_event_wakeup(child_event);
12285 * Child events can be cleaned up.
12288 sync_child_event(child_event, child);
12291 * Remove this event from the parent's list
12293 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12294 mutex_lock(&parent_event->child_mutex);
12295 list_del_init(&child_event->child_list);
12296 mutex_unlock(&parent_event->child_mutex);
12299 * Kick perf_poll() for is_event_hup().
12301 perf_event_wakeup(parent_event);
12302 free_event(child_event);
12303 put_event(parent_event);
12306 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12308 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12309 struct perf_event *child_event, *next;
12311 WARN_ON_ONCE(child != current);
12313 child_ctx = perf_pin_task_context(child, ctxn);
12318 * In order to reduce the amount of tricky in ctx tear-down, we hold
12319 * ctx::mutex over the entire thing. This serializes against almost
12320 * everything that wants to access the ctx.
12322 * The exception is sys_perf_event_open() /
12323 * perf_event_create_kernel_count() which does find_get_context()
12324 * without ctx::mutex (it cannot because of the move_group double mutex
12325 * lock thing). See the comments in perf_install_in_context().
12327 mutex_lock(&child_ctx->mutex);
12330 * In a single ctx::lock section, de-schedule the events and detach the
12331 * context from the task such that we cannot ever get it scheduled back
12334 raw_spin_lock_irq(&child_ctx->lock);
12335 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12338 * Now that the context is inactive, destroy the task <-> ctx relation
12339 * and mark the context dead.
12341 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12342 put_ctx(child_ctx); /* cannot be last */
12343 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12344 put_task_struct(current); /* cannot be last */
12346 clone_ctx = unclone_ctx(child_ctx);
12347 raw_spin_unlock_irq(&child_ctx->lock);
12350 put_ctx(clone_ctx);
12353 * Report the task dead after unscheduling the events so that we
12354 * won't get any samples after PERF_RECORD_EXIT. We can however still
12355 * get a few PERF_RECORD_READ events.
12357 perf_event_task(child, child_ctx, 0);
12359 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12360 perf_event_exit_event(child_event, child_ctx, child);
12362 mutex_unlock(&child_ctx->mutex);
12364 put_ctx(child_ctx);
12368 * When a child task exits, feed back event values to parent events.
12370 * Can be called with exec_update_mutex held when called from
12371 * setup_new_exec().
12373 void perf_event_exit_task(struct task_struct *child)
12375 struct perf_event *event, *tmp;
12378 mutex_lock(&child->perf_event_mutex);
12379 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12381 list_del_init(&event->owner_entry);
12384 * Ensure the list deletion is visible before we clear
12385 * the owner, closes a race against perf_release() where
12386 * we need to serialize on the owner->perf_event_mutex.
12388 smp_store_release(&event->owner, NULL);
12390 mutex_unlock(&child->perf_event_mutex);
12392 for_each_task_context_nr(ctxn)
12393 perf_event_exit_task_context(child, ctxn);
12396 * The perf_event_exit_task_context calls perf_event_task
12397 * with child's task_ctx, which generates EXIT events for
12398 * child contexts and sets child->perf_event_ctxp[] to NULL.
12399 * At this point we need to send EXIT events to cpu contexts.
12401 perf_event_task(child, NULL, 0);
12404 static void perf_free_event(struct perf_event *event,
12405 struct perf_event_context *ctx)
12407 struct perf_event *parent = event->parent;
12409 if (WARN_ON_ONCE(!parent))
12412 mutex_lock(&parent->child_mutex);
12413 list_del_init(&event->child_list);
12414 mutex_unlock(&parent->child_mutex);
12418 raw_spin_lock_irq(&ctx->lock);
12419 perf_group_detach(event);
12420 list_del_event(event, ctx);
12421 raw_spin_unlock_irq(&ctx->lock);
12426 * Free a context as created by inheritance by perf_event_init_task() below,
12427 * used by fork() in case of fail.
12429 * Even though the task has never lived, the context and events have been
12430 * exposed through the child_list, so we must take care tearing it all down.
12432 void perf_event_free_task(struct task_struct *task)
12434 struct perf_event_context *ctx;
12435 struct perf_event *event, *tmp;
12438 for_each_task_context_nr(ctxn) {
12439 ctx = task->perf_event_ctxp[ctxn];
12443 mutex_lock(&ctx->mutex);
12444 raw_spin_lock_irq(&ctx->lock);
12446 * Destroy the task <-> ctx relation and mark the context dead.
12448 * This is important because even though the task hasn't been
12449 * exposed yet the context has been (through child_list).
12451 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12452 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12453 put_task_struct(task); /* cannot be last */
12454 raw_spin_unlock_irq(&ctx->lock);
12456 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12457 perf_free_event(event, ctx);
12459 mutex_unlock(&ctx->mutex);
12462 * perf_event_release_kernel() could've stolen some of our
12463 * child events and still have them on its free_list. In that
12464 * case we must wait for these events to have been freed (in
12465 * particular all their references to this task must've been
12468 * Without this copy_process() will unconditionally free this
12469 * task (irrespective of its reference count) and
12470 * _free_event()'s put_task_struct(event->hw.target) will be a
12473 * Wait for all events to drop their context reference.
12475 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12476 put_ctx(ctx); /* must be last */
12480 void perf_event_delayed_put(struct task_struct *task)
12484 for_each_task_context_nr(ctxn)
12485 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12488 struct file *perf_event_get(unsigned int fd)
12490 struct file *file = fget(fd);
12492 return ERR_PTR(-EBADF);
12494 if (file->f_op != &perf_fops) {
12496 return ERR_PTR(-EBADF);
12502 const struct perf_event *perf_get_event(struct file *file)
12504 if (file->f_op != &perf_fops)
12505 return ERR_PTR(-EINVAL);
12507 return file->private_data;
12510 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12513 return ERR_PTR(-EINVAL);
12515 return &event->attr;
12519 * Inherit an event from parent task to child task.
12522 * - valid pointer on success
12523 * - NULL for orphaned events
12524 * - IS_ERR() on error
12526 static struct perf_event *
12527 inherit_event(struct perf_event *parent_event,
12528 struct task_struct *parent,
12529 struct perf_event_context *parent_ctx,
12530 struct task_struct *child,
12531 struct perf_event *group_leader,
12532 struct perf_event_context *child_ctx)
12534 enum perf_event_state parent_state = parent_event->state;
12535 struct perf_event *child_event;
12536 unsigned long flags;
12539 * Instead of creating recursive hierarchies of events,
12540 * we link inherited events back to the original parent,
12541 * which has a filp for sure, which we use as the reference
12544 if (parent_event->parent)
12545 parent_event = parent_event->parent;
12547 child_event = perf_event_alloc(&parent_event->attr,
12550 group_leader, parent_event,
12552 if (IS_ERR(child_event))
12553 return child_event;
12556 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12557 !child_ctx->task_ctx_data) {
12558 struct pmu *pmu = child_event->pmu;
12560 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12561 if (!child_ctx->task_ctx_data) {
12562 free_event(child_event);
12563 return ERR_PTR(-ENOMEM);
12568 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12569 * must be under the same lock in order to serialize against
12570 * perf_event_release_kernel(), such that either we must observe
12571 * is_orphaned_event() or they will observe us on the child_list.
12573 mutex_lock(&parent_event->child_mutex);
12574 if (is_orphaned_event(parent_event) ||
12575 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12576 mutex_unlock(&parent_event->child_mutex);
12577 /* task_ctx_data is freed with child_ctx */
12578 free_event(child_event);
12582 get_ctx(child_ctx);
12585 * Make the child state follow the state of the parent event,
12586 * not its attr.disabled bit. We hold the parent's mutex,
12587 * so we won't race with perf_event_{en, dis}able_family.
12589 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12590 child_event->state = PERF_EVENT_STATE_INACTIVE;
12592 child_event->state = PERF_EVENT_STATE_OFF;
12594 if (parent_event->attr.freq) {
12595 u64 sample_period = parent_event->hw.sample_period;
12596 struct hw_perf_event *hwc = &child_event->hw;
12598 hwc->sample_period = sample_period;
12599 hwc->last_period = sample_period;
12601 local64_set(&hwc->period_left, sample_period);
12604 child_event->ctx = child_ctx;
12605 child_event->overflow_handler = parent_event->overflow_handler;
12606 child_event->overflow_handler_context
12607 = parent_event->overflow_handler_context;
12610 * Precalculate sample_data sizes
12612 perf_event__header_size(child_event);
12613 perf_event__id_header_size(child_event);
12616 * Link it up in the child's context:
12618 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12619 add_event_to_ctx(child_event, child_ctx);
12620 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12623 * Link this into the parent event's child list
12625 list_add_tail(&child_event->child_list, &parent_event->child_list);
12626 mutex_unlock(&parent_event->child_mutex);
12628 return child_event;
12632 * Inherits an event group.
12634 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12635 * This matches with perf_event_release_kernel() removing all child events.
12641 static int inherit_group(struct perf_event *parent_event,
12642 struct task_struct *parent,
12643 struct perf_event_context *parent_ctx,
12644 struct task_struct *child,
12645 struct perf_event_context *child_ctx)
12647 struct perf_event *leader;
12648 struct perf_event *sub;
12649 struct perf_event *child_ctr;
12651 leader = inherit_event(parent_event, parent, parent_ctx,
12652 child, NULL, child_ctx);
12653 if (IS_ERR(leader))
12654 return PTR_ERR(leader);
12656 * @leader can be NULL here because of is_orphaned_event(). In this
12657 * case inherit_event() will create individual events, similar to what
12658 * perf_group_detach() would do anyway.
12660 for_each_sibling_event(sub, parent_event) {
12661 child_ctr = inherit_event(sub, parent, parent_ctx,
12662 child, leader, child_ctx);
12663 if (IS_ERR(child_ctr))
12664 return PTR_ERR(child_ctr);
12666 if (sub->aux_event == parent_event && child_ctr &&
12667 !perf_get_aux_event(child_ctr, leader))
12674 * Creates the child task context and tries to inherit the event-group.
12676 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12677 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12678 * consistent with perf_event_release_kernel() removing all child events.
12685 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12686 struct perf_event_context *parent_ctx,
12687 struct task_struct *child, int ctxn,
12688 int *inherited_all)
12691 struct perf_event_context *child_ctx;
12693 if (!event->attr.inherit) {
12694 *inherited_all = 0;
12698 child_ctx = child->perf_event_ctxp[ctxn];
12701 * This is executed from the parent task context, so
12702 * inherit events that have been marked for cloning.
12703 * First allocate and initialize a context for the
12706 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12710 child->perf_event_ctxp[ctxn] = child_ctx;
12713 ret = inherit_group(event, parent, parent_ctx,
12717 *inherited_all = 0;
12723 * Initialize the perf_event context in task_struct
12725 static int perf_event_init_context(struct task_struct *child, int ctxn)
12727 struct perf_event_context *child_ctx, *parent_ctx;
12728 struct perf_event_context *cloned_ctx;
12729 struct perf_event *event;
12730 struct task_struct *parent = current;
12731 int inherited_all = 1;
12732 unsigned long flags;
12735 if (likely(!parent->perf_event_ctxp[ctxn]))
12739 * If the parent's context is a clone, pin it so it won't get
12740 * swapped under us.
12742 parent_ctx = perf_pin_task_context(parent, ctxn);
12747 * No need to check if parent_ctx != NULL here; since we saw
12748 * it non-NULL earlier, the only reason for it to become NULL
12749 * is if we exit, and since we're currently in the middle of
12750 * a fork we can't be exiting at the same time.
12754 * Lock the parent list. No need to lock the child - not PID
12755 * hashed yet and not running, so nobody can access it.
12757 mutex_lock(&parent_ctx->mutex);
12760 * We dont have to disable NMIs - we are only looking at
12761 * the list, not manipulating it:
12763 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12764 ret = inherit_task_group(event, parent, parent_ctx,
12765 child, ctxn, &inherited_all);
12771 * We can't hold ctx->lock when iterating the ->flexible_group list due
12772 * to allocations, but we need to prevent rotation because
12773 * rotate_ctx() will change the list from interrupt context.
12775 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12776 parent_ctx->rotate_disable = 1;
12777 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12779 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12780 ret = inherit_task_group(event, parent, parent_ctx,
12781 child, ctxn, &inherited_all);
12786 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12787 parent_ctx->rotate_disable = 0;
12789 child_ctx = child->perf_event_ctxp[ctxn];
12791 if (child_ctx && inherited_all) {
12793 * Mark the child context as a clone of the parent
12794 * context, or of whatever the parent is a clone of.
12796 * Note that if the parent is a clone, the holding of
12797 * parent_ctx->lock avoids it from being uncloned.
12799 cloned_ctx = parent_ctx->parent_ctx;
12801 child_ctx->parent_ctx = cloned_ctx;
12802 child_ctx->parent_gen = parent_ctx->parent_gen;
12804 child_ctx->parent_ctx = parent_ctx;
12805 child_ctx->parent_gen = parent_ctx->generation;
12807 get_ctx(child_ctx->parent_ctx);
12810 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12812 mutex_unlock(&parent_ctx->mutex);
12814 perf_unpin_context(parent_ctx);
12815 put_ctx(parent_ctx);
12821 * Initialize the perf_event context in task_struct
12823 int perf_event_init_task(struct task_struct *child)
12827 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12828 mutex_init(&child->perf_event_mutex);
12829 INIT_LIST_HEAD(&child->perf_event_list);
12831 for_each_task_context_nr(ctxn) {
12832 ret = perf_event_init_context(child, ctxn);
12834 perf_event_free_task(child);
12842 static void __init perf_event_init_all_cpus(void)
12844 struct swevent_htable *swhash;
12847 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12849 for_each_possible_cpu(cpu) {
12850 swhash = &per_cpu(swevent_htable, cpu);
12851 mutex_init(&swhash->hlist_mutex);
12852 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12854 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12855 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12857 #ifdef CONFIG_CGROUP_PERF
12858 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12863 static void perf_swevent_init_cpu(unsigned int cpu)
12865 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12867 mutex_lock(&swhash->hlist_mutex);
12868 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12869 struct swevent_hlist *hlist;
12871 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12873 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12875 mutex_unlock(&swhash->hlist_mutex);
12878 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12879 static void __perf_event_exit_context(void *__info)
12881 struct perf_event_context *ctx = __info;
12882 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12883 struct perf_event *event;
12885 raw_spin_lock(&ctx->lock);
12886 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12887 list_for_each_entry(event, &ctx->event_list, event_entry)
12888 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12889 raw_spin_unlock(&ctx->lock);
12892 static void perf_event_exit_cpu_context(int cpu)
12894 struct perf_cpu_context *cpuctx;
12895 struct perf_event_context *ctx;
12898 mutex_lock(&pmus_lock);
12899 list_for_each_entry(pmu, &pmus, entry) {
12900 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12901 ctx = &cpuctx->ctx;
12903 mutex_lock(&ctx->mutex);
12904 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12905 cpuctx->online = 0;
12906 mutex_unlock(&ctx->mutex);
12908 cpumask_clear_cpu(cpu, perf_online_mask);
12909 mutex_unlock(&pmus_lock);
12913 static void perf_event_exit_cpu_context(int cpu) { }
12917 int perf_event_init_cpu(unsigned int cpu)
12919 struct perf_cpu_context *cpuctx;
12920 struct perf_event_context *ctx;
12923 perf_swevent_init_cpu(cpu);
12925 mutex_lock(&pmus_lock);
12926 cpumask_set_cpu(cpu, perf_online_mask);
12927 list_for_each_entry(pmu, &pmus, entry) {
12928 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12929 ctx = &cpuctx->ctx;
12931 mutex_lock(&ctx->mutex);
12932 cpuctx->online = 1;
12933 mutex_unlock(&ctx->mutex);
12935 mutex_unlock(&pmus_lock);
12940 int perf_event_exit_cpu(unsigned int cpu)
12942 perf_event_exit_cpu_context(cpu);
12947 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12951 for_each_online_cpu(cpu)
12952 perf_event_exit_cpu(cpu);
12958 * Run the perf reboot notifier at the very last possible moment so that
12959 * the generic watchdog code runs as long as possible.
12961 static struct notifier_block perf_reboot_notifier = {
12962 .notifier_call = perf_reboot,
12963 .priority = INT_MIN,
12966 void __init perf_event_init(void)
12970 idr_init(&pmu_idr);
12972 perf_event_init_all_cpus();
12973 init_srcu_struct(&pmus_srcu);
12974 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12975 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12976 perf_pmu_register(&perf_task_clock, NULL, -1);
12977 perf_tp_register();
12978 perf_event_init_cpu(smp_processor_id());
12979 register_reboot_notifier(&perf_reboot_notifier);
12981 ret = init_hw_breakpoint();
12982 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12985 * Build time assertion that we keep the data_head at the intended
12986 * location. IOW, validation we got the __reserved[] size right.
12988 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12992 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12995 struct perf_pmu_events_attr *pmu_attr =
12996 container_of(attr, struct perf_pmu_events_attr, attr);
12998 if (pmu_attr->event_str)
12999 return sprintf(page, "%s\n", pmu_attr->event_str);
13003 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13005 static int __init perf_event_sysfs_init(void)
13010 mutex_lock(&pmus_lock);
13012 ret = bus_register(&pmu_bus);
13016 list_for_each_entry(pmu, &pmus, entry) {
13017 if (!pmu->name || pmu->type < 0)
13020 ret = pmu_dev_alloc(pmu);
13021 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13023 pmu_bus_running = 1;
13027 mutex_unlock(&pmus_lock);
13031 device_initcall(perf_event_sysfs_init);
13033 #ifdef CONFIG_CGROUP_PERF
13034 static struct cgroup_subsys_state *
13035 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13037 struct perf_cgroup *jc;
13039 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13041 return ERR_PTR(-ENOMEM);
13043 jc->info = alloc_percpu(struct perf_cgroup_info);
13046 return ERR_PTR(-ENOMEM);
13052 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13054 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13056 free_percpu(jc->info);
13060 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13062 perf_event_cgroup(css->cgroup);
13066 static int __perf_cgroup_move(void *info)
13068 struct task_struct *task = info;
13070 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13075 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13077 struct task_struct *task;
13078 struct cgroup_subsys_state *css;
13080 cgroup_taskset_for_each(task, css, tset)
13081 task_function_call(task, __perf_cgroup_move, task);
13084 struct cgroup_subsys perf_event_cgrp_subsys = {
13085 .css_alloc = perf_cgroup_css_alloc,
13086 .css_free = perf_cgroup_css_free,
13087 .css_online = perf_cgroup_css_online,
13088 .attach = perf_cgroup_attach,
13090 * Implicitly enable on dfl hierarchy so that perf events can
13091 * always be filtered by cgroup2 path as long as perf_event
13092 * controller is not mounted on a legacy hierarchy.
13094 .implicit_on_dfl = true,
13097 #endif /* CONFIG_CGROUP_PERF */