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(int, perf_sched_cb_usages);
387 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
389 static atomic_t nr_mmap_events __read_mostly;
390 static atomic_t nr_comm_events __read_mostly;
391 static atomic_t nr_namespaces_events __read_mostly;
392 static atomic_t nr_task_events __read_mostly;
393 static atomic_t nr_freq_events __read_mostly;
394 static atomic_t nr_switch_events __read_mostly;
395 static atomic_t nr_ksymbol_events __read_mostly;
396 static atomic_t nr_bpf_events __read_mostly;
397 static atomic_t nr_cgroup_events __read_mostly;
398 static atomic_t nr_text_poke_events __read_mostly;
400 static LIST_HEAD(pmus);
401 static DEFINE_MUTEX(pmus_lock);
402 static struct srcu_struct pmus_srcu;
403 static cpumask_var_t perf_online_mask;
406 * perf event paranoia level:
407 * -1 - not paranoid at all
408 * 0 - disallow raw tracepoint access for unpriv
409 * 1 - disallow cpu events for unpriv
410 * 2 - disallow kernel profiling for unpriv
412 int sysctl_perf_event_paranoid __read_mostly = 2;
414 /* Minimum for 512 kiB + 1 user control page */
415 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
418 * max perf event sample rate
420 #define DEFAULT_MAX_SAMPLE_RATE 100000
421 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
422 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
424 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
426 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
427 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
429 static int perf_sample_allowed_ns __read_mostly =
430 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
432 static void update_perf_cpu_limits(void)
434 u64 tmp = perf_sample_period_ns;
436 tmp *= sysctl_perf_cpu_time_max_percent;
437 tmp = div_u64(tmp, 100);
441 WRITE_ONCE(perf_sample_allowed_ns, tmp);
444 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
446 int perf_proc_update_handler(struct ctl_table *table, int write,
447 void *buffer, size_t *lenp, loff_t *ppos)
450 int perf_cpu = sysctl_perf_cpu_time_max_percent;
452 * If throttling is disabled don't allow the write:
454 if (write && (perf_cpu == 100 || perf_cpu == 0))
457 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
461 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
462 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
463 update_perf_cpu_limits();
468 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
470 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
471 void *buffer, size_t *lenp, loff_t *ppos)
473 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
478 if (sysctl_perf_cpu_time_max_percent == 100 ||
479 sysctl_perf_cpu_time_max_percent == 0) {
481 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
482 WRITE_ONCE(perf_sample_allowed_ns, 0);
484 update_perf_cpu_limits();
491 * perf samples are done in some very critical code paths (NMIs).
492 * If they take too much CPU time, the system can lock up and not
493 * get any real work done. This will drop the sample rate when
494 * we detect that events are taking too long.
496 #define NR_ACCUMULATED_SAMPLES 128
497 static DEFINE_PER_CPU(u64, running_sample_length);
499 static u64 __report_avg;
500 static u64 __report_allowed;
502 static void perf_duration_warn(struct irq_work *w)
504 printk_ratelimited(KERN_INFO
505 "perf: interrupt took too long (%lld > %lld), lowering "
506 "kernel.perf_event_max_sample_rate to %d\n",
507 __report_avg, __report_allowed,
508 sysctl_perf_event_sample_rate);
511 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
513 void perf_sample_event_took(u64 sample_len_ns)
515 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
523 /* Decay the counter by 1 average sample. */
524 running_len = __this_cpu_read(running_sample_length);
525 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
526 running_len += sample_len_ns;
527 __this_cpu_write(running_sample_length, running_len);
530 * Note: this will be biased artifically low until we have
531 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
532 * from having to maintain a count.
534 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
535 if (avg_len <= max_len)
538 __report_avg = avg_len;
539 __report_allowed = max_len;
542 * Compute a throttle threshold 25% below the current duration.
544 avg_len += avg_len / 4;
545 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
551 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
552 WRITE_ONCE(max_samples_per_tick, max);
554 sysctl_perf_event_sample_rate = max * HZ;
555 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
557 if (!irq_work_queue(&perf_duration_work)) {
558 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
559 "kernel.perf_event_max_sample_rate to %d\n",
560 __report_avg, __report_allowed,
561 sysctl_perf_event_sample_rate);
565 static atomic64_t perf_event_id;
567 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
568 enum event_type_t event_type);
570 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
571 enum event_type_t event_type,
572 struct task_struct *task);
574 static void update_context_time(struct perf_event_context *ctx);
575 static u64 perf_event_time(struct perf_event *event);
577 void __weak perf_event_print_debug(void) { }
579 extern __weak const char *perf_pmu_name(void)
584 static inline u64 perf_clock(void)
586 return local_clock();
589 static inline u64 perf_event_clock(struct perf_event *event)
591 return event->clock();
595 * State based event timekeeping...
597 * The basic idea is to use event->state to determine which (if any) time
598 * fields to increment with the current delta. This means we only need to
599 * update timestamps when we change state or when they are explicitly requested
602 * Event groups make things a little more complicated, but not terribly so. The
603 * rules for a group are that if the group leader is OFF the entire group is
604 * OFF, irrespecive of what the group member states are. This results in
605 * __perf_effective_state().
607 * A futher ramification is that when a group leader flips between OFF and
608 * !OFF, we need to update all group member times.
611 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
612 * need to make sure the relevant context time is updated before we try and
613 * update our timestamps.
616 static __always_inline enum perf_event_state
617 __perf_effective_state(struct perf_event *event)
619 struct perf_event *leader = event->group_leader;
621 if (leader->state <= PERF_EVENT_STATE_OFF)
622 return leader->state;
627 static __always_inline void
628 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
630 enum perf_event_state state = __perf_effective_state(event);
631 u64 delta = now - event->tstamp;
633 *enabled = event->total_time_enabled;
634 if (state >= PERF_EVENT_STATE_INACTIVE)
637 *running = event->total_time_running;
638 if (state >= PERF_EVENT_STATE_ACTIVE)
642 static void perf_event_update_time(struct perf_event *event)
644 u64 now = perf_event_time(event);
646 __perf_update_times(event, now, &event->total_time_enabled,
647 &event->total_time_running);
651 static void perf_event_update_sibling_time(struct perf_event *leader)
653 struct perf_event *sibling;
655 for_each_sibling_event(sibling, leader)
656 perf_event_update_time(sibling);
660 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
662 if (event->state == state)
665 perf_event_update_time(event);
667 * If a group leader gets enabled/disabled all its siblings
670 if ((event->state < 0) ^ (state < 0))
671 perf_event_update_sibling_time(event);
673 WRITE_ONCE(event->state, state);
676 #ifdef CONFIG_CGROUP_PERF
679 perf_cgroup_match(struct perf_event *event)
681 struct perf_event_context *ctx = event->ctx;
682 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
684 /* @event doesn't care about cgroup */
688 /* wants specific cgroup scope but @cpuctx isn't associated with any */
693 * Cgroup scoping is recursive. An event enabled for a cgroup is
694 * also enabled for all its descendant cgroups. If @cpuctx's
695 * cgroup is a descendant of @event's (the test covers identity
696 * case), it's a match.
698 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
699 event->cgrp->css.cgroup);
702 static inline void perf_detach_cgroup(struct perf_event *event)
704 css_put(&event->cgrp->css);
708 static inline int is_cgroup_event(struct perf_event *event)
710 return event->cgrp != NULL;
713 static inline u64 perf_cgroup_event_time(struct perf_event *event)
715 struct perf_cgroup_info *t;
717 t = per_cpu_ptr(event->cgrp->info, event->cpu);
721 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
723 struct perf_cgroup_info *info;
728 info = this_cpu_ptr(cgrp->info);
730 info->time += now - info->timestamp;
731 info->timestamp = now;
734 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
736 struct perf_cgroup *cgrp = cpuctx->cgrp;
737 struct cgroup_subsys_state *css;
740 for (css = &cgrp->css; css; css = css->parent) {
741 cgrp = container_of(css, struct perf_cgroup, css);
742 __update_cgrp_time(cgrp);
747 static inline void update_cgrp_time_from_event(struct perf_event *event)
749 struct perf_cgroup *cgrp;
752 * ensure we access cgroup data only when needed and
753 * when we know the cgroup is pinned (css_get)
755 if (!is_cgroup_event(event))
758 cgrp = perf_cgroup_from_task(current, event->ctx);
760 * Do not update time when cgroup is not active
762 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
763 __update_cgrp_time(event->cgrp);
767 perf_cgroup_set_timestamp(struct task_struct *task,
768 struct perf_event_context *ctx)
770 struct perf_cgroup *cgrp;
771 struct perf_cgroup_info *info;
772 struct cgroup_subsys_state *css;
775 * ctx->lock held by caller
776 * ensure we do not access cgroup data
777 * unless we have the cgroup pinned (css_get)
779 if (!task || !ctx->nr_cgroups)
782 cgrp = perf_cgroup_from_task(task, ctx);
784 for (css = &cgrp->css; css; css = css->parent) {
785 cgrp = container_of(css, struct perf_cgroup, css);
786 info = this_cpu_ptr(cgrp->info);
787 info->timestamp = ctx->timestamp;
791 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
793 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
794 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
797 * reschedule events based on the cgroup constraint of task.
799 * mode SWOUT : schedule out everything
800 * mode SWIN : schedule in based on cgroup for next
802 static void perf_cgroup_switch(struct task_struct *task, int mode)
804 struct perf_cpu_context *cpuctx;
805 struct list_head *list;
809 * Disable interrupts and preemption to avoid this CPU's
810 * cgrp_cpuctx_entry to change under us.
812 local_irq_save(flags);
814 list = this_cpu_ptr(&cgrp_cpuctx_list);
815 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
816 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
818 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
819 perf_pmu_disable(cpuctx->ctx.pmu);
821 if (mode & PERF_CGROUP_SWOUT) {
822 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
824 * must not be done before ctxswout due
825 * to event_filter_match() in event_sched_out()
830 if (mode & PERF_CGROUP_SWIN) {
831 WARN_ON_ONCE(cpuctx->cgrp);
833 * set cgrp before ctxsw in to allow
834 * event_filter_match() to not have to pass
836 * we pass the cpuctx->ctx to perf_cgroup_from_task()
837 * because cgorup events are only per-cpu
839 cpuctx->cgrp = perf_cgroup_from_task(task,
841 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
843 perf_pmu_enable(cpuctx->ctx.pmu);
844 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
847 local_irq_restore(flags);
850 static inline void perf_cgroup_sched_out(struct task_struct *task,
851 struct task_struct *next)
853 struct perf_cgroup *cgrp1;
854 struct perf_cgroup *cgrp2 = NULL;
858 * we come here when we know perf_cgroup_events > 0
859 * we do not need to pass the ctx here because we know
860 * we are holding the rcu lock
862 cgrp1 = perf_cgroup_from_task(task, NULL);
863 cgrp2 = perf_cgroup_from_task(next, NULL);
866 * only schedule out current cgroup events if we know
867 * that we are switching to a different cgroup. Otherwise,
868 * do no touch the cgroup events.
871 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
876 static inline void perf_cgroup_sched_in(struct task_struct *prev,
877 struct task_struct *task)
879 struct perf_cgroup *cgrp1;
880 struct perf_cgroup *cgrp2 = NULL;
884 * we come here when we know perf_cgroup_events > 0
885 * we do not need to pass the ctx here because we know
886 * we are holding the rcu lock
888 cgrp1 = perf_cgroup_from_task(task, NULL);
889 cgrp2 = perf_cgroup_from_task(prev, NULL);
892 * only need to schedule in cgroup events if we are changing
893 * cgroup during ctxsw. Cgroup events were not scheduled
894 * out of ctxsw out if that was not the case.
897 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
902 static int perf_cgroup_ensure_storage(struct perf_event *event,
903 struct cgroup_subsys_state *css)
905 struct perf_cpu_context *cpuctx;
906 struct perf_event **storage;
907 int cpu, heap_size, ret = 0;
910 * Allow storage to have sufficent space for an iterator for each
911 * possibly nested cgroup plus an iterator for events with no cgroup.
913 for (heap_size = 1; css; css = css->parent)
916 for_each_possible_cpu(cpu) {
917 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
918 if (heap_size <= cpuctx->heap_size)
921 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
922 GFP_KERNEL, cpu_to_node(cpu));
928 raw_spin_lock_irq(&cpuctx->ctx.lock);
929 if (cpuctx->heap_size < heap_size) {
930 swap(cpuctx->heap, storage);
931 if (storage == cpuctx->heap_default)
933 cpuctx->heap_size = heap_size;
935 raw_spin_unlock_irq(&cpuctx->ctx.lock);
943 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
944 struct perf_event_attr *attr,
945 struct perf_event *group_leader)
947 struct perf_cgroup *cgrp;
948 struct cgroup_subsys_state *css;
949 struct fd f = fdget(fd);
955 css = css_tryget_online_from_dir(f.file->f_path.dentry,
956 &perf_event_cgrp_subsys);
962 ret = perf_cgroup_ensure_storage(event, css);
966 cgrp = container_of(css, struct perf_cgroup, css);
970 * all events in a group must monitor
971 * the same cgroup because a task belongs
972 * to only one perf cgroup at a time
974 if (group_leader && group_leader->cgrp != cgrp) {
975 perf_detach_cgroup(event);
984 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
986 struct perf_cgroup_info *t;
987 t = per_cpu_ptr(event->cgrp->info, event->cpu);
988 event->shadow_ctx_time = now - t->timestamp;
992 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
994 struct perf_cpu_context *cpuctx;
996 if (!is_cgroup_event(event))
1000 * Because cgroup events are always per-cpu events,
1001 * @ctx == &cpuctx->ctx.
1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1006 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1007 * matching the event's cgroup, we must do this for every new event,
1008 * because if the first would mismatch, the second would not try again
1009 * and we would leave cpuctx->cgrp unset.
1011 if (ctx->is_active && !cpuctx->cgrp) {
1012 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1014 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1015 cpuctx->cgrp = cgrp;
1018 if (ctx->nr_cgroups++)
1021 list_add(&cpuctx->cgrp_cpuctx_entry,
1022 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
1026 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1028 struct perf_cpu_context *cpuctx;
1030 if (!is_cgroup_event(event))
1034 * Because cgroup events are always per-cpu events,
1035 * @ctx == &cpuctx->ctx.
1037 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1039 if (--ctx->nr_cgroups)
1042 if (ctx->is_active && cpuctx->cgrp)
1043 cpuctx->cgrp = NULL;
1045 list_del(&cpuctx->cgrp_cpuctx_entry);
1048 #else /* !CONFIG_CGROUP_PERF */
1051 perf_cgroup_match(struct perf_event *event)
1056 static inline void perf_detach_cgroup(struct perf_event *event)
1059 static inline int is_cgroup_event(struct perf_event *event)
1064 static inline void update_cgrp_time_from_event(struct perf_event *event)
1068 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1072 static inline void perf_cgroup_sched_out(struct task_struct *task,
1073 struct task_struct *next)
1077 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1078 struct task_struct *task)
1082 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1083 struct perf_event_attr *attr,
1084 struct perf_event *group_leader)
1090 perf_cgroup_set_timestamp(struct task_struct *task,
1091 struct perf_event_context *ctx)
1096 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1101 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1105 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1111 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1116 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1122 * set default to be dependent on timer tick just
1123 * like original code
1125 #define PERF_CPU_HRTIMER (1000 / HZ)
1127 * function must be called with interrupts disabled
1129 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1131 struct perf_cpu_context *cpuctx;
1134 lockdep_assert_irqs_disabled();
1136 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1137 rotations = perf_rotate_context(cpuctx);
1139 raw_spin_lock(&cpuctx->hrtimer_lock);
1141 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1143 cpuctx->hrtimer_active = 0;
1144 raw_spin_unlock(&cpuctx->hrtimer_lock);
1146 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1149 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1151 struct hrtimer *timer = &cpuctx->hrtimer;
1152 struct pmu *pmu = cpuctx->ctx.pmu;
1155 /* no multiplexing needed for SW PMU */
1156 if (pmu->task_ctx_nr == perf_sw_context)
1160 * check default is sane, if not set then force to
1161 * default interval (1/tick)
1163 interval = pmu->hrtimer_interval_ms;
1165 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1167 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1169 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1170 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1171 timer->function = perf_mux_hrtimer_handler;
1174 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1176 struct hrtimer *timer = &cpuctx->hrtimer;
1177 struct pmu *pmu = cpuctx->ctx.pmu;
1178 unsigned long flags;
1180 /* not for SW PMU */
1181 if (pmu->task_ctx_nr == perf_sw_context)
1184 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1185 if (!cpuctx->hrtimer_active) {
1186 cpuctx->hrtimer_active = 1;
1187 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1188 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1190 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1195 void perf_pmu_disable(struct pmu *pmu)
1197 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1199 pmu->pmu_disable(pmu);
1202 void perf_pmu_enable(struct pmu *pmu)
1204 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1206 pmu->pmu_enable(pmu);
1209 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1212 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1213 * perf_event_task_tick() are fully serialized because they're strictly cpu
1214 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1215 * disabled, while perf_event_task_tick is called from IRQ context.
1217 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1219 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1221 lockdep_assert_irqs_disabled();
1223 WARN_ON(!list_empty(&ctx->active_ctx_list));
1225 list_add(&ctx->active_ctx_list, head);
1228 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1230 lockdep_assert_irqs_disabled();
1232 WARN_ON(list_empty(&ctx->active_ctx_list));
1234 list_del_init(&ctx->active_ctx_list);
1237 static void get_ctx(struct perf_event_context *ctx)
1239 refcount_inc(&ctx->refcount);
1242 static void *alloc_task_ctx_data(struct pmu *pmu)
1244 if (pmu->task_ctx_cache)
1245 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1250 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1252 if (pmu->task_ctx_cache && task_ctx_data)
1253 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1256 static void free_ctx(struct rcu_head *head)
1258 struct perf_event_context *ctx;
1260 ctx = container_of(head, struct perf_event_context, rcu_head);
1261 free_task_ctx_data(ctx->pmu, ctx->task_ctx_data);
1265 static void put_ctx(struct perf_event_context *ctx)
1267 if (refcount_dec_and_test(&ctx->refcount)) {
1268 if (ctx->parent_ctx)
1269 put_ctx(ctx->parent_ctx);
1270 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1271 put_task_struct(ctx->task);
1272 call_rcu(&ctx->rcu_head, free_ctx);
1277 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1278 * perf_pmu_migrate_context() we need some magic.
1280 * Those places that change perf_event::ctx will hold both
1281 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1283 * Lock ordering is by mutex address. There are two other sites where
1284 * perf_event_context::mutex nests and those are:
1286 * - perf_event_exit_task_context() [ child , 0 ]
1287 * perf_event_exit_event()
1288 * put_event() [ parent, 1 ]
1290 * - perf_event_init_context() [ parent, 0 ]
1291 * inherit_task_group()
1294 * perf_event_alloc()
1296 * perf_try_init_event() [ child , 1 ]
1298 * While it appears there is an obvious deadlock here -- the parent and child
1299 * nesting levels are inverted between the two. This is in fact safe because
1300 * life-time rules separate them. That is an exiting task cannot fork, and a
1301 * spawning task cannot (yet) exit.
1303 * But remember that that these are parent<->child context relations, and
1304 * migration does not affect children, therefore these two orderings should not
1307 * The change in perf_event::ctx does not affect children (as claimed above)
1308 * because the sys_perf_event_open() case will install a new event and break
1309 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1310 * concerned with cpuctx and that doesn't have children.
1312 * The places that change perf_event::ctx will issue:
1314 * perf_remove_from_context();
1315 * synchronize_rcu();
1316 * perf_install_in_context();
1318 * to affect the change. The remove_from_context() + synchronize_rcu() should
1319 * quiesce the event, after which we can install it in the new location. This
1320 * means that only external vectors (perf_fops, prctl) can perturb the event
1321 * while in transit. Therefore all such accessors should also acquire
1322 * perf_event_context::mutex to serialize against this.
1324 * However; because event->ctx can change while we're waiting to acquire
1325 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1330 * task_struct::perf_event_mutex
1331 * perf_event_context::mutex
1332 * perf_event::child_mutex;
1333 * perf_event_context::lock
1334 * perf_event::mmap_mutex
1336 * perf_addr_filters_head::lock
1340 * cpuctx->mutex / perf_event_context::mutex
1342 static struct perf_event_context *
1343 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1345 struct perf_event_context *ctx;
1349 ctx = READ_ONCE(event->ctx);
1350 if (!refcount_inc_not_zero(&ctx->refcount)) {
1356 mutex_lock_nested(&ctx->mutex, nesting);
1357 if (event->ctx != ctx) {
1358 mutex_unlock(&ctx->mutex);
1366 static inline struct perf_event_context *
1367 perf_event_ctx_lock(struct perf_event *event)
1369 return perf_event_ctx_lock_nested(event, 0);
1372 static void perf_event_ctx_unlock(struct perf_event *event,
1373 struct perf_event_context *ctx)
1375 mutex_unlock(&ctx->mutex);
1380 * This must be done under the ctx->lock, such as to serialize against
1381 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1382 * calling scheduler related locks and ctx->lock nests inside those.
1384 static __must_check struct perf_event_context *
1385 unclone_ctx(struct perf_event_context *ctx)
1387 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1389 lockdep_assert_held(&ctx->lock);
1392 ctx->parent_ctx = NULL;
1398 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1403 * only top level events have the pid namespace they were created in
1406 event = event->parent;
1408 nr = __task_pid_nr_ns(p, type, event->ns);
1409 /* avoid -1 if it is idle thread or runs in another ns */
1410 if (!nr && !pid_alive(p))
1415 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1417 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1420 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1422 return perf_event_pid_type(event, p, PIDTYPE_PID);
1426 * If we inherit events we want to return the parent event id
1429 static u64 primary_event_id(struct perf_event *event)
1434 id = event->parent->id;
1440 * Get the perf_event_context for a task and lock it.
1442 * This has to cope with with the fact that until it is locked,
1443 * the context could get moved to another task.
1445 static struct perf_event_context *
1446 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1448 struct perf_event_context *ctx;
1452 * One of the few rules of preemptible RCU is that one cannot do
1453 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1454 * part of the read side critical section was irqs-enabled -- see
1455 * rcu_read_unlock_special().
1457 * Since ctx->lock nests under rq->lock we must ensure the entire read
1458 * side critical section has interrupts disabled.
1460 local_irq_save(*flags);
1462 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1465 * If this context is a clone of another, it might
1466 * get swapped for another underneath us by
1467 * perf_event_task_sched_out, though the
1468 * rcu_read_lock() protects us from any context
1469 * getting freed. Lock the context and check if it
1470 * got swapped before we could get the lock, and retry
1471 * if so. If we locked the right context, then it
1472 * can't get swapped on us any more.
1474 raw_spin_lock(&ctx->lock);
1475 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1476 raw_spin_unlock(&ctx->lock);
1478 local_irq_restore(*flags);
1482 if (ctx->task == TASK_TOMBSTONE ||
1483 !refcount_inc_not_zero(&ctx->refcount)) {
1484 raw_spin_unlock(&ctx->lock);
1487 WARN_ON_ONCE(ctx->task != task);
1492 local_irq_restore(*flags);
1497 * Get the context for a task and increment its pin_count so it
1498 * can't get swapped to another task. This also increments its
1499 * reference count so that the context can't get freed.
1501 static struct perf_event_context *
1502 perf_pin_task_context(struct task_struct *task, int ctxn)
1504 struct perf_event_context *ctx;
1505 unsigned long flags;
1507 ctx = perf_lock_task_context(task, ctxn, &flags);
1510 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1515 static void perf_unpin_context(struct perf_event_context *ctx)
1517 unsigned long flags;
1519 raw_spin_lock_irqsave(&ctx->lock, flags);
1521 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1525 * Update the record of the current time in a context.
1527 static void update_context_time(struct perf_event_context *ctx)
1529 u64 now = perf_clock();
1531 ctx->time += now - ctx->timestamp;
1532 ctx->timestamp = now;
1535 static u64 perf_event_time(struct perf_event *event)
1537 struct perf_event_context *ctx = event->ctx;
1539 if (is_cgroup_event(event))
1540 return perf_cgroup_event_time(event);
1542 return ctx ? ctx->time : 0;
1545 static enum event_type_t get_event_type(struct perf_event *event)
1547 struct perf_event_context *ctx = event->ctx;
1548 enum event_type_t event_type;
1550 lockdep_assert_held(&ctx->lock);
1553 * It's 'group type', really, because if our group leader is
1554 * pinned, so are we.
1556 if (event->group_leader != event)
1557 event = event->group_leader;
1559 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1561 event_type |= EVENT_CPU;
1567 * Helper function to initialize event group nodes.
1569 static void init_event_group(struct perf_event *event)
1571 RB_CLEAR_NODE(&event->group_node);
1572 event->group_index = 0;
1576 * Extract pinned or flexible groups from the context
1577 * based on event attrs bits.
1579 static struct perf_event_groups *
1580 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1582 if (event->attr.pinned)
1583 return &ctx->pinned_groups;
1585 return &ctx->flexible_groups;
1589 * Helper function to initializes perf_event_group trees.
1591 static void perf_event_groups_init(struct perf_event_groups *groups)
1593 groups->tree = RB_ROOT;
1598 * Compare function for event groups;
1600 * Implements complex key that first sorts by CPU and then by virtual index
1601 * which provides ordering when rotating groups for the same CPU.
1604 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1606 if (left->cpu < right->cpu)
1608 if (left->cpu > right->cpu)
1611 #ifdef CONFIG_CGROUP_PERF
1612 if (left->cgrp != right->cgrp) {
1613 if (!left->cgrp || !left->cgrp->css.cgroup) {
1615 * Left has no cgroup but right does, no cgroups come
1620 if (!right->cgrp || !right->cgrp->css.cgroup) {
1622 * Right has no cgroup but left does, no cgroups come
1627 /* Two dissimilar cgroups, order by id. */
1628 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1635 if (left->group_index < right->group_index)
1637 if (left->group_index > right->group_index)
1644 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1645 * key (see perf_event_groups_less). This places it last inside the CPU
1649 perf_event_groups_insert(struct perf_event_groups *groups,
1650 struct perf_event *event)
1652 struct perf_event *node_event;
1653 struct rb_node *parent;
1654 struct rb_node **node;
1656 event->group_index = ++groups->index;
1658 node = &groups->tree.rb_node;
1663 node_event = container_of(*node, struct perf_event, group_node);
1665 if (perf_event_groups_less(event, node_event))
1666 node = &parent->rb_left;
1668 node = &parent->rb_right;
1671 rb_link_node(&event->group_node, parent, node);
1672 rb_insert_color(&event->group_node, &groups->tree);
1676 * Helper function to insert event into the pinned or flexible groups.
1679 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1681 struct perf_event_groups *groups;
1683 groups = get_event_groups(event, ctx);
1684 perf_event_groups_insert(groups, event);
1688 * Delete a group from a tree.
1691 perf_event_groups_delete(struct perf_event_groups *groups,
1692 struct perf_event *event)
1694 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1695 RB_EMPTY_ROOT(&groups->tree));
1697 rb_erase(&event->group_node, &groups->tree);
1698 init_event_group(event);
1702 * Helper function to delete event from its groups.
1705 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1707 struct perf_event_groups *groups;
1709 groups = get_event_groups(event, ctx);
1710 perf_event_groups_delete(groups, event);
1714 * Get the leftmost event in the cpu/cgroup subtree.
1716 static struct perf_event *
1717 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1718 struct cgroup *cgrp)
1720 struct perf_event *node_event = NULL, *match = NULL;
1721 struct rb_node *node = groups->tree.rb_node;
1722 #ifdef CONFIG_CGROUP_PERF
1723 u64 node_cgrp_id, cgrp_id = 0;
1726 cgrp_id = cgrp->kn->id;
1730 node_event = container_of(node, struct perf_event, group_node);
1732 if (cpu < node_event->cpu) {
1733 node = node->rb_left;
1736 if (cpu > node_event->cpu) {
1737 node = node->rb_right;
1740 #ifdef CONFIG_CGROUP_PERF
1742 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1743 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1745 if (cgrp_id < node_cgrp_id) {
1746 node = node->rb_left;
1749 if (cgrp_id > node_cgrp_id) {
1750 node = node->rb_right;
1755 node = node->rb_left;
1762 * Like rb_entry_next_safe() for the @cpu subtree.
1764 static struct perf_event *
1765 perf_event_groups_next(struct perf_event *event)
1767 struct perf_event *next;
1768 #ifdef CONFIG_CGROUP_PERF
1769 u64 curr_cgrp_id = 0;
1770 u64 next_cgrp_id = 0;
1773 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1774 if (next == NULL || next->cpu != event->cpu)
1777 #ifdef CONFIG_CGROUP_PERF
1778 if (event->cgrp && event->cgrp->css.cgroup)
1779 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1781 if (next->cgrp && next->cgrp->css.cgroup)
1782 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1784 if (curr_cgrp_id != next_cgrp_id)
1791 * Iterate through the whole groups tree.
1793 #define perf_event_groups_for_each(event, groups) \
1794 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1795 typeof(*event), group_node); event; \
1796 event = rb_entry_safe(rb_next(&event->group_node), \
1797 typeof(*event), group_node))
1800 * Add an event from the lists for its context.
1801 * Must be called with ctx->mutex and ctx->lock held.
1804 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1806 lockdep_assert_held(&ctx->lock);
1808 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1809 event->attach_state |= PERF_ATTACH_CONTEXT;
1811 event->tstamp = perf_event_time(event);
1814 * If we're a stand alone event or group leader, we go to the context
1815 * list, group events are kept attached to the group so that
1816 * perf_group_detach can, at all times, locate all siblings.
1818 if (event->group_leader == event) {
1819 event->group_caps = event->event_caps;
1820 add_event_to_groups(event, ctx);
1823 list_add_rcu(&event->event_entry, &ctx->event_list);
1825 if (event->attr.inherit_stat)
1828 if (event->state > PERF_EVENT_STATE_OFF)
1829 perf_cgroup_event_enable(event, ctx);
1835 * Initialize event state based on the perf_event_attr::disabled.
1837 static inline void perf_event__state_init(struct perf_event *event)
1839 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1840 PERF_EVENT_STATE_INACTIVE;
1843 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1845 int entry = sizeof(u64); /* value */
1849 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1850 size += sizeof(u64);
1852 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1853 size += sizeof(u64);
1855 if (event->attr.read_format & PERF_FORMAT_ID)
1856 entry += sizeof(u64);
1858 if (event->attr.read_format & PERF_FORMAT_GROUP) {
1860 size += sizeof(u64);
1864 event->read_size = size;
1867 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1869 struct perf_sample_data *data;
1872 if (sample_type & PERF_SAMPLE_IP)
1873 size += sizeof(data->ip);
1875 if (sample_type & PERF_SAMPLE_ADDR)
1876 size += sizeof(data->addr);
1878 if (sample_type & PERF_SAMPLE_PERIOD)
1879 size += sizeof(data->period);
1881 if (sample_type & PERF_SAMPLE_WEIGHT)
1882 size += sizeof(data->weight);
1884 if (sample_type & PERF_SAMPLE_READ)
1885 size += event->read_size;
1887 if (sample_type & PERF_SAMPLE_DATA_SRC)
1888 size += sizeof(data->data_src.val);
1890 if (sample_type & PERF_SAMPLE_TRANSACTION)
1891 size += sizeof(data->txn);
1893 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1894 size += sizeof(data->phys_addr);
1896 if (sample_type & PERF_SAMPLE_CGROUP)
1897 size += sizeof(data->cgroup);
1899 event->header_size = size;
1903 * Called at perf_event creation and when events are attached/detached from a
1906 static void perf_event__header_size(struct perf_event *event)
1908 __perf_event_read_size(event,
1909 event->group_leader->nr_siblings);
1910 __perf_event_header_size(event, event->attr.sample_type);
1913 static void perf_event__id_header_size(struct perf_event *event)
1915 struct perf_sample_data *data;
1916 u64 sample_type = event->attr.sample_type;
1919 if (sample_type & PERF_SAMPLE_TID)
1920 size += sizeof(data->tid_entry);
1922 if (sample_type & PERF_SAMPLE_TIME)
1923 size += sizeof(data->time);
1925 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1926 size += sizeof(data->id);
1928 if (sample_type & PERF_SAMPLE_ID)
1929 size += sizeof(data->id);
1931 if (sample_type & PERF_SAMPLE_STREAM_ID)
1932 size += sizeof(data->stream_id);
1934 if (sample_type & PERF_SAMPLE_CPU)
1935 size += sizeof(data->cpu_entry);
1937 event->id_header_size = size;
1940 static bool perf_event_validate_size(struct perf_event *event)
1943 * The values computed here will be over-written when we actually
1946 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1947 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1948 perf_event__id_header_size(event);
1951 * Sum the lot; should not exceed the 64k limit we have on records.
1952 * Conservative limit to allow for callchains and other variable fields.
1954 if (event->read_size + event->header_size +
1955 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1961 static void perf_group_attach(struct perf_event *event)
1963 struct perf_event *group_leader = event->group_leader, *pos;
1965 lockdep_assert_held(&event->ctx->lock);
1968 * We can have double attach due to group movement in perf_event_open.
1970 if (event->attach_state & PERF_ATTACH_GROUP)
1973 event->attach_state |= PERF_ATTACH_GROUP;
1975 if (group_leader == event)
1978 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1980 group_leader->group_caps &= event->event_caps;
1982 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1983 group_leader->nr_siblings++;
1985 perf_event__header_size(group_leader);
1987 for_each_sibling_event(pos, group_leader)
1988 perf_event__header_size(pos);
1992 * Remove an event from the lists for its context.
1993 * Must be called with ctx->mutex and ctx->lock held.
1996 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1998 WARN_ON_ONCE(event->ctx != ctx);
1999 lockdep_assert_held(&ctx->lock);
2002 * We can have double detach due to exit/hot-unplug + close.
2004 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2007 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2010 if (event->attr.inherit_stat)
2013 list_del_rcu(&event->event_entry);
2015 if (event->group_leader == event)
2016 del_event_from_groups(event, ctx);
2019 * If event was in error state, then keep it
2020 * that way, otherwise bogus counts will be
2021 * returned on read(). The only way to get out
2022 * of error state is by explicit re-enabling
2025 if (event->state > PERF_EVENT_STATE_OFF) {
2026 perf_cgroup_event_disable(event, ctx);
2027 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2034 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2036 if (!has_aux(aux_event))
2039 if (!event->pmu->aux_output_match)
2042 return event->pmu->aux_output_match(aux_event);
2045 static void put_event(struct perf_event *event);
2046 static void event_sched_out(struct perf_event *event,
2047 struct perf_cpu_context *cpuctx,
2048 struct perf_event_context *ctx);
2050 static void perf_put_aux_event(struct perf_event *event)
2052 struct perf_event_context *ctx = event->ctx;
2053 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2054 struct perf_event *iter;
2057 * If event uses aux_event tear down the link
2059 if (event->aux_event) {
2060 iter = event->aux_event;
2061 event->aux_event = NULL;
2067 * If the event is an aux_event, tear down all links to
2068 * it from other events.
2070 for_each_sibling_event(iter, event->group_leader) {
2071 if (iter->aux_event != event)
2074 iter->aux_event = NULL;
2078 * If it's ACTIVE, schedule it out and put it into ERROR
2079 * state so that we don't try to schedule it again. Note
2080 * that perf_event_enable() will clear the ERROR status.
2082 event_sched_out(iter, cpuctx, ctx);
2083 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2087 static bool perf_need_aux_event(struct perf_event *event)
2089 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2092 static int perf_get_aux_event(struct perf_event *event,
2093 struct perf_event *group_leader)
2096 * Our group leader must be an aux event if we want to be
2097 * an aux_output. This way, the aux event will precede its
2098 * aux_output events in the group, and therefore will always
2105 * aux_output and aux_sample_size are mutually exclusive.
2107 if (event->attr.aux_output && event->attr.aux_sample_size)
2110 if (event->attr.aux_output &&
2111 !perf_aux_output_match(event, group_leader))
2114 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2117 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2121 * Link aux_outputs to their aux event; this is undone in
2122 * perf_group_detach() by perf_put_aux_event(). When the
2123 * group in torn down, the aux_output events loose their
2124 * link to the aux_event and can't schedule any more.
2126 event->aux_event = group_leader;
2131 static inline struct list_head *get_event_list(struct perf_event *event)
2133 struct perf_event_context *ctx = event->ctx;
2134 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2138 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2139 * cannot exist on their own, schedule them out and move them into the ERROR
2140 * state. Also see _perf_event_enable(), it will not be able to recover
2143 static inline void perf_remove_sibling_event(struct perf_event *event)
2145 struct perf_event_context *ctx = event->ctx;
2146 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2148 event_sched_out(event, cpuctx, ctx);
2149 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2152 static void perf_group_detach(struct perf_event *event)
2154 struct perf_event *leader = event->group_leader;
2155 struct perf_event *sibling, *tmp;
2156 struct perf_event_context *ctx = event->ctx;
2158 lockdep_assert_held(&ctx->lock);
2161 * We can have double detach due to exit/hot-unplug + close.
2163 if (!(event->attach_state & PERF_ATTACH_GROUP))
2166 event->attach_state &= ~PERF_ATTACH_GROUP;
2168 perf_put_aux_event(event);
2171 * If this is a sibling, remove it from its group.
2173 if (leader != event) {
2174 list_del_init(&event->sibling_list);
2175 event->group_leader->nr_siblings--;
2180 * If this was a group event with sibling events then
2181 * upgrade the siblings to singleton events by adding them
2182 * to whatever list we are on.
2184 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2186 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2187 perf_remove_sibling_event(sibling);
2189 sibling->group_leader = sibling;
2190 list_del_init(&sibling->sibling_list);
2192 /* Inherit group flags from the previous leader */
2193 sibling->group_caps = event->group_caps;
2195 if (!RB_EMPTY_NODE(&event->group_node)) {
2196 add_event_to_groups(sibling, event->ctx);
2198 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2199 list_add_tail(&sibling->active_list, get_event_list(sibling));
2202 WARN_ON_ONCE(sibling->ctx != event->ctx);
2206 for_each_sibling_event(tmp, leader)
2207 perf_event__header_size(tmp);
2209 perf_event__header_size(leader);
2212 static bool is_orphaned_event(struct perf_event *event)
2214 return event->state == PERF_EVENT_STATE_DEAD;
2217 static inline int __pmu_filter_match(struct perf_event *event)
2219 struct pmu *pmu = event->pmu;
2220 return pmu->filter_match ? pmu->filter_match(event) : 1;
2224 * Check whether we should attempt to schedule an event group based on
2225 * PMU-specific filtering. An event group can consist of HW and SW events,
2226 * potentially with a SW leader, so we must check all the filters, to
2227 * determine whether a group is schedulable:
2229 static inline int pmu_filter_match(struct perf_event *event)
2231 struct perf_event *sibling;
2233 if (!__pmu_filter_match(event))
2236 for_each_sibling_event(sibling, event) {
2237 if (!__pmu_filter_match(sibling))
2245 event_filter_match(struct perf_event *event)
2247 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2248 perf_cgroup_match(event) && pmu_filter_match(event);
2252 event_sched_out(struct perf_event *event,
2253 struct perf_cpu_context *cpuctx,
2254 struct perf_event_context *ctx)
2256 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2258 WARN_ON_ONCE(event->ctx != ctx);
2259 lockdep_assert_held(&ctx->lock);
2261 if (event->state != PERF_EVENT_STATE_ACTIVE)
2265 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2266 * we can schedule events _OUT_ individually through things like
2267 * __perf_remove_from_context().
2269 list_del_init(&event->active_list);
2271 perf_pmu_disable(event->pmu);
2273 event->pmu->del(event, 0);
2276 if (READ_ONCE(event->pending_disable) >= 0) {
2277 WRITE_ONCE(event->pending_disable, -1);
2278 perf_cgroup_event_disable(event, ctx);
2279 state = PERF_EVENT_STATE_OFF;
2281 perf_event_set_state(event, state);
2283 if (!is_software_event(event))
2284 cpuctx->active_oncpu--;
2285 if (!--ctx->nr_active)
2286 perf_event_ctx_deactivate(ctx);
2287 if (event->attr.freq && event->attr.sample_freq)
2289 if (event->attr.exclusive || !cpuctx->active_oncpu)
2290 cpuctx->exclusive = 0;
2292 perf_pmu_enable(event->pmu);
2296 group_sched_out(struct perf_event *group_event,
2297 struct perf_cpu_context *cpuctx,
2298 struct perf_event_context *ctx)
2300 struct perf_event *event;
2302 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2305 perf_pmu_disable(ctx->pmu);
2307 event_sched_out(group_event, cpuctx, ctx);
2310 * Schedule out siblings (if any):
2312 for_each_sibling_event(event, group_event)
2313 event_sched_out(event, cpuctx, ctx);
2315 perf_pmu_enable(ctx->pmu);
2318 #define DETACH_GROUP 0x01UL
2321 * Cross CPU call to remove a performance event
2323 * We disable the event on the hardware level first. After that we
2324 * remove it from the context list.
2327 __perf_remove_from_context(struct perf_event *event,
2328 struct perf_cpu_context *cpuctx,
2329 struct perf_event_context *ctx,
2332 unsigned long flags = (unsigned long)info;
2334 if (ctx->is_active & EVENT_TIME) {
2335 update_context_time(ctx);
2336 update_cgrp_time_from_cpuctx(cpuctx);
2339 event_sched_out(event, cpuctx, ctx);
2340 if (flags & DETACH_GROUP)
2341 perf_group_detach(event);
2342 list_del_event(event, ctx);
2344 if (!ctx->nr_events && ctx->is_active) {
2346 ctx->rotate_necessary = 0;
2348 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2349 cpuctx->task_ctx = NULL;
2355 * Remove the event from a task's (or a CPU's) list of events.
2357 * If event->ctx is a cloned context, callers must make sure that
2358 * every task struct that event->ctx->task could possibly point to
2359 * remains valid. This is OK when called from perf_release since
2360 * that only calls us on the top-level context, which can't be a clone.
2361 * When called from perf_event_exit_task, it's OK because the
2362 * context has been detached from its task.
2364 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2366 struct perf_event_context *ctx = event->ctx;
2368 lockdep_assert_held(&ctx->mutex);
2370 event_function_call(event, __perf_remove_from_context, (void *)flags);
2373 * The above event_function_call() can NO-OP when it hits
2374 * TASK_TOMBSTONE. In that case we must already have been detached
2375 * from the context (by perf_event_exit_event()) but the grouping
2376 * might still be in-tact.
2378 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2379 if ((flags & DETACH_GROUP) &&
2380 (event->attach_state & PERF_ATTACH_GROUP)) {
2382 * Since in that case we cannot possibly be scheduled, simply
2385 raw_spin_lock_irq(&ctx->lock);
2386 perf_group_detach(event);
2387 raw_spin_unlock_irq(&ctx->lock);
2392 * Cross CPU call to disable a performance event
2394 static void __perf_event_disable(struct perf_event *event,
2395 struct perf_cpu_context *cpuctx,
2396 struct perf_event_context *ctx,
2399 if (event->state < PERF_EVENT_STATE_INACTIVE)
2402 if (ctx->is_active & EVENT_TIME) {
2403 update_context_time(ctx);
2404 update_cgrp_time_from_event(event);
2407 if (event == event->group_leader)
2408 group_sched_out(event, cpuctx, ctx);
2410 event_sched_out(event, cpuctx, ctx);
2412 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2413 perf_cgroup_event_disable(event, ctx);
2419 * If event->ctx is a cloned context, callers must make sure that
2420 * every task struct that event->ctx->task could possibly point to
2421 * remains valid. This condition is satisfied when called through
2422 * perf_event_for_each_child or perf_event_for_each because they
2423 * hold the top-level event's child_mutex, so any descendant that
2424 * goes to exit will block in perf_event_exit_event().
2426 * When called from perf_pending_event it's OK because event->ctx
2427 * is the current context on this CPU and preemption is disabled,
2428 * hence we can't get into perf_event_task_sched_out for this context.
2430 static void _perf_event_disable(struct perf_event *event)
2432 struct perf_event_context *ctx = event->ctx;
2434 raw_spin_lock_irq(&ctx->lock);
2435 if (event->state <= PERF_EVENT_STATE_OFF) {
2436 raw_spin_unlock_irq(&ctx->lock);
2439 raw_spin_unlock_irq(&ctx->lock);
2441 event_function_call(event, __perf_event_disable, NULL);
2444 void perf_event_disable_local(struct perf_event *event)
2446 event_function_local(event, __perf_event_disable, NULL);
2450 * Strictly speaking kernel users cannot create groups and therefore this
2451 * interface does not need the perf_event_ctx_lock() magic.
2453 void perf_event_disable(struct perf_event *event)
2455 struct perf_event_context *ctx;
2457 ctx = perf_event_ctx_lock(event);
2458 _perf_event_disable(event);
2459 perf_event_ctx_unlock(event, ctx);
2461 EXPORT_SYMBOL_GPL(perf_event_disable);
2463 void perf_event_disable_inatomic(struct perf_event *event)
2465 WRITE_ONCE(event->pending_disable, smp_processor_id());
2466 /* can fail, see perf_pending_event_disable() */
2467 irq_work_queue(&event->pending);
2470 static void perf_set_shadow_time(struct perf_event *event,
2471 struct perf_event_context *ctx)
2474 * use the correct time source for the time snapshot
2476 * We could get by without this by leveraging the
2477 * fact that to get to this function, the caller
2478 * has most likely already called update_context_time()
2479 * and update_cgrp_time_xx() and thus both timestamp
2480 * are identical (or very close). Given that tstamp is,
2481 * already adjusted for cgroup, we could say that:
2482 * tstamp - ctx->timestamp
2484 * tstamp - cgrp->timestamp.
2486 * Then, in perf_output_read(), the calculation would
2487 * work with no changes because:
2488 * - event is guaranteed scheduled in
2489 * - no scheduled out in between
2490 * - thus the timestamp would be the same
2492 * But this is a bit hairy.
2494 * So instead, we have an explicit cgroup call to remain
2495 * within the time time source all along. We believe it
2496 * is cleaner and simpler to understand.
2498 if (is_cgroup_event(event))
2499 perf_cgroup_set_shadow_time(event, event->tstamp);
2501 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2504 #define MAX_INTERRUPTS (~0ULL)
2506 static void perf_log_throttle(struct perf_event *event, int enable);
2507 static void perf_log_itrace_start(struct perf_event *event);
2510 event_sched_in(struct perf_event *event,
2511 struct perf_cpu_context *cpuctx,
2512 struct perf_event_context *ctx)
2516 WARN_ON_ONCE(event->ctx != ctx);
2518 lockdep_assert_held(&ctx->lock);
2520 if (event->state <= PERF_EVENT_STATE_OFF)
2523 WRITE_ONCE(event->oncpu, smp_processor_id());
2525 * Order event::oncpu write to happen before the ACTIVE state is
2526 * visible. This allows perf_event_{stop,read}() to observe the correct
2527 * ->oncpu if it sees ACTIVE.
2530 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2533 * Unthrottle events, since we scheduled we might have missed several
2534 * ticks already, also for a heavily scheduling task there is little
2535 * guarantee it'll get a tick in a timely manner.
2537 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2538 perf_log_throttle(event, 1);
2539 event->hw.interrupts = 0;
2542 perf_pmu_disable(event->pmu);
2544 perf_set_shadow_time(event, ctx);
2546 perf_log_itrace_start(event);
2548 if (event->pmu->add(event, PERF_EF_START)) {
2549 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2555 if (!is_software_event(event))
2556 cpuctx->active_oncpu++;
2557 if (!ctx->nr_active++)
2558 perf_event_ctx_activate(ctx);
2559 if (event->attr.freq && event->attr.sample_freq)
2562 if (event->attr.exclusive)
2563 cpuctx->exclusive = 1;
2566 perf_pmu_enable(event->pmu);
2572 group_sched_in(struct perf_event *group_event,
2573 struct perf_cpu_context *cpuctx,
2574 struct perf_event_context *ctx)
2576 struct perf_event *event, *partial_group = NULL;
2577 struct pmu *pmu = ctx->pmu;
2579 if (group_event->state == PERF_EVENT_STATE_OFF)
2582 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2584 if (event_sched_in(group_event, cpuctx, ctx))
2588 * Schedule in siblings as one group (if any):
2590 for_each_sibling_event(event, group_event) {
2591 if (event_sched_in(event, cpuctx, ctx)) {
2592 partial_group = event;
2597 if (!pmu->commit_txn(pmu))
2602 * Groups can be scheduled in as one unit only, so undo any
2603 * partial group before returning:
2604 * The events up to the failed event are scheduled out normally.
2606 for_each_sibling_event(event, group_event) {
2607 if (event == partial_group)
2610 event_sched_out(event, cpuctx, ctx);
2612 event_sched_out(group_event, cpuctx, ctx);
2615 pmu->cancel_txn(pmu);
2620 * Work out whether we can put this event group on the CPU now.
2622 static int group_can_go_on(struct perf_event *event,
2623 struct perf_cpu_context *cpuctx,
2627 * Groups consisting entirely of software events can always go on.
2629 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2632 * If an exclusive group is already on, no other hardware
2635 if (cpuctx->exclusive)
2638 * If this group is exclusive and there are already
2639 * events on the CPU, it can't go on.
2641 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2644 * Otherwise, try to add it if all previous groups were able
2650 static void add_event_to_ctx(struct perf_event *event,
2651 struct perf_event_context *ctx)
2653 list_add_event(event, ctx);
2654 perf_group_attach(event);
2657 static void ctx_sched_out(struct perf_event_context *ctx,
2658 struct perf_cpu_context *cpuctx,
2659 enum event_type_t event_type);
2661 ctx_sched_in(struct perf_event_context *ctx,
2662 struct perf_cpu_context *cpuctx,
2663 enum event_type_t event_type,
2664 struct task_struct *task);
2666 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2667 struct perf_event_context *ctx,
2668 enum event_type_t event_type)
2670 if (!cpuctx->task_ctx)
2673 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2676 ctx_sched_out(ctx, cpuctx, event_type);
2679 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2680 struct perf_event_context *ctx,
2681 struct task_struct *task)
2683 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2685 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2686 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2688 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2692 * We want to maintain the following priority of scheduling:
2693 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2694 * - task pinned (EVENT_PINNED)
2695 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2696 * - task flexible (EVENT_FLEXIBLE).
2698 * In order to avoid unscheduling and scheduling back in everything every
2699 * time an event is added, only do it for the groups of equal priority and
2702 * This can be called after a batch operation on task events, in which case
2703 * event_type is a bit mask of the types of events involved. For CPU events,
2704 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2706 static void ctx_resched(struct perf_cpu_context *cpuctx,
2707 struct perf_event_context *task_ctx,
2708 enum event_type_t event_type)
2710 enum event_type_t ctx_event_type;
2711 bool cpu_event = !!(event_type & EVENT_CPU);
2714 * If pinned groups are involved, flexible groups also need to be
2717 if (event_type & EVENT_PINNED)
2718 event_type |= EVENT_FLEXIBLE;
2720 ctx_event_type = event_type & EVENT_ALL;
2722 perf_pmu_disable(cpuctx->ctx.pmu);
2724 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2727 * Decide which cpu ctx groups to schedule out based on the types
2728 * of events that caused rescheduling:
2729 * - EVENT_CPU: schedule out corresponding groups;
2730 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2731 * - otherwise, do nothing more.
2734 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2735 else if (ctx_event_type & EVENT_PINNED)
2736 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2738 perf_event_sched_in(cpuctx, task_ctx, current);
2739 perf_pmu_enable(cpuctx->ctx.pmu);
2742 void perf_pmu_resched(struct pmu *pmu)
2744 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2745 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2747 perf_ctx_lock(cpuctx, task_ctx);
2748 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2749 perf_ctx_unlock(cpuctx, task_ctx);
2753 * Cross CPU call to install and enable a performance event
2755 * Very similar to remote_function() + event_function() but cannot assume that
2756 * things like ctx->is_active and cpuctx->task_ctx are set.
2758 static int __perf_install_in_context(void *info)
2760 struct perf_event *event = info;
2761 struct perf_event_context *ctx = event->ctx;
2762 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2763 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2764 bool reprogram = true;
2767 raw_spin_lock(&cpuctx->ctx.lock);
2769 raw_spin_lock(&ctx->lock);
2772 reprogram = (ctx->task == current);
2775 * If the task is running, it must be running on this CPU,
2776 * otherwise we cannot reprogram things.
2778 * If its not running, we don't care, ctx->lock will
2779 * serialize against it becoming runnable.
2781 if (task_curr(ctx->task) && !reprogram) {
2786 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2787 } else if (task_ctx) {
2788 raw_spin_lock(&task_ctx->lock);
2791 #ifdef CONFIG_CGROUP_PERF
2792 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2794 * If the current cgroup doesn't match the event's
2795 * cgroup, we should not try to schedule it.
2797 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2798 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2799 event->cgrp->css.cgroup);
2804 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2805 add_event_to_ctx(event, ctx);
2806 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2808 add_event_to_ctx(event, ctx);
2812 perf_ctx_unlock(cpuctx, task_ctx);
2817 static bool exclusive_event_installable(struct perf_event *event,
2818 struct perf_event_context *ctx);
2821 * Attach a performance event to a context.
2823 * Very similar to event_function_call, see comment there.
2826 perf_install_in_context(struct perf_event_context *ctx,
2827 struct perf_event *event,
2830 struct task_struct *task = READ_ONCE(ctx->task);
2832 lockdep_assert_held(&ctx->mutex);
2834 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2836 if (event->cpu != -1)
2840 * Ensures that if we can observe event->ctx, both the event and ctx
2841 * will be 'complete'. See perf_iterate_sb_cpu().
2843 smp_store_release(&event->ctx, ctx);
2846 * perf_event_attr::disabled events will not run and can be initialized
2847 * without IPI. Except when this is the first event for the context, in
2848 * that case we need the magic of the IPI to set ctx->is_active.
2850 * The IOC_ENABLE that is sure to follow the creation of a disabled
2851 * event will issue the IPI and reprogram the hardware.
2853 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2854 raw_spin_lock_irq(&ctx->lock);
2855 if (ctx->task == TASK_TOMBSTONE) {
2856 raw_spin_unlock_irq(&ctx->lock);
2859 add_event_to_ctx(event, ctx);
2860 raw_spin_unlock_irq(&ctx->lock);
2865 cpu_function_call(cpu, __perf_install_in_context, event);
2870 * Should not happen, we validate the ctx is still alive before calling.
2872 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2876 * Installing events is tricky because we cannot rely on ctx->is_active
2877 * to be set in case this is the nr_events 0 -> 1 transition.
2879 * Instead we use task_curr(), which tells us if the task is running.
2880 * However, since we use task_curr() outside of rq::lock, we can race
2881 * against the actual state. This means the result can be wrong.
2883 * If we get a false positive, we retry, this is harmless.
2885 * If we get a false negative, things are complicated. If we are after
2886 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2887 * value must be correct. If we're before, it doesn't matter since
2888 * perf_event_context_sched_in() will program the counter.
2890 * However, this hinges on the remote context switch having observed
2891 * our task->perf_event_ctxp[] store, such that it will in fact take
2892 * ctx::lock in perf_event_context_sched_in().
2894 * We do this by task_function_call(), if the IPI fails to hit the task
2895 * we know any future context switch of task must see the
2896 * perf_event_ctpx[] store.
2900 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2901 * task_cpu() load, such that if the IPI then does not find the task
2902 * running, a future context switch of that task must observe the
2907 if (!task_function_call(task, __perf_install_in_context, event))
2910 raw_spin_lock_irq(&ctx->lock);
2912 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2914 * Cannot happen because we already checked above (which also
2915 * cannot happen), and we hold ctx->mutex, which serializes us
2916 * against perf_event_exit_task_context().
2918 raw_spin_unlock_irq(&ctx->lock);
2922 * If the task is not running, ctx->lock will avoid it becoming so,
2923 * thus we can safely install the event.
2925 if (task_curr(task)) {
2926 raw_spin_unlock_irq(&ctx->lock);
2929 add_event_to_ctx(event, ctx);
2930 raw_spin_unlock_irq(&ctx->lock);
2934 * Cross CPU call to enable a performance event
2936 static void __perf_event_enable(struct perf_event *event,
2937 struct perf_cpu_context *cpuctx,
2938 struct perf_event_context *ctx,
2941 struct perf_event *leader = event->group_leader;
2942 struct perf_event_context *task_ctx;
2944 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2945 event->state <= PERF_EVENT_STATE_ERROR)
2949 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2951 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2952 perf_cgroup_event_enable(event, ctx);
2954 if (!ctx->is_active)
2957 if (!event_filter_match(event)) {
2958 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2963 * If the event is in a group and isn't the group leader,
2964 * then don't put it on unless the group is on.
2966 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2967 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2971 task_ctx = cpuctx->task_ctx;
2973 WARN_ON_ONCE(task_ctx != ctx);
2975 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2981 * If event->ctx is a cloned context, callers must make sure that
2982 * every task struct that event->ctx->task could possibly point to
2983 * remains valid. This condition is satisfied when called through
2984 * perf_event_for_each_child or perf_event_for_each as described
2985 * for perf_event_disable.
2987 static void _perf_event_enable(struct perf_event *event)
2989 struct perf_event_context *ctx = event->ctx;
2991 raw_spin_lock_irq(&ctx->lock);
2992 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2993 event->state < PERF_EVENT_STATE_ERROR) {
2995 raw_spin_unlock_irq(&ctx->lock);
3000 * If the event is in error state, clear that first.
3002 * That way, if we see the event in error state below, we know that it
3003 * has gone back into error state, as distinct from the task having
3004 * been scheduled away before the cross-call arrived.
3006 if (event->state == PERF_EVENT_STATE_ERROR) {
3008 * Detached SIBLING events cannot leave ERROR state.
3010 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3011 event->group_leader == event)
3014 event->state = PERF_EVENT_STATE_OFF;
3016 raw_spin_unlock_irq(&ctx->lock);
3018 event_function_call(event, __perf_event_enable, NULL);
3022 * See perf_event_disable();
3024 void perf_event_enable(struct perf_event *event)
3026 struct perf_event_context *ctx;
3028 ctx = perf_event_ctx_lock(event);
3029 _perf_event_enable(event);
3030 perf_event_ctx_unlock(event, ctx);
3032 EXPORT_SYMBOL_GPL(perf_event_enable);
3034 struct stop_event_data {
3035 struct perf_event *event;
3036 unsigned int restart;
3039 static int __perf_event_stop(void *info)
3041 struct stop_event_data *sd = info;
3042 struct perf_event *event = sd->event;
3044 /* if it's already INACTIVE, do nothing */
3045 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3048 /* matches smp_wmb() in event_sched_in() */
3052 * There is a window with interrupts enabled before we get here,
3053 * so we need to check again lest we try to stop another CPU's event.
3055 if (READ_ONCE(event->oncpu) != smp_processor_id())
3058 event->pmu->stop(event, PERF_EF_UPDATE);
3061 * May race with the actual stop (through perf_pmu_output_stop()),
3062 * but it is only used for events with AUX ring buffer, and such
3063 * events will refuse to restart because of rb::aux_mmap_count==0,
3064 * see comments in perf_aux_output_begin().
3066 * Since this is happening on an event-local CPU, no trace is lost
3070 event->pmu->start(event, 0);
3075 static int perf_event_stop(struct perf_event *event, int restart)
3077 struct stop_event_data sd = {
3084 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3087 /* matches smp_wmb() in event_sched_in() */
3091 * We only want to restart ACTIVE events, so if the event goes
3092 * inactive here (event->oncpu==-1), there's nothing more to do;
3093 * fall through with ret==-ENXIO.
3095 ret = cpu_function_call(READ_ONCE(event->oncpu),
3096 __perf_event_stop, &sd);
3097 } while (ret == -EAGAIN);
3103 * In order to contain the amount of racy and tricky in the address filter
3104 * configuration management, it is a two part process:
3106 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3107 * we update the addresses of corresponding vmas in
3108 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3109 * (p2) when an event is scheduled in (pmu::add), it calls
3110 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3111 * if the generation has changed since the previous call.
3113 * If (p1) happens while the event is active, we restart it to force (p2).
3115 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3116 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3118 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3119 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3121 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3124 void perf_event_addr_filters_sync(struct perf_event *event)
3126 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3128 if (!has_addr_filter(event))
3131 raw_spin_lock(&ifh->lock);
3132 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3133 event->pmu->addr_filters_sync(event);
3134 event->hw.addr_filters_gen = event->addr_filters_gen;
3136 raw_spin_unlock(&ifh->lock);
3138 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3140 static int _perf_event_refresh(struct perf_event *event, int refresh)
3143 * not supported on inherited events
3145 if (event->attr.inherit || !is_sampling_event(event))
3148 atomic_add(refresh, &event->event_limit);
3149 _perf_event_enable(event);
3155 * See perf_event_disable()
3157 int perf_event_refresh(struct perf_event *event, int refresh)
3159 struct perf_event_context *ctx;
3162 ctx = perf_event_ctx_lock(event);
3163 ret = _perf_event_refresh(event, refresh);
3164 perf_event_ctx_unlock(event, ctx);
3168 EXPORT_SYMBOL_GPL(perf_event_refresh);
3170 static int perf_event_modify_breakpoint(struct perf_event *bp,
3171 struct perf_event_attr *attr)
3175 _perf_event_disable(bp);
3177 err = modify_user_hw_breakpoint_check(bp, attr, true);
3179 if (!bp->attr.disabled)
3180 _perf_event_enable(bp);
3185 static int perf_event_modify_attr(struct perf_event *event,
3186 struct perf_event_attr *attr)
3188 if (event->attr.type != attr->type)
3191 switch (event->attr.type) {
3192 case PERF_TYPE_BREAKPOINT:
3193 return perf_event_modify_breakpoint(event, attr);
3195 /* Place holder for future additions. */
3200 static void ctx_sched_out(struct perf_event_context *ctx,
3201 struct perf_cpu_context *cpuctx,
3202 enum event_type_t event_type)
3204 struct perf_event *event, *tmp;
3205 int is_active = ctx->is_active;
3207 lockdep_assert_held(&ctx->lock);
3209 if (likely(!ctx->nr_events)) {
3211 * See __perf_remove_from_context().
3213 WARN_ON_ONCE(ctx->is_active);
3215 WARN_ON_ONCE(cpuctx->task_ctx);
3219 ctx->is_active &= ~event_type;
3220 if (!(ctx->is_active & EVENT_ALL))
3224 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3225 if (!ctx->is_active)
3226 cpuctx->task_ctx = NULL;
3230 * Always update time if it was set; not only when it changes.
3231 * Otherwise we can 'forget' to update time for any but the last
3232 * context we sched out. For example:
3234 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3235 * ctx_sched_out(.event_type = EVENT_PINNED)
3237 * would only update time for the pinned events.
3239 if (is_active & EVENT_TIME) {
3240 /* update (and stop) ctx time */
3241 update_context_time(ctx);
3242 update_cgrp_time_from_cpuctx(cpuctx);
3245 is_active ^= ctx->is_active; /* changed bits */
3247 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3250 perf_pmu_disable(ctx->pmu);
3251 if (is_active & EVENT_PINNED) {
3252 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3253 group_sched_out(event, cpuctx, ctx);
3256 if (is_active & EVENT_FLEXIBLE) {
3257 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3258 group_sched_out(event, cpuctx, ctx);
3261 * Since we cleared EVENT_FLEXIBLE, also clear
3262 * rotate_necessary, is will be reset by
3263 * ctx_flexible_sched_in() when needed.
3265 ctx->rotate_necessary = 0;
3267 perf_pmu_enable(ctx->pmu);
3271 * Test whether two contexts are equivalent, i.e. whether they have both been
3272 * cloned from the same version of the same context.
3274 * Equivalence is measured using a generation number in the context that is
3275 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3276 * and list_del_event().
3278 static int context_equiv(struct perf_event_context *ctx1,
3279 struct perf_event_context *ctx2)
3281 lockdep_assert_held(&ctx1->lock);
3282 lockdep_assert_held(&ctx2->lock);
3284 /* Pinning disables the swap optimization */
3285 if (ctx1->pin_count || ctx2->pin_count)
3288 /* If ctx1 is the parent of ctx2 */
3289 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3292 /* If ctx2 is the parent of ctx1 */
3293 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3297 * If ctx1 and ctx2 have the same parent; we flatten the parent
3298 * hierarchy, see perf_event_init_context().
3300 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3301 ctx1->parent_gen == ctx2->parent_gen)
3308 static void __perf_event_sync_stat(struct perf_event *event,
3309 struct perf_event *next_event)
3313 if (!event->attr.inherit_stat)
3317 * Update the event value, we cannot use perf_event_read()
3318 * because we're in the middle of a context switch and have IRQs
3319 * disabled, which upsets smp_call_function_single(), however
3320 * we know the event must be on the current CPU, therefore we
3321 * don't need to use it.
3323 if (event->state == PERF_EVENT_STATE_ACTIVE)
3324 event->pmu->read(event);
3326 perf_event_update_time(event);
3329 * In order to keep per-task stats reliable we need to flip the event
3330 * values when we flip the contexts.
3332 value = local64_read(&next_event->count);
3333 value = local64_xchg(&event->count, value);
3334 local64_set(&next_event->count, value);
3336 swap(event->total_time_enabled, next_event->total_time_enabled);
3337 swap(event->total_time_running, next_event->total_time_running);
3340 * Since we swizzled the values, update the user visible data too.
3342 perf_event_update_userpage(event);
3343 perf_event_update_userpage(next_event);
3346 static void perf_event_sync_stat(struct perf_event_context *ctx,
3347 struct perf_event_context *next_ctx)
3349 struct perf_event *event, *next_event;
3354 update_context_time(ctx);
3356 event = list_first_entry(&ctx->event_list,
3357 struct perf_event, event_entry);
3359 next_event = list_first_entry(&next_ctx->event_list,
3360 struct perf_event, event_entry);
3362 while (&event->event_entry != &ctx->event_list &&
3363 &next_event->event_entry != &next_ctx->event_list) {
3365 __perf_event_sync_stat(event, next_event);
3367 event = list_next_entry(event, event_entry);
3368 next_event = list_next_entry(next_event, event_entry);
3372 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3373 struct task_struct *next)
3375 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3376 struct perf_event_context *next_ctx;
3377 struct perf_event_context *parent, *next_parent;
3378 struct perf_cpu_context *cpuctx;
3386 cpuctx = __get_cpu_context(ctx);
3387 if (!cpuctx->task_ctx)
3391 next_ctx = next->perf_event_ctxp[ctxn];
3395 parent = rcu_dereference(ctx->parent_ctx);
3396 next_parent = rcu_dereference(next_ctx->parent_ctx);
3398 /* If neither context have a parent context; they cannot be clones. */
3399 if (!parent && !next_parent)
3402 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3404 * Looks like the two contexts are clones, so we might be
3405 * able to optimize the context switch. We lock both
3406 * contexts and check that they are clones under the
3407 * lock (including re-checking that neither has been
3408 * uncloned in the meantime). It doesn't matter which
3409 * order we take the locks because no other cpu could
3410 * be trying to lock both of these tasks.
3412 raw_spin_lock(&ctx->lock);
3413 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3414 if (context_equiv(ctx, next_ctx)) {
3416 WRITE_ONCE(ctx->task, next);
3417 WRITE_ONCE(next_ctx->task, task);
3419 perf_pmu_disable(pmu);
3421 if (cpuctx->sched_cb_usage && pmu->sched_task)
3422 pmu->sched_task(ctx, false);
3425 * PMU specific parts of task perf context can require
3426 * additional synchronization. As an example of such
3427 * synchronization see implementation details of Intel
3428 * LBR call stack data profiling;
3430 if (pmu->swap_task_ctx)
3431 pmu->swap_task_ctx(ctx, next_ctx);
3433 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3435 perf_pmu_enable(pmu);
3438 * RCU_INIT_POINTER here is safe because we've not
3439 * modified the ctx and the above modification of
3440 * ctx->task and ctx->task_ctx_data are immaterial
3441 * since those values are always verified under
3442 * ctx->lock which we're now holding.
3444 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3445 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3449 perf_event_sync_stat(ctx, next_ctx);
3451 raw_spin_unlock(&next_ctx->lock);
3452 raw_spin_unlock(&ctx->lock);
3458 raw_spin_lock(&ctx->lock);
3459 perf_pmu_disable(pmu);
3461 if (cpuctx->sched_cb_usage && pmu->sched_task)
3462 pmu->sched_task(ctx, false);
3463 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3465 perf_pmu_enable(pmu);
3466 raw_spin_unlock(&ctx->lock);
3470 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3472 void perf_sched_cb_dec(struct pmu *pmu)
3474 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3476 this_cpu_dec(perf_sched_cb_usages);
3478 if (!--cpuctx->sched_cb_usage)
3479 list_del(&cpuctx->sched_cb_entry);
3483 void perf_sched_cb_inc(struct pmu *pmu)
3485 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3487 if (!cpuctx->sched_cb_usage++)
3488 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3490 this_cpu_inc(perf_sched_cb_usages);
3494 * This function provides the context switch callback to the lower code
3495 * layer. It is invoked ONLY when the context switch callback is enabled.
3497 * This callback is relevant even to per-cpu events; for example multi event
3498 * PEBS requires this to provide PID/TID information. This requires we flush
3499 * all queued PEBS records before we context switch to a new task.
3501 static void __perf_pmu_sched_task(struct perf_cpu_context *cpuctx, bool sched_in)
3505 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3507 if (WARN_ON_ONCE(!pmu->sched_task))
3510 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3511 perf_pmu_disable(pmu);
3513 pmu->sched_task(cpuctx->task_ctx, sched_in);
3515 perf_pmu_enable(pmu);
3516 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3519 static void perf_pmu_sched_task(struct task_struct *prev,
3520 struct task_struct *next,
3523 struct perf_cpu_context *cpuctx;
3528 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3529 /* will be handled in perf_event_context_sched_in/out */
3530 if (cpuctx->task_ctx)
3533 __perf_pmu_sched_task(cpuctx, sched_in);
3537 static void perf_event_switch(struct task_struct *task,
3538 struct task_struct *next_prev, bool sched_in);
3540 #define for_each_task_context_nr(ctxn) \
3541 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3544 * Called from scheduler to remove the events of the current task,
3545 * with interrupts disabled.
3547 * We stop each event and update the event value in event->count.
3549 * This does not protect us against NMI, but disable()
3550 * sets the disabled bit in the control field of event _before_
3551 * accessing the event control register. If a NMI hits, then it will
3552 * not restart the event.
3554 void __perf_event_task_sched_out(struct task_struct *task,
3555 struct task_struct *next)
3559 if (__this_cpu_read(perf_sched_cb_usages))
3560 perf_pmu_sched_task(task, next, false);
3562 if (atomic_read(&nr_switch_events))
3563 perf_event_switch(task, next, false);
3565 for_each_task_context_nr(ctxn)
3566 perf_event_context_sched_out(task, ctxn, next);
3569 * if cgroup events exist on this CPU, then we need
3570 * to check if we have to switch out PMU state.
3571 * cgroup event are system-wide mode only
3573 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3574 perf_cgroup_sched_out(task, next);
3578 * Called with IRQs disabled
3580 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3581 enum event_type_t event_type)
3583 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3586 static bool perf_less_group_idx(const void *l, const void *r)
3588 const struct perf_event *le = *(const struct perf_event **)l;
3589 const struct perf_event *re = *(const struct perf_event **)r;
3591 return le->group_index < re->group_index;
3594 static void swap_ptr(void *l, void *r)
3596 void **lp = l, **rp = r;
3601 static const struct min_heap_callbacks perf_min_heap = {
3602 .elem_size = sizeof(struct perf_event *),
3603 .less = perf_less_group_idx,
3607 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3609 struct perf_event **itrs = heap->data;
3612 itrs[heap->nr] = event;
3617 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3618 struct perf_event_groups *groups, int cpu,
3619 int (*func)(struct perf_event *, void *),
3622 #ifdef CONFIG_CGROUP_PERF
3623 struct cgroup_subsys_state *css = NULL;
3625 /* Space for per CPU and/or any CPU event iterators. */
3626 struct perf_event *itrs[2];
3627 struct min_heap event_heap;
3628 struct perf_event **evt;
3632 event_heap = (struct min_heap){
3633 .data = cpuctx->heap,
3635 .size = cpuctx->heap_size,
3638 lockdep_assert_held(&cpuctx->ctx.lock);
3640 #ifdef CONFIG_CGROUP_PERF
3642 css = &cpuctx->cgrp->css;
3645 event_heap = (struct min_heap){
3648 .size = ARRAY_SIZE(itrs),
3650 /* Events not within a CPU context may be on any CPU. */
3651 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
3653 evt = event_heap.data;
3655 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3657 #ifdef CONFIG_CGROUP_PERF
3658 for (; css; css = css->parent)
3659 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3662 min_heapify_all(&event_heap, &perf_min_heap);
3664 while (event_heap.nr) {
3665 ret = func(*evt, data);
3669 *evt = perf_event_groups_next(*evt);
3671 min_heapify(&event_heap, 0, &perf_min_heap);
3673 min_heap_pop(&event_heap, &perf_min_heap);
3679 static inline bool event_update_userpage(struct perf_event *event)
3681 if (likely(!atomic_read(&event->mmap_count)))
3684 perf_event_update_time(event);
3685 perf_set_shadow_time(event, event->ctx);
3686 perf_event_update_userpage(event);
3691 static inline void group_update_userpage(struct perf_event *group_event)
3693 struct perf_event *event;
3695 if (!event_update_userpage(group_event))
3698 for_each_sibling_event(event, group_event)
3699 event_update_userpage(event);
3702 static int merge_sched_in(struct perf_event *event, void *data)
3704 struct perf_event_context *ctx = event->ctx;
3705 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3706 int *can_add_hw = data;
3708 if (event->state <= PERF_EVENT_STATE_OFF)
3711 if (!event_filter_match(event))
3714 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3715 if (!group_sched_in(event, cpuctx, ctx))
3716 list_add_tail(&event->active_list, get_event_list(event));
3719 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3721 if (event->attr.pinned) {
3722 perf_cgroup_event_disable(event, ctx);
3723 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3725 ctx->rotate_necessary = 1;
3726 perf_mux_hrtimer_restart(cpuctx);
3727 group_update_userpage(event);
3735 ctx_pinned_sched_in(struct perf_event_context *ctx,
3736 struct perf_cpu_context *cpuctx)
3740 if (ctx != &cpuctx->ctx)
3743 visit_groups_merge(cpuctx, &ctx->pinned_groups,
3745 merge_sched_in, &can_add_hw);
3749 ctx_flexible_sched_in(struct perf_event_context *ctx,
3750 struct perf_cpu_context *cpuctx)
3754 if (ctx != &cpuctx->ctx)
3757 visit_groups_merge(cpuctx, &ctx->flexible_groups,
3759 merge_sched_in, &can_add_hw);
3763 ctx_sched_in(struct perf_event_context *ctx,
3764 struct perf_cpu_context *cpuctx,
3765 enum event_type_t event_type,
3766 struct task_struct *task)
3768 int is_active = ctx->is_active;
3771 lockdep_assert_held(&ctx->lock);
3773 if (likely(!ctx->nr_events))
3776 ctx->is_active |= (event_type | EVENT_TIME);
3779 cpuctx->task_ctx = ctx;
3781 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3784 is_active ^= ctx->is_active; /* changed bits */
3786 if (is_active & EVENT_TIME) {
3787 /* start ctx time */
3789 ctx->timestamp = now;
3790 perf_cgroup_set_timestamp(task, ctx);
3794 * First go through the list and put on any pinned groups
3795 * in order to give them the best chance of going on.
3797 if (is_active & EVENT_PINNED)
3798 ctx_pinned_sched_in(ctx, cpuctx);
3800 /* Then walk through the lower prio flexible groups */
3801 if (is_active & EVENT_FLEXIBLE)
3802 ctx_flexible_sched_in(ctx, cpuctx);
3805 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3806 enum event_type_t event_type,
3807 struct task_struct *task)
3809 struct perf_event_context *ctx = &cpuctx->ctx;
3811 ctx_sched_in(ctx, cpuctx, event_type, task);
3814 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3815 struct task_struct *task)
3817 struct perf_cpu_context *cpuctx;
3818 struct pmu *pmu = ctx->pmu;
3820 cpuctx = __get_cpu_context(ctx);
3821 if (cpuctx->task_ctx == ctx) {
3822 if (cpuctx->sched_cb_usage)
3823 __perf_pmu_sched_task(cpuctx, true);
3827 perf_ctx_lock(cpuctx, ctx);
3829 * We must check ctx->nr_events while holding ctx->lock, such
3830 * that we serialize against perf_install_in_context().
3832 if (!ctx->nr_events)
3835 perf_pmu_disable(pmu);
3837 * We want to keep the following priority order:
3838 * cpu pinned (that don't need to move), task pinned,
3839 * cpu flexible, task flexible.
3841 * However, if task's ctx is not carrying any pinned
3842 * events, no need to flip the cpuctx's events around.
3844 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3845 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3846 perf_event_sched_in(cpuctx, ctx, task);
3848 if (cpuctx->sched_cb_usage && pmu->sched_task)
3849 pmu->sched_task(cpuctx->task_ctx, true);
3851 perf_pmu_enable(pmu);
3854 perf_ctx_unlock(cpuctx, ctx);
3858 * Called from scheduler to add the events of the current task
3859 * with interrupts disabled.
3861 * We restore the event value and then enable it.
3863 * This does not protect us against NMI, but enable()
3864 * sets the enabled bit in the control field of event _before_
3865 * accessing the event control register. If a NMI hits, then it will
3866 * keep the event running.
3868 void __perf_event_task_sched_in(struct task_struct *prev,
3869 struct task_struct *task)
3871 struct perf_event_context *ctx;
3875 * If cgroup events exist on this CPU, then we need to check if we have
3876 * to switch in PMU state; cgroup event are system-wide mode only.
3878 * Since cgroup events are CPU events, we must schedule these in before
3879 * we schedule in the task events.
3881 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3882 perf_cgroup_sched_in(prev, task);
3884 for_each_task_context_nr(ctxn) {
3885 ctx = task->perf_event_ctxp[ctxn];
3889 perf_event_context_sched_in(ctx, task);
3892 if (atomic_read(&nr_switch_events))
3893 perf_event_switch(task, prev, true);
3895 if (__this_cpu_read(perf_sched_cb_usages))
3896 perf_pmu_sched_task(prev, task, true);
3899 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3901 u64 frequency = event->attr.sample_freq;
3902 u64 sec = NSEC_PER_SEC;
3903 u64 divisor, dividend;
3905 int count_fls, nsec_fls, frequency_fls, sec_fls;
3907 count_fls = fls64(count);
3908 nsec_fls = fls64(nsec);
3909 frequency_fls = fls64(frequency);
3913 * We got @count in @nsec, with a target of sample_freq HZ
3914 * the target period becomes:
3917 * period = -------------------
3918 * @nsec * sample_freq
3923 * Reduce accuracy by one bit such that @a and @b converge
3924 * to a similar magnitude.
3926 #define REDUCE_FLS(a, b) \
3928 if (a##_fls > b##_fls) { \
3938 * Reduce accuracy until either term fits in a u64, then proceed with
3939 * the other, so that finally we can do a u64/u64 division.
3941 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3942 REDUCE_FLS(nsec, frequency);
3943 REDUCE_FLS(sec, count);
3946 if (count_fls + sec_fls > 64) {
3947 divisor = nsec * frequency;
3949 while (count_fls + sec_fls > 64) {
3950 REDUCE_FLS(count, sec);
3954 dividend = count * sec;
3956 dividend = count * sec;
3958 while (nsec_fls + frequency_fls > 64) {
3959 REDUCE_FLS(nsec, frequency);
3963 divisor = nsec * frequency;
3969 return div64_u64(dividend, divisor);
3972 static DEFINE_PER_CPU(int, perf_throttled_count);
3973 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3975 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3977 struct hw_perf_event *hwc = &event->hw;
3978 s64 period, sample_period;
3981 period = perf_calculate_period(event, nsec, count);
3983 delta = (s64)(period - hwc->sample_period);
3984 delta = (delta + 7) / 8; /* low pass filter */
3986 sample_period = hwc->sample_period + delta;
3991 hwc->sample_period = sample_period;
3993 if (local64_read(&hwc->period_left) > 8*sample_period) {
3995 event->pmu->stop(event, PERF_EF_UPDATE);
3997 local64_set(&hwc->period_left, 0);
4000 event->pmu->start(event, PERF_EF_RELOAD);
4005 * combine freq adjustment with unthrottling to avoid two passes over the
4006 * events. At the same time, make sure, having freq events does not change
4007 * the rate of unthrottling as that would introduce bias.
4009 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
4012 struct perf_event *event;
4013 struct hw_perf_event *hwc;
4014 u64 now, period = TICK_NSEC;
4018 * only need to iterate over all events iff:
4019 * - context have events in frequency mode (needs freq adjust)
4020 * - there are events to unthrottle on this cpu
4022 if (!(ctx->nr_freq || needs_unthr))
4025 raw_spin_lock(&ctx->lock);
4026 perf_pmu_disable(ctx->pmu);
4028 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4029 if (event->state != PERF_EVENT_STATE_ACTIVE)
4032 if (!event_filter_match(event))
4035 perf_pmu_disable(event->pmu);
4039 if (hwc->interrupts == MAX_INTERRUPTS) {
4040 hwc->interrupts = 0;
4041 perf_log_throttle(event, 1);
4042 event->pmu->start(event, 0);
4045 if (!event->attr.freq || !event->attr.sample_freq)
4049 * stop the event and update event->count
4051 event->pmu->stop(event, PERF_EF_UPDATE);
4053 now = local64_read(&event->count);
4054 delta = now - hwc->freq_count_stamp;
4055 hwc->freq_count_stamp = now;
4059 * reload only if value has changed
4060 * we have stopped the event so tell that
4061 * to perf_adjust_period() to avoid stopping it
4065 perf_adjust_period(event, period, delta, false);
4067 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4069 perf_pmu_enable(event->pmu);
4072 perf_pmu_enable(ctx->pmu);
4073 raw_spin_unlock(&ctx->lock);
4077 * Move @event to the tail of the @ctx's elegible events.
4079 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4082 * Rotate the first entry last of non-pinned groups. Rotation might be
4083 * disabled by the inheritance code.
4085 if (ctx->rotate_disable)
4088 perf_event_groups_delete(&ctx->flexible_groups, event);
4089 perf_event_groups_insert(&ctx->flexible_groups, event);
4092 /* pick an event from the flexible_groups to rotate */
4093 static inline struct perf_event *
4094 ctx_event_to_rotate(struct perf_event_context *ctx)
4096 struct perf_event *event;
4098 /* pick the first active flexible event */
4099 event = list_first_entry_or_null(&ctx->flexible_active,
4100 struct perf_event, active_list);
4102 /* if no active flexible event, pick the first event */
4104 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
4105 typeof(*event), group_node);
4109 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4110 * finds there are unschedulable events, it will set it again.
4112 ctx->rotate_necessary = 0;
4117 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4119 struct perf_event *cpu_event = NULL, *task_event = NULL;
4120 struct perf_event_context *task_ctx = NULL;
4121 int cpu_rotate, task_rotate;
4124 * Since we run this from IRQ context, nobody can install new
4125 * events, thus the event count values are stable.
4128 cpu_rotate = cpuctx->ctx.rotate_necessary;
4129 task_ctx = cpuctx->task_ctx;
4130 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
4132 if (!(cpu_rotate || task_rotate))
4135 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4136 perf_pmu_disable(cpuctx->ctx.pmu);
4139 task_event = ctx_event_to_rotate(task_ctx);
4141 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
4144 * As per the order given at ctx_resched() first 'pop' task flexible
4145 * and then, if needed CPU flexible.
4147 if (task_event || (task_ctx && cpu_event))
4148 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
4150 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
4153 rotate_ctx(task_ctx, task_event);
4155 rotate_ctx(&cpuctx->ctx, cpu_event);
4157 perf_event_sched_in(cpuctx, task_ctx, current);
4159 perf_pmu_enable(cpuctx->ctx.pmu);
4160 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4165 void perf_event_task_tick(void)
4167 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4168 struct perf_event_context *ctx, *tmp;
4171 lockdep_assert_irqs_disabled();
4173 __this_cpu_inc(perf_throttled_seq);
4174 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4175 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4177 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
4178 perf_adjust_freq_unthr_context(ctx, throttled);
4181 static int event_enable_on_exec(struct perf_event *event,
4182 struct perf_event_context *ctx)
4184 if (!event->attr.enable_on_exec)
4187 event->attr.enable_on_exec = 0;
4188 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4191 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4197 * Enable all of a task's events that have been marked enable-on-exec.
4198 * This expects task == current.
4200 static void perf_event_enable_on_exec(int ctxn)
4202 struct perf_event_context *ctx, *clone_ctx = NULL;
4203 enum event_type_t event_type = 0;
4204 struct perf_cpu_context *cpuctx;
4205 struct perf_event *event;
4206 unsigned long flags;
4209 local_irq_save(flags);
4210 ctx = current->perf_event_ctxp[ctxn];
4211 if (!ctx || !ctx->nr_events)
4214 cpuctx = __get_cpu_context(ctx);
4215 perf_ctx_lock(cpuctx, ctx);
4216 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
4217 list_for_each_entry(event, &ctx->event_list, event_entry) {
4218 enabled |= event_enable_on_exec(event, ctx);
4219 event_type |= get_event_type(event);
4223 * Unclone and reschedule this context if we enabled any event.
4226 clone_ctx = unclone_ctx(ctx);
4227 ctx_resched(cpuctx, ctx, event_type);
4229 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
4231 perf_ctx_unlock(cpuctx, ctx);
4234 local_irq_restore(flags);
4240 struct perf_read_data {
4241 struct perf_event *event;
4246 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4248 u16 local_pkg, event_pkg;
4250 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4251 int local_cpu = smp_processor_id();
4253 event_pkg = topology_physical_package_id(event_cpu);
4254 local_pkg = topology_physical_package_id(local_cpu);
4256 if (event_pkg == local_pkg)
4264 * Cross CPU call to read the hardware event
4266 static void __perf_event_read(void *info)
4268 struct perf_read_data *data = info;
4269 struct perf_event *sub, *event = data->event;
4270 struct perf_event_context *ctx = event->ctx;
4271 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4272 struct pmu *pmu = event->pmu;
4275 * If this is a task context, we need to check whether it is
4276 * the current task context of this cpu. If not it has been
4277 * scheduled out before the smp call arrived. In that case
4278 * event->count would have been updated to a recent sample
4279 * when the event was scheduled out.
4281 if (ctx->task && cpuctx->task_ctx != ctx)
4284 raw_spin_lock(&ctx->lock);
4285 if (ctx->is_active & EVENT_TIME) {
4286 update_context_time(ctx);
4287 update_cgrp_time_from_event(event);
4290 perf_event_update_time(event);
4292 perf_event_update_sibling_time(event);
4294 if (event->state != PERF_EVENT_STATE_ACTIVE)
4303 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4307 for_each_sibling_event(sub, event) {
4308 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4310 * Use sibling's PMU rather than @event's since
4311 * sibling could be on different (eg: software) PMU.
4313 sub->pmu->read(sub);
4317 data->ret = pmu->commit_txn(pmu);
4320 raw_spin_unlock(&ctx->lock);
4323 static inline u64 perf_event_count(struct perf_event *event)
4325 return local64_read(&event->count) + atomic64_read(&event->child_count);
4329 * NMI-safe method to read a local event, that is an event that
4331 * - either for the current task, or for this CPU
4332 * - does not have inherit set, for inherited task events
4333 * will not be local and we cannot read them atomically
4334 * - must not have a pmu::count method
4336 int perf_event_read_local(struct perf_event *event, u64 *value,
4337 u64 *enabled, u64 *running)
4339 unsigned long flags;
4343 * Disabling interrupts avoids all counter scheduling (context
4344 * switches, timer based rotation and IPIs).
4346 local_irq_save(flags);
4349 * It must not be an event with inherit set, we cannot read
4350 * all child counters from atomic context.
4352 if (event->attr.inherit) {
4357 /* If this is a per-task event, it must be for current */
4358 if ((event->attach_state & PERF_ATTACH_TASK) &&
4359 event->hw.target != current) {
4364 /* If this is a per-CPU event, it must be for this CPU */
4365 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4366 event->cpu != smp_processor_id()) {
4371 /* If this is a pinned event it must be running on this CPU */
4372 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4378 * If the event is currently on this CPU, its either a per-task event,
4379 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4382 if (event->oncpu == smp_processor_id())
4383 event->pmu->read(event);
4385 *value = local64_read(&event->count);
4386 if (enabled || running) {
4387 u64 now = event->shadow_ctx_time + perf_clock();
4388 u64 __enabled, __running;
4390 __perf_update_times(event, now, &__enabled, &__running);
4392 *enabled = __enabled;
4394 *running = __running;
4397 local_irq_restore(flags);
4402 static int perf_event_read(struct perf_event *event, bool group)
4404 enum perf_event_state state = READ_ONCE(event->state);
4405 int event_cpu, ret = 0;
4408 * If event is enabled and currently active on a CPU, update the
4409 * value in the event structure:
4412 if (state == PERF_EVENT_STATE_ACTIVE) {
4413 struct perf_read_data data;
4416 * Orders the ->state and ->oncpu loads such that if we see
4417 * ACTIVE we must also see the right ->oncpu.
4419 * Matches the smp_wmb() from event_sched_in().
4423 event_cpu = READ_ONCE(event->oncpu);
4424 if ((unsigned)event_cpu >= nr_cpu_ids)
4427 data = (struct perf_read_data){
4434 event_cpu = __perf_event_read_cpu(event, event_cpu);
4437 * Purposely ignore the smp_call_function_single() return
4440 * If event_cpu isn't a valid CPU it means the event got
4441 * scheduled out and that will have updated the event count.
4443 * Therefore, either way, we'll have an up-to-date event count
4446 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4450 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4451 struct perf_event_context *ctx = event->ctx;
4452 unsigned long flags;
4454 raw_spin_lock_irqsave(&ctx->lock, flags);
4455 state = event->state;
4456 if (state != PERF_EVENT_STATE_INACTIVE) {
4457 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4462 * May read while context is not active (e.g., thread is
4463 * blocked), in that case we cannot update context time
4465 if (ctx->is_active & EVENT_TIME) {
4466 update_context_time(ctx);
4467 update_cgrp_time_from_event(event);
4470 perf_event_update_time(event);
4472 perf_event_update_sibling_time(event);
4473 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4480 * Initialize the perf_event context in a task_struct:
4482 static void __perf_event_init_context(struct perf_event_context *ctx)
4484 raw_spin_lock_init(&ctx->lock);
4485 mutex_init(&ctx->mutex);
4486 INIT_LIST_HEAD(&ctx->active_ctx_list);
4487 perf_event_groups_init(&ctx->pinned_groups);
4488 perf_event_groups_init(&ctx->flexible_groups);
4489 INIT_LIST_HEAD(&ctx->event_list);
4490 INIT_LIST_HEAD(&ctx->pinned_active);
4491 INIT_LIST_HEAD(&ctx->flexible_active);
4492 refcount_set(&ctx->refcount, 1);
4495 static struct perf_event_context *
4496 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4498 struct perf_event_context *ctx;
4500 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4504 __perf_event_init_context(ctx);
4506 ctx->task = get_task_struct(task);
4512 static struct task_struct *
4513 find_lively_task_by_vpid(pid_t vpid)
4515 struct task_struct *task;
4521 task = find_task_by_vpid(vpid);
4523 get_task_struct(task);
4527 return ERR_PTR(-ESRCH);
4533 * Returns a matching context with refcount and pincount.
4535 static struct perf_event_context *
4536 find_get_context(struct pmu *pmu, struct task_struct *task,
4537 struct perf_event *event)
4539 struct perf_event_context *ctx, *clone_ctx = NULL;
4540 struct perf_cpu_context *cpuctx;
4541 void *task_ctx_data = NULL;
4542 unsigned long flags;
4544 int cpu = event->cpu;
4547 /* Must be root to operate on a CPU event: */
4548 err = perf_allow_cpu(&event->attr);
4550 return ERR_PTR(err);
4552 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4555 raw_spin_lock_irqsave(&ctx->lock, flags);
4557 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4563 ctxn = pmu->task_ctx_nr;
4567 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4568 task_ctx_data = alloc_task_ctx_data(pmu);
4569 if (!task_ctx_data) {
4576 ctx = perf_lock_task_context(task, ctxn, &flags);
4578 clone_ctx = unclone_ctx(ctx);
4581 if (task_ctx_data && !ctx->task_ctx_data) {
4582 ctx->task_ctx_data = task_ctx_data;
4583 task_ctx_data = NULL;
4585 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4590 ctx = alloc_perf_context(pmu, task);
4595 if (task_ctx_data) {
4596 ctx->task_ctx_data = task_ctx_data;
4597 task_ctx_data = NULL;
4601 mutex_lock(&task->perf_event_mutex);
4603 * If it has already passed perf_event_exit_task().
4604 * we must see PF_EXITING, it takes this mutex too.
4606 if (task->flags & PF_EXITING)
4608 else if (task->perf_event_ctxp[ctxn])
4613 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4615 mutex_unlock(&task->perf_event_mutex);
4617 if (unlikely(err)) {
4626 free_task_ctx_data(pmu, task_ctx_data);
4630 free_task_ctx_data(pmu, task_ctx_data);
4631 return ERR_PTR(err);
4634 static void perf_event_free_filter(struct perf_event *event);
4635 static void perf_event_free_bpf_prog(struct perf_event *event);
4637 static void free_event_rcu(struct rcu_head *head)
4639 struct perf_event *event;
4641 event = container_of(head, struct perf_event, rcu_head);
4643 put_pid_ns(event->ns);
4644 perf_event_free_filter(event);
4648 static void ring_buffer_attach(struct perf_event *event,
4649 struct perf_buffer *rb);
4651 static void detach_sb_event(struct perf_event *event)
4653 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4655 raw_spin_lock(&pel->lock);
4656 list_del_rcu(&event->sb_list);
4657 raw_spin_unlock(&pel->lock);
4660 static bool is_sb_event(struct perf_event *event)
4662 struct perf_event_attr *attr = &event->attr;
4667 if (event->attach_state & PERF_ATTACH_TASK)
4670 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4671 attr->comm || attr->comm_exec ||
4672 attr->task || attr->ksymbol ||
4673 attr->context_switch || attr->text_poke ||
4679 static void unaccount_pmu_sb_event(struct perf_event *event)
4681 if (is_sb_event(event))
4682 detach_sb_event(event);
4685 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4690 if (is_cgroup_event(event))
4691 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4694 #ifdef CONFIG_NO_HZ_FULL
4695 static DEFINE_SPINLOCK(nr_freq_lock);
4698 static void unaccount_freq_event_nohz(void)
4700 #ifdef CONFIG_NO_HZ_FULL
4701 spin_lock(&nr_freq_lock);
4702 if (atomic_dec_and_test(&nr_freq_events))
4703 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4704 spin_unlock(&nr_freq_lock);
4708 static void unaccount_freq_event(void)
4710 if (tick_nohz_full_enabled())
4711 unaccount_freq_event_nohz();
4713 atomic_dec(&nr_freq_events);
4716 static void unaccount_event(struct perf_event *event)
4723 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
4725 if (event->attr.mmap || event->attr.mmap_data)
4726 atomic_dec(&nr_mmap_events);
4727 if (event->attr.comm)
4728 atomic_dec(&nr_comm_events);
4729 if (event->attr.namespaces)
4730 atomic_dec(&nr_namespaces_events);
4731 if (event->attr.cgroup)
4732 atomic_dec(&nr_cgroup_events);
4733 if (event->attr.task)
4734 atomic_dec(&nr_task_events);
4735 if (event->attr.freq)
4736 unaccount_freq_event();
4737 if (event->attr.context_switch) {
4739 atomic_dec(&nr_switch_events);
4741 if (is_cgroup_event(event))
4743 if (has_branch_stack(event))
4745 if (event->attr.ksymbol)
4746 atomic_dec(&nr_ksymbol_events);
4747 if (event->attr.bpf_event)
4748 atomic_dec(&nr_bpf_events);
4749 if (event->attr.text_poke)
4750 atomic_dec(&nr_text_poke_events);
4753 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4754 schedule_delayed_work(&perf_sched_work, HZ);
4757 unaccount_event_cpu(event, event->cpu);
4759 unaccount_pmu_sb_event(event);
4762 static void perf_sched_delayed(struct work_struct *work)
4764 mutex_lock(&perf_sched_mutex);
4765 if (atomic_dec_and_test(&perf_sched_count))
4766 static_branch_disable(&perf_sched_events);
4767 mutex_unlock(&perf_sched_mutex);
4771 * The following implement mutual exclusion of events on "exclusive" pmus
4772 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4773 * at a time, so we disallow creating events that might conflict, namely:
4775 * 1) cpu-wide events in the presence of per-task events,
4776 * 2) per-task events in the presence of cpu-wide events,
4777 * 3) two matching events on the same context.
4779 * The former two cases are handled in the allocation path (perf_event_alloc(),
4780 * _free_event()), the latter -- before the first perf_install_in_context().
4782 static int exclusive_event_init(struct perf_event *event)
4784 struct pmu *pmu = event->pmu;
4786 if (!is_exclusive_pmu(pmu))
4790 * Prevent co-existence of per-task and cpu-wide events on the
4791 * same exclusive pmu.
4793 * Negative pmu::exclusive_cnt means there are cpu-wide
4794 * events on this "exclusive" pmu, positive means there are
4797 * Since this is called in perf_event_alloc() path, event::ctx
4798 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4799 * to mean "per-task event", because unlike other attach states it
4800 * never gets cleared.
4802 if (event->attach_state & PERF_ATTACH_TASK) {
4803 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4806 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4813 static void exclusive_event_destroy(struct perf_event *event)
4815 struct pmu *pmu = event->pmu;
4817 if (!is_exclusive_pmu(pmu))
4820 /* see comment in exclusive_event_init() */
4821 if (event->attach_state & PERF_ATTACH_TASK)
4822 atomic_dec(&pmu->exclusive_cnt);
4824 atomic_inc(&pmu->exclusive_cnt);
4827 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4829 if ((e1->pmu == e2->pmu) &&
4830 (e1->cpu == e2->cpu ||
4837 static bool exclusive_event_installable(struct perf_event *event,
4838 struct perf_event_context *ctx)
4840 struct perf_event *iter_event;
4841 struct pmu *pmu = event->pmu;
4843 lockdep_assert_held(&ctx->mutex);
4845 if (!is_exclusive_pmu(pmu))
4848 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4849 if (exclusive_event_match(iter_event, event))
4856 static void perf_addr_filters_splice(struct perf_event *event,
4857 struct list_head *head);
4859 static void _free_event(struct perf_event *event)
4861 irq_work_sync(&event->pending);
4863 unaccount_event(event);
4865 security_perf_event_free(event);
4869 * Can happen when we close an event with re-directed output.
4871 * Since we have a 0 refcount, perf_mmap_close() will skip
4872 * over us; possibly making our ring_buffer_put() the last.
4874 mutex_lock(&event->mmap_mutex);
4875 ring_buffer_attach(event, NULL);
4876 mutex_unlock(&event->mmap_mutex);
4879 if (is_cgroup_event(event))
4880 perf_detach_cgroup(event);
4882 if (!event->parent) {
4883 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4884 put_callchain_buffers();
4887 perf_event_free_bpf_prog(event);
4888 perf_addr_filters_splice(event, NULL);
4889 kfree(event->addr_filter_ranges);
4892 event->destroy(event);
4895 * Must be after ->destroy(), due to uprobe_perf_close() using
4898 if (event->hw.target)
4899 put_task_struct(event->hw.target);
4902 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4903 * all task references must be cleaned up.
4906 put_ctx(event->ctx);
4908 exclusive_event_destroy(event);
4909 module_put(event->pmu->module);
4911 call_rcu(&event->rcu_head, free_event_rcu);
4915 * Used to free events which have a known refcount of 1, such as in error paths
4916 * where the event isn't exposed yet and inherited events.
4918 static void free_event(struct perf_event *event)
4920 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4921 "unexpected event refcount: %ld; ptr=%p\n",
4922 atomic_long_read(&event->refcount), event)) {
4923 /* leak to avoid use-after-free */
4931 * Remove user event from the owner task.
4933 static void perf_remove_from_owner(struct perf_event *event)
4935 struct task_struct *owner;
4939 * Matches the smp_store_release() in perf_event_exit_task(). If we
4940 * observe !owner it means the list deletion is complete and we can
4941 * indeed free this event, otherwise we need to serialize on
4942 * owner->perf_event_mutex.
4944 owner = READ_ONCE(event->owner);
4947 * Since delayed_put_task_struct() also drops the last
4948 * task reference we can safely take a new reference
4949 * while holding the rcu_read_lock().
4951 get_task_struct(owner);
4957 * If we're here through perf_event_exit_task() we're already
4958 * holding ctx->mutex which would be an inversion wrt. the
4959 * normal lock order.
4961 * However we can safely take this lock because its the child
4964 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4967 * We have to re-check the event->owner field, if it is cleared
4968 * we raced with perf_event_exit_task(), acquiring the mutex
4969 * ensured they're done, and we can proceed with freeing the
4973 list_del_init(&event->owner_entry);
4974 smp_store_release(&event->owner, NULL);
4976 mutex_unlock(&owner->perf_event_mutex);
4977 put_task_struct(owner);
4981 static void put_event(struct perf_event *event)
4983 if (!atomic_long_dec_and_test(&event->refcount))
4990 * Kill an event dead; while event:refcount will preserve the event
4991 * object, it will not preserve its functionality. Once the last 'user'
4992 * gives up the object, we'll destroy the thing.
4994 int perf_event_release_kernel(struct perf_event *event)
4996 struct perf_event_context *ctx = event->ctx;
4997 struct perf_event *child, *tmp;
4998 LIST_HEAD(free_list);
5001 * If we got here through err_file: fput(event_file); we will not have
5002 * attached to a context yet.
5005 WARN_ON_ONCE(event->attach_state &
5006 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5010 if (!is_kernel_event(event))
5011 perf_remove_from_owner(event);
5013 ctx = perf_event_ctx_lock(event);
5014 WARN_ON_ONCE(ctx->parent_ctx);
5015 perf_remove_from_context(event, DETACH_GROUP);
5017 raw_spin_lock_irq(&ctx->lock);
5019 * Mark this event as STATE_DEAD, there is no external reference to it
5022 * Anybody acquiring event->child_mutex after the below loop _must_
5023 * also see this, most importantly inherit_event() which will avoid
5024 * placing more children on the list.
5026 * Thus this guarantees that we will in fact observe and kill _ALL_
5029 event->state = PERF_EVENT_STATE_DEAD;
5030 raw_spin_unlock_irq(&ctx->lock);
5032 perf_event_ctx_unlock(event, ctx);
5035 mutex_lock(&event->child_mutex);
5036 list_for_each_entry(child, &event->child_list, child_list) {
5039 * Cannot change, child events are not migrated, see the
5040 * comment with perf_event_ctx_lock_nested().
5042 ctx = READ_ONCE(child->ctx);
5044 * Since child_mutex nests inside ctx::mutex, we must jump
5045 * through hoops. We start by grabbing a reference on the ctx.
5047 * Since the event cannot get freed while we hold the
5048 * child_mutex, the context must also exist and have a !0
5054 * Now that we have a ctx ref, we can drop child_mutex, and
5055 * acquire ctx::mutex without fear of it going away. Then we
5056 * can re-acquire child_mutex.
5058 mutex_unlock(&event->child_mutex);
5059 mutex_lock(&ctx->mutex);
5060 mutex_lock(&event->child_mutex);
5063 * Now that we hold ctx::mutex and child_mutex, revalidate our
5064 * state, if child is still the first entry, it didn't get freed
5065 * and we can continue doing so.
5067 tmp = list_first_entry_or_null(&event->child_list,
5068 struct perf_event, child_list);
5070 perf_remove_from_context(child, DETACH_GROUP);
5071 list_move(&child->child_list, &free_list);
5073 * This matches the refcount bump in inherit_event();
5074 * this can't be the last reference.
5079 mutex_unlock(&event->child_mutex);
5080 mutex_unlock(&ctx->mutex);
5084 mutex_unlock(&event->child_mutex);
5086 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5087 void *var = &child->ctx->refcount;
5089 list_del(&child->child_list);
5093 * Wake any perf_event_free_task() waiting for this event to be
5096 smp_mb(); /* pairs with wait_var_event() */
5101 put_event(event); /* Must be the 'last' reference */
5104 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5107 * Called when the last reference to the file is gone.
5109 static int perf_release(struct inode *inode, struct file *file)
5111 perf_event_release_kernel(file->private_data);
5115 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5117 struct perf_event *child;
5123 mutex_lock(&event->child_mutex);
5125 (void)perf_event_read(event, false);
5126 total += perf_event_count(event);
5128 *enabled += event->total_time_enabled +
5129 atomic64_read(&event->child_total_time_enabled);
5130 *running += event->total_time_running +
5131 atomic64_read(&event->child_total_time_running);
5133 list_for_each_entry(child, &event->child_list, child_list) {
5134 (void)perf_event_read(child, false);
5135 total += perf_event_count(child);
5136 *enabled += child->total_time_enabled;
5137 *running += child->total_time_running;
5139 mutex_unlock(&event->child_mutex);
5144 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5146 struct perf_event_context *ctx;
5149 ctx = perf_event_ctx_lock(event);
5150 count = __perf_event_read_value(event, enabled, running);
5151 perf_event_ctx_unlock(event, ctx);
5155 EXPORT_SYMBOL_GPL(perf_event_read_value);
5157 static int __perf_read_group_add(struct perf_event *leader,
5158 u64 read_format, u64 *values)
5160 struct perf_event_context *ctx = leader->ctx;
5161 struct perf_event *sub;
5162 unsigned long flags;
5163 int n = 1; /* skip @nr */
5166 ret = perf_event_read(leader, true);
5170 raw_spin_lock_irqsave(&ctx->lock, flags);
5173 * Since we co-schedule groups, {enabled,running} times of siblings
5174 * will be identical to those of the leader, so we only publish one
5177 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5178 values[n++] += leader->total_time_enabled +
5179 atomic64_read(&leader->child_total_time_enabled);
5182 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5183 values[n++] += leader->total_time_running +
5184 atomic64_read(&leader->child_total_time_running);
5188 * Write {count,id} tuples for every sibling.
5190 values[n++] += perf_event_count(leader);
5191 if (read_format & PERF_FORMAT_ID)
5192 values[n++] = primary_event_id(leader);
5194 for_each_sibling_event(sub, leader) {
5195 values[n++] += perf_event_count(sub);
5196 if (read_format & PERF_FORMAT_ID)
5197 values[n++] = primary_event_id(sub);
5200 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5204 static int perf_read_group(struct perf_event *event,
5205 u64 read_format, char __user *buf)
5207 struct perf_event *leader = event->group_leader, *child;
5208 struct perf_event_context *ctx = leader->ctx;
5212 lockdep_assert_held(&ctx->mutex);
5214 values = kzalloc(event->read_size, GFP_KERNEL);
5218 values[0] = 1 + leader->nr_siblings;
5221 * By locking the child_mutex of the leader we effectively
5222 * lock the child list of all siblings.. XXX explain how.
5224 mutex_lock(&leader->child_mutex);
5226 ret = __perf_read_group_add(leader, read_format, values);
5230 list_for_each_entry(child, &leader->child_list, child_list) {
5231 ret = __perf_read_group_add(child, read_format, values);
5236 mutex_unlock(&leader->child_mutex);
5238 ret = event->read_size;
5239 if (copy_to_user(buf, values, event->read_size))
5244 mutex_unlock(&leader->child_mutex);
5250 static int perf_read_one(struct perf_event *event,
5251 u64 read_format, char __user *buf)
5253 u64 enabled, running;
5257 values[n++] = __perf_event_read_value(event, &enabled, &running);
5258 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5259 values[n++] = enabled;
5260 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5261 values[n++] = running;
5262 if (read_format & PERF_FORMAT_ID)
5263 values[n++] = primary_event_id(event);
5265 if (copy_to_user(buf, values, n * sizeof(u64)))
5268 return n * sizeof(u64);
5271 static bool is_event_hup(struct perf_event *event)
5275 if (event->state > PERF_EVENT_STATE_EXIT)
5278 mutex_lock(&event->child_mutex);
5279 no_children = list_empty(&event->child_list);
5280 mutex_unlock(&event->child_mutex);
5285 * Read the performance event - simple non blocking version for now
5288 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5290 u64 read_format = event->attr.read_format;
5294 * Return end-of-file for a read on an event that is in
5295 * error state (i.e. because it was pinned but it couldn't be
5296 * scheduled on to the CPU at some point).
5298 if (event->state == PERF_EVENT_STATE_ERROR)
5301 if (count < event->read_size)
5304 WARN_ON_ONCE(event->ctx->parent_ctx);
5305 if (read_format & PERF_FORMAT_GROUP)
5306 ret = perf_read_group(event, read_format, buf);
5308 ret = perf_read_one(event, read_format, buf);
5314 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5316 struct perf_event *event = file->private_data;
5317 struct perf_event_context *ctx;
5320 ret = security_perf_event_read(event);
5324 ctx = perf_event_ctx_lock(event);
5325 ret = __perf_read(event, buf, count);
5326 perf_event_ctx_unlock(event, ctx);
5331 static __poll_t perf_poll(struct file *file, poll_table *wait)
5333 struct perf_event *event = file->private_data;
5334 struct perf_buffer *rb;
5335 __poll_t events = EPOLLHUP;
5337 poll_wait(file, &event->waitq, wait);
5339 if (is_event_hup(event))
5343 * Pin the event->rb by taking event->mmap_mutex; otherwise
5344 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5346 mutex_lock(&event->mmap_mutex);
5349 events = atomic_xchg(&rb->poll, 0);
5350 mutex_unlock(&event->mmap_mutex);
5354 static void _perf_event_reset(struct perf_event *event)
5356 (void)perf_event_read(event, false);
5357 local64_set(&event->count, 0);
5358 perf_event_update_userpage(event);
5361 /* Assume it's not an event with inherit set. */
5362 u64 perf_event_pause(struct perf_event *event, bool reset)
5364 struct perf_event_context *ctx;
5367 ctx = perf_event_ctx_lock(event);
5368 WARN_ON_ONCE(event->attr.inherit);
5369 _perf_event_disable(event);
5370 count = local64_read(&event->count);
5372 local64_set(&event->count, 0);
5373 perf_event_ctx_unlock(event, ctx);
5377 EXPORT_SYMBOL_GPL(perf_event_pause);
5380 * Holding the top-level event's child_mutex means that any
5381 * descendant process that has inherited this event will block
5382 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5383 * task existence requirements of perf_event_enable/disable.
5385 static void perf_event_for_each_child(struct perf_event *event,
5386 void (*func)(struct perf_event *))
5388 struct perf_event *child;
5390 WARN_ON_ONCE(event->ctx->parent_ctx);
5392 mutex_lock(&event->child_mutex);
5394 list_for_each_entry(child, &event->child_list, child_list)
5396 mutex_unlock(&event->child_mutex);
5399 static void perf_event_for_each(struct perf_event *event,
5400 void (*func)(struct perf_event *))
5402 struct perf_event_context *ctx = event->ctx;
5403 struct perf_event *sibling;
5405 lockdep_assert_held(&ctx->mutex);
5407 event = event->group_leader;
5409 perf_event_for_each_child(event, func);
5410 for_each_sibling_event(sibling, event)
5411 perf_event_for_each_child(sibling, func);
5414 static void __perf_event_period(struct perf_event *event,
5415 struct perf_cpu_context *cpuctx,
5416 struct perf_event_context *ctx,
5419 u64 value = *((u64 *)info);
5422 if (event->attr.freq) {
5423 event->attr.sample_freq = value;
5425 event->attr.sample_period = value;
5426 event->hw.sample_period = value;
5429 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5431 perf_pmu_disable(ctx->pmu);
5433 * We could be throttled; unthrottle now to avoid the tick
5434 * trying to unthrottle while we already re-started the event.
5436 if (event->hw.interrupts == MAX_INTERRUPTS) {
5437 event->hw.interrupts = 0;
5438 perf_log_throttle(event, 1);
5440 event->pmu->stop(event, PERF_EF_UPDATE);
5443 local64_set(&event->hw.period_left, 0);
5446 event->pmu->start(event, PERF_EF_RELOAD);
5447 perf_pmu_enable(ctx->pmu);
5451 static int perf_event_check_period(struct perf_event *event, u64 value)
5453 return event->pmu->check_period(event, value);
5456 static int _perf_event_period(struct perf_event *event, u64 value)
5458 if (!is_sampling_event(event))
5464 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5467 if (perf_event_check_period(event, value))
5470 if (!event->attr.freq && (value & (1ULL << 63)))
5473 event_function_call(event, __perf_event_period, &value);
5478 int perf_event_period(struct perf_event *event, u64 value)
5480 struct perf_event_context *ctx;
5483 ctx = perf_event_ctx_lock(event);
5484 ret = _perf_event_period(event, value);
5485 perf_event_ctx_unlock(event, ctx);
5489 EXPORT_SYMBOL_GPL(perf_event_period);
5491 static const struct file_operations perf_fops;
5493 static inline int perf_fget_light(int fd, struct fd *p)
5495 struct fd f = fdget(fd);
5499 if (f.file->f_op != &perf_fops) {
5507 static int perf_event_set_output(struct perf_event *event,
5508 struct perf_event *output_event);
5509 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5510 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5511 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5512 struct perf_event_attr *attr);
5514 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5516 void (*func)(struct perf_event *);
5520 case PERF_EVENT_IOC_ENABLE:
5521 func = _perf_event_enable;
5523 case PERF_EVENT_IOC_DISABLE:
5524 func = _perf_event_disable;
5526 case PERF_EVENT_IOC_RESET:
5527 func = _perf_event_reset;
5530 case PERF_EVENT_IOC_REFRESH:
5531 return _perf_event_refresh(event, arg);
5533 case PERF_EVENT_IOC_PERIOD:
5537 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5540 return _perf_event_period(event, value);
5542 case PERF_EVENT_IOC_ID:
5544 u64 id = primary_event_id(event);
5546 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5551 case PERF_EVENT_IOC_SET_OUTPUT:
5555 struct perf_event *output_event;
5557 ret = perf_fget_light(arg, &output);
5560 output_event = output.file->private_data;
5561 ret = perf_event_set_output(event, output_event);
5564 ret = perf_event_set_output(event, NULL);
5569 case PERF_EVENT_IOC_SET_FILTER:
5570 return perf_event_set_filter(event, (void __user *)arg);
5572 case PERF_EVENT_IOC_SET_BPF:
5573 return perf_event_set_bpf_prog(event, arg);
5575 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5576 struct perf_buffer *rb;
5579 rb = rcu_dereference(event->rb);
5580 if (!rb || !rb->nr_pages) {
5584 rb_toggle_paused(rb, !!arg);
5589 case PERF_EVENT_IOC_QUERY_BPF:
5590 return perf_event_query_prog_array(event, (void __user *)arg);
5592 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5593 struct perf_event_attr new_attr;
5594 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5600 return perf_event_modify_attr(event, &new_attr);
5606 if (flags & PERF_IOC_FLAG_GROUP)
5607 perf_event_for_each(event, func);
5609 perf_event_for_each_child(event, func);
5614 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5616 struct perf_event *event = file->private_data;
5617 struct perf_event_context *ctx;
5620 /* Treat ioctl like writes as it is likely a mutating operation. */
5621 ret = security_perf_event_write(event);
5625 ctx = perf_event_ctx_lock(event);
5626 ret = _perf_ioctl(event, cmd, arg);
5627 perf_event_ctx_unlock(event, ctx);
5632 #ifdef CONFIG_COMPAT
5633 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5636 switch (_IOC_NR(cmd)) {
5637 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5638 case _IOC_NR(PERF_EVENT_IOC_ID):
5639 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5640 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5641 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5642 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5643 cmd &= ~IOCSIZE_MASK;
5644 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5648 return perf_ioctl(file, cmd, arg);
5651 # define perf_compat_ioctl NULL
5654 int perf_event_task_enable(void)
5656 struct perf_event_context *ctx;
5657 struct perf_event *event;
5659 mutex_lock(¤t->perf_event_mutex);
5660 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5661 ctx = perf_event_ctx_lock(event);
5662 perf_event_for_each_child(event, _perf_event_enable);
5663 perf_event_ctx_unlock(event, ctx);
5665 mutex_unlock(¤t->perf_event_mutex);
5670 int perf_event_task_disable(void)
5672 struct perf_event_context *ctx;
5673 struct perf_event *event;
5675 mutex_lock(¤t->perf_event_mutex);
5676 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5677 ctx = perf_event_ctx_lock(event);
5678 perf_event_for_each_child(event, _perf_event_disable);
5679 perf_event_ctx_unlock(event, ctx);
5681 mutex_unlock(¤t->perf_event_mutex);
5686 static int perf_event_index(struct perf_event *event)
5688 if (event->hw.state & PERF_HES_STOPPED)
5691 if (event->state != PERF_EVENT_STATE_ACTIVE)
5694 return event->pmu->event_idx(event);
5697 static void calc_timer_values(struct perf_event *event,
5704 *now = perf_clock();
5705 ctx_time = event->shadow_ctx_time + *now;
5706 __perf_update_times(event, ctx_time, enabled, running);
5709 static void perf_event_init_userpage(struct perf_event *event)
5711 struct perf_event_mmap_page *userpg;
5712 struct perf_buffer *rb;
5715 rb = rcu_dereference(event->rb);
5719 userpg = rb->user_page;
5721 /* Allow new userspace to detect that bit 0 is deprecated */
5722 userpg->cap_bit0_is_deprecated = 1;
5723 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5724 userpg->data_offset = PAGE_SIZE;
5725 userpg->data_size = perf_data_size(rb);
5731 void __weak arch_perf_update_userpage(
5732 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5737 * Callers need to ensure there can be no nesting of this function, otherwise
5738 * the seqlock logic goes bad. We can not serialize this because the arch
5739 * code calls this from NMI context.
5741 void perf_event_update_userpage(struct perf_event *event)
5743 struct perf_event_mmap_page *userpg;
5744 struct perf_buffer *rb;
5745 u64 enabled, running, now;
5748 rb = rcu_dereference(event->rb);
5753 * compute total_time_enabled, total_time_running
5754 * based on snapshot values taken when the event
5755 * was last scheduled in.
5757 * we cannot simply called update_context_time()
5758 * because of locking issue as we can be called in
5761 calc_timer_values(event, &now, &enabled, &running);
5763 userpg = rb->user_page;
5765 * Disable preemption to guarantee consistent time stamps are stored to
5771 userpg->index = perf_event_index(event);
5772 userpg->offset = perf_event_count(event);
5774 userpg->offset -= local64_read(&event->hw.prev_count);
5776 userpg->time_enabled = enabled +
5777 atomic64_read(&event->child_total_time_enabled);
5779 userpg->time_running = running +
5780 atomic64_read(&event->child_total_time_running);
5782 arch_perf_update_userpage(event, userpg, now);
5790 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5792 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5794 struct perf_event *event = vmf->vma->vm_file->private_data;
5795 struct perf_buffer *rb;
5796 vm_fault_t ret = VM_FAULT_SIGBUS;
5798 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5799 if (vmf->pgoff == 0)
5805 rb = rcu_dereference(event->rb);
5809 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5812 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5816 get_page(vmf->page);
5817 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5818 vmf->page->index = vmf->pgoff;
5827 static void ring_buffer_attach(struct perf_event *event,
5828 struct perf_buffer *rb)
5830 struct perf_buffer *old_rb = NULL;
5831 unsigned long flags;
5835 * Should be impossible, we set this when removing
5836 * event->rb_entry and wait/clear when adding event->rb_entry.
5838 WARN_ON_ONCE(event->rcu_pending);
5841 spin_lock_irqsave(&old_rb->event_lock, flags);
5842 list_del_rcu(&event->rb_entry);
5843 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5845 event->rcu_batches = get_state_synchronize_rcu();
5846 event->rcu_pending = 1;
5850 if (event->rcu_pending) {
5851 cond_synchronize_rcu(event->rcu_batches);
5852 event->rcu_pending = 0;
5855 spin_lock_irqsave(&rb->event_lock, flags);
5856 list_add_rcu(&event->rb_entry, &rb->event_list);
5857 spin_unlock_irqrestore(&rb->event_lock, flags);
5861 * Avoid racing with perf_mmap_close(AUX): stop the event
5862 * before swizzling the event::rb pointer; if it's getting
5863 * unmapped, its aux_mmap_count will be 0 and it won't
5864 * restart. See the comment in __perf_pmu_output_stop().
5866 * Data will inevitably be lost when set_output is done in
5867 * mid-air, but then again, whoever does it like this is
5868 * not in for the data anyway.
5871 perf_event_stop(event, 0);
5873 rcu_assign_pointer(event->rb, rb);
5876 ring_buffer_put(old_rb);
5878 * Since we detached before setting the new rb, so that we
5879 * could attach the new rb, we could have missed a wakeup.
5882 wake_up_all(&event->waitq);
5886 static void ring_buffer_wakeup(struct perf_event *event)
5888 struct perf_buffer *rb;
5891 rb = rcu_dereference(event->rb);
5893 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5894 wake_up_all(&event->waitq);
5899 struct perf_buffer *ring_buffer_get(struct perf_event *event)
5901 struct perf_buffer *rb;
5904 rb = rcu_dereference(event->rb);
5906 if (!refcount_inc_not_zero(&rb->refcount))
5914 void ring_buffer_put(struct perf_buffer *rb)
5916 if (!refcount_dec_and_test(&rb->refcount))
5919 WARN_ON_ONCE(!list_empty(&rb->event_list));
5921 call_rcu(&rb->rcu_head, rb_free_rcu);
5924 static void perf_mmap_open(struct vm_area_struct *vma)
5926 struct perf_event *event = vma->vm_file->private_data;
5928 atomic_inc(&event->mmap_count);
5929 atomic_inc(&event->rb->mmap_count);
5932 atomic_inc(&event->rb->aux_mmap_count);
5934 if (event->pmu->event_mapped)
5935 event->pmu->event_mapped(event, vma->vm_mm);
5938 static void perf_pmu_output_stop(struct perf_event *event);
5941 * A buffer can be mmap()ed multiple times; either directly through the same
5942 * event, or through other events by use of perf_event_set_output().
5944 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5945 * the buffer here, where we still have a VM context. This means we need
5946 * to detach all events redirecting to us.
5948 static void perf_mmap_close(struct vm_area_struct *vma)
5950 struct perf_event *event = vma->vm_file->private_data;
5951 struct perf_buffer *rb = ring_buffer_get(event);
5952 struct user_struct *mmap_user = rb->mmap_user;
5953 int mmap_locked = rb->mmap_locked;
5954 unsigned long size = perf_data_size(rb);
5955 bool detach_rest = false;
5957 if (event->pmu->event_unmapped)
5958 event->pmu->event_unmapped(event, vma->vm_mm);
5961 * rb->aux_mmap_count will always drop before rb->mmap_count and
5962 * event->mmap_count, so it is ok to use event->mmap_mutex to
5963 * serialize with perf_mmap here.
5965 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5966 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5968 * Stop all AUX events that are writing to this buffer,
5969 * so that we can free its AUX pages and corresponding PMU
5970 * data. Note that after rb::aux_mmap_count dropped to zero,
5971 * they won't start any more (see perf_aux_output_begin()).
5973 perf_pmu_output_stop(event);
5975 /* now it's safe to free the pages */
5976 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5977 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5979 /* this has to be the last one */
5981 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5983 mutex_unlock(&event->mmap_mutex);
5986 if (atomic_dec_and_test(&rb->mmap_count))
5989 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5992 ring_buffer_attach(event, NULL);
5993 mutex_unlock(&event->mmap_mutex);
5995 /* If there's still other mmap()s of this buffer, we're done. */
6000 * No other mmap()s, detach from all other events that might redirect
6001 * into the now unreachable buffer. Somewhat complicated by the
6002 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6006 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6007 if (!atomic_long_inc_not_zero(&event->refcount)) {
6009 * This event is en-route to free_event() which will
6010 * detach it and remove it from the list.
6016 mutex_lock(&event->mmap_mutex);
6018 * Check we didn't race with perf_event_set_output() which can
6019 * swizzle the rb from under us while we were waiting to
6020 * acquire mmap_mutex.
6022 * If we find a different rb; ignore this event, a next
6023 * iteration will no longer find it on the list. We have to
6024 * still restart the iteration to make sure we're not now
6025 * iterating the wrong list.
6027 if (event->rb == rb)
6028 ring_buffer_attach(event, NULL);
6030 mutex_unlock(&event->mmap_mutex);
6034 * Restart the iteration; either we're on the wrong list or
6035 * destroyed its integrity by doing a deletion.
6042 * It could be there's still a few 0-ref events on the list; they'll
6043 * get cleaned up by free_event() -- they'll also still have their
6044 * ref on the rb and will free it whenever they are done with it.
6046 * Aside from that, this buffer is 'fully' detached and unmapped,
6047 * undo the VM accounting.
6050 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6051 &mmap_user->locked_vm);
6052 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6053 free_uid(mmap_user);
6056 ring_buffer_put(rb); /* could be last */
6059 static const struct vm_operations_struct perf_mmap_vmops = {
6060 .open = perf_mmap_open,
6061 .close = perf_mmap_close, /* non mergeable */
6062 .fault = perf_mmap_fault,
6063 .page_mkwrite = perf_mmap_fault,
6066 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6068 struct perf_event *event = file->private_data;
6069 unsigned long user_locked, user_lock_limit;
6070 struct user_struct *user = current_user();
6071 struct perf_buffer *rb = NULL;
6072 unsigned long locked, lock_limit;
6073 unsigned long vma_size;
6074 unsigned long nr_pages;
6075 long user_extra = 0, extra = 0;
6076 int ret = 0, flags = 0;
6079 * Don't allow mmap() of inherited per-task counters. This would
6080 * create a performance issue due to all children writing to the
6083 if (event->cpu == -1 && event->attr.inherit)
6086 if (!(vma->vm_flags & VM_SHARED))
6089 ret = security_perf_event_read(event);
6093 vma_size = vma->vm_end - vma->vm_start;
6095 if (vma->vm_pgoff == 0) {
6096 nr_pages = (vma_size / PAGE_SIZE) - 1;
6099 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6100 * mapped, all subsequent mappings should have the same size
6101 * and offset. Must be above the normal perf buffer.
6103 u64 aux_offset, aux_size;
6108 nr_pages = vma_size / PAGE_SIZE;
6110 mutex_lock(&event->mmap_mutex);
6117 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6118 aux_size = READ_ONCE(rb->user_page->aux_size);
6120 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6123 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6126 /* already mapped with a different offset */
6127 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6130 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6133 /* already mapped with a different size */
6134 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6137 if (!is_power_of_2(nr_pages))
6140 if (!atomic_inc_not_zero(&rb->mmap_count))
6143 if (rb_has_aux(rb)) {
6144 atomic_inc(&rb->aux_mmap_count);
6149 atomic_set(&rb->aux_mmap_count, 1);
6150 user_extra = nr_pages;
6156 * If we have rb pages ensure they're a power-of-two number, so we
6157 * can do bitmasks instead of modulo.
6159 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6162 if (vma_size != PAGE_SIZE * (1 + nr_pages))
6165 WARN_ON_ONCE(event->ctx->parent_ctx);
6167 mutex_lock(&event->mmap_mutex);
6169 if (event->rb->nr_pages != nr_pages) {
6174 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6176 * Raced against perf_mmap_close() through
6177 * perf_event_set_output(). Try again, hope for better
6180 mutex_unlock(&event->mmap_mutex);
6187 user_extra = nr_pages + 1;
6190 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6193 * Increase the limit linearly with more CPUs:
6195 user_lock_limit *= num_online_cpus();
6197 user_locked = atomic_long_read(&user->locked_vm);
6200 * sysctl_perf_event_mlock may have changed, so that
6201 * user->locked_vm > user_lock_limit
6203 if (user_locked > user_lock_limit)
6204 user_locked = user_lock_limit;
6205 user_locked += user_extra;
6207 if (user_locked > user_lock_limit) {
6209 * charge locked_vm until it hits user_lock_limit;
6210 * charge the rest from pinned_vm
6212 extra = user_locked - user_lock_limit;
6213 user_extra -= extra;
6216 lock_limit = rlimit(RLIMIT_MEMLOCK);
6217 lock_limit >>= PAGE_SHIFT;
6218 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6220 if ((locked > lock_limit) && perf_is_paranoid() &&
6221 !capable(CAP_IPC_LOCK)) {
6226 WARN_ON(!rb && event->rb);
6228 if (vma->vm_flags & VM_WRITE)
6229 flags |= RING_BUFFER_WRITABLE;
6232 rb = rb_alloc(nr_pages,
6233 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6241 atomic_set(&rb->mmap_count, 1);
6242 rb->mmap_user = get_current_user();
6243 rb->mmap_locked = extra;
6245 ring_buffer_attach(event, rb);
6247 perf_event_update_time(event);
6248 perf_set_shadow_time(event, event->ctx);
6249 perf_event_init_userpage(event);
6250 perf_event_update_userpage(event);
6252 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6253 event->attr.aux_watermark, flags);
6255 rb->aux_mmap_locked = extra;
6260 atomic_long_add(user_extra, &user->locked_vm);
6261 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6263 atomic_inc(&event->mmap_count);
6265 atomic_dec(&rb->mmap_count);
6268 mutex_unlock(&event->mmap_mutex);
6271 * Since pinned accounting is per vm we cannot allow fork() to copy our
6274 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6275 vma->vm_ops = &perf_mmap_vmops;
6277 if (event->pmu->event_mapped)
6278 event->pmu->event_mapped(event, vma->vm_mm);
6283 static int perf_fasync(int fd, struct file *filp, int on)
6285 struct inode *inode = file_inode(filp);
6286 struct perf_event *event = filp->private_data;
6290 retval = fasync_helper(fd, filp, on, &event->fasync);
6291 inode_unlock(inode);
6299 static const struct file_operations perf_fops = {
6300 .llseek = no_llseek,
6301 .release = perf_release,
6304 .unlocked_ioctl = perf_ioctl,
6305 .compat_ioctl = perf_compat_ioctl,
6307 .fasync = perf_fasync,
6313 * If there's data, ensure we set the poll() state and publish everything
6314 * to user-space before waking everybody up.
6317 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6319 /* only the parent has fasync state */
6321 event = event->parent;
6322 return &event->fasync;
6325 void perf_event_wakeup(struct perf_event *event)
6327 ring_buffer_wakeup(event);
6329 if (event->pending_kill) {
6330 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6331 event->pending_kill = 0;
6335 static void perf_pending_event_disable(struct perf_event *event)
6337 int cpu = READ_ONCE(event->pending_disable);
6342 if (cpu == smp_processor_id()) {
6343 WRITE_ONCE(event->pending_disable, -1);
6344 perf_event_disable_local(event);
6351 * perf_event_disable_inatomic()
6352 * @pending_disable = CPU-A;
6356 * @pending_disable = -1;
6359 * perf_event_disable_inatomic()
6360 * @pending_disable = CPU-B;
6361 * irq_work_queue(); // FAILS
6364 * perf_pending_event()
6366 * But the event runs on CPU-B and wants disabling there.
6368 irq_work_queue_on(&event->pending, cpu);
6371 static void perf_pending_event(struct irq_work *entry)
6373 struct perf_event *event = container_of(entry, struct perf_event, pending);
6376 rctx = perf_swevent_get_recursion_context();
6378 * If we 'fail' here, that's OK, it means recursion is already disabled
6379 * and we won't recurse 'further'.
6382 perf_pending_event_disable(event);
6384 if (event->pending_wakeup) {
6385 event->pending_wakeup = 0;
6386 perf_event_wakeup(event);
6390 perf_swevent_put_recursion_context(rctx);
6394 * We assume there is only KVM supporting the callbacks.
6395 * Later on, we might change it to a list if there is
6396 * another virtualization implementation supporting the callbacks.
6398 struct perf_guest_info_callbacks *perf_guest_cbs;
6400 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6402 perf_guest_cbs = cbs;
6405 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6407 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6409 perf_guest_cbs = NULL;
6412 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6415 perf_output_sample_regs(struct perf_output_handle *handle,
6416 struct pt_regs *regs, u64 mask)
6419 DECLARE_BITMAP(_mask, 64);
6421 bitmap_from_u64(_mask, mask);
6422 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6425 val = perf_reg_value(regs, bit);
6426 perf_output_put(handle, val);
6430 static void perf_sample_regs_user(struct perf_regs *regs_user,
6431 struct pt_regs *regs)
6433 if (user_mode(regs)) {
6434 regs_user->abi = perf_reg_abi(current);
6435 regs_user->regs = regs;
6436 } else if (!(current->flags & PF_KTHREAD)) {
6437 perf_get_regs_user(regs_user, regs);
6439 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6440 regs_user->regs = NULL;
6444 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6445 struct pt_regs *regs)
6447 regs_intr->regs = regs;
6448 regs_intr->abi = perf_reg_abi(current);
6453 * Get remaining task size from user stack pointer.
6455 * It'd be better to take stack vma map and limit this more
6456 * precisely, but there's no way to get it safely under interrupt,
6457 * so using TASK_SIZE as limit.
6459 static u64 perf_ustack_task_size(struct pt_regs *regs)
6461 unsigned long addr = perf_user_stack_pointer(regs);
6463 if (!addr || addr >= TASK_SIZE)
6466 return TASK_SIZE - addr;
6470 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6471 struct pt_regs *regs)
6475 /* No regs, no stack pointer, no dump. */
6480 * Check if we fit in with the requested stack size into the:
6482 * If we don't, we limit the size to the TASK_SIZE.
6484 * - remaining sample size
6485 * If we don't, we customize the stack size to
6486 * fit in to the remaining sample size.
6489 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6490 stack_size = min(stack_size, (u16) task_size);
6492 /* Current header size plus static size and dynamic size. */
6493 header_size += 2 * sizeof(u64);
6495 /* Do we fit in with the current stack dump size? */
6496 if ((u16) (header_size + stack_size) < header_size) {
6498 * If we overflow the maximum size for the sample,
6499 * we customize the stack dump size to fit in.
6501 stack_size = USHRT_MAX - header_size - sizeof(u64);
6502 stack_size = round_up(stack_size, sizeof(u64));
6509 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6510 struct pt_regs *regs)
6512 /* Case of a kernel thread, nothing to dump */
6515 perf_output_put(handle, size);
6525 * - the size requested by user or the best one we can fit
6526 * in to the sample max size
6528 * - user stack dump data
6530 * - the actual dumped size
6534 perf_output_put(handle, dump_size);
6537 sp = perf_user_stack_pointer(regs);
6538 fs = force_uaccess_begin();
6539 rem = __output_copy_user(handle, (void *) sp, dump_size);
6540 force_uaccess_end(fs);
6541 dyn_size = dump_size - rem;
6543 perf_output_skip(handle, rem);
6546 perf_output_put(handle, dyn_size);
6550 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6551 struct perf_sample_data *data,
6554 struct perf_event *sampler = event->aux_event;
6555 struct perf_buffer *rb;
6562 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6565 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6568 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6573 * If this is an NMI hit inside sampling code, don't take
6574 * the sample. See also perf_aux_sample_output().
6576 if (READ_ONCE(rb->aux_in_sampling)) {
6579 size = min_t(size_t, size, perf_aux_size(rb));
6580 data->aux_size = ALIGN(size, sizeof(u64));
6582 ring_buffer_put(rb);
6585 return data->aux_size;
6588 long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6589 struct perf_event *event,
6590 struct perf_output_handle *handle,
6593 unsigned long flags;
6597 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6598 * paths. If we start calling them in NMI context, they may race with
6599 * the IRQ ones, that is, for example, re-starting an event that's just
6600 * been stopped, which is why we're using a separate callback that
6601 * doesn't change the event state.
6603 * IRQs need to be disabled to prevent IPIs from racing with us.
6605 local_irq_save(flags);
6607 * Guard against NMI hits inside the critical section;
6608 * see also perf_prepare_sample_aux().
6610 WRITE_ONCE(rb->aux_in_sampling, 1);
6613 ret = event->pmu->snapshot_aux(event, handle, size);
6616 WRITE_ONCE(rb->aux_in_sampling, 0);
6617 local_irq_restore(flags);
6622 static void perf_aux_sample_output(struct perf_event *event,
6623 struct perf_output_handle *handle,
6624 struct perf_sample_data *data)
6626 struct perf_event *sampler = event->aux_event;
6627 struct perf_buffer *rb;
6631 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6634 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6638 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6641 * An error here means that perf_output_copy() failed (returned a
6642 * non-zero surplus that it didn't copy), which in its current
6643 * enlightened implementation is not possible. If that changes, we'd
6646 if (WARN_ON_ONCE(size < 0))
6650 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6651 * perf_prepare_sample_aux(), so should not be more than that.
6653 pad = data->aux_size - size;
6654 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6659 perf_output_copy(handle, &zero, pad);
6663 ring_buffer_put(rb);
6666 static void __perf_event_header__init_id(struct perf_event_header *header,
6667 struct perf_sample_data *data,
6668 struct perf_event *event)
6670 u64 sample_type = event->attr.sample_type;
6672 data->type = sample_type;
6673 header->size += event->id_header_size;
6675 if (sample_type & PERF_SAMPLE_TID) {
6676 /* namespace issues */
6677 data->tid_entry.pid = perf_event_pid(event, current);
6678 data->tid_entry.tid = perf_event_tid(event, current);
6681 if (sample_type & PERF_SAMPLE_TIME)
6682 data->time = perf_event_clock(event);
6684 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6685 data->id = primary_event_id(event);
6687 if (sample_type & PERF_SAMPLE_STREAM_ID)
6688 data->stream_id = event->id;
6690 if (sample_type & PERF_SAMPLE_CPU) {
6691 data->cpu_entry.cpu = raw_smp_processor_id();
6692 data->cpu_entry.reserved = 0;
6696 void perf_event_header__init_id(struct perf_event_header *header,
6697 struct perf_sample_data *data,
6698 struct perf_event *event)
6700 if (event->attr.sample_id_all)
6701 __perf_event_header__init_id(header, data, event);
6704 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6705 struct perf_sample_data *data)
6707 u64 sample_type = data->type;
6709 if (sample_type & PERF_SAMPLE_TID)
6710 perf_output_put(handle, data->tid_entry);
6712 if (sample_type & PERF_SAMPLE_TIME)
6713 perf_output_put(handle, data->time);
6715 if (sample_type & PERF_SAMPLE_ID)
6716 perf_output_put(handle, data->id);
6718 if (sample_type & PERF_SAMPLE_STREAM_ID)
6719 perf_output_put(handle, data->stream_id);
6721 if (sample_type & PERF_SAMPLE_CPU)
6722 perf_output_put(handle, data->cpu_entry);
6724 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6725 perf_output_put(handle, data->id);
6728 void perf_event__output_id_sample(struct perf_event *event,
6729 struct perf_output_handle *handle,
6730 struct perf_sample_data *sample)
6732 if (event->attr.sample_id_all)
6733 __perf_event__output_id_sample(handle, sample);
6736 static void perf_output_read_one(struct perf_output_handle *handle,
6737 struct perf_event *event,
6738 u64 enabled, u64 running)
6740 u64 read_format = event->attr.read_format;
6744 values[n++] = perf_event_count(event);
6745 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6746 values[n++] = enabled +
6747 atomic64_read(&event->child_total_time_enabled);
6749 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6750 values[n++] = running +
6751 atomic64_read(&event->child_total_time_running);
6753 if (read_format & PERF_FORMAT_ID)
6754 values[n++] = primary_event_id(event);
6756 __output_copy(handle, values, n * sizeof(u64));
6759 static void perf_output_read_group(struct perf_output_handle *handle,
6760 struct perf_event *event,
6761 u64 enabled, u64 running)
6763 struct perf_event *leader = event->group_leader, *sub;
6764 u64 read_format = event->attr.read_format;
6768 values[n++] = 1 + leader->nr_siblings;
6770 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6771 values[n++] = enabled;
6773 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6774 values[n++] = running;
6776 if ((leader != event) &&
6777 (leader->state == PERF_EVENT_STATE_ACTIVE))
6778 leader->pmu->read(leader);
6780 values[n++] = perf_event_count(leader);
6781 if (read_format & PERF_FORMAT_ID)
6782 values[n++] = primary_event_id(leader);
6784 __output_copy(handle, values, n * sizeof(u64));
6786 for_each_sibling_event(sub, leader) {
6789 if ((sub != event) &&
6790 (sub->state == PERF_EVENT_STATE_ACTIVE))
6791 sub->pmu->read(sub);
6793 values[n++] = perf_event_count(sub);
6794 if (read_format & PERF_FORMAT_ID)
6795 values[n++] = primary_event_id(sub);
6797 __output_copy(handle, values, n * sizeof(u64));
6801 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6802 PERF_FORMAT_TOTAL_TIME_RUNNING)
6805 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6807 * The problem is that its both hard and excessively expensive to iterate the
6808 * child list, not to mention that its impossible to IPI the children running
6809 * on another CPU, from interrupt/NMI context.
6811 static void perf_output_read(struct perf_output_handle *handle,
6812 struct perf_event *event)
6814 u64 enabled = 0, running = 0, now;
6815 u64 read_format = event->attr.read_format;
6818 * compute total_time_enabled, total_time_running
6819 * based on snapshot values taken when the event
6820 * was last scheduled in.
6822 * we cannot simply called update_context_time()
6823 * because of locking issue as we are called in
6826 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6827 calc_timer_values(event, &now, &enabled, &running);
6829 if (event->attr.read_format & PERF_FORMAT_GROUP)
6830 perf_output_read_group(handle, event, enabled, running);
6832 perf_output_read_one(handle, event, enabled, running);
6835 static inline bool perf_sample_save_hw_index(struct perf_event *event)
6837 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6840 void perf_output_sample(struct perf_output_handle *handle,
6841 struct perf_event_header *header,
6842 struct perf_sample_data *data,
6843 struct perf_event *event)
6845 u64 sample_type = data->type;
6847 perf_output_put(handle, *header);
6849 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6850 perf_output_put(handle, data->id);
6852 if (sample_type & PERF_SAMPLE_IP)
6853 perf_output_put(handle, data->ip);
6855 if (sample_type & PERF_SAMPLE_TID)
6856 perf_output_put(handle, data->tid_entry);
6858 if (sample_type & PERF_SAMPLE_TIME)
6859 perf_output_put(handle, data->time);
6861 if (sample_type & PERF_SAMPLE_ADDR)
6862 perf_output_put(handle, data->addr);
6864 if (sample_type & PERF_SAMPLE_ID)
6865 perf_output_put(handle, data->id);
6867 if (sample_type & PERF_SAMPLE_STREAM_ID)
6868 perf_output_put(handle, data->stream_id);
6870 if (sample_type & PERF_SAMPLE_CPU)
6871 perf_output_put(handle, data->cpu_entry);
6873 if (sample_type & PERF_SAMPLE_PERIOD)
6874 perf_output_put(handle, data->period);
6876 if (sample_type & PERF_SAMPLE_READ)
6877 perf_output_read(handle, event);
6879 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6882 size += data->callchain->nr;
6883 size *= sizeof(u64);
6884 __output_copy(handle, data->callchain, size);
6887 if (sample_type & PERF_SAMPLE_RAW) {
6888 struct perf_raw_record *raw = data->raw;
6891 struct perf_raw_frag *frag = &raw->frag;
6893 perf_output_put(handle, raw->size);
6896 __output_custom(handle, frag->copy,
6897 frag->data, frag->size);
6899 __output_copy(handle, frag->data,
6902 if (perf_raw_frag_last(frag))
6907 __output_skip(handle, NULL, frag->pad);
6913 .size = sizeof(u32),
6916 perf_output_put(handle, raw);
6920 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6921 if (data->br_stack) {
6924 size = data->br_stack->nr
6925 * sizeof(struct perf_branch_entry);
6927 perf_output_put(handle, data->br_stack->nr);
6928 if (perf_sample_save_hw_index(event))
6929 perf_output_put(handle, data->br_stack->hw_idx);
6930 perf_output_copy(handle, data->br_stack->entries, size);
6933 * we always store at least the value of nr
6936 perf_output_put(handle, nr);
6940 if (sample_type & PERF_SAMPLE_REGS_USER) {
6941 u64 abi = data->regs_user.abi;
6944 * If there are no regs to dump, notice it through
6945 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6947 perf_output_put(handle, abi);
6950 u64 mask = event->attr.sample_regs_user;
6951 perf_output_sample_regs(handle,
6952 data->regs_user.regs,
6957 if (sample_type & PERF_SAMPLE_STACK_USER) {
6958 perf_output_sample_ustack(handle,
6959 data->stack_user_size,
6960 data->regs_user.regs);
6963 if (sample_type & PERF_SAMPLE_WEIGHT)
6964 perf_output_put(handle, data->weight);
6966 if (sample_type & PERF_SAMPLE_DATA_SRC)
6967 perf_output_put(handle, data->data_src.val);
6969 if (sample_type & PERF_SAMPLE_TRANSACTION)
6970 perf_output_put(handle, data->txn);
6972 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6973 u64 abi = data->regs_intr.abi;
6975 * If there are no regs to dump, notice it through
6976 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6978 perf_output_put(handle, abi);
6981 u64 mask = event->attr.sample_regs_intr;
6983 perf_output_sample_regs(handle,
6984 data->regs_intr.regs,
6989 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6990 perf_output_put(handle, data->phys_addr);
6992 if (sample_type & PERF_SAMPLE_CGROUP)
6993 perf_output_put(handle, data->cgroup);
6995 if (sample_type & PERF_SAMPLE_AUX) {
6996 perf_output_put(handle, data->aux_size);
6999 perf_aux_sample_output(event, handle, data);
7002 if (!event->attr.watermark) {
7003 int wakeup_events = event->attr.wakeup_events;
7005 if (wakeup_events) {
7006 struct perf_buffer *rb = handle->rb;
7007 int events = local_inc_return(&rb->events);
7009 if (events >= wakeup_events) {
7010 local_sub(wakeup_events, &rb->events);
7011 local_inc(&rb->wakeup);
7017 static u64 perf_virt_to_phys(u64 virt)
7024 if (virt >= TASK_SIZE) {
7025 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7026 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7027 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7028 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7031 * Walking the pages tables for user address.
7032 * Interrupts are disabled, so it prevents any tear down
7033 * of the page tables.
7034 * Try IRQ-safe get_user_page_fast_only first.
7035 * If failed, leave phys_addr as 0.
7037 if (current->mm != NULL) {
7040 pagefault_disable();
7041 if (get_user_page_fast_only(virt, 0, &p)) {
7042 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7052 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7054 struct perf_callchain_entry *
7055 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7057 bool kernel = !event->attr.exclude_callchain_kernel;
7058 bool user = !event->attr.exclude_callchain_user;
7059 /* Disallow cross-task user callchains. */
7060 bool crosstask = event->ctx->task && event->ctx->task != current;
7061 const u32 max_stack = event->attr.sample_max_stack;
7062 struct perf_callchain_entry *callchain;
7064 if (!kernel && !user)
7065 return &__empty_callchain;
7067 callchain = get_perf_callchain(regs, 0, kernel, user,
7068 max_stack, crosstask, true);
7069 return callchain ?: &__empty_callchain;
7072 void perf_prepare_sample(struct perf_event_header *header,
7073 struct perf_sample_data *data,
7074 struct perf_event *event,
7075 struct pt_regs *regs)
7077 u64 sample_type = event->attr.sample_type;
7079 header->type = PERF_RECORD_SAMPLE;
7080 header->size = sizeof(*header) + event->header_size;
7083 header->misc |= perf_misc_flags(regs);
7085 __perf_event_header__init_id(header, data, event);
7087 if (sample_type & PERF_SAMPLE_IP)
7088 data->ip = perf_instruction_pointer(regs);
7090 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7093 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
7094 data->callchain = perf_callchain(event, regs);
7096 size += data->callchain->nr;
7098 header->size += size * sizeof(u64);
7101 if (sample_type & PERF_SAMPLE_RAW) {
7102 struct perf_raw_record *raw = data->raw;
7106 struct perf_raw_frag *frag = &raw->frag;
7111 if (perf_raw_frag_last(frag))
7116 size = round_up(sum + sizeof(u32), sizeof(u64));
7117 raw->size = size - sizeof(u32);
7118 frag->pad = raw->size - sum;
7123 header->size += size;
7126 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7127 int size = sizeof(u64); /* nr */
7128 if (data->br_stack) {
7129 if (perf_sample_save_hw_index(event))
7130 size += sizeof(u64);
7132 size += data->br_stack->nr
7133 * sizeof(struct perf_branch_entry);
7135 header->size += size;
7138 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7139 perf_sample_regs_user(&data->regs_user, regs);
7141 if (sample_type & PERF_SAMPLE_REGS_USER) {
7142 /* regs dump ABI info */
7143 int size = sizeof(u64);
7145 if (data->regs_user.regs) {
7146 u64 mask = event->attr.sample_regs_user;
7147 size += hweight64(mask) * sizeof(u64);
7150 header->size += size;
7153 if (sample_type & PERF_SAMPLE_STACK_USER) {
7155 * Either we need PERF_SAMPLE_STACK_USER bit to be always
7156 * processed as the last one or have additional check added
7157 * in case new sample type is added, because we could eat
7158 * up the rest of the sample size.
7160 u16 stack_size = event->attr.sample_stack_user;
7161 u16 size = sizeof(u64);
7163 stack_size = perf_sample_ustack_size(stack_size, header->size,
7164 data->regs_user.regs);
7167 * If there is something to dump, add space for the dump
7168 * itself and for the field that tells the dynamic size,
7169 * which is how many have been actually dumped.
7172 size += sizeof(u64) + stack_size;
7174 data->stack_user_size = stack_size;
7175 header->size += size;
7178 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7179 /* regs dump ABI info */
7180 int size = sizeof(u64);
7182 perf_sample_regs_intr(&data->regs_intr, regs);
7184 if (data->regs_intr.regs) {
7185 u64 mask = event->attr.sample_regs_intr;
7187 size += hweight64(mask) * sizeof(u64);
7190 header->size += size;
7193 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7194 data->phys_addr = perf_virt_to_phys(data->addr);
7196 #ifdef CONFIG_CGROUP_PERF
7197 if (sample_type & PERF_SAMPLE_CGROUP) {
7198 struct cgroup *cgrp;
7200 /* protected by RCU */
7201 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7202 data->cgroup = cgroup_id(cgrp);
7206 if (sample_type & PERF_SAMPLE_AUX) {
7209 header->size += sizeof(u64); /* size */
7212 * Given the 16bit nature of header::size, an AUX sample can
7213 * easily overflow it, what with all the preceding sample bits.
7214 * Make sure this doesn't happen by using up to U16_MAX bytes
7215 * per sample in total (rounded down to 8 byte boundary).
7217 size = min_t(size_t, U16_MAX - header->size,
7218 event->attr.aux_sample_size);
7219 size = rounddown(size, 8);
7220 size = perf_prepare_sample_aux(event, data, size);
7222 WARN_ON_ONCE(size + header->size > U16_MAX);
7223 header->size += size;
7226 * If you're adding more sample types here, you likely need to do
7227 * something about the overflowing header::size, like repurpose the
7228 * lowest 3 bits of size, which should be always zero at the moment.
7229 * This raises a more important question, do we really need 512k sized
7230 * samples and why, so good argumentation is in order for whatever you
7233 WARN_ON_ONCE(header->size & 7);
7236 static __always_inline int
7237 __perf_event_output(struct perf_event *event,
7238 struct perf_sample_data *data,
7239 struct pt_regs *regs,
7240 int (*output_begin)(struct perf_output_handle *,
7241 struct perf_sample_data *,
7242 struct perf_event *,
7245 struct perf_output_handle handle;
7246 struct perf_event_header header;
7249 /* protect the callchain buffers */
7252 perf_prepare_sample(&header, data, event, regs);
7254 err = output_begin(&handle, data, event, header.size);
7258 perf_output_sample(&handle, &header, data, event);
7260 perf_output_end(&handle);
7268 perf_event_output_forward(struct perf_event *event,
7269 struct perf_sample_data *data,
7270 struct pt_regs *regs)
7272 __perf_event_output(event, data, regs, perf_output_begin_forward);
7276 perf_event_output_backward(struct perf_event *event,
7277 struct perf_sample_data *data,
7278 struct pt_regs *regs)
7280 __perf_event_output(event, data, regs, perf_output_begin_backward);
7284 perf_event_output(struct perf_event *event,
7285 struct perf_sample_data *data,
7286 struct pt_regs *regs)
7288 return __perf_event_output(event, data, regs, perf_output_begin);
7295 struct perf_read_event {
7296 struct perf_event_header header;
7303 perf_event_read_event(struct perf_event *event,
7304 struct task_struct *task)
7306 struct perf_output_handle handle;
7307 struct perf_sample_data sample;
7308 struct perf_read_event read_event = {
7310 .type = PERF_RECORD_READ,
7312 .size = sizeof(read_event) + event->read_size,
7314 .pid = perf_event_pid(event, task),
7315 .tid = perf_event_tid(event, task),
7319 perf_event_header__init_id(&read_event.header, &sample, event);
7320 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7324 perf_output_put(&handle, read_event);
7325 perf_output_read(&handle, event);
7326 perf_event__output_id_sample(event, &handle, &sample);
7328 perf_output_end(&handle);
7331 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7334 perf_iterate_ctx(struct perf_event_context *ctx,
7335 perf_iterate_f output,
7336 void *data, bool all)
7338 struct perf_event *event;
7340 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7342 if (event->state < PERF_EVENT_STATE_INACTIVE)
7344 if (!event_filter_match(event))
7348 output(event, data);
7352 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7354 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7355 struct perf_event *event;
7357 list_for_each_entry_rcu(event, &pel->list, sb_list) {
7359 * Skip events that are not fully formed yet; ensure that
7360 * if we observe event->ctx, both event and ctx will be
7361 * complete enough. See perf_install_in_context().
7363 if (!smp_load_acquire(&event->ctx))
7366 if (event->state < PERF_EVENT_STATE_INACTIVE)
7368 if (!event_filter_match(event))
7370 output(event, data);
7375 * Iterate all events that need to receive side-band events.
7377 * For new callers; ensure that account_pmu_sb_event() includes
7378 * your event, otherwise it might not get delivered.
7381 perf_iterate_sb(perf_iterate_f output, void *data,
7382 struct perf_event_context *task_ctx)
7384 struct perf_event_context *ctx;
7391 * If we have task_ctx != NULL we only notify the task context itself.
7392 * The task_ctx is set only for EXIT events before releasing task
7396 perf_iterate_ctx(task_ctx, output, data, false);
7400 perf_iterate_sb_cpu(output, data);
7402 for_each_task_context_nr(ctxn) {
7403 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7405 perf_iterate_ctx(ctx, output, data, false);
7413 * Clear all file-based filters at exec, they'll have to be
7414 * re-instated when/if these objects are mmapped again.
7416 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7418 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7419 struct perf_addr_filter *filter;
7420 unsigned int restart = 0, count = 0;
7421 unsigned long flags;
7423 if (!has_addr_filter(event))
7426 raw_spin_lock_irqsave(&ifh->lock, flags);
7427 list_for_each_entry(filter, &ifh->list, entry) {
7428 if (filter->path.dentry) {
7429 event->addr_filter_ranges[count].start = 0;
7430 event->addr_filter_ranges[count].size = 0;
7438 event->addr_filters_gen++;
7439 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7442 perf_event_stop(event, 1);
7445 void perf_event_exec(void)
7447 struct perf_event_context *ctx;
7451 for_each_task_context_nr(ctxn) {
7452 ctx = current->perf_event_ctxp[ctxn];
7456 perf_event_enable_on_exec(ctxn);
7458 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7464 struct remote_output {
7465 struct perf_buffer *rb;
7469 static void __perf_event_output_stop(struct perf_event *event, void *data)
7471 struct perf_event *parent = event->parent;
7472 struct remote_output *ro = data;
7473 struct perf_buffer *rb = ro->rb;
7474 struct stop_event_data sd = {
7478 if (!has_aux(event))
7485 * In case of inheritance, it will be the parent that links to the
7486 * ring-buffer, but it will be the child that's actually using it.
7488 * We are using event::rb to determine if the event should be stopped,
7489 * however this may race with ring_buffer_attach() (through set_output),
7490 * which will make us skip the event that actually needs to be stopped.
7491 * So ring_buffer_attach() has to stop an aux event before re-assigning
7494 if (rcu_dereference(parent->rb) == rb)
7495 ro->err = __perf_event_stop(&sd);
7498 static int __perf_pmu_output_stop(void *info)
7500 struct perf_event *event = info;
7501 struct pmu *pmu = event->ctx->pmu;
7502 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7503 struct remote_output ro = {
7508 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7509 if (cpuctx->task_ctx)
7510 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7517 static void perf_pmu_output_stop(struct perf_event *event)
7519 struct perf_event *iter;
7524 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7526 * For per-CPU events, we need to make sure that neither they
7527 * nor their children are running; for cpu==-1 events it's
7528 * sufficient to stop the event itself if it's active, since
7529 * it can't have children.
7533 cpu = READ_ONCE(iter->oncpu);
7538 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7539 if (err == -EAGAIN) {
7548 * task tracking -- fork/exit
7550 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7553 struct perf_task_event {
7554 struct task_struct *task;
7555 struct perf_event_context *task_ctx;
7558 struct perf_event_header header;
7568 static int perf_event_task_match(struct perf_event *event)
7570 return event->attr.comm || event->attr.mmap ||
7571 event->attr.mmap2 || event->attr.mmap_data ||
7575 static void perf_event_task_output(struct perf_event *event,
7578 struct perf_task_event *task_event = data;
7579 struct perf_output_handle handle;
7580 struct perf_sample_data sample;
7581 struct task_struct *task = task_event->task;
7582 int ret, size = task_event->event_id.header.size;
7584 if (!perf_event_task_match(event))
7587 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7589 ret = perf_output_begin(&handle, &sample, event,
7590 task_event->event_id.header.size);
7594 task_event->event_id.pid = perf_event_pid(event, task);
7595 task_event->event_id.tid = perf_event_tid(event, task);
7597 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7598 task_event->event_id.ppid = perf_event_pid(event,
7600 task_event->event_id.ptid = perf_event_pid(event,
7602 } else { /* PERF_RECORD_FORK */
7603 task_event->event_id.ppid = perf_event_pid(event, current);
7604 task_event->event_id.ptid = perf_event_tid(event, current);
7607 task_event->event_id.time = perf_event_clock(event);
7609 perf_output_put(&handle, task_event->event_id);
7611 perf_event__output_id_sample(event, &handle, &sample);
7613 perf_output_end(&handle);
7615 task_event->event_id.header.size = size;
7618 static void perf_event_task(struct task_struct *task,
7619 struct perf_event_context *task_ctx,
7622 struct perf_task_event task_event;
7624 if (!atomic_read(&nr_comm_events) &&
7625 !atomic_read(&nr_mmap_events) &&
7626 !atomic_read(&nr_task_events))
7629 task_event = (struct perf_task_event){
7631 .task_ctx = task_ctx,
7634 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7636 .size = sizeof(task_event.event_id),
7646 perf_iterate_sb(perf_event_task_output,
7651 void perf_event_fork(struct task_struct *task)
7653 perf_event_task(task, NULL, 1);
7654 perf_event_namespaces(task);
7661 struct perf_comm_event {
7662 struct task_struct *task;
7667 struct perf_event_header header;
7674 static int perf_event_comm_match(struct perf_event *event)
7676 return event->attr.comm;
7679 static void perf_event_comm_output(struct perf_event *event,
7682 struct perf_comm_event *comm_event = data;
7683 struct perf_output_handle handle;
7684 struct perf_sample_data sample;
7685 int size = comm_event->event_id.header.size;
7688 if (!perf_event_comm_match(event))
7691 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7692 ret = perf_output_begin(&handle, &sample, event,
7693 comm_event->event_id.header.size);
7698 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7699 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7701 perf_output_put(&handle, comm_event->event_id);
7702 __output_copy(&handle, comm_event->comm,
7703 comm_event->comm_size);
7705 perf_event__output_id_sample(event, &handle, &sample);
7707 perf_output_end(&handle);
7709 comm_event->event_id.header.size = size;
7712 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7714 char comm[TASK_COMM_LEN];
7717 memset(comm, 0, sizeof(comm));
7718 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7719 size = ALIGN(strlen(comm)+1, sizeof(u64));
7721 comm_event->comm = comm;
7722 comm_event->comm_size = size;
7724 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7726 perf_iterate_sb(perf_event_comm_output,
7731 void perf_event_comm(struct task_struct *task, bool exec)
7733 struct perf_comm_event comm_event;
7735 if (!atomic_read(&nr_comm_events))
7738 comm_event = (struct perf_comm_event){
7744 .type = PERF_RECORD_COMM,
7745 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7753 perf_event_comm_event(&comm_event);
7757 * namespaces tracking
7760 struct perf_namespaces_event {
7761 struct task_struct *task;
7764 struct perf_event_header header;
7769 struct perf_ns_link_info link_info[NR_NAMESPACES];
7773 static int perf_event_namespaces_match(struct perf_event *event)
7775 return event->attr.namespaces;
7778 static void perf_event_namespaces_output(struct perf_event *event,
7781 struct perf_namespaces_event *namespaces_event = data;
7782 struct perf_output_handle handle;
7783 struct perf_sample_data sample;
7784 u16 header_size = namespaces_event->event_id.header.size;
7787 if (!perf_event_namespaces_match(event))
7790 perf_event_header__init_id(&namespaces_event->event_id.header,
7792 ret = perf_output_begin(&handle, &sample, event,
7793 namespaces_event->event_id.header.size);
7797 namespaces_event->event_id.pid = perf_event_pid(event,
7798 namespaces_event->task);
7799 namespaces_event->event_id.tid = perf_event_tid(event,
7800 namespaces_event->task);
7802 perf_output_put(&handle, namespaces_event->event_id);
7804 perf_event__output_id_sample(event, &handle, &sample);
7806 perf_output_end(&handle);
7808 namespaces_event->event_id.header.size = header_size;
7811 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7812 struct task_struct *task,
7813 const struct proc_ns_operations *ns_ops)
7815 struct path ns_path;
7816 struct inode *ns_inode;
7819 error = ns_get_path(&ns_path, task, ns_ops);
7821 ns_inode = ns_path.dentry->d_inode;
7822 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7823 ns_link_info->ino = ns_inode->i_ino;
7828 void perf_event_namespaces(struct task_struct *task)
7830 struct perf_namespaces_event namespaces_event;
7831 struct perf_ns_link_info *ns_link_info;
7833 if (!atomic_read(&nr_namespaces_events))
7836 namespaces_event = (struct perf_namespaces_event){
7840 .type = PERF_RECORD_NAMESPACES,
7842 .size = sizeof(namespaces_event.event_id),
7846 .nr_namespaces = NR_NAMESPACES,
7847 /* .link_info[NR_NAMESPACES] */
7851 ns_link_info = namespaces_event.event_id.link_info;
7853 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7854 task, &mntns_operations);
7856 #ifdef CONFIG_USER_NS
7857 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7858 task, &userns_operations);
7860 #ifdef CONFIG_NET_NS
7861 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7862 task, &netns_operations);
7864 #ifdef CONFIG_UTS_NS
7865 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7866 task, &utsns_operations);
7868 #ifdef CONFIG_IPC_NS
7869 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7870 task, &ipcns_operations);
7872 #ifdef CONFIG_PID_NS
7873 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7874 task, &pidns_operations);
7876 #ifdef CONFIG_CGROUPS
7877 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7878 task, &cgroupns_operations);
7881 perf_iterate_sb(perf_event_namespaces_output,
7889 #ifdef CONFIG_CGROUP_PERF
7891 struct perf_cgroup_event {
7895 struct perf_event_header header;
7901 static int perf_event_cgroup_match(struct perf_event *event)
7903 return event->attr.cgroup;
7906 static void perf_event_cgroup_output(struct perf_event *event, void *data)
7908 struct perf_cgroup_event *cgroup_event = data;
7909 struct perf_output_handle handle;
7910 struct perf_sample_data sample;
7911 u16 header_size = cgroup_event->event_id.header.size;
7914 if (!perf_event_cgroup_match(event))
7917 perf_event_header__init_id(&cgroup_event->event_id.header,
7919 ret = perf_output_begin(&handle, &sample, event,
7920 cgroup_event->event_id.header.size);
7924 perf_output_put(&handle, cgroup_event->event_id);
7925 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7927 perf_event__output_id_sample(event, &handle, &sample);
7929 perf_output_end(&handle);
7931 cgroup_event->event_id.header.size = header_size;
7934 static void perf_event_cgroup(struct cgroup *cgrp)
7936 struct perf_cgroup_event cgroup_event;
7937 char path_enomem[16] = "//enomem";
7941 if (!atomic_read(&nr_cgroup_events))
7944 cgroup_event = (struct perf_cgroup_event){
7947 .type = PERF_RECORD_CGROUP,
7949 .size = sizeof(cgroup_event.event_id),
7951 .id = cgroup_id(cgrp),
7955 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7956 if (pathname == NULL) {
7957 cgroup_event.path = path_enomem;
7959 /* just to be sure to have enough space for alignment */
7960 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7961 cgroup_event.path = pathname;
7965 * Since our buffer works in 8 byte units we need to align our string
7966 * size to a multiple of 8. However, we must guarantee the tail end is
7967 * zero'd out to avoid leaking random bits to userspace.
7969 size = strlen(cgroup_event.path) + 1;
7970 while (!IS_ALIGNED(size, sizeof(u64)))
7971 cgroup_event.path[size++] = '\0';
7973 cgroup_event.event_id.header.size += size;
7974 cgroup_event.path_size = size;
7976 perf_iterate_sb(perf_event_cgroup_output,
7989 struct perf_mmap_event {
7990 struct vm_area_struct *vma;
7992 const char *file_name;
8000 struct perf_event_header header;
8010 static int perf_event_mmap_match(struct perf_event *event,
8013 struct perf_mmap_event *mmap_event = data;
8014 struct vm_area_struct *vma = mmap_event->vma;
8015 int executable = vma->vm_flags & VM_EXEC;
8017 return (!executable && event->attr.mmap_data) ||
8018 (executable && (event->attr.mmap || event->attr.mmap2));
8021 static void perf_event_mmap_output(struct perf_event *event,
8024 struct perf_mmap_event *mmap_event = data;
8025 struct perf_output_handle handle;
8026 struct perf_sample_data sample;
8027 int size = mmap_event->event_id.header.size;
8028 u32 type = mmap_event->event_id.header.type;
8031 if (!perf_event_mmap_match(event, data))
8034 if (event->attr.mmap2) {
8035 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8036 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8037 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8038 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8039 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8040 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8041 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8044 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8045 ret = perf_output_begin(&handle, &sample, event,
8046 mmap_event->event_id.header.size);
8050 mmap_event->event_id.pid = perf_event_pid(event, current);
8051 mmap_event->event_id.tid = perf_event_tid(event, current);
8053 perf_output_put(&handle, mmap_event->event_id);
8055 if (event->attr.mmap2) {
8056 perf_output_put(&handle, mmap_event->maj);
8057 perf_output_put(&handle, mmap_event->min);
8058 perf_output_put(&handle, mmap_event->ino);
8059 perf_output_put(&handle, mmap_event->ino_generation);
8060 perf_output_put(&handle, mmap_event->prot);
8061 perf_output_put(&handle, mmap_event->flags);
8064 __output_copy(&handle, mmap_event->file_name,
8065 mmap_event->file_size);
8067 perf_event__output_id_sample(event, &handle, &sample);
8069 perf_output_end(&handle);
8071 mmap_event->event_id.header.size = size;
8072 mmap_event->event_id.header.type = type;
8075 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8077 struct vm_area_struct *vma = mmap_event->vma;
8078 struct file *file = vma->vm_file;
8079 int maj = 0, min = 0;
8080 u64 ino = 0, gen = 0;
8081 u32 prot = 0, flags = 0;
8087 if (vma->vm_flags & VM_READ)
8089 if (vma->vm_flags & VM_WRITE)
8091 if (vma->vm_flags & VM_EXEC)
8094 if (vma->vm_flags & VM_MAYSHARE)
8097 flags = MAP_PRIVATE;
8099 if (vma->vm_flags & VM_DENYWRITE)
8100 flags |= MAP_DENYWRITE;
8101 if (vma->vm_flags & VM_MAYEXEC)
8102 flags |= MAP_EXECUTABLE;
8103 if (vma->vm_flags & VM_LOCKED)
8104 flags |= MAP_LOCKED;
8105 if (is_vm_hugetlb_page(vma))
8106 flags |= MAP_HUGETLB;
8109 struct inode *inode;
8112 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8118 * d_path() works from the end of the rb backwards, so we
8119 * need to add enough zero bytes after the string to handle
8120 * the 64bit alignment we do later.
8122 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8127 inode = file_inode(vma->vm_file);
8128 dev = inode->i_sb->s_dev;
8130 gen = inode->i_generation;
8136 if (vma->vm_ops && vma->vm_ops->name) {
8137 name = (char *) vma->vm_ops->name(vma);
8142 name = (char *)arch_vma_name(vma);
8146 if (vma->vm_start <= vma->vm_mm->start_brk &&
8147 vma->vm_end >= vma->vm_mm->brk) {
8151 if (vma->vm_start <= vma->vm_mm->start_stack &&
8152 vma->vm_end >= vma->vm_mm->start_stack) {
8162 strlcpy(tmp, name, sizeof(tmp));
8166 * Since our buffer works in 8 byte units we need to align our string
8167 * size to a multiple of 8. However, we must guarantee the tail end is
8168 * zero'd out to avoid leaking random bits to userspace.
8170 size = strlen(name)+1;
8171 while (!IS_ALIGNED(size, sizeof(u64)))
8172 name[size++] = '\0';
8174 mmap_event->file_name = name;
8175 mmap_event->file_size = size;
8176 mmap_event->maj = maj;
8177 mmap_event->min = min;
8178 mmap_event->ino = ino;
8179 mmap_event->ino_generation = gen;
8180 mmap_event->prot = prot;
8181 mmap_event->flags = flags;
8183 if (!(vma->vm_flags & VM_EXEC))
8184 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8186 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8188 perf_iterate_sb(perf_event_mmap_output,
8196 * Check whether inode and address range match filter criteria.
8198 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8199 struct file *file, unsigned long offset,
8202 /* d_inode(NULL) won't be equal to any mapped user-space file */
8203 if (!filter->path.dentry)
8206 if (d_inode(filter->path.dentry) != file_inode(file))
8209 if (filter->offset > offset + size)
8212 if (filter->offset + filter->size < offset)
8218 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8219 struct vm_area_struct *vma,
8220 struct perf_addr_filter_range *fr)
8222 unsigned long vma_size = vma->vm_end - vma->vm_start;
8223 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8224 struct file *file = vma->vm_file;
8226 if (!perf_addr_filter_match(filter, file, off, vma_size))
8229 if (filter->offset < off) {
8230 fr->start = vma->vm_start;
8231 fr->size = min(vma_size, filter->size - (off - filter->offset));
8233 fr->start = vma->vm_start + filter->offset - off;
8234 fr->size = min(vma->vm_end - fr->start, filter->size);
8240 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8242 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8243 struct vm_area_struct *vma = data;
8244 struct perf_addr_filter *filter;
8245 unsigned int restart = 0, count = 0;
8246 unsigned long flags;
8248 if (!has_addr_filter(event))
8254 raw_spin_lock_irqsave(&ifh->lock, flags);
8255 list_for_each_entry(filter, &ifh->list, entry) {
8256 if (perf_addr_filter_vma_adjust(filter, vma,
8257 &event->addr_filter_ranges[count]))
8264 event->addr_filters_gen++;
8265 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8268 perf_event_stop(event, 1);
8272 * Adjust all task's events' filters to the new vma
8274 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8276 struct perf_event_context *ctx;
8280 * Data tracing isn't supported yet and as such there is no need
8281 * to keep track of anything that isn't related to executable code:
8283 if (!(vma->vm_flags & VM_EXEC))
8287 for_each_task_context_nr(ctxn) {
8288 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8292 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8297 void perf_event_mmap(struct vm_area_struct *vma)
8299 struct perf_mmap_event mmap_event;
8301 if (!atomic_read(&nr_mmap_events))
8304 mmap_event = (struct perf_mmap_event){
8310 .type = PERF_RECORD_MMAP,
8311 .misc = PERF_RECORD_MISC_USER,
8316 .start = vma->vm_start,
8317 .len = vma->vm_end - vma->vm_start,
8318 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
8320 /* .maj (attr_mmap2 only) */
8321 /* .min (attr_mmap2 only) */
8322 /* .ino (attr_mmap2 only) */
8323 /* .ino_generation (attr_mmap2 only) */
8324 /* .prot (attr_mmap2 only) */
8325 /* .flags (attr_mmap2 only) */
8328 perf_addr_filters_adjust(vma);
8329 perf_event_mmap_event(&mmap_event);
8332 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8333 unsigned long size, u64 flags)
8335 struct perf_output_handle handle;
8336 struct perf_sample_data sample;
8337 struct perf_aux_event {
8338 struct perf_event_header header;
8344 .type = PERF_RECORD_AUX,
8346 .size = sizeof(rec),
8354 perf_event_header__init_id(&rec.header, &sample, event);
8355 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8360 perf_output_put(&handle, rec);
8361 perf_event__output_id_sample(event, &handle, &sample);
8363 perf_output_end(&handle);
8367 * Lost/dropped samples logging
8369 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8371 struct perf_output_handle handle;
8372 struct perf_sample_data sample;
8376 struct perf_event_header header;
8378 } lost_samples_event = {
8380 .type = PERF_RECORD_LOST_SAMPLES,
8382 .size = sizeof(lost_samples_event),
8387 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8389 ret = perf_output_begin(&handle, &sample, event,
8390 lost_samples_event.header.size);
8394 perf_output_put(&handle, lost_samples_event);
8395 perf_event__output_id_sample(event, &handle, &sample);
8396 perf_output_end(&handle);
8400 * context_switch tracking
8403 struct perf_switch_event {
8404 struct task_struct *task;
8405 struct task_struct *next_prev;
8408 struct perf_event_header header;
8414 static int perf_event_switch_match(struct perf_event *event)
8416 return event->attr.context_switch;
8419 static void perf_event_switch_output(struct perf_event *event, void *data)
8421 struct perf_switch_event *se = data;
8422 struct perf_output_handle handle;
8423 struct perf_sample_data sample;
8426 if (!perf_event_switch_match(event))
8429 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8430 if (event->ctx->task) {
8431 se->event_id.header.type = PERF_RECORD_SWITCH;
8432 se->event_id.header.size = sizeof(se->event_id.header);
8434 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8435 se->event_id.header.size = sizeof(se->event_id);
8436 se->event_id.next_prev_pid =
8437 perf_event_pid(event, se->next_prev);
8438 se->event_id.next_prev_tid =
8439 perf_event_tid(event, se->next_prev);
8442 perf_event_header__init_id(&se->event_id.header, &sample, event);
8444 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8448 if (event->ctx->task)
8449 perf_output_put(&handle, se->event_id.header);
8451 perf_output_put(&handle, se->event_id);
8453 perf_event__output_id_sample(event, &handle, &sample);
8455 perf_output_end(&handle);
8458 static void perf_event_switch(struct task_struct *task,
8459 struct task_struct *next_prev, bool sched_in)
8461 struct perf_switch_event switch_event;
8463 /* N.B. caller checks nr_switch_events != 0 */
8465 switch_event = (struct perf_switch_event){
8467 .next_prev = next_prev,
8471 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8474 /* .next_prev_pid */
8475 /* .next_prev_tid */
8479 if (!sched_in && task->state == TASK_RUNNING)
8480 switch_event.event_id.header.misc |=
8481 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8483 perf_iterate_sb(perf_event_switch_output,
8489 * IRQ throttle logging
8492 static void perf_log_throttle(struct perf_event *event, int enable)
8494 struct perf_output_handle handle;
8495 struct perf_sample_data sample;
8499 struct perf_event_header header;
8503 } throttle_event = {
8505 .type = PERF_RECORD_THROTTLE,
8507 .size = sizeof(throttle_event),
8509 .time = perf_event_clock(event),
8510 .id = primary_event_id(event),
8511 .stream_id = event->id,
8515 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
8517 perf_event_header__init_id(&throttle_event.header, &sample, event);
8519 ret = perf_output_begin(&handle, &sample, event,
8520 throttle_event.header.size);
8524 perf_output_put(&handle, throttle_event);
8525 perf_event__output_id_sample(event, &handle, &sample);
8526 perf_output_end(&handle);
8530 * ksymbol register/unregister tracking
8533 struct perf_ksymbol_event {
8537 struct perf_event_header header;
8545 static int perf_event_ksymbol_match(struct perf_event *event)
8547 return event->attr.ksymbol;
8550 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8552 struct perf_ksymbol_event *ksymbol_event = data;
8553 struct perf_output_handle handle;
8554 struct perf_sample_data sample;
8557 if (!perf_event_ksymbol_match(event))
8560 perf_event_header__init_id(&ksymbol_event->event_id.header,
8562 ret = perf_output_begin(&handle, &sample, event,
8563 ksymbol_event->event_id.header.size);
8567 perf_output_put(&handle, ksymbol_event->event_id);
8568 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8569 perf_event__output_id_sample(event, &handle, &sample);
8571 perf_output_end(&handle);
8574 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8577 struct perf_ksymbol_event ksymbol_event;
8578 char name[KSYM_NAME_LEN];
8582 if (!atomic_read(&nr_ksymbol_events))
8585 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8586 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8589 strlcpy(name, sym, KSYM_NAME_LEN);
8590 name_len = strlen(name) + 1;
8591 while (!IS_ALIGNED(name_len, sizeof(u64)))
8592 name[name_len++] = '\0';
8593 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8596 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8598 ksymbol_event = (struct perf_ksymbol_event){
8600 .name_len = name_len,
8603 .type = PERF_RECORD_KSYMBOL,
8604 .size = sizeof(ksymbol_event.event_id) +
8609 .ksym_type = ksym_type,
8614 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8617 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8621 * bpf program load/unload tracking
8624 struct perf_bpf_event {
8625 struct bpf_prog *prog;
8627 struct perf_event_header header;
8631 u8 tag[BPF_TAG_SIZE];
8635 static int perf_event_bpf_match(struct perf_event *event)
8637 return event->attr.bpf_event;
8640 static void perf_event_bpf_output(struct perf_event *event, void *data)
8642 struct perf_bpf_event *bpf_event = data;
8643 struct perf_output_handle handle;
8644 struct perf_sample_data sample;
8647 if (!perf_event_bpf_match(event))
8650 perf_event_header__init_id(&bpf_event->event_id.header,
8652 ret = perf_output_begin(&handle, data, event,
8653 bpf_event->event_id.header.size);
8657 perf_output_put(&handle, bpf_event->event_id);
8658 perf_event__output_id_sample(event, &handle, &sample);
8660 perf_output_end(&handle);
8663 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8664 enum perf_bpf_event_type type)
8666 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8669 if (prog->aux->func_cnt == 0) {
8670 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8671 (u64)(unsigned long)prog->bpf_func,
8672 prog->jited_len, unregister,
8673 prog->aux->ksym.name);
8675 for (i = 0; i < prog->aux->func_cnt; i++) {
8676 struct bpf_prog *subprog = prog->aux->func[i];
8679 PERF_RECORD_KSYMBOL_TYPE_BPF,
8680 (u64)(unsigned long)subprog->bpf_func,
8681 subprog->jited_len, unregister,
8682 prog->aux->ksym.name);
8687 void perf_event_bpf_event(struct bpf_prog *prog,
8688 enum perf_bpf_event_type type,
8691 struct perf_bpf_event bpf_event;
8693 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8694 type >= PERF_BPF_EVENT_MAX)
8698 case PERF_BPF_EVENT_PROG_LOAD:
8699 case PERF_BPF_EVENT_PROG_UNLOAD:
8700 if (atomic_read(&nr_ksymbol_events))
8701 perf_event_bpf_emit_ksymbols(prog, type);
8707 if (!atomic_read(&nr_bpf_events))
8710 bpf_event = (struct perf_bpf_event){
8714 .type = PERF_RECORD_BPF_EVENT,
8715 .size = sizeof(bpf_event.event_id),
8719 .id = prog->aux->id,
8723 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8725 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8726 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8729 struct perf_text_poke_event {
8730 const void *old_bytes;
8731 const void *new_bytes;
8737 struct perf_event_header header;
8743 static int perf_event_text_poke_match(struct perf_event *event)
8745 return event->attr.text_poke;
8748 static void perf_event_text_poke_output(struct perf_event *event, void *data)
8750 struct perf_text_poke_event *text_poke_event = data;
8751 struct perf_output_handle handle;
8752 struct perf_sample_data sample;
8756 if (!perf_event_text_poke_match(event))
8759 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
8761 ret = perf_output_begin(&handle, &sample, event,
8762 text_poke_event->event_id.header.size);
8766 perf_output_put(&handle, text_poke_event->event_id);
8767 perf_output_put(&handle, text_poke_event->old_len);
8768 perf_output_put(&handle, text_poke_event->new_len);
8770 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
8771 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
8773 if (text_poke_event->pad)
8774 __output_copy(&handle, &padding, text_poke_event->pad);
8776 perf_event__output_id_sample(event, &handle, &sample);
8778 perf_output_end(&handle);
8781 void perf_event_text_poke(const void *addr, const void *old_bytes,
8782 size_t old_len, const void *new_bytes, size_t new_len)
8784 struct perf_text_poke_event text_poke_event;
8787 if (!atomic_read(&nr_text_poke_events))
8790 tot = sizeof(text_poke_event.old_len) + old_len;
8791 tot += sizeof(text_poke_event.new_len) + new_len;
8792 pad = ALIGN(tot, sizeof(u64)) - tot;
8794 text_poke_event = (struct perf_text_poke_event){
8795 .old_bytes = old_bytes,
8796 .new_bytes = new_bytes,
8802 .type = PERF_RECORD_TEXT_POKE,
8803 .misc = PERF_RECORD_MISC_KERNEL,
8804 .size = sizeof(text_poke_event.event_id) + tot + pad,
8806 .addr = (unsigned long)addr,
8810 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
8813 void perf_event_itrace_started(struct perf_event *event)
8815 event->attach_state |= PERF_ATTACH_ITRACE;
8818 static void perf_log_itrace_start(struct perf_event *event)
8820 struct perf_output_handle handle;
8821 struct perf_sample_data sample;
8822 struct perf_aux_event {
8823 struct perf_event_header header;
8830 event = event->parent;
8832 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8833 event->attach_state & PERF_ATTACH_ITRACE)
8836 rec.header.type = PERF_RECORD_ITRACE_START;
8837 rec.header.misc = 0;
8838 rec.header.size = sizeof(rec);
8839 rec.pid = perf_event_pid(event, current);
8840 rec.tid = perf_event_tid(event, current);
8842 perf_event_header__init_id(&rec.header, &sample, event);
8843 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8848 perf_output_put(&handle, rec);
8849 perf_event__output_id_sample(event, &handle, &sample);
8851 perf_output_end(&handle);
8855 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8857 struct hw_perf_event *hwc = &event->hw;
8861 seq = __this_cpu_read(perf_throttled_seq);
8862 if (seq != hwc->interrupts_seq) {
8863 hwc->interrupts_seq = seq;
8864 hwc->interrupts = 1;
8867 if (unlikely(throttle
8868 && hwc->interrupts >= max_samples_per_tick)) {
8869 __this_cpu_inc(perf_throttled_count);
8870 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8871 hwc->interrupts = MAX_INTERRUPTS;
8872 perf_log_throttle(event, 0);
8877 if (event->attr.freq) {
8878 u64 now = perf_clock();
8879 s64 delta = now - hwc->freq_time_stamp;
8881 hwc->freq_time_stamp = now;
8883 if (delta > 0 && delta < 2*TICK_NSEC)
8884 perf_adjust_period(event, delta, hwc->last_period, true);
8890 int perf_event_account_interrupt(struct perf_event *event)
8892 return __perf_event_account_interrupt(event, 1);
8896 * Generic event overflow handling, sampling.
8899 static int __perf_event_overflow(struct perf_event *event,
8900 int throttle, struct perf_sample_data *data,
8901 struct pt_regs *regs)
8903 int events = atomic_read(&event->event_limit);
8907 * Non-sampling counters might still use the PMI to fold short
8908 * hardware counters, ignore those.
8910 if (unlikely(!is_sampling_event(event)))
8913 ret = __perf_event_account_interrupt(event, throttle);
8916 * XXX event_limit might not quite work as expected on inherited
8920 event->pending_kill = POLL_IN;
8921 if (events && atomic_dec_and_test(&event->event_limit)) {
8923 event->pending_kill = POLL_HUP;
8925 perf_event_disable_inatomic(event);
8928 READ_ONCE(event->overflow_handler)(event, data, regs);
8930 if (*perf_event_fasync(event) && event->pending_kill) {
8931 event->pending_wakeup = 1;
8932 irq_work_queue(&event->pending);
8938 int perf_event_overflow(struct perf_event *event,
8939 struct perf_sample_data *data,
8940 struct pt_regs *regs)
8942 return __perf_event_overflow(event, 1, data, regs);
8946 * Generic software event infrastructure
8949 struct swevent_htable {
8950 struct swevent_hlist *swevent_hlist;
8951 struct mutex hlist_mutex;
8954 /* Recursion avoidance in each contexts */
8955 int recursion[PERF_NR_CONTEXTS];
8958 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8961 * We directly increment event->count and keep a second value in
8962 * event->hw.period_left to count intervals. This period event
8963 * is kept in the range [-sample_period, 0] so that we can use the
8967 u64 perf_swevent_set_period(struct perf_event *event)
8969 struct hw_perf_event *hwc = &event->hw;
8970 u64 period = hwc->last_period;
8974 hwc->last_period = hwc->sample_period;
8977 old = val = local64_read(&hwc->period_left);
8981 nr = div64_u64(period + val, period);
8982 offset = nr * period;
8984 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8990 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8991 struct perf_sample_data *data,
8992 struct pt_regs *regs)
8994 struct hw_perf_event *hwc = &event->hw;
8998 overflow = perf_swevent_set_period(event);
9000 if (hwc->interrupts == MAX_INTERRUPTS)
9003 for (; overflow; overflow--) {
9004 if (__perf_event_overflow(event, throttle,
9007 * We inhibit the overflow from happening when
9008 * hwc->interrupts == MAX_INTERRUPTS.
9016 static void perf_swevent_event(struct perf_event *event, u64 nr,
9017 struct perf_sample_data *data,
9018 struct pt_regs *regs)
9020 struct hw_perf_event *hwc = &event->hw;
9022 local64_add(nr, &event->count);
9027 if (!is_sampling_event(event))
9030 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9032 return perf_swevent_overflow(event, 1, data, regs);
9034 data->period = event->hw.last_period;
9036 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9037 return perf_swevent_overflow(event, 1, data, regs);
9039 if (local64_add_negative(nr, &hwc->period_left))
9042 perf_swevent_overflow(event, 0, data, regs);
9045 static int perf_exclude_event(struct perf_event *event,
9046 struct pt_regs *regs)
9048 if (event->hw.state & PERF_HES_STOPPED)
9052 if (event->attr.exclude_user && user_mode(regs))
9055 if (event->attr.exclude_kernel && !user_mode(regs))
9062 static int perf_swevent_match(struct perf_event *event,
9063 enum perf_type_id type,
9065 struct perf_sample_data *data,
9066 struct pt_regs *regs)
9068 if (event->attr.type != type)
9071 if (event->attr.config != event_id)
9074 if (perf_exclude_event(event, regs))
9080 static inline u64 swevent_hash(u64 type, u32 event_id)
9082 u64 val = event_id | (type << 32);
9084 return hash_64(val, SWEVENT_HLIST_BITS);
9087 static inline struct hlist_head *
9088 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9090 u64 hash = swevent_hash(type, event_id);
9092 return &hlist->heads[hash];
9095 /* For the read side: events when they trigger */
9096 static inline struct hlist_head *
9097 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9099 struct swevent_hlist *hlist;
9101 hlist = rcu_dereference(swhash->swevent_hlist);
9105 return __find_swevent_head(hlist, type, event_id);
9108 /* For the event head insertion and removal in the hlist */
9109 static inline struct hlist_head *
9110 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9112 struct swevent_hlist *hlist;
9113 u32 event_id = event->attr.config;
9114 u64 type = event->attr.type;
9117 * Event scheduling is always serialized against hlist allocation
9118 * and release. Which makes the protected version suitable here.
9119 * The context lock guarantees that.
9121 hlist = rcu_dereference_protected(swhash->swevent_hlist,
9122 lockdep_is_held(&event->ctx->lock));
9126 return __find_swevent_head(hlist, type, event_id);
9129 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9131 struct perf_sample_data *data,
9132 struct pt_regs *regs)
9134 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9135 struct perf_event *event;
9136 struct hlist_head *head;
9139 head = find_swevent_head_rcu(swhash, type, event_id);
9143 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9144 if (perf_swevent_match(event, type, event_id, data, regs))
9145 perf_swevent_event(event, nr, data, regs);
9151 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9153 int perf_swevent_get_recursion_context(void)
9155 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9157 return get_recursion_context(swhash->recursion);
9159 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9161 void perf_swevent_put_recursion_context(int rctx)
9163 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9165 put_recursion_context(swhash->recursion, rctx);
9168 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9170 struct perf_sample_data data;
9172 if (WARN_ON_ONCE(!regs))
9175 perf_sample_data_init(&data, addr, 0);
9176 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9179 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9183 preempt_disable_notrace();
9184 rctx = perf_swevent_get_recursion_context();
9185 if (unlikely(rctx < 0))
9188 ___perf_sw_event(event_id, nr, regs, addr);
9190 perf_swevent_put_recursion_context(rctx);
9192 preempt_enable_notrace();
9195 static void perf_swevent_read(struct perf_event *event)
9199 static int perf_swevent_add(struct perf_event *event, int flags)
9201 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9202 struct hw_perf_event *hwc = &event->hw;
9203 struct hlist_head *head;
9205 if (is_sampling_event(event)) {
9206 hwc->last_period = hwc->sample_period;
9207 perf_swevent_set_period(event);
9210 hwc->state = !(flags & PERF_EF_START);
9212 head = find_swevent_head(swhash, event);
9213 if (WARN_ON_ONCE(!head))
9216 hlist_add_head_rcu(&event->hlist_entry, head);
9217 perf_event_update_userpage(event);
9222 static void perf_swevent_del(struct perf_event *event, int flags)
9224 hlist_del_rcu(&event->hlist_entry);
9227 static void perf_swevent_start(struct perf_event *event, int flags)
9229 event->hw.state = 0;
9232 static void perf_swevent_stop(struct perf_event *event, int flags)
9234 event->hw.state = PERF_HES_STOPPED;
9237 /* Deref the hlist from the update side */
9238 static inline struct swevent_hlist *
9239 swevent_hlist_deref(struct swevent_htable *swhash)
9241 return rcu_dereference_protected(swhash->swevent_hlist,
9242 lockdep_is_held(&swhash->hlist_mutex));
9245 static void swevent_hlist_release(struct swevent_htable *swhash)
9247 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9252 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9253 kfree_rcu(hlist, rcu_head);
9256 static void swevent_hlist_put_cpu(int cpu)
9258 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9260 mutex_lock(&swhash->hlist_mutex);
9262 if (!--swhash->hlist_refcount)
9263 swevent_hlist_release(swhash);
9265 mutex_unlock(&swhash->hlist_mutex);
9268 static void swevent_hlist_put(void)
9272 for_each_possible_cpu(cpu)
9273 swevent_hlist_put_cpu(cpu);
9276 static int swevent_hlist_get_cpu(int cpu)
9278 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9281 mutex_lock(&swhash->hlist_mutex);
9282 if (!swevent_hlist_deref(swhash) &&
9283 cpumask_test_cpu(cpu, perf_online_mask)) {
9284 struct swevent_hlist *hlist;
9286 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9291 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9293 swhash->hlist_refcount++;
9295 mutex_unlock(&swhash->hlist_mutex);
9300 static int swevent_hlist_get(void)
9302 int err, cpu, failed_cpu;
9304 mutex_lock(&pmus_lock);
9305 for_each_possible_cpu(cpu) {
9306 err = swevent_hlist_get_cpu(cpu);
9312 mutex_unlock(&pmus_lock);
9315 for_each_possible_cpu(cpu) {
9316 if (cpu == failed_cpu)
9318 swevent_hlist_put_cpu(cpu);
9320 mutex_unlock(&pmus_lock);
9324 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9326 static void sw_perf_event_destroy(struct perf_event *event)
9328 u64 event_id = event->attr.config;
9330 WARN_ON(event->parent);
9332 static_key_slow_dec(&perf_swevent_enabled[event_id]);
9333 swevent_hlist_put();
9336 static int perf_swevent_init(struct perf_event *event)
9338 u64 event_id = event->attr.config;
9340 if (event->attr.type != PERF_TYPE_SOFTWARE)
9344 * no branch sampling for software events
9346 if (has_branch_stack(event))
9350 case PERF_COUNT_SW_CPU_CLOCK:
9351 case PERF_COUNT_SW_TASK_CLOCK:
9358 if (event_id >= PERF_COUNT_SW_MAX)
9361 if (!event->parent) {
9364 err = swevent_hlist_get();
9368 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9369 event->destroy = sw_perf_event_destroy;
9375 static struct pmu perf_swevent = {
9376 .task_ctx_nr = perf_sw_context,
9378 .capabilities = PERF_PMU_CAP_NO_NMI,
9380 .event_init = perf_swevent_init,
9381 .add = perf_swevent_add,
9382 .del = perf_swevent_del,
9383 .start = perf_swevent_start,
9384 .stop = perf_swevent_stop,
9385 .read = perf_swevent_read,
9388 #ifdef CONFIG_EVENT_TRACING
9390 static int perf_tp_filter_match(struct perf_event *event,
9391 struct perf_sample_data *data)
9393 void *record = data->raw->frag.data;
9395 /* only top level events have filters set */
9397 event = event->parent;
9399 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9404 static int perf_tp_event_match(struct perf_event *event,
9405 struct perf_sample_data *data,
9406 struct pt_regs *regs)
9408 if (event->hw.state & PERF_HES_STOPPED)
9411 * If exclude_kernel, only trace user-space tracepoints (uprobes)
9413 if (event->attr.exclude_kernel && !user_mode(regs))
9416 if (!perf_tp_filter_match(event, data))
9422 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9423 struct trace_event_call *call, u64 count,
9424 struct pt_regs *regs, struct hlist_head *head,
9425 struct task_struct *task)
9427 if (bpf_prog_array_valid(call)) {
9428 *(struct pt_regs **)raw_data = regs;
9429 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
9430 perf_swevent_put_recursion_context(rctx);
9434 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
9437 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9439 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
9440 struct pt_regs *regs, struct hlist_head *head, int rctx,
9441 struct task_struct *task)
9443 struct perf_sample_data data;
9444 struct perf_event *event;
9446 struct perf_raw_record raw = {
9453 perf_sample_data_init(&data, 0, 0);
9456 perf_trace_buf_update(record, event_type);
9458 hlist_for_each_entry_rcu(event, head, hlist_entry) {
9459 if (perf_tp_event_match(event, &data, regs))
9460 perf_swevent_event(event, count, &data, regs);
9464 * If we got specified a target task, also iterate its context and
9465 * deliver this event there too.
9467 if (task && task != current) {
9468 struct perf_event_context *ctx;
9469 struct trace_entry *entry = record;
9472 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9476 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9477 if (event->cpu != smp_processor_id())
9479 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9481 if (event->attr.config != entry->type)
9483 if (perf_tp_event_match(event, &data, regs))
9484 perf_swevent_event(event, count, &data, regs);
9490 perf_swevent_put_recursion_context(rctx);
9492 EXPORT_SYMBOL_GPL(perf_tp_event);
9494 static void tp_perf_event_destroy(struct perf_event *event)
9496 perf_trace_destroy(event);
9499 static int perf_tp_event_init(struct perf_event *event)
9503 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9507 * no branch sampling for tracepoint events
9509 if (has_branch_stack(event))
9512 err = perf_trace_init(event);
9516 event->destroy = tp_perf_event_destroy;
9521 static struct pmu perf_tracepoint = {
9522 .task_ctx_nr = perf_sw_context,
9524 .event_init = perf_tp_event_init,
9525 .add = perf_trace_add,
9526 .del = perf_trace_del,
9527 .start = perf_swevent_start,
9528 .stop = perf_swevent_stop,
9529 .read = perf_swevent_read,
9532 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
9534 * Flags in config, used by dynamic PMU kprobe and uprobe
9535 * The flags should match following PMU_FORMAT_ATTR().
9537 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9538 * if not set, create kprobe/uprobe
9540 * The following values specify a reference counter (or semaphore in the
9541 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9542 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9544 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9545 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
9547 enum perf_probe_config {
9548 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
9549 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9550 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
9553 PMU_FORMAT_ATTR(retprobe, "config:0");
9556 #ifdef CONFIG_KPROBE_EVENTS
9557 static struct attribute *kprobe_attrs[] = {
9558 &format_attr_retprobe.attr,
9562 static struct attribute_group kprobe_format_group = {
9564 .attrs = kprobe_attrs,
9567 static const struct attribute_group *kprobe_attr_groups[] = {
9568 &kprobe_format_group,
9572 static int perf_kprobe_event_init(struct perf_event *event);
9573 static struct pmu perf_kprobe = {
9574 .task_ctx_nr = perf_sw_context,
9575 .event_init = perf_kprobe_event_init,
9576 .add = perf_trace_add,
9577 .del = perf_trace_del,
9578 .start = perf_swevent_start,
9579 .stop = perf_swevent_stop,
9580 .read = perf_swevent_read,
9581 .attr_groups = kprobe_attr_groups,
9584 static int perf_kprobe_event_init(struct perf_event *event)
9589 if (event->attr.type != perf_kprobe.type)
9592 if (!perfmon_capable())
9596 * no branch sampling for probe events
9598 if (has_branch_stack(event))
9601 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9602 err = perf_kprobe_init(event, is_retprobe);
9606 event->destroy = perf_kprobe_destroy;
9610 #endif /* CONFIG_KPROBE_EVENTS */
9612 #ifdef CONFIG_UPROBE_EVENTS
9613 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9615 static struct attribute *uprobe_attrs[] = {
9616 &format_attr_retprobe.attr,
9617 &format_attr_ref_ctr_offset.attr,
9621 static struct attribute_group uprobe_format_group = {
9623 .attrs = uprobe_attrs,
9626 static const struct attribute_group *uprobe_attr_groups[] = {
9627 &uprobe_format_group,
9631 static int perf_uprobe_event_init(struct perf_event *event);
9632 static struct pmu perf_uprobe = {
9633 .task_ctx_nr = perf_sw_context,
9634 .event_init = perf_uprobe_event_init,
9635 .add = perf_trace_add,
9636 .del = perf_trace_del,
9637 .start = perf_swevent_start,
9638 .stop = perf_swevent_stop,
9639 .read = perf_swevent_read,
9640 .attr_groups = uprobe_attr_groups,
9643 static int perf_uprobe_event_init(struct perf_event *event)
9646 unsigned long ref_ctr_offset;
9649 if (event->attr.type != perf_uprobe.type)
9652 if (!perfmon_capable())
9656 * no branch sampling for probe events
9658 if (has_branch_stack(event))
9661 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9662 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9663 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9667 event->destroy = perf_uprobe_destroy;
9671 #endif /* CONFIG_UPROBE_EVENTS */
9673 static inline void perf_tp_register(void)
9675 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9676 #ifdef CONFIG_KPROBE_EVENTS
9677 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9679 #ifdef CONFIG_UPROBE_EVENTS
9680 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9684 static void perf_event_free_filter(struct perf_event *event)
9686 ftrace_profile_free_filter(event);
9689 #ifdef CONFIG_BPF_SYSCALL
9690 static void bpf_overflow_handler(struct perf_event *event,
9691 struct perf_sample_data *data,
9692 struct pt_regs *regs)
9694 struct bpf_perf_event_data_kern ctx = {
9700 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9701 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9704 ret = BPF_PROG_RUN(event->prog, &ctx);
9707 __this_cpu_dec(bpf_prog_active);
9711 event->orig_overflow_handler(event, data, regs);
9714 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9716 struct bpf_prog *prog;
9718 if (event->overflow_handler_context)
9719 /* hw breakpoint or kernel counter */
9725 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9727 return PTR_ERR(prog);
9729 if (event->attr.precise_ip &&
9730 prog->call_get_stack &&
9731 (!(event->attr.sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY) ||
9732 event->attr.exclude_callchain_kernel ||
9733 event->attr.exclude_callchain_user)) {
9735 * On perf_event with precise_ip, calling bpf_get_stack()
9736 * may trigger unwinder warnings and occasional crashes.
9737 * bpf_get_[stack|stackid] works around this issue by using
9738 * callchain attached to perf_sample_data. If the
9739 * perf_event does not full (kernel and user) callchain
9740 * attached to perf_sample_data, do not allow attaching BPF
9741 * program that calls bpf_get_[stack|stackid].
9748 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9749 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9753 static void perf_event_free_bpf_handler(struct perf_event *event)
9755 struct bpf_prog *prog = event->prog;
9760 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9765 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9769 static void perf_event_free_bpf_handler(struct perf_event *event)
9775 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9776 * with perf_event_open()
9778 static inline bool perf_event_is_tracing(struct perf_event *event)
9780 if (event->pmu == &perf_tracepoint)
9782 #ifdef CONFIG_KPROBE_EVENTS
9783 if (event->pmu == &perf_kprobe)
9786 #ifdef CONFIG_UPROBE_EVENTS
9787 if (event->pmu == &perf_uprobe)
9793 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9795 bool is_kprobe, is_tracepoint, is_syscall_tp;
9796 struct bpf_prog *prog;
9799 if (!perf_event_is_tracing(event))
9800 return perf_event_set_bpf_handler(event, prog_fd);
9802 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9803 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9804 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9805 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9806 /* bpf programs can only be attached to u/kprobe or tracepoint */
9809 prog = bpf_prog_get(prog_fd);
9811 return PTR_ERR(prog);
9813 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9814 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9815 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9816 /* valid fd, but invalid bpf program type */
9821 /* Kprobe override only works for kprobes, not uprobes. */
9822 if (prog->kprobe_override &&
9823 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9828 if (is_tracepoint || is_syscall_tp) {
9829 int off = trace_event_get_offsets(event->tp_event);
9831 if (prog->aux->max_ctx_offset > off) {
9837 ret = perf_event_attach_bpf_prog(event, prog);
9843 static void perf_event_free_bpf_prog(struct perf_event *event)
9845 if (!perf_event_is_tracing(event)) {
9846 perf_event_free_bpf_handler(event);
9849 perf_event_detach_bpf_prog(event);
9854 static inline void perf_tp_register(void)
9858 static void perf_event_free_filter(struct perf_event *event)
9862 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9867 static void perf_event_free_bpf_prog(struct perf_event *event)
9870 #endif /* CONFIG_EVENT_TRACING */
9872 #ifdef CONFIG_HAVE_HW_BREAKPOINT
9873 void perf_bp_event(struct perf_event *bp, void *data)
9875 struct perf_sample_data sample;
9876 struct pt_regs *regs = data;
9878 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9880 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9881 perf_swevent_event(bp, 1, &sample, regs);
9886 * Allocate a new address filter
9888 static struct perf_addr_filter *
9889 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9891 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9892 struct perf_addr_filter *filter;
9894 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9898 INIT_LIST_HEAD(&filter->entry);
9899 list_add_tail(&filter->entry, filters);
9904 static void free_filters_list(struct list_head *filters)
9906 struct perf_addr_filter *filter, *iter;
9908 list_for_each_entry_safe(filter, iter, filters, entry) {
9909 path_put(&filter->path);
9910 list_del(&filter->entry);
9916 * Free existing address filters and optionally install new ones
9918 static void perf_addr_filters_splice(struct perf_event *event,
9919 struct list_head *head)
9921 unsigned long flags;
9924 if (!has_addr_filter(event))
9927 /* don't bother with children, they don't have their own filters */
9931 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9933 list_splice_init(&event->addr_filters.list, &list);
9935 list_splice(head, &event->addr_filters.list);
9937 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9939 free_filters_list(&list);
9943 * Scan through mm's vmas and see if one of them matches the
9944 * @filter; if so, adjust filter's address range.
9945 * Called with mm::mmap_lock down for reading.
9947 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9948 struct mm_struct *mm,
9949 struct perf_addr_filter_range *fr)
9951 struct vm_area_struct *vma;
9953 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9957 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9963 * Update event's address range filters based on the
9964 * task's existing mappings, if any.
9966 static void perf_event_addr_filters_apply(struct perf_event *event)
9968 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9969 struct task_struct *task = READ_ONCE(event->ctx->task);
9970 struct perf_addr_filter *filter;
9971 struct mm_struct *mm = NULL;
9972 unsigned int count = 0;
9973 unsigned long flags;
9976 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9977 * will stop on the parent's child_mutex that our caller is also holding
9979 if (task == TASK_TOMBSTONE)
9982 if (ifh->nr_file_filters) {
9983 mm = get_task_mm(task);
9990 raw_spin_lock_irqsave(&ifh->lock, flags);
9991 list_for_each_entry(filter, &ifh->list, entry) {
9992 if (filter->path.dentry) {
9994 * Adjust base offset if the filter is associated to a
9995 * binary that needs to be mapped:
9997 event->addr_filter_ranges[count].start = 0;
9998 event->addr_filter_ranges[count].size = 0;
10000 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10002 event->addr_filter_ranges[count].start = filter->offset;
10003 event->addr_filter_ranges[count].size = filter->size;
10009 event->addr_filters_gen++;
10010 raw_spin_unlock_irqrestore(&ifh->lock, flags);
10012 if (ifh->nr_file_filters) {
10013 mmap_read_unlock(mm);
10019 perf_event_stop(event, 1);
10023 * Address range filtering: limiting the data to certain
10024 * instruction address ranges. Filters are ioctl()ed to us from
10025 * userspace as ascii strings.
10027 * Filter string format:
10029 * ACTION RANGE_SPEC
10030 * where ACTION is one of the
10031 * * "filter": limit the trace to this region
10032 * * "start": start tracing from this address
10033 * * "stop": stop tracing at this address/region;
10035 * * for kernel addresses: <start address>[/<size>]
10036 * * for object files: <start address>[/<size>]@</path/to/object/file>
10038 * if <size> is not specified or is zero, the range is treated as a single
10039 * address; not valid for ACTION=="filter".
10053 IF_STATE_ACTION = 0,
10058 static const match_table_t if_tokens = {
10059 { IF_ACT_FILTER, "filter" },
10060 { IF_ACT_START, "start" },
10061 { IF_ACT_STOP, "stop" },
10062 { IF_SRC_FILE, "%u/%u@%s" },
10063 { IF_SRC_KERNEL, "%u/%u" },
10064 { IF_SRC_FILEADDR, "%u@%s" },
10065 { IF_SRC_KERNELADDR, "%u" },
10066 { IF_ACT_NONE, NULL },
10070 * Address filter string parser
10073 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10074 struct list_head *filters)
10076 struct perf_addr_filter *filter = NULL;
10077 char *start, *orig, *filename = NULL;
10078 substring_t args[MAX_OPT_ARGS];
10079 int state = IF_STATE_ACTION, token;
10080 unsigned int kernel = 0;
10083 orig = fstr = kstrdup(fstr, GFP_KERNEL);
10087 while ((start = strsep(&fstr, " ,\n")) != NULL) {
10088 static const enum perf_addr_filter_action_t actions[] = {
10089 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10090 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
10091 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
10098 /* filter definition begins */
10099 if (state == IF_STATE_ACTION) {
10100 filter = perf_addr_filter_new(event, filters);
10105 token = match_token(start, if_tokens, args);
10107 case IF_ACT_FILTER:
10110 if (state != IF_STATE_ACTION)
10113 filter->action = actions[token];
10114 state = IF_STATE_SOURCE;
10117 case IF_SRC_KERNELADDR:
10118 case IF_SRC_KERNEL:
10122 case IF_SRC_FILEADDR:
10124 if (state != IF_STATE_SOURCE)
10128 ret = kstrtoul(args[0].from, 0, &filter->offset);
10132 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10134 ret = kstrtoul(args[1].from, 0, &filter->size);
10139 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10140 int fpos = token == IF_SRC_FILE ? 2 : 1;
10143 filename = match_strdup(&args[fpos]);
10150 state = IF_STATE_END;
10158 * Filter definition is fully parsed, validate and install it.
10159 * Make sure that it doesn't contradict itself or the event's
10162 if (state == IF_STATE_END) {
10164 if (kernel && event->attr.exclude_kernel)
10168 * ACTION "filter" must have a non-zero length region
10171 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10180 * For now, we only support file-based filters
10181 * in per-task events; doing so for CPU-wide
10182 * events requires additional context switching
10183 * trickery, since same object code will be
10184 * mapped at different virtual addresses in
10185 * different processes.
10188 if (!event->ctx->task)
10191 /* look up the path and grab its inode */
10192 ret = kern_path(filename, LOOKUP_FOLLOW,
10198 if (!filter->path.dentry ||
10199 !S_ISREG(d_inode(filter->path.dentry)
10203 event->addr_filters.nr_file_filters++;
10206 /* ready to consume more filters */
10207 state = IF_STATE_ACTION;
10212 if (state != IF_STATE_ACTION)
10222 free_filters_list(filters);
10229 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10231 LIST_HEAD(filters);
10235 * Since this is called in perf_ioctl() path, we're already holding
10238 lockdep_assert_held(&event->ctx->mutex);
10240 if (WARN_ON_ONCE(event->parent))
10243 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10245 goto fail_clear_files;
10247 ret = event->pmu->addr_filters_validate(&filters);
10249 goto fail_free_filters;
10251 /* remove existing filters, if any */
10252 perf_addr_filters_splice(event, &filters);
10254 /* install new filters */
10255 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10260 free_filters_list(&filters);
10263 event->addr_filters.nr_file_filters = 0;
10268 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10273 filter_str = strndup_user(arg, PAGE_SIZE);
10274 if (IS_ERR(filter_str))
10275 return PTR_ERR(filter_str);
10277 #ifdef CONFIG_EVENT_TRACING
10278 if (perf_event_is_tracing(event)) {
10279 struct perf_event_context *ctx = event->ctx;
10282 * Beware, here be dragons!!
10284 * the tracepoint muck will deadlock against ctx->mutex, but
10285 * the tracepoint stuff does not actually need it. So
10286 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10287 * already have a reference on ctx.
10289 * This can result in event getting moved to a different ctx,
10290 * but that does not affect the tracepoint state.
10292 mutex_unlock(&ctx->mutex);
10293 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10294 mutex_lock(&ctx->mutex);
10297 if (has_addr_filter(event))
10298 ret = perf_event_set_addr_filter(event, filter_str);
10305 * hrtimer based swevent callback
10308 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10310 enum hrtimer_restart ret = HRTIMER_RESTART;
10311 struct perf_sample_data data;
10312 struct pt_regs *regs;
10313 struct perf_event *event;
10316 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10318 if (event->state != PERF_EVENT_STATE_ACTIVE)
10319 return HRTIMER_NORESTART;
10321 event->pmu->read(event);
10323 perf_sample_data_init(&data, 0, event->hw.last_period);
10324 regs = get_irq_regs();
10326 if (regs && !perf_exclude_event(event, regs)) {
10327 if (!(event->attr.exclude_idle && is_idle_task(current)))
10328 if (__perf_event_overflow(event, 1, &data, regs))
10329 ret = HRTIMER_NORESTART;
10332 period = max_t(u64, 10000, event->hw.sample_period);
10333 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10338 static void perf_swevent_start_hrtimer(struct perf_event *event)
10340 struct hw_perf_event *hwc = &event->hw;
10343 if (!is_sampling_event(event))
10346 period = local64_read(&hwc->period_left);
10351 local64_set(&hwc->period_left, 0);
10353 period = max_t(u64, 10000, hwc->sample_period);
10355 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10356 HRTIMER_MODE_REL_PINNED_HARD);
10359 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10361 struct hw_perf_event *hwc = &event->hw;
10363 if (is_sampling_event(event)) {
10364 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
10365 local64_set(&hwc->period_left, ktime_to_ns(remaining));
10367 hrtimer_cancel(&hwc->hrtimer);
10371 static void perf_swevent_init_hrtimer(struct perf_event *event)
10373 struct hw_perf_event *hwc = &event->hw;
10375 if (!is_sampling_event(event))
10378 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
10379 hwc->hrtimer.function = perf_swevent_hrtimer;
10382 * Since hrtimers have a fixed rate, we can do a static freq->period
10383 * mapping and avoid the whole period adjust feedback stuff.
10385 if (event->attr.freq) {
10386 long freq = event->attr.sample_freq;
10388 event->attr.sample_period = NSEC_PER_SEC / freq;
10389 hwc->sample_period = event->attr.sample_period;
10390 local64_set(&hwc->period_left, hwc->sample_period);
10391 hwc->last_period = hwc->sample_period;
10392 event->attr.freq = 0;
10397 * Software event: cpu wall time clock
10400 static void cpu_clock_event_update(struct perf_event *event)
10405 now = local_clock();
10406 prev = local64_xchg(&event->hw.prev_count, now);
10407 local64_add(now - prev, &event->count);
10410 static void cpu_clock_event_start(struct perf_event *event, int flags)
10412 local64_set(&event->hw.prev_count, local_clock());
10413 perf_swevent_start_hrtimer(event);
10416 static void cpu_clock_event_stop(struct perf_event *event, int flags)
10418 perf_swevent_cancel_hrtimer(event);
10419 cpu_clock_event_update(event);
10422 static int cpu_clock_event_add(struct perf_event *event, int flags)
10424 if (flags & PERF_EF_START)
10425 cpu_clock_event_start(event, flags);
10426 perf_event_update_userpage(event);
10431 static void cpu_clock_event_del(struct perf_event *event, int flags)
10433 cpu_clock_event_stop(event, flags);
10436 static void cpu_clock_event_read(struct perf_event *event)
10438 cpu_clock_event_update(event);
10441 static int cpu_clock_event_init(struct perf_event *event)
10443 if (event->attr.type != PERF_TYPE_SOFTWARE)
10446 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10450 * no branch sampling for software events
10452 if (has_branch_stack(event))
10453 return -EOPNOTSUPP;
10455 perf_swevent_init_hrtimer(event);
10460 static struct pmu perf_cpu_clock = {
10461 .task_ctx_nr = perf_sw_context,
10463 .capabilities = PERF_PMU_CAP_NO_NMI,
10465 .event_init = cpu_clock_event_init,
10466 .add = cpu_clock_event_add,
10467 .del = cpu_clock_event_del,
10468 .start = cpu_clock_event_start,
10469 .stop = cpu_clock_event_stop,
10470 .read = cpu_clock_event_read,
10474 * Software event: task time clock
10477 static void task_clock_event_update(struct perf_event *event, u64 now)
10482 prev = local64_xchg(&event->hw.prev_count, now);
10483 delta = now - prev;
10484 local64_add(delta, &event->count);
10487 static void task_clock_event_start(struct perf_event *event, int flags)
10489 local64_set(&event->hw.prev_count, event->ctx->time);
10490 perf_swevent_start_hrtimer(event);
10493 static void task_clock_event_stop(struct perf_event *event, int flags)
10495 perf_swevent_cancel_hrtimer(event);
10496 task_clock_event_update(event, event->ctx->time);
10499 static int task_clock_event_add(struct perf_event *event, int flags)
10501 if (flags & PERF_EF_START)
10502 task_clock_event_start(event, flags);
10503 perf_event_update_userpage(event);
10508 static void task_clock_event_del(struct perf_event *event, int flags)
10510 task_clock_event_stop(event, PERF_EF_UPDATE);
10513 static void task_clock_event_read(struct perf_event *event)
10515 u64 now = perf_clock();
10516 u64 delta = now - event->ctx->timestamp;
10517 u64 time = event->ctx->time + delta;
10519 task_clock_event_update(event, time);
10522 static int task_clock_event_init(struct perf_event *event)
10524 if (event->attr.type != PERF_TYPE_SOFTWARE)
10527 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10531 * no branch sampling for software events
10533 if (has_branch_stack(event))
10534 return -EOPNOTSUPP;
10536 perf_swevent_init_hrtimer(event);
10541 static struct pmu perf_task_clock = {
10542 .task_ctx_nr = perf_sw_context,
10544 .capabilities = PERF_PMU_CAP_NO_NMI,
10546 .event_init = task_clock_event_init,
10547 .add = task_clock_event_add,
10548 .del = task_clock_event_del,
10549 .start = task_clock_event_start,
10550 .stop = task_clock_event_stop,
10551 .read = task_clock_event_read,
10554 static void perf_pmu_nop_void(struct pmu *pmu)
10558 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10562 static int perf_pmu_nop_int(struct pmu *pmu)
10567 static int perf_event_nop_int(struct perf_event *event, u64 value)
10572 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
10574 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
10576 __this_cpu_write(nop_txn_flags, flags);
10578 if (flags & ~PERF_PMU_TXN_ADD)
10581 perf_pmu_disable(pmu);
10584 static int perf_pmu_commit_txn(struct pmu *pmu)
10586 unsigned int flags = __this_cpu_read(nop_txn_flags);
10588 __this_cpu_write(nop_txn_flags, 0);
10590 if (flags & ~PERF_PMU_TXN_ADD)
10593 perf_pmu_enable(pmu);
10597 static void perf_pmu_cancel_txn(struct pmu *pmu)
10599 unsigned int flags = __this_cpu_read(nop_txn_flags);
10601 __this_cpu_write(nop_txn_flags, 0);
10603 if (flags & ~PERF_PMU_TXN_ADD)
10606 perf_pmu_enable(pmu);
10609 static int perf_event_idx_default(struct perf_event *event)
10615 * Ensures all contexts with the same task_ctx_nr have the same
10616 * pmu_cpu_context too.
10618 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
10625 list_for_each_entry(pmu, &pmus, entry) {
10626 if (pmu->task_ctx_nr == ctxn)
10627 return pmu->pmu_cpu_context;
10633 static void free_pmu_context(struct pmu *pmu)
10636 * Static contexts such as perf_sw_context have a global lifetime
10637 * and may be shared between different PMUs. Avoid freeing them
10638 * when a single PMU is going away.
10640 if (pmu->task_ctx_nr > perf_invalid_context)
10643 free_percpu(pmu->pmu_cpu_context);
10647 * Let userspace know that this PMU supports address range filtering:
10649 static ssize_t nr_addr_filters_show(struct device *dev,
10650 struct device_attribute *attr,
10653 struct pmu *pmu = dev_get_drvdata(dev);
10655 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10657 DEVICE_ATTR_RO(nr_addr_filters);
10659 static struct idr pmu_idr;
10662 type_show(struct device *dev, struct device_attribute *attr, char *page)
10664 struct pmu *pmu = dev_get_drvdata(dev);
10666 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10668 static DEVICE_ATTR_RO(type);
10671 perf_event_mux_interval_ms_show(struct device *dev,
10672 struct device_attribute *attr,
10675 struct pmu *pmu = dev_get_drvdata(dev);
10677 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10680 static DEFINE_MUTEX(mux_interval_mutex);
10683 perf_event_mux_interval_ms_store(struct device *dev,
10684 struct device_attribute *attr,
10685 const char *buf, size_t count)
10687 struct pmu *pmu = dev_get_drvdata(dev);
10688 int timer, cpu, ret;
10690 ret = kstrtoint(buf, 0, &timer);
10697 /* same value, noting to do */
10698 if (timer == pmu->hrtimer_interval_ms)
10701 mutex_lock(&mux_interval_mutex);
10702 pmu->hrtimer_interval_ms = timer;
10704 /* update all cpuctx for this PMU */
10706 for_each_online_cpu(cpu) {
10707 struct perf_cpu_context *cpuctx;
10708 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10709 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10711 cpu_function_call(cpu,
10712 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
10714 cpus_read_unlock();
10715 mutex_unlock(&mux_interval_mutex);
10719 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10721 static struct attribute *pmu_dev_attrs[] = {
10722 &dev_attr_type.attr,
10723 &dev_attr_perf_event_mux_interval_ms.attr,
10726 ATTRIBUTE_GROUPS(pmu_dev);
10728 static int pmu_bus_running;
10729 static struct bus_type pmu_bus = {
10730 .name = "event_source",
10731 .dev_groups = pmu_dev_groups,
10734 static void pmu_dev_release(struct device *dev)
10739 static int pmu_dev_alloc(struct pmu *pmu)
10743 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10747 pmu->dev->groups = pmu->attr_groups;
10748 device_initialize(pmu->dev);
10749 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10753 dev_set_drvdata(pmu->dev, pmu);
10754 pmu->dev->bus = &pmu_bus;
10755 pmu->dev->release = pmu_dev_release;
10756 ret = device_add(pmu->dev);
10760 /* For PMUs with address filters, throw in an extra attribute: */
10761 if (pmu->nr_addr_filters)
10762 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10767 if (pmu->attr_update)
10768 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10777 device_del(pmu->dev);
10780 put_device(pmu->dev);
10784 static struct lock_class_key cpuctx_mutex;
10785 static struct lock_class_key cpuctx_lock;
10787 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10789 int cpu, ret, max = PERF_TYPE_MAX;
10791 mutex_lock(&pmus_lock);
10793 pmu->pmu_disable_count = alloc_percpu(int);
10794 if (!pmu->pmu_disable_count)
10802 if (type != PERF_TYPE_SOFTWARE) {
10806 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10810 WARN_ON(type >= 0 && ret != type);
10816 if (pmu_bus_running) {
10817 ret = pmu_dev_alloc(pmu);
10823 if (pmu->task_ctx_nr == perf_hw_context) {
10824 static int hw_context_taken = 0;
10827 * Other than systems with heterogeneous CPUs, it never makes
10828 * sense for two PMUs to share perf_hw_context. PMUs which are
10829 * uncore must use perf_invalid_context.
10831 if (WARN_ON_ONCE(hw_context_taken &&
10832 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10833 pmu->task_ctx_nr = perf_invalid_context;
10835 hw_context_taken = 1;
10838 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10839 if (pmu->pmu_cpu_context)
10840 goto got_cpu_context;
10843 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10844 if (!pmu->pmu_cpu_context)
10847 for_each_possible_cpu(cpu) {
10848 struct perf_cpu_context *cpuctx;
10850 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10851 __perf_event_init_context(&cpuctx->ctx);
10852 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10853 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10854 cpuctx->ctx.pmu = pmu;
10855 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10857 __perf_mux_hrtimer_init(cpuctx, cpu);
10859 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10860 cpuctx->heap = cpuctx->heap_default;
10864 if (!pmu->start_txn) {
10865 if (pmu->pmu_enable) {
10867 * If we have pmu_enable/pmu_disable calls, install
10868 * transaction stubs that use that to try and batch
10869 * hardware accesses.
10871 pmu->start_txn = perf_pmu_start_txn;
10872 pmu->commit_txn = perf_pmu_commit_txn;
10873 pmu->cancel_txn = perf_pmu_cancel_txn;
10875 pmu->start_txn = perf_pmu_nop_txn;
10876 pmu->commit_txn = perf_pmu_nop_int;
10877 pmu->cancel_txn = perf_pmu_nop_void;
10881 if (!pmu->pmu_enable) {
10882 pmu->pmu_enable = perf_pmu_nop_void;
10883 pmu->pmu_disable = perf_pmu_nop_void;
10886 if (!pmu->check_period)
10887 pmu->check_period = perf_event_nop_int;
10889 if (!pmu->event_idx)
10890 pmu->event_idx = perf_event_idx_default;
10893 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10894 * since these cannot be in the IDR. This way the linear search
10895 * is fast, provided a valid software event is provided.
10897 if (type == PERF_TYPE_SOFTWARE || !name)
10898 list_add_rcu(&pmu->entry, &pmus);
10900 list_add_tail_rcu(&pmu->entry, &pmus);
10902 atomic_set(&pmu->exclusive_cnt, 0);
10905 mutex_unlock(&pmus_lock);
10910 device_del(pmu->dev);
10911 put_device(pmu->dev);
10914 if (pmu->type != PERF_TYPE_SOFTWARE)
10915 idr_remove(&pmu_idr, pmu->type);
10918 free_percpu(pmu->pmu_disable_count);
10921 EXPORT_SYMBOL_GPL(perf_pmu_register);
10923 void perf_pmu_unregister(struct pmu *pmu)
10925 mutex_lock(&pmus_lock);
10926 list_del_rcu(&pmu->entry);
10929 * We dereference the pmu list under both SRCU and regular RCU, so
10930 * synchronize against both of those.
10932 synchronize_srcu(&pmus_srcu);
10935 free_percpu(pmu->pmu_disable_count);
10936 if (pmu->type != PERF_TYPE_SOFTWARE)
10937 idr_remove(&pmu_idr, pmu->type);
10938 if (pmu_bus_running) {
10939 if (pmu->nr_addr_filters)
10940 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10941 device_del(pmu->dev);
10942 put_device(pmu->dev);
10944 free_pmu_context(pmu);
10945 mutex_unlock(&pmus_lock);
10947 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10949 static inline bool has_extended_regs(struct perf_event *event)
10951 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10952 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10955 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10957 struct perf_event_context *ctx = NULL;
10960 if (!try_module_get(pmu->module))
10964 * A number of pmu->event_init() methods iterate the sibling_list to,
10965 * for example, validate if the group fits on the PMU. Therefore,
10966 * if this is a sibling event, acquire the ctx->mutex to protect
10967 * the sibling_list.
10969 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10971 * This ctx->mutex can nest when we're called through
10972 * inheritance. See the perf_event_ctx_lock_nested() comment.
10974 ctx = perf_event_ctx_lock_nested(event->group_leader,
10975 SINGLE_DEPTH_NESTING);
10980 ret = pmu->event_init(event);
10983 perf_event_ctx_unlock(event->group_leader, ctx);
10986 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10987 has_extended_regs(event))
10990 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10991 event_has_any_exclude_flag(event))
10994 if (ret && event->destroy)
10995 event->destroy(event);
10999 module_put(pmu->module);
11004 static struct pmu *perf_init_event(struct perf_event *event)
11006 int idx, type, ret;
11009 idx = srcu_read_lock(&pmus_srcu);
11011 /* Try parent's PMU first: */
11012 if (event->parent && event->parent->pmu) {
11013 pmu = event->parent->pmu;
11014 ret = perf_try_init_event(pmu, event);
11020 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11021 * are often aliases for PERF_TYPE_RAW.
11023 type = event->attr.type;
11024 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
11025 type = PERF_TYPE_RAW;
11029 pmu = idr_find(&pmu_idr, type);
11032 ret = perf_try_init_event(pmu, event);
11033 if (ret == -ENOENT && event->attr.type != type) {
11034 type = event->attr.type;
11039 pmu = ERR_PTR(ret);
11044 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11045 ret = perf_try_init_event(pmu, event);
11049 if (ret != -ENOENT) {
11050 pmu = ERR_PTR(ret);
11054 pmu = ERR_PTR(-ENOENT);
11056 srcu_read_unlock(&pmus_srcu, idx);
11061 static void attach_sb_event(struct perf_event *event)
11063 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11065 raw_spin_lock(&pel->lock);
11066 list_add_rcu(&event->sb_list, &pel->list);
11067 raw_spin_unlock(&pel->lock);
11071 * We keep a list of all !task (and therefore per-cpu) events
11072 * that need to receive side-band records.
11074 * This avoids having to scan all the various PMU per-cpu contexts
11075 * looking for them.
11077 static void account_pmu_sb_event(struct perf_event *event)
11079 if (is_sb_event(event))
11080 attach_sb_event(event);
11083 static void account_event_cpu(struct perf_event *event, int cpu)
11088 if (is_cgroup_event(event))
11089 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
11092 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11093 static void account_freq_event_nohz(void)
11095 #ifdef CONFIG_NO_HZ_FULL
11096 /* Lock so we don't race with concurrent unaccount */
11097 spin_lock(&nr_freq_lock);
11098 if (atomic_inc_return(&nr_freq_events) == 1)
11099 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11100 spin_unlock(&nr_freq_lock);
11104 static void account_freq_event(void)
11106 if (tick_nohz_full_enabled())
11107 account_freq_event_nohz();
11109 atomic_inc(&nr_freq_events);
11113 static void account_event(struct perf_event *event)
11120 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11122 if (event->attr.mmap || event->attr.mmap_data)
11123 atomic_inc(&nr_mmap_events);
11124 if (event->attr.comm)
11125 atomic_inc(&nr_comm_events);
11126 if (event->attr.namespaces)
11127 atomic_inc(&nr_namespaces_events);
11128 if (event->attr.cgroup)
11129 atomic_inc(&nr_cgroup_events);
11130 if (event->attr.task)
11131 atomic_inc(&nr_task_events);
11132 if (event->attr.freq)
11133 account_freq_event();
11134 if (event->attr.context_switch) {
11135 atomic_inc(&nr_switch_events);
11138 if (has_branch_stack(event))
11140 if (is_cgroup_event(event))
11142 if (event->attr.ksymbol)
11143 atomic_inc(&nr_ksymbol_events);
11144 if (event->attr.bpf_event)
11145 atomic_inc(&nr_bpf_events);
11146 if (event->attr.text_poke)
11147 atomic_inc(&nr_text_poke_events);
11151 * We need the mutex here because static_branch_enable()
11152 * must complete *before* the perf_sched_count increment
11155 if (atomic_inc_not_zero(&perf_sched_count))
11158 mutex_lock(&perf_sched_mutex);
11159 if (!atomic_read(&perf_sched_count)) {
11160 static_branch_enable(&perf_sched_events);
11162 * Guarantee that all CPUs observe they key change and
11163 * call the perf scheduling hooks before proceeding to
11164 * install events that need them.
11169 * Now that we have waited for the sync_sched(), allow further
11170 * increments to by-pass the mutex.
11172 atomic_inc(&perf_sched_count);
11173 mutex_unlock(&perf_sched_mutex);
11177 account_event_cpu(event, event->cpu);
11179 account_pmu_sb_event(event);
11183 * Allocate and initialize an event structure
11185 static struct perf_event *
11186 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11187 struct task_struct *task,
11188 struct perf_event *group_leader,
11189 struct perf_event *parent_event,
11190 perf_overflow_handler_t overflow_handler,
11191 void *context, int cgroup_fd)
11194 struct perf_event *event;
11195 struct hw_perf_event *hwc;
11196 long err = -EINVAL;
11198 if ((unsigned)cpu >= nr_cpu_ids) {
11199 if (!task || cpu != -1)
11200 return ERR_PTR(-EINVAL);
11203 event = kzalloc(sizeof(*event), GFP_KERNEL);
11205 return ERR_PTR(-ENOMEM);
11208 * Single events are their own group leaders, with an
11209 * empty sibling list:
11212 group_leader = event;
11214 mutex_init(&event->child_mutex);
11215 INIT_LIST_HEAD(&event->child_list);
11217 INIT_LIST_HEAD(&event->event_entry);
11218 INIT_LIST_HEAD(&event->sibling_list);
11219 INIT_LIST_HEAD(&event->active_list);
11220 init_event_group(event);
11221 INIT_LIST_HEAD(&event->rb_entry);
11222 INIT_LIST_HEAD(&event->active_entry);
11223 INIT_LIST_HEAD(&event->addr_filters.list);
11224 INIT_HLIST_NODE(&event->hlist_entry);
11227 init_waitqueue_head(&event->waitq);
11228 event->pending_disable = -1;
11229 init_irq_work(&event->pending, perf_pending_event);
11231 mutex_init(&event->mmap_mutex);
11232 raw_spin_lock_init(&event->addr_filters.lock);
11234 atomic_long_set(&event->refcount, 1);
11236 event->attr = *attr;
11237 event->group_leader = group_leader;
11241 event->parent = parent_event;
11243 event->ns = get_pid_ns(task_active_pid_ns(current));
11244 event->id = atomic64_inc_return(&perf_event_id);
11246 event->state = PERF_EVENT_STATE_INACTIVE;
11249 event->attach_state = PERF_ATTACH_TASK;
11251 * XXX pmu::event_init needs to know what task to account to
11252 * and we cannot use the ctx information because we need the
11253 * pmu before we get a ctx.
11255 event->hw.target = get_task_struct(task);
11258 event->clock = &local_clock;
11260 event->clock = parent_event->clock;
11262 if (!overflow_handler && parent_event) {
11263 overflow_handler = parent_event->overflow_handler;
11264 context = parent_event->overflow_handler_context;
11265 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11266 if (overflow_handler == bpf_overflow_handler) {
11267 struct bpf_prog *prog = parent_event->prog;
11269 bpf_prog_inc(prog);
11270 event->prog = prog;
11271 event->orig_overflow_handler =
11272 parent_event->orig_overflow_handler;
11277 if (overflow_handler) {
11278 event->overflow_handler = overflow_handler;
11279 event->overflow_handler_context = context;
11280 } else if (is_write_backward(event)){
11281 event->overflow_handler = perf_event_output_backward;
11282 event->overflow_handler_context = NULL;
11284 event->overflow_handler = perf_event_output_forward;
11285 event->overflow_handler_context = NULL;
11288 perf_event__state_init(event);
11293 hwc->sample_period = attr->sample_period;
11294 if (attr->freq && attr->sample_freq)
11295 hwc->sample_period = 1;
11296 hwc->last_period = hwc->sample_period;
11298 local64_set(&hwc->period_left, hwc->sample_period);
11301 * We currently do not support PERF_SAMPLE_READ on inherited events.
11302 * See perf_output_read().
11304 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11307 if (!has_branch_stack(event))
11308 event->attr.branch_sample_type = 0;
11310 pmu = perf_init_event(event);
11312 err = PTR_ERR(pmu);
11317 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11318 * be different on other CPUs in the uncore mask.
11320 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11325 if (event->attr.aux_output &&
11326 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11331 if (cgroup_fd != -1) {
11332 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11337 err = exclusive_event_init(event);
11341 if (has_addr_filter(event)) {
11342 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11343 sizeof(struct perf_addr_filter_range),
11345 if (!event->addr_filter_ranges) {
11351 * Clone the parent's vma offsets: they are valid until exec()
11352 * even if the mm is not shared with the parent.
11354 if (event->parent) {
11355 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11357 raw_spin_lock_irq(&ifh->lock);
11358 memcpy(event->addr_filter_ranges,
11359 event->parent->addr_filter_ranges,
11360 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11361 raw_spin_unlock_irq(&ifh->lock);
11364 /* force hw sync on the address filters */
11365 event->addr_filters_gen = 1;
11368 if (!event->parent) {
11369 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11370 err = get_callchain_buffers(attr->sample_max_stack);
11372 goto err_addr_filters;
11376 err = security_perf_event_alloc(event);
11378 goto err_callchain_buffer;
11380 /* symmetric to unaccount_event() in _free_event() */
11381 account_event(event);
11385 err_callchain_buffer:
11386 if (!event->parent) {
11387 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11388 put_callchain_buffers();
11391 kfree(event->addr_filter_ranges);
11394 exclusive_event_destroy(event);
11397 if (is_cgroup_event(event))
11398 perf_detach_cgroup(event);
11399 if (event->destroy)
11400 event->destroy(event);
11401 module_put(pmu->module);
11404 put_pid_ns(event->ns);
11405 if (event->hw.target)
11406 put_task_struct(event->hw.target);
11409 return ERR_PTR(err);
11412 static int perf_copy_attr(struct perf_event_attr __user *uattr,
11413 struct perf_event_attr *attr)
11418 /* Zero the full structure, so that a short copy will be nice. */
11419 memset(attr, 0, sizeof(*attr));
11421 ret = get_user(size, &uattr->size);
11425 /* ABI compatibility quirk: */
11427 size = PERF_ATTR_SIZE_VER0;
11428 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
11431 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11440 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
11443 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11446 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11449 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11450 u64 mask = attr->branch_sample_type;
11452 /* only using defined bits */
11453 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11456 /* at least one branch bit must be set */
11457 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11460 /* propagate priv level, when not set for branch */
11461 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11463 /* exclude_kernel checked on syscall entry */
11464 if (!attr->exclude_kernel)
11465 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11467 if (!attr->exclude_user)
11468 mask |= PERF_SAMPLE_BRANCH_USER;
11470 if (!attr->exclude_hv)
11471 mask |= PERF_SAMPLE_BRANCH_HV;
11473 * adjust user setting (for HW filter setup)
11475 attr->branch_sample_type = mask;
11477 /* privileged levels capture (kernel, hv): check permissions */
11478 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11479 ret = perf_allow_kernel(attr);
11485 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
11486 ret = perf_reg_validate(attr->sample_regs_user);
11491 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11492 if (!arch_perf_have_user_stack_dump())
11496 * We have __u32 type for the size, but so far
11497 * we can only use __u16 as maximum due to the
11498 * __u16 sample size limit.
11500 if (attr->sample_stack_user >= USHRT_MAX)
11502 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
11506 if (!attr->sample_max_stack)
11507 attr->sample_max_stack = sysctl_perf_event_max_stack;
11509 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11510 ret = perf_reg_validate(attr->sample_regs_intr);
11512 #ifndef CONFIG_CGROUP_PERF
11513 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11521 put_user(sizeof(*attr), &uattr->size);
11527 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
11529 struct perf_buffer *rb = NULL;
11535 /* don't allow circular references */
11536 if (event == output_event)
11540 * Don't allow cross-cpu buffers
11542 if (output_event->cpu != event->cpu)
11546 * If its not a per-cpu rb, it must be the same task.
11548 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11552 * Mixing clocks in the same buffer is trouble you don't need.
11554 if (output_event->clock != event->clock)
11558 * Either writing ring buffer from beginning or from end.
11559 * Mixing is not allowed.
11561 if (is_write_backward(output_event) != is_write_backward(event))
11565 * If both events generate aux data, they must be on the same PMU
11567 if (has_aux(event) && has_aux(output_event) &&
11568 event->pmu != output_event->pmu)
11572 mutex_lock(&event->mmap_mutex);
11573 /* Can't redirect output if we've got an active mmap() */
11574 if (atomic_read(&event->mmap_count))
11577 if (output_event) {
11578 /* get the rb we want to redirect to */
11579 rb = ring_buffer_get(output_event);
11584 ring_buffer_attach(event, rb);
11588 mutex_unlock(&event->mmap_mutex);
11594 static void mutex_lock_double(struct mutex *a, struct mutex *b)
11600 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11603 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11605 bool nmi_safe = false;
11608 case CLOCK_MONOTONIC:
11609 event->clock = &ktime_get_mono_fast_ns;
11613 case CLOCK_MONOTONIC_RAW:
11614 event->clock = &ktime_get_raw_fast_ns;
11618 case CLOCK_REALTIME:
11619 event->clock = &ktime_get_real_ns;
11622 case CLOCK_BOOTTIME:
11623 event->clock = &ktime_get_boottime_ns;
11627 event->clock = &ktime_get_clocktai_ns;
11634 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11641 * Variation on perf_event_ctx_lock_nested(), except we take two context
11644 static struct perf_event_context *
11645 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11646 struct perf_event_context *ctx)
11648 struct perf_event_context *gctx;
11652 gctx = READ_ONCE(group_leader->ctx);
11653 if (!refcount_inc_not_zero(&gctx->refcount)) {
11659 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11661 if (group_leader->ctx != gctx) {
11662 mutex_unlock(&ctx->mutex);
11663 mutex_unlock(&gctx->mutex);
11672 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11674 * @attr_uptr: event_id type attributes for monitoring/sampling
11677 * @group_fd: group leader event fd
11679 SYSCALL_DEFINE5(perf_event_open,
11680 struct perf_event_attr __user *, attr_uptr,
11681 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11683 struct perf_event *group_leader = NULL, *output_event = NULL;
11684 struct perf_event *event, *sibling;
11685 struct perf_event_attr attr;
11686 struct perf_event_context *ctx, *gctx;
11687 struct file *event_file = NULL;
11688 struct fd group = {NULL, 0};
11689 struct task_struct *task = NULL;
11692 int move_group = 0;
11694 int f_flags = O_RDWR;
11695 int cgroup_fd = -1;
11697 /* for future expandability... */
11698 if (flags & ~PERF_FLAG_ALL)
11701 /* Do we allow access to perf_event_open(2) ? */
11702 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11706 err = perf_copy_attr(attr_uptr, &attr);
11710 if (!attr.exclude_kernel) {
11711 err = perf_allow_kernel(&attr);
11716 if (attr.namespaces) {
11717 if (!perfmon_capable())
11722 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11725 if (attr.sample_period & (1ULL << 63))
11729 /* Only privileged users can get physical addresses */
11730 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11731 err = perf_allow_kernel(&attr);
11736 /* REGS_INTR can leak data, lockdown must prevent this */
11737 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
11738 err = security_locked_down(LOCKDOWN_PERF);
11744 * In cgroup mode, the pid argument is used to pass the fd
11745 * opened to the cgroup directory in cgroupfs. The cpu argument
11746 * designates the cpu on which to monitor threads from that
11749 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11752 if (flags & PERF_FLAG_FD_CLOEXEC)
11753 f_flags |= O_CLOEXEC;
11755 event_fd = get_unused_fd_flags(f_flags);
11759 if (group_fd != -1) {
11760 err = perf_fget_light(group_fd, &group);
11763 group_leader = group.file->private_data;
11764 if (flags & PERF_FLAG_FD_OUTPUT)
11765 output_event = group_leader;
11766 if (flags & PERF_FLAG_FD_NO_GROUP)
11767 group_leader = NULL;
11770 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11771 task = find_lively_task_by_vpid(pid);
11772 if (IS_ERR(task)) {
11773 err = PTR_ERR(task);
11778 if (task && group_leader &&
11779 group_leader->attr.inherit != attr.inherit) {
11784 if (flags & PERF_FLAG_PID_CGROUP)
11787 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11788 NULL, NULL, cgroup_fd);
11789 if (IS_ERR(event)) {
11790 err = PTR_ERR(event);
11794 if (is_sampling_event(event)) {
11795 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11802 * Special case software events and allow them to be part of
11803 * any hardware group.
11807 if (attr.use_clockid) {
11808 err = perf_event_set_clock(event, attr.clockid);
11813 if (pmu->task_ctx_nr == perf_sw_context)
11814 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11816 if (group_leader) {
11817 if (is_software_event(event) &&
11818 !in_software_context(group_leader)) {
11820 * If the event is a sw event, but the group_leader
11821 * is on hw context.
11823 * Allow the addition of software events to hw
11824 * groups, this is safe because software events
11825 * never fail to schedule.
11827 pmu = group_leader->ctx->pmu;
11828 } else if (!is_software_event(event) &&
11829 is_software_event(group_leader) &&
11830 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11832 * In case the group is a pure software group, and we
11833 * try to add a hardware event, move the whole group to
11834 * the hardware context.
11841 * Get the target context (task or percpu):
11843 ctx = find_get_context(pmu, task, event);
11845 err = PTR_ERR(ctx);
11850 * Look up the group leader (we will attach this event to it):
11852 if (group_leader) {
11856 * Do not allow a recursive hierarchy (this new sibling
11857 * becoming part of another group-sibling):
11859 if (group_leader->group_leader != group_leader)
11862 /* All events in a group should have the same clock */
11863 if (group_leader->clock != event->clock)
11867 * Make sure we're both events for the same CPU;
11868 * grouping events for different CPUs is broken; since
11869 * you can never concurrently schedule them anyhow.
11871 if (group_leader->cpu != event->cpu)
11875 * Make sure we're both on the same task, or both
11878 if (group_leader->ctx->task != ctx->task)
11882 * Do not allow to attach to a group in a different task
11883 * or CPU context. If we're moving SW events, we'll fix
11884 * this up later, so allow that.
11886 if (!move_group && group_leader->ctx != ctx)
11890 * Only a group leader can be exclusive or pinned
11892 if (attr.exclusive || attr.pinned)
11896 if (output_event) {
11897 err = perf_event_set_output(event, output_event);
11902 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11904 if (IS_ERR(event_file)) {
11905 err = PTR_ERR(event_file);
11911 err = down_read_interruptible(&task->signal->exec_update_lock);
11916 * Preserve ptrace permission check for backwards compatibility.
11918 * We must hold exec_update_lock across this and any potential
11919 * perf_install_in_context() call for this new event to
11920 * serialize against exec() altering our credentials (and the
11921 * perf_event_exit_task() that could imply).
11924 if (!perfmon_capable() && !ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11929 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11931 if (gctx->task == TASK_TOMBSTONE) {
11937 * Check if we raced against another sys_perf_event_open() call
11938 * moving the software group underneath us.
11940 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11942 * If someone moved the group out from under us, check
11943 * if this new event wound up on the same ctx, if so
11944 * its the regular !move_group case, otherwise fail.
11950 perf_event_ctx_unlock(group_leader, gctx);
11956 * Failure to create exclusive events returns -EBUSY.
11959 if (!exclusive_event_installable(group_leader, ctx))
11962 for_each_sibling_event(sibling, group_leader) {
11963 if (!exclusive_event_installable(sibling, ctx))
11967 mutex_lock(&ctx->mutex);
11970 if (ctx->task == TASK_TOMBSTONE) {
11975 if (!perf_event_validate_size(event)) {
11982 * Check if the @cpu we're creating an event for is online.
11984 * We use the perf_cpu_context::ctx::mutex to serialize against
11985 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11987 struct perf_cpu_context *cpuctx =
11988 container_of(ctx, struct perf_cpu_context, ctx);
11990 if (!cpuctx->online) {
11996 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12002 * Must be under the same ctx::mutex as perf_install_in_context(),
12003 * because we need to serialize with concurrent event creation.
12005 if (!exclusive_event_installable(event, ctx)) {
12010 WARN_ON_ONCE(ctx->parent_ctx);
12013 * This is the point on no return; we cannot fail hereafter. This is
12014 * where we start modifying current state.
12019 * See perf_event_ctx_lock() for comments on the details
12020 * of swizzling perf_event::ctx.
12022 perf_remove_from_context(group_leader, 0);
12025 for_each_sibling_event(sibling, group_leader) {
12026 perf_remove_from_context(sibling, 0);
12031 * Wait for everybody to stop referencing the events through
12032 * the old lists, before installing it on new lists.
12037 * Install the group siblings before the group leader.
12039 * Because a group leader will try and install the entire group
12040 * (through the sibling list, which is still in-tact), we can
12041 * end up with siblings installed in the wrong context.
12043 * By installing siblings first we NO-OP because they're not
12044 * reachable through the group lists.
12046 for_each_sibling_event(sibling, group_leader) {
12047 perf_event__state_init(sibling);
12048 perf_install_in_context(ctx, sibling, sibling->cpu);
12053 * Removing from the context ends up with disabled
12054 * event. What we want here is event in the initial
12055 * startup state, ready to be add into new context.
12057 perf_event__state_init(group_leader);
12058 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12063 * Precalculate sample_data sizes; do while holding ctx::mutex such
12064 * that we're serialized against further additions and before
12065 * perf_install_in_context() which is the point the event is active and
12066 * can use these values.
12068 perf_event__header_size(event);
12069 perf_event__id_header_size(event);
12071 event->owner = current;
12073 perf_install_in_context(ctx, event, event->cpu);
12074 perf_unpin_context(ctx);
12077 perf_event_ctx_unlock(group_leader, gctx);
12078 mutex_unlock(&ctx->mutex);
12081 up_read(&task->signal->exec_update_lock);
12082 put_task_struct(task);
12085 mutex_lock(¤t->perf_event_mutex);
12086 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
12087 mutex_unlock(¤t->perf_event_mutex);
12090 * Drop the reference on the group_event after placing the
12091 * new event on the sibling_list. This ensures destruction
12092 * of the group leader will find the pointer to itself in
12093 * perf_group_detach().
12096 fd_install(event_fd, event_file);
12101 perf_event_ctx_unlock(group_leader, gctx);
12102 mutex_unlock(&ctx->mutex);
12105 up_read(&task->signal->exec_update_lock);
12109 perf_unpin_context(ctx);
12113 * If event_file is set, the fput() above will have called ->release()
12114 * and that will take care of freeing the event.
12120 put_task_struct(task);
12124 put_unused_fd(event_fd);
12129 * perf_event_create_kernel_counter
12131 * @attr: attributes of the counter to create
12132 * @cpu: cpu in which the counter is bound
12133 * @task: task to profile (NULL for percpu)
12135 struct perf_event *
12136 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12137 struct task_struct *task,
12138 perf_overflow_handler_t overflow_handler,
12141 struct perf_event_context *ctx;
12142 struct perf_event *event;
12146 * Grouping is not supported for kernel events, neither is 'AUX',
12147 * make sure the caller's intentions are adjusted.
12149 if (attr->aux_output)
12150 return ERR_PTR(-EINVAL);
12152 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12153 overflow_handler, context, -1);
12154 if (IS_ERR(event)) {
12155 err = PTR_ERR(event);
12159 /* Mark owner so we could distinguish it from user events. */
12160 event->owner = TASK_TOMBSTONE;
12163 * Get the target context (task or percpu):
12165 ctx = find_get_context(event->pmu, task, event);
12167 err = PTR_ERR(ctx);
12171 WARN_ON_ONCE(ctx->parent_ctx);
12172 mutex_lock(&ctx->mutex);
12173 if (ctx->task == TASK_TOMBSTONE) {
12180 * Check if the @cpu we're creating an event for is online.
12182 * We use the perf_cpu_context::ctx::mutex to serialize against
12183 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12185 struct perf_cpu_context *cpuctx =
12186 container_of(ctx, struct perf_cpu_context, ctx);
12187 if (!cpuctx->online) {
12193 if (!exclusive_event_installable(event, ctx)) {
12198 perf_install_in_context(ctx, event, event->cpu);
12199 perf_unpin_context(ctx);
12200 mutex_unlock(&ctx->mutex);
12205 mutex_unlock(&ctx->mutex);
12206 perf_unpin_context(ctx);
12211 return ERR_PTR(err);
12213 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12215 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12217 struct perf_event_context *src_ctx;
12218 struct perf_event_context *dst_ctx;
12219 struct perf_event *event, *tmp;
12222 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
12223 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
12226 * See perf_event_ctx_lock() for comments on the details
12227 * of swizzling perf_event::ctx.
12229 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12230 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12232 perf_remove_from_context(event, 0);
12233 unaccount_event_cpu(event, src_cpu);
12235 list_add(&event->migrate_entry, &events);
12239 * Wait for the events to quiesce before re-instating them.
12244 * Re-instate events in 2 passes.
12246 * Skip over group leaders and only install siblings on this first
12247 * pass, siblings will not get enabled without a leader, however a
12248 * leader will enable its siblings, even if those are still on the old
12251 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12252 if (event->group_leader == event)
12255 list_del(&event->migrate_entry);
12256 if (event->state >= PERF_EVENT_STATE_OFF)
12257 event->state = PERF_EVENT_STATE_INACTIVE;
12258 account_event_cpu(event, dst_cpu);
12259 perf_install_in_context(dst_ctx, event, dst_cpu);
12264 * Once all the siblings are setup properly, install the group leaders
12267 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12268 list_del(&event->migrate_entry);
12269 if (event->state >= PERF_EVENT_STATE_OFF)
12270 event->state = PERF_EVENT_STATE_INACTIVE;
12271 account_event_cpu(event, dst_cpu);
12272 perf_install_in_context(dst_ctx, event, dst_cpu);
12275 mutex_unlock(&dst_ctx->mutex);
12276 mutex_unlock(&src_ctx->mutex);
12278 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12280 static void sync_child_event(struct perf_event *child_event,
12281 struct task_struct *child)
12283 struct perf_event *parent_event = child_event->parent;
12286 if (child_event->attr.inherit_stat)
12287 perf_event_read_event(child_event, child);
12289 child_val = perf_event_count(child_event);
12292 * Add back the child's count to the parent's count:
12294 atomic64_add(child_val, &parent_event->child_count);
12295 atomic64_add(child_event->total_time_enabled,
12296 &parent_event->child_total_time_enabled);
12297 atomic64_add(child_event->total_time_running,
12298 &parent_event->child_total_time_running);
12302 perf_event_exit_event(struct perf_event *child_event,
12303 struct perf_event_context *child_ctx,
12304 struct task_struct *child)
12306 struct perf_event *parent_event = child_event->parent;
12309 * Do not destroy the 'original' grouping; because of the context
12310 * switch optimization the original events could've ended up in a
12311 * random child task.
12313 * If we were to destroy the original group, all group related
12314 * operations would cease to function properly after this random
12317 * Do destroy all inherited groups, we don't care about those
12318 * and being thorough is better.
12320 raw_spin_lock_irq(&child_ctx->lock);
12321 WARN_ON_ONCE(child_ctx->is_active);
12324 perf_group_detach(child_event);
12325 list_del_event(child_event, child_ctx);
12326 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
12327 raw_spin_unlock_irq(&child_ctx->lock);
12330 * Parent events are governed by their filedesc, retain them.
12332 if (!parent_event) {
12333 perf_event_wakeup(child_event);
12337 * Child events can be cleaned up.
12340 sync_child_event(child_event, child);
12343 * Remove this event from the parent's list
12345 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12346 mutex_lock(&parent_event->child_mutex);
12347 list_del_init(&child_event->child_list);
12348 mutex_unlock(&parent_event->child_mutex);
12351 * Kick perf_poll() for is_event_hup().
12353 perf_event_wakeup(parent_event);
12354 free_event(child_event);
12355 put_event(parent_event);
12358 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
12360 struct perf_event_context *child_ctx, *clone_ctx = NULL;
12361 struct perf_event *child_event, *next;
12363 WARN_ON_ONCE(child != current);
12365 child_ctx = perf_pin_task_context(child, ctxn);
12370 * In order to reduce the amount of tricky in ctx tear-down, we hold
12371 * ctx::mutex over the entire thing. This serializes against almost
12372 * everything that wants to access the ctx.
12374 * The exception is sys_perf_event_open() /
12375 * perf_event_create_kernel_count() which does find_get_context()
12376 * without ctx::mutex (it cannot because of the move_group double mutex
12377 * lock thing). See the comments in perf_install_in_context().
12379 mutex_lock(&child_ctx->mutex);
12382 * In a single ctx::lock section, de-schedule the events and detach the
12383 * context from the task such that we cannot ever get it scheduled back
12386 raw_spin_lock_irq(&child_ctx->lock);
12387 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
12390 * Now that the context is inactive, destroy the task <-> ctx relation
12391 * and mark the context dead.
12393 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12394 put_ctx(child_ctx); /* cannot be last */
12395 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12396 put_task_struct(current); /* cannot be last */
12398 clone_ctx = unclone_ctx(child_ctx);
12399 raw_spin_unlock_irq(&child_ctx->lock);
12402 put_ctx(clone_ctx);
12405 * Report the task dead after unscheduling the events so that we
12406 * won't get any samples after PERF_RECORD_EXIT. We can however still
12407 * get a few PERF_RECORD_READ events.
12409 perf_event_task(child, child_ctx, 0);
12411 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
12412 perf_event_exit_event(child_event, child_ctx, child);
12414 mutex_unlock(&child_ctx->mutex);
12416 put_ctx(child_ctx);
12420 * When a child task exits, feed back event values to parent events.
12422 * Can be called with exec_update_lock held when called from
12423 * setup_new_exec().
12425 void perf_event_exit_task(struct task_struct *child)
12427 struct perf_event *event, *tmp;
12430 mutex_lock(&child->perf_event_mutex);
12431 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12433 list_del_init(&event->owner_entry);
12436 * Ensure the list deletion is visible before we clear
12437 * the owner, closes a race against perf_release() where
12438 * we need to serialize on the owner->perf_event_mutex.
12440 smp_store_release(&event->owner, NULL);
12442 mutex_unlock(&child->perf_event_mutex);
12444 for_each_task_context_nr(ctxn)
12445 perf_event_exit_task_context(child, ctxn);
12448 * The perf_event_exit_task_context calls perf_event_task
12449 * with child's task_ctx, which generates EXIT events for
12450 * child contexts and sets child->perf_event_ctxp[] to NULL.
12451 * At this point we need to send EXIT events to cpu contexts.
12453 perf_event_task(child, NULL, 0);
12456 static void perf_free_event(struct perf_event *event,
12457 struct perf_event_context *ctx)
12459 struct perf_event *parent = event->parent;
12461 if (WARN_ON_ONCE(!parent))
12464 mutex_lock(&parent->child_mutex);
12465 list_del_init(&event->child_list);
12466 mutex_unlock(&parent->child_mutex);
12470 raw_spin_lock_irq(&ctx->lock);
12471 perf_group_detach(event);
12472 list_del_event(event, ctx);
12473 raw_spin_unlock_irq(&ctx->lock);
12478 * Free a context as created by inheritance by perf_event_init_task() below,
12479 * used by fork() in case of fail.
12481 * Even though the task has never lived, the context and events have been
12482 * exposed through the child_list, so we must take care tearing it all down.
12484 void perf_event_free_task(struct task_struct *task)
12486 struct perf_event_context *ctx;
12487 struct perf_event *event, *tmp;
12490 for_each_task_context_nr(ctxn) {
12491 ctx = task->perf_event_ctxp[ctxn];
12495 mutex_lock(&ctx->mutex);
12496 raw_spin_lock_irq(&ctx->lock);
12498 * Destroy the task <-> ctx relation and mark the context dead.
12500 * This is important because even though the task hasn't been
12501 * exposed yet the context has been (through child_list).
12503 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12504 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12505 put_task_struct(task); /* cannot be last */
12506 raw_spin_unlock_irq(&ctx->lock);
12508 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
12509 perf_free_event(event, ctx);
12511 mutex_unlock(&ctx->mutex);
12514 * perf_event_release_kernel() could've stolen some of our
12515 * child events and still have them on its free_list. In that
12516 * case we must wait for these events to have been freed (in
12517 * particular all their references to this task must've been
12520 * Without this copy_process() will unconditionally free this
12521 * task (irrespective of its reference count) and
12522 * _free_event()'s put_task_struct(event->hw.target) will be a
12525 * Wait for all events to drop their context reference.
12527 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12528 put_ctx(ctx); /* must be last */
12532 void perf_event_delayed_put(struct task_struct *task)
12536 for_each_task_context_nr(ctxn)
12537 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12540 struct file *perf_event_get(unsigned int fd)
12542 struct file *file = fget(fd);
12544 return ERR_PTR(-EBADF);
12546 if (file->f_op != &perf_fops) {
12548 return ERR_PTR(-EBADF);
12554 const struct perf_event *perf_get_event(struct file *file)
12556 if (file->f_op != &perf_fops)
12557 return ERR_PTR(-EINVAL);
12559 return file->private_data;
12562 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12565 return ERR_PTR(-EINVAL);
12567 return &event->attr;
12571 * Inherit an event from parent task to child task.
12574 * - valid pointer on success
12575 * - NULL for orphaned events
12576 * - IS_ERR() on error
12578 static struct perf_event *
12579 inherit_event(struct perf_event *parent_event,
12580 struct task_struct *parent,
12581 struct perf_event_context *parent_ctx,
12582 struct task_struct *child,
12583 struct perf_event *group_leader,
12584 struct perf_event_context *child_ctx)
12586 enum perf_event_state parent_state = parent_event->state;
12587 struct perf_event *child_event;
12588 unsigned long flags;
12591 * Instead of creating recursive hierarchies of events,
12592 * we link inherited events back to the original parent,
12593 * which has a filp for sure, which we use as the reference
12596 if (parent_event->parent)
12597 parent_event = parent_event->parent;
12599 child_event = perf_event_alloc(&parent_event->attr,
12602 group_leader, parent_event,
12604 if (IS_ERR(child_event))
12605 return child_event;
12608 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12609 !child_ctx->task_ctx_data) {
12610 struct pmu *pmu = child_event->pmu;
12612 child_ctx->task_ctx_data = alloc_task_ctx_data(pmu);
12613 if (!child_ctx->task_ctx_data) {
12614 free_event(child_event);
12615 return ERR_PTR(-ENOMEM);
12620 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12621 * must be under the same lock in order to serialize against
12622 * perf_event_release_kernel(), such that either we must observe
12623 * is_orphaned_event() or they will observe us on the child_list.
12625 mutex_lock(&parent_event->child_mutex);
12626 if (is_orphaned_event(parent_event) ||
12627 !atomic_long_inc_not_zero(&parent_event->refcount)) {
12628 mutex_unlock(&parent_event->child_mutex);
12629 /* task_ctx_data is freed with child_ctx */
12630 free_event(child_event);
12634 get_ctx(child_ctx);
12637 * Make the child state follow the state of the parent event,
12638 * not its attr.disabled bit. We hold the parent's mutex,
12639 * so we won't race with perf_event_{en, dis}able_family.
12641 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12642 child_event->state = PERF_EVENT_STATE_INACTIVE;
12644 child_event->state = PERF_EVENT_STATE_OFF;
12646 if (parent_event->attr.freq) {
12647 u64 sample_period = parent_event->hw.sample_period;
12648 struct hw_perf_event *hwc = &child_event->hw;
12650 hwc->sample_period = sample_period;
12651 hwc->last_period = sample_period;
12653 local64_set(&hwc->period_left, sample_period);
12656 child_event->ctx = child_ctx;
12657 child_event->overflow_handler = parent_event->overflow_handler;
12658 child_event->overflow_handler_context
12659 = parent_event->overflow_handler_context;
12662 * Precalculate sample_data sizes
12664 perf_event__header_size(child_event);
12665 perf_event__id_header_size(child_event);
12668 * Link it up in the child's context:
12670 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12671 add_event_to_ctx(child_event, child_ctx);
12672 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12675 * Link this into the parent event's child list
12677 list_add_tail(&child_event->child_list, &parent_event->child_list);
12678 mutex_unlock(&parent_event->child_mutex);
12680 return child_event;
12684 * Inherits an event group.
12686 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12687 * This matches with perf_event_release_kernel() removing all child events.
12693 static int inherit_group(struct perf_event *parent_event,
12694 struct task_struct *parent,
12695 struct perf_event_context *parent_ctx,
12696 struct task_struct *child,
12697 struct perf_event_context *child_ctx)
12699 struct perf_event *leader;
12700 struct perf_event *sub;
12701 struct perf_event *child_ctr;
12703 leader = inherit_event(parent_event, parent, parent_ctx,
12704 child, NULL, child_ctx);
12705 if (IS_ERR(leader))
12706 return PTR_ERR(leader);
12708 * @leader can be NULL here because of is_orphaned_event(). In this
12709 * case inherit_event() will create individual events, similar to what
12710 * perf_group_detach() would do anyway.
12712 for_each_sibling_event(sub, parent_event) {
12713 child_ctr = inherit_event(sub, parent, parent_ctx,
12714 child, leader, child_ctx);
12715 if (IS_ERR(child_ctr))
12716 return PTR_ERR(child_ctr);
12718 if (sub->aux_event == parent_event && child_ctr &&
12719 !perf_get_aux_event(child_ctr, leader))
12726 * Creates the child task context and tries to inherit the event-group.
12728 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12729 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12730 * consistent with perf_event_release_kernel() removing all child events.
12737 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12738 struct perf_event_context *parent_ctx,
12739 struct task_struct *child, int ctxn,
12740 int *inherited_all)
12743 struct perf_event_context *child_ctx;
12745 if (!event->attr.inherit) {
12746 *inherited_all = 0;
12750 child_ctx = child->perf_event_ctxp[ctxn];
12753 * This is executed from the parent task context, so
12754 * inherit events that have been marked for cloning.
12755 * First allocate and initialize a context for the
12758 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12762 child->perf_event_ctxp[ctxn] = child_ctx;
12765 ret = inherit_group(event, parent, parent_ctx,
12769 *inherited_all = 0;
12775 * Initialize the perf_event context in task_struct
12777 static int perf_event_init_context(struct task_struct *child, int ctxn)
12779 struct perf_event_context *child_ctx, *parent_ctx;
12780 struct perf_event_context *cloned_ctx;
12781 struct perf_event *event;
12782 struct task_struct *parent = current;
12783 int inherited_all = 1;
12784 unsigned long flags;
12787 if (likely(!parent->perf_event_ctxp[ctxn]))
12791 * If the parent's context is a clone, pin it so it won't get
12792 * swapped under us.
12794 parent_ctx = perf_pin_task_context(parent, ctxn);
12799 * No need to check if parent_ctx != NULL here; since we saw
12800 * it non-NULL earlier, the only reason for it to become NULL
12801 * is if we exit, and since we're currently in the middle of
12802 * a fork we can't be exiting at the same time.
12806 * Lock the parent list. No need to lock the child - not PID
12807 * hashed yet and not running, so nobody can access it.
12809 mutex_lock(&parent_ctx->mutex);
12812 * We dont have to disable NMIs - we are only looking at
12813 * the list, not manipulating it:
12815 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12816 ret = inherit_task_group(event, parent, parent_ctx,
12817 child, ctxn, &inherited_all);
12823 * We can't hold ctx->lock when iterating the ->flexible_group list due
12824 * to allocations, but we need to prevent rotation because
12825 * rotate_ctx() will change the list from interrupt context.
12827 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12828 parent_ctx->rotate_disable = 1;
12829 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12831 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12832 ret = inherit_task_group(event, parent, parent_ctx,
12833 child, ctxn, &inherited_all);
12838 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12839 parent_ctx->rotate_disable = 0;
12841 child_ctx = child->perf_event_ctxp[ctxn];
12843 if (child_ctx && inherited_all) {
12845 * Mark the child context as a clone of the parent
12846 * context, or of whatever the parent is a clone of.
12848 * Note that if the parent is a clone, the holding of
12849 * parent_ctx->lock avoids it from being uncloned.
12851 cloned_ctx = parent_ctx->parent_ctx;
12853 child_ctx->parent_ctx = cloned_ctx;
12854 child_ctx->parent_gen = parent_ctx->parent_gen;
12856 child_ctx->parent_ctx = parent_ctx;
12857 child_ctx->parent_gen = parent_ctx->generation;
12859 get_ctx(child_ctx->parent_ctx);
12862 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12864 mutex_unlock(&parent_ctx->mutex);
12866 perf_unpin_context(parent_ctx);
12867 put_ctx(parent_ctx);
12873 * Initialize the perf_event context in task_struct
12875 int perf_event_init_task(struct task_struct *child)
12879 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12880 mutex_init(&child->perf_event_mutex);
12881 INIT_LIST_HEAD(&child->perf_event_list);
12883 for_each_task_context_nr(ctxn) {
12884 ret = perf_event_init_context(child, ctxn);
12886 perf_event_free_task(child);
12894 static void __init perf_event_init_all_cpus(void)
12896 struct swevent_htable *swhash;
12899 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12901 for_each_possible_cpu(cpu) {
12902 swhash = &per_cpu(swevent_htable, cpu);
12903 mutex_init(&swhash->hlist_mutex);
12904 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12906 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12907 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12909 #ifdef CONFIG_CGROUP_PERF
12910 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12912 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
12916 static void perf_swevent_init_cpu(unsigned int cpu)
12918 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12920 mutex_lock(&swhash->hlist_mutex);
12921 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12922 struct swevent_hlist *hlist;
12924 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12926 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12928 mutex_unlock(&swhash->hlist_mutex);
12931 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
12932 static void __perf_event_exit_context(void *__info)
12934 struct perf_event_context *ctx = __info;
12935 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12936 struct perf_event *event;
12938 raw_spin_lock(&ctx->lock);
12939 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12940 list_for_each_entry(event, &ctx->event_list, event_entry)
12941 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12942 raw_spin_unlock(&ctx->lock);
12945 static void perf_event_exit_cpu_context(int cpu)
12947 struct perf_cpu_context *cpuctx;
12948 struct perf_event_context *ctx;
12951 mutex_lock(&pmus_lock);
12952 list_for_each_entry(pmu, &pmus, entry) {
12953 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12954 ctx = &cpuctx->ctx;
12956 mutex_lock(&ctx->mutex);
12957 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12958 cpuctx->online = 0;
12959 mutex_unlock(&ctx->mutex);
12961 cpumask_clear_cpu(cpu, perf_online_mask);
12962 mutex_unlock(&pmus_lock);
12966 static void perf_event_exit_cpu_context(int cpu) { }
12970 int perf_event_init_cpu(unsigned int cpu)
12972 struct perf_cpu_context *cpuctx;
12973 struct perf_event_context *ctx;
12976 perf_swevent_init_cpu(cpu);
12978 mutex_lock(&pmus_lock);
12979 cpumask_set_cpu(cpu, perf_online_mask);
12980 list_for_each_entry(pmu, &pmus, entry) {
12981 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12982 ctx = &cpuctx->ctx;
12984 mutex_lock(&ctx->mutex);
12985 cpuctx->online = 1;
12986 mutex_unlock(&ctx->mutex);
12988 mutex_unlock(&pmus_lock);
12993 int perf_event_exit_cpu(unsigned int cpu)
12995 perf_event_exit_cpu_context(cpu);
13000 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13004 for_each_online_cpu(cpu)
13005 perf_event_exit_cpu(cpu);
13011 * Run the perf reboot notifier at the very last possible moment so that
13012 * the generic watchdog code runs as long as possible.
13014 static struct notifier_block perf_reboot_notifier = {
13015 .notifier_call = perf_reboot,
13016 .priority = INT_MIN,
13019 void __init perf_event_init(void)
13023 idr_init(&pmu_idr);
13025 perf_event_init_all_cpus();
13026 init_srcu_struct(&pmus_srcu);
13027 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13028 perf_pmu_register(&perf_cpu_clock, NULL, -1);
13029 perf_pmu_register(&perf_task_clock, NULL, -1);
13030 perf_tp_register();
13031 perf_event_init_cpu(smp_processor_id());
13032 register_reboot_notifier(&perf_reboot_notifier);
13034 ret = init_hw_breakpoint();
13035 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13038 * Build time assertion that we keep the data_head at the intended
13039 * location. IOW, validation we got the __reserved[] size right.
13041 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13045 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13048 struct perf_pmu_events_attr *pmu_attr =
13049 container_of(attr, struct perf_pmu_events_attr, attr);
13051 if (pmu_attr->event_str)
13052 return sprintf(page, "%s\n", pmu_attr->event_str);
13056 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13058 static int __init perf_event_sysfs_init(void)
13063 mutex_lock(&pmus_lock);
13065 ret = bus_register(&pmu_bus);
13069 list_for_each_entry(pmu, &pmus, entry) {
13070 if (!pmu->name || pmu->type < 0)
13073 ret = pmu_dev_alloc(pmu);
13074 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13076 pmu_bus_running = 1;
13080 mutex_unlock(&pmus_lock);
13084 device_initcall(perf_event_sysfs_init);
13086 #ifdef CONFIG_CGROUP_PERF
13087 static struct cgroup_subsys_state *
13088 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13090 struct perf_cgroup *jc;
13092 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13094 return ERR_PTR(-ENOMEM);
13096 jc->info = alloc_percpu(struct perf_cgroup_info);
13099 return ERR_PTR(-ENOMEM);
13105 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13107 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13109 free_percpu(jc->info);
13113 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13115 perf_event_cgroup(css->cgroup);
13119 static int __perf_cgroup_move(void *info)
13121 struct task_struct *task = info;
13123 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
13128 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13130 struct task_struct *task;
13131 struct cgroup_subsys_state *css;
13133 cgroup_taskset_for_each(task, css, tset)
13134 task_function_call(task, __perf_cgroup_move, task);
13137 struct cgroup_subsys perf_event_cgrp_subsys = {
13138 .css_alloc = perf_cgroup_css_alloc,
13139 .css_free = perf_cgroup_css_free,
13140 .css_online = perf_cgroup_css_online,
13141 .attach = perf_cgroup_attach,
13143 * Implicitly enable on dfl hierarchy so that perf events can
13144 * always be filtered by cgroup2 path as long as perf_event
13145 * controller is not mounted on a legacy hierarchy.
13147 .implicit_on_dfl = true,
13150 #endif /* CONFIG_CGROUP_PERF */